Compare commits
7 Commits
master
...
remove-pri
Author | SHA1 | Date |
---|---|---|
Stéphane Adjemian (Ryûk) | a4152295d7 | |
Stéphane Adjemian (Ryûk) | 3229919762 | |
Stéphane Adjemian (Ryûk) | 302d991a25 | |
Stéphane Adjemian (Ryûk) | b448780c34 | |
Stéphane Adjemian (Ryûk) | 394c8e21b8 | |
Stéphane Adjemian (Ryûk) | 7abea05d33 | |
Stéphane Adjemian (Ryûk) | 3e1fb6dd2f |
|
@ -1,25 +1,21 @@
|
|||
# NB: whenever the present file is modified, the same modification should be
|
||||
# applied to the copy in preprocessor.git
|
||||
|
||||
# For general information about our coding style, and the specific version
|
||||
# of clang-format used, see:
|
||||
# https://git.dynare.org/Dynare/dynare/-/wikis/CodingGuidelines#c-code
|
||||
# For the list of options of clang-format, see:
|
||||
# https://clang.llvm.org/docs/ClangFormatStyleOptions.html
|
||||
# For the list of options (clang-format 14, present in Debian “bookworm” 12), see:
|
||||
# https://releases.llvm.org/14.0.0/tools/clang/docs/ClangFormatStyleOptions.html
|
||||
# Effective configuration can be obtained with:
|
||||
# clang-format --dump-config
|
||||
Language: Cpp
|
||||
Standard: c++20
|
||||
ColumnLimit: 100
|
||||
BasedOnStyle: GNU
|
||||
AllowShortFunctionsOnASingleLine: None
|
||||
AllowShortFunctionsOnASingleLine: InlineOnly
|
||||
AlwaysBreakTemplateDeclarations: Yes
|
||||
BreakConstructorInitializers: AfterColon
|
||||
BreakInheritanceList: AfterColon
|
||||
Cpp11BracedListStyle: true
|
||||
DeriveLineEnding: false
|
||||
IndentPPDirectives: AfterHash
|
||||
PackConstructorInitializers: NextLine
|
||||
PPIndentWidth: 1
|
||||
PointerAlignment: Left
|
||||
SpaceAfterTemplateKeyword: false
|
||||
|
|
|
@ -1,8 +0,0 @@
|
|||
# NB: to use clang-tidy on the MEX source code, make sure that you have
|
||||
# libomp-dev installed (the LLVM implementation of OpenMP)
|
||||
|
||||
# TODO: add the following check families:
|
||||
# - bugprone-*
|
||||
# - cppcoreguidelines-
|
||||
|
||||
Checks: 'performance-*,modernize-*,-modernize-use-trailing-return-type,-clang-diagnostic-unqualified-std-cast-call'
|
|
@ -1,8 +1,6 @@
|
|||
((c-mode . ((indent-tabs-mode . nil)
|
||||
(fill-column . 100)
|
||||
(c-file-style . "gnu")))
|
||||
(c++-mode . ((indent-tabs-mode . nil)
|
||||
(fill-column . 100)
|
||||
(c-file-style . "gnu")))
|
||||
(makefile-mode . ((indent-tabs-mode . t)))
|
||||
(octave-mode . ((indent-tabs-mode . nil)
|
||||
|
|
|
@ -2,23 +2,21 @@ variables:
|
|||
GIT_SUBMODULE_STRATEGY: recursive
|
||||
TERM: linux
|
||||
MATLAB_VERSION: R2023b
|
||||
OLD_MATLAB_VERSION: R2018b
|
||||
# To ensure that "false && true" fails, see https://gitlab.com/gitlab-org/gitlab-runner/-/issues/25394#note_412609647
|
||||
FF_ENABLE_BASH_EXIT_CODE_CHECK: 'true'
|
||||
OLD_MATLAB_VERSION: R2014a
|
||||
|
||||
# The next stanza creates the version number used for the source tarball and the
|
||||
# binary packages. Here are the following possible cases:
|
||||
# - if VERSION was already set (when manually running a pipeline), use it
|
||||
# - if we are in the official Dynare repository:
|
||||
# + if on a tag: use the tag
|
||||
# + if on master: use 7-unstable-$TIMESTAMP-$COMMIT
|
||||
# + if on master: use 6-unstable-$TIMESTAMP-$COMMIT
|
||||
# + on another branch: use $BRANCH-$TIMESTAMP-$COMMIT
|
||||
# - if in a personal repository: use $USER-$TIMESTAMP-$COMMIT
|
||||
before_script:
|
||||
- 'if [[ -z $VERSION ]] && [[ $CI_PROJECT_NAMESPACE == Dynare ]] && [[ -n $CI_COMMIT_TAG ]]; then export VERSION=$CI_COMMIT_TAG; fi'
|
||||
- 'if [[ -z $VERSION ]] && [[ $CI_PROJECT_NAMESPACE == Dynare ]] && [[ $CI_COMMIT_REF_NAME == master ]]; then export VERSION=7-unstable-$(date +%F-%H%M)-$CI_COMMIT_SHORT_SHA; fi'
|
||||
- 'if [[ -z $VERSION ]] && [[ $CI_PROJECT_NAMESPACE == Dynare ]]; then export VERSION=$CI_COMMIT_REF_NAME-$(date +%F-%H%M)-$CI_COMMIT_SHORT_SHA; fi'
|
||||
- 'if [[ -z $VERSION ]]; then export VERSION=$CI_PROJECT_NAMESPACE-$(date +%F-%H%M)-$CI_COMMIT_SHORT_SHA; fi'
|
||||
- '[[ -z $VERSION ]] && [[ $CI_PROJECT_NAMESPACE == Dynare ]] && [[ -n $CI_COMMIT_TAG ]] && export VERSION=$CI_COMMIT_TAG'
|
||||
- '[[ -z $VERSION ]] && [[ $CI_PROJECT_NAMESPACE == Dynare ]] && [[ $CI_COMMIT_REF_NAME == master ]] && export VERSION=6-unstable-$(date +%F-%H%M)-$CI_COMMIT_SHORT_SHA'
|
||||
- '[[ -z $VERSION ]] && [[ $CI_PROJECT_NAMESPACE == Dynare ]] && export VERSION=$CI_COMMIT_REF_NAME-$(date +%F-%H%M)-$CI_COMMIT_SHORT_SHA'
|
||||
- '[[ -z $VERSION ]] && export VERSION=$CI_PROJECT_NAMESPACE-$(date +%F-%H%M)-$CI_COMMIT_SHORT_SHA'
|
||||
|
||||
stages:
|
||||
- build
|
||||
|
@ -177,13 +175,6 @@ test_octave:
|
|||
needs: [ "build_octave" ]
|
||||
when: manual
|
||||
|
||||
test_clang_format:
|
||||
stage: test
|
||||
script:
|
||||
- meson setup -Dbuild_for=octave build-clang-format
|
||||
- ninja -C build-clang-format clang-format-check
|
||||
needs: []
|
||||
|
||||
# For the sign and deploy jobs, we don’t use the “needs” keyword, since we
|
||||
# don’t want those jobs to start before the “test” and “pkg” stages have
|
||||
# succeeded. Hence we stick to the “dependencies” keyword.
|
||||
|
|
|
@ -11,9 +11,12 @@
|
|||
path = matlab/utilities/tests
|
||||
url = ../../Dynare/m-unit-tests.git
|
||||
[submodule "matlab/modules/dseries"]
|
||||
path = matlab/dseries
|
||||
path = matlab/modules/dseries
|
||||
url = ../../Dynare/dseries.git
|
||||
branch = master
|
||||
[submodule "contrib/jsonlab"]
|
||||
path = contrib/jsonlab
|
||||
url = https://github.com/fangq/jsonlab.git
|
||||
[submodule "preprocessor"]
|
||||
path = preprocessor
|
||||
url = ../../Dynare/preprocessor.git
|
||||
|
|
402
NEWS.md
402
NEWS.md
|
@ -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 model’s
|
||||
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. 434–455.
|
||||
- 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), 1–45.
|
||||
- Christiano, Lawrence J., Mathias Trabandt, and Karl Walentin (2010): “DSGE
|
||||
Models for Monetary Policy Analysis,” In: *Handbook of Monetary Economics
|
||||
3*, 285–367.
|
||||
- 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)
|
||||
===========================================
|
||||
|
||||
|
|
|
@ -70,7 +70,7 @@ A number of tools and libraries are needed in order to recompile everything. You
|
|||
- [GNU Octave](https://www.octave.org) with
|
||||
- the development headers (if you want to compile the MEX for Octave)
|
||||
- the development libraries corresponding to the [UMFPACK](https://people.engr.tamu.edu/davis/suitesparse.html) packaged with Octave (if you want to compile the MEX for Octave)
|
||||
- the [statistics](https://octave.sourceforge.io/statistics/) package and, optionally, the [control](https://octave.sourceforge.io/control/), [io](https://octave.sourceforge.io/io/) and [optimization](https://octave.sourceforge.io/optim/) packages, either installed via your package manager or through [Octave Forge](https://octave.sourceforge.io/)
|
||||
- Optionally, the [Control](https://octave.sourceforge.io/control/), [IO](https://octave.sourceforge.io/io/), [Optimization](https://octave.sourceforge.io/optim/) and [Statistics](https://octave.sourceforge.io/statistics/) package either installed via your package manager or through [Octave Forge](https://octave.sourceforge.io/).
|
||||
- [Meson](https://mesonbuild.com), version 0.64.0 or later
|
||||
- [Pkgconf](http://pkgconf.org/), or another pkg-config implementation
|
||||
- [Bash](https://www.gnu.org/software/bash/)
|
||||
|
@ -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
|
||||
|
@ -480,7 +479,7 @@ If you want a certain version (e.g. 5.x) , then add `--single-branch --branch 5.
|
|||
```sh
|
||||
export BUILDDIR=build-matlab
|
||||
export MATLABPATH=/Applications/MATLAB_R2023b.app
|
||||
arch -$ARCH meson setup --native-file macOS/homebrew-native-$ARCH.ini -Dmatlab_path=$MATLABPATH -Dbuildtype=debugoptimized -Dfortran_args="['-B','$DYNAREDIR/slicot/lib']" $BUILDDIR
|
||||
arch -$ARCH meson setup --native-file scripts/homebrew-native-$ARCH.ini -Dmatlab_path=$MATLABPATH -Dbuildtype=debugoptimized -Dfortran_args="['-B','$DYNAREDIR/slicot/lib']" $BUILDDIR
|
||||
```
|
||||
where you need to adapt the path to MATLAB.
|
||||
Similarly, if you want to compile for Octave, replace the `-Dmatlab_path` option by `-Dbuild_for=octave`, and change the build directory to `build-octave`.
|
||||
|
@ -515,4 +514,4 @@ e.g. by adding this to your mod file. Alternatively, you can create a `startup.m
|
|||
## Docker
|
||||
We offer a variety of pre-configured Docker containers for Dynare, pre-configured with Octave and MATLAB including all recommended toolboxes.
|
||||
These are readily available for your convenience on [Docker Hub](https://hub.docker.com/r/dynare/dynare).
|
||||
The `scripts/docker` folder contains [information and instructions](scripts/docker/README.md) to interact, built and customize the containers.
|
||||
The docker folder contains [information and instructions](docker/README.md) to interact, built and customize the containers.
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 5a58fafdca239e61be4d7b2270307b2445bb571a
|
139
doc/gsa/gsa.tex
139
doc/gsa/gsa.tex
|
@ -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.
|
||||
|
|
|
@ -2,6 +2,7 @@ function build_internal_documentation()
|
|||
% The name of the function should be explicit...
|
||||
|
||||
datafiles = [];
|
||||
datafiles = [ datafiles ; {'../../matlab/utilities/dataset'}, {'initialize_dataset'}];
|
||||
datafiles = [ datafiles ; {'../../matlab/utilities/dataset'}, {'descriptive_statistics'}];
|
||||
datafiles = [ datafiles ; {'../../matlab/utilities/dataset'}, {'compute_stdv'}];
|
||||
datafiles = [ datafiles ; {'../../matlab/utilities/dataset'}, {'compute_cova'}];
|
||||
|
@ -80,4 +81,4 @@ if rows(miscfiles)
|
|||
fprintf(fid,'\n\n\n');
|
||||
end
|
||||
end
|
||||
fclose(fid);
|
||||
fclose(fid);
|
|
@ -16,20 +16,18 @@ Bibliography
|
|||
* Bini, Dario A., Guy Latouche, and Beatrice Meini (2002): “Solving matrix polynomial equations arising in queueing problems,” *Linear Algebra and its Applications*, 340, 225–244.
|
||||
* 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, 711–734.
|
||||
* 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. 434–455.
|
||||
* 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, 19–38.
|
||||
* Christiano, Lawrence J., Martin Eichenbaum and Charles L. Evans (2005): “Nominal Rigidities and the Dynamic Effects of a Shock to Monetary Policy,” *Journal of Political Economy*, 113(1), 1–45.
|
||||
* Christiano, Lawrence J., Mathias Trabandt, and Karl Walentin (2010): “DSGE Models for Monetary Policy Analysis,” In: *Handbook of Monetary Economics 3*, 285–367.
|
||||
* Christiano, Lawrence J., Mathias Trabandt and Karl Walentin (2011): “Introducing financial frictions and unemployment into a small open economy model,” *Journal of Economic Dynamics and Control*, 35(12), 1999–2041.
|
||||
* Christoffel, Kai, Günter Coenen and Anders Warne (2010): “Forecasting with DSGE models,” *ECB Working Paper Series*, 1185.
|
||||
* Collard, Fabrice (2001): “Stochastic simulations with Dynare: A practical guide”.
|
||||
* Collard, Fabrice and Michel Juillard (2001a): “Accuracy of stochastic perturbation methods: The case of asset pricing models,” *Journal of Economic Dynamics and Control*, 25, 979–999.
|
||||
* 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, 125–139.
|
||||
* 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), 262–280.
|
||||
* 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), 643–673.
|
||||
* Dennis, Richard (2007): “Optimal Policy In Rational Expectations Models: New Solution Algorithms”, *Macroeconomic Dynamics*, 11(1), 31–55.
|
||||
* Duffie, Darrel and Kenneth J. Singleton (1993): “Simulated Moments Estimation of Markov Models of Asset Prices”, *Econometrica*, 61(4), 929-952.
|
||||
|
@ -49,7 +47,6 @@ Bibliography
|
|||
* Hansen, Lars P. (1982): “Large sample properties of generalized method of moments estimators,” Econometrica, 50(4), 1029–1054.
|
||||
* 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, 282–291.
|
||||
* Harvey, Andrew C. and Garry D.A. Phillips (1979): “Maximum likelihood estimation of regression models with autoregressive-moving average disturbances,” *Biometrika*, 66(1), 49–58.
|
||||
* 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), 693–705.
|
||||
* Ireland, Peter (2004): “A Method for Taking Models to the Data,” *Journal of Economic Dynamics and Control*, 28, 1205–26.
|
||||
* Iskrev, Nikolay (2010): “Local identification in DSGE models,” *Journal of Monetary Economics*, 57(2), 189–202.
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright © 2018-2024 Dynare Team
|
||||
# Copyright © 2018-2023 Dynare Team
|
||||
#
|
||||
# This file is part of Dynare.
|
||||
#
|
||||
|
@ -34,7 +34,7 @@ html_static_path = ['_static']
|
|||
master_doc = 'index'
|
||||
|
||||
project = u'Dynare'
|
||||
copyright = u'1996–2024 Dynare Team'
|
||||
copyright = u'1996–2023 Dynare Team'
|
||||
author = u'Dynare Team'
|
||||
|
||||
add_function_parentheses = False
|
||||
|
@ -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 = [
|
||||
|
|
|
@ -8,20 +8,6 @@
|
|||
Dynare misc commands
|
||||
####################
|
||||
|
||||
.. 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 ;
|
||||
|
||||
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 ;
|
||||
|
||||
Puts the IRFs stored in ``oo_.irfs`` into vectors with the same name into the base workspace.
|
||||
|
||||
.. command:: prior_function(OPTIONS);
|
||||
|
||||
Executes a user-defined function on parameter draws from the prior
|
||||
|
@ -230,97 +216,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;
|
||||
|
|
|
@ -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:
|
||||
|
@ -26,7 +26,7 @@ The following people used to be members of the team:
|
|||
* Ferhat Mihoubi
|
||||
* George Perendia
|
||||
|
||||
Copyright © 1996-2024, Dynare Team.
|
||||
Copyright © 1996-2023, 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 Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
|
||||
|
||||
|
|
|
@ -14,8 +14,8 @@ compilation steps are necessary in that case.
|
|||
|
||||
In order to run Dynare, you need one of the following:
|
||||
|
||||
* MATLAB, any version ranging from 9.5 (R2018b) to 23.2 (R2023b);
|
||||
* GNU Octave, any version ranging from 7.1.0 to 8.4.0, with the ``statistics`` package
|
||||
* MATLAB, any version ranging from 8.3 (R2014a) to 23.2 (R2023b);
|
||||
* GNU Octave, any version ranging from 6.2.0 to 8.4.0, with the statistics package
|
||||
from `Octave-Forge`_. Note however that the Dynare installer for Windows
|
||||
requires a more specific version of Octave, as indicated on the download
|
||||
page.
|
||||
|
@ -26,8 +26,8 @@ extra features, but are in no way required:
|
|||
* If under MATLAB: the Optimization Toolbox, the Statistics Toolbox,
|
||||
the Control System Toolbox;
|
||||
|
||||
* If under Octave, the following `Octave-Forge`_ packages: ``optim``, ``io``,
|
||||
``control``.
|
||||
* If under Octave, the following `Octave-Forge`_ packages: ``optim, io,
|
||||
control``.
|
||||
|
||||
|
||||
Installation of Dynare
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -15,16 +15,11 @@ related to the model (and hence not placed in the model file). At the
|
|||
moment, it is only used when using Dynare to run parallel
|
||||
computations.
|
||||
|
||||
On Linux and macOS, the configuration file is 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 searched by default in
|
||||
``%APPDATA%\dynare\dynare.ini`` (typically
|
||||
``c:\Users\USERNAME\AppData\Roaming\dynare\dynare.ini``). You can specify a non
|
||||
standard location using the ``conffile`` option of the ``dynare`` command (see
|
||||
:ref:`dyn-invoc`).
|
||||
On Linux and macOS, the default location of the configuration file is
|
||||
``$HOME/.dynare``, while on Windows it is ``%APPDATA%\dynare.ini``
|
||||
(typically ``c:\Users\USERNAME\AppData\dynare.ini``). You
|
||||
can specify a non standard location using the ``conffile`` option of
|
||||
the ``dynare`` command (see :ref:`dyn-invoc`).
|
||||
|
||||
The parsing of the configuration file is case-sensitive and it should
|
||||
take the following form, with each option/choice pair placed on a
|
||||
|
@ -81,15 +76,8 @@ processing. Currently, there is only one option available.
|
|||
|
||||
.. option:: GlobalInitFile = PATH_AND_FILE
|
||||
|
||||
The location of a global initialization file that can be used to
|
||||
customize some Dynare internals (typically default option values). This
|
||||
is a MATLAB/Octave script.
|
||||
|
||||
If this option is not specified, Dynare will look for a
|
||||
``global_init.m`` file in its 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).
|
||||
The location of the global initialization file to be run at
|
||||
the end of ``global_initialization.m``.
|
||||
|
||||
*Example*
|
||||
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -22,8 +22,6 @@ Dates
|
|||
=====
|
||||
.. highlight:: matlab
|
||||
|
||||
.. _dates in a mod file:
|
||||
|
||||
Dates in a mod 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
|
||||
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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
|
|
@ -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 .
|
|
@ -26,17 +26,13 @@
|
|||
* The model is written in the beginning of period stock notation. To make the model
|
||||
* conform with Dynare’s end of period stock notation, we use the
|
||||
* predetermined_variables-command.
|
||||
*
|
||||
* The model has been implemented in detrended form, i.e. the \mu_{i,t} are actually
|
||||
* the the growth rates of the original \mu_{i,t}^{orig} in the paper, i.e.
|
||||
* log(\mu_{i,t})=log(\mu_{i,t}^{orig}/\mu_{i,t-1}^{orig})
|
||||
*
|
||||
*
|
||||
* Please note that the following copyright notice only applies to this Dynare
|
||||
* implementation of the model.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Copyright © 2013-2023 Dynare Team
|
||||
* Copyright © 2013-2020 Dynare Team
|
||||
*
|
||||
* This file is part of Dynare.
|
||||
*
|
||||
|
@ -155,12 +151,12 @@ gammmaPI =1.29;
|
|||
PIbar = 1.01;
|
||||
rhod = 0.12;
|
||||
rhophi = 0.93;
|
||||
sigma_A = exp(-3.97);
|
||||
sigma_d = exp(-1.51);
|
||||
sigma_A = -3.97;
|
||||
sigma_d = -1.51;
|
||||
|
||||
sigma_phi =exp(-2.36);
|
||||
sigma_mu =exp(-5.43);
|
||||
sigma_m =exp(-5.85);
|
||||
sigma_phi =-2.36;
|
||||
sigma_mu =-5.43;
|
||||
sigma_m =-5.85;
|
||||
Lambdamu=3.4e-3;
|
||||
LambdaA = 2.8e-3;
|
||||
|
||||
|
@ -218,7 +214,7 @@ mc=(1/(1-alppha))^(1-alppha)*(1/alppha)^alppha*w^(1-alppha)*r^alppha;
|
|||
1=thetap*(PI(-1)^chi/PI)^(1-epsilon)+(1-thetap)*PIstar^(1-epsilon);
|
||||
|
||||
[name='Taylor Rule']
|
||||
R/Rbar=(R(-1)/Rbar)^gammmaR*((PI/PIbar)^gammmaPI*((yd/yd(-1)*mu_z)/exp(LambdaYd))^gammmay)^(1-gammmaR)*exp(sigma_m*epsm);
|
||||
R/Rbar=(R(-1)/Rbar)^gammmaR*((PI/PIbar)^gammmaPI*((yd/yd(-1)*mu_z)/exp(LambdaYd))^gammmay)^(1-gammmaR)*exp(epsm);
|
||||
|
||||
[name='Resource constraint']
|
||||
yd=c+x+mu_z^(-1)*mu_I^(-1)*(gammma1*(u-1)+gammma2/2*(u-1)^2)*k;
|
||||
|
@ -239,24 +235,24 @@ PIstarw=wstar/w;
|
|||
|
||||
//exogenous processes
|
||||
[name='Preference Shock']
|
||||
log(d)=rhod*log(d(-1))+sigma_d*epsd;
|
||||
log(d)=rhod*log(d(-1))+epsd;
|
||||
[name='Labor disutility Shock']
|
||||
log(phi)=rhophi*log(phi(-1))+sigma_phi*epsphi;
|
||||
log(phi)=rhophi*log(phi(-1))+epsphi;
|
||||
[name='Investment specific technology']
|
||||
log(mu_I)=Lambdamu+sigma_mu*epsmu_I;
|
||||
log(mu_I)=Lambdamu+epsmu_I;
|
||||
[name='Neutral technology']
|
||||
log(mu_A)=LambdaA+sigma_A*epsA;
|
||||
log(mu_A)=LambdaA+epsA;
|
||||
[name='Defininition composite technology']
|
||||
mu_z=mu_A^(1/(1-alppha))*mu_I^(alppha/(1-alppha));
|
||||
|
||||
end;
|
||||
|
||||
shocks;
|
||||
var epsd; stderr 1;
|
||||
var epsphi; stderr 1;
|
||||
var epsmu_I; stderr 1;
|
||||
var epsA; stderr 1;
|
||||
var epsm; stderr 1;
|
||||
var epsd; stderr exp(sigma_d);
|
||||
var epsphi; stderr exp(sigma_phi);
|
||||
var epsmu_I; stderr exp(sigma_mu);
|
||||
var epsA; stderr exp(sigma_A);
|
||||
var epsm; stderr exp(sigma_m);
|
||||
end;
|
||||
|
||||
steady;
|
||||
|
|
|
@ -0,0 +1,6 @@
|
|||
Assuming that the dynare++ binary is in your PATH, you can run the example by using the following command
|
||||
in a Command Prompt Window:
|
||||
|
||||
... > dynare++ example1.mod
|
||||
|
||||
Please, read the manual (doc\dynare++\dynare++-tutorial.pdf) for a description of the generated output.
|
|
@ -0,0 +1,45 @@
|
|||
/*
|
||||
* This Dynare++ mod-file implements the RBC model with time-to-build
|
||||
* described in Kamenik (2011): "DSGE Models with Dynare++. A Tutorial."
|
||||
* Note that Dynare++ uses the same stock-at-the-end-of-period timing convention
|
||||
* as the regular Dynare
|
||||
*/
|
||||
|
||||
var Y, C, K, A, H, B;
|
||||
|
||||
varexo EPS, NU;
|
||||
|
||||
parameters beta, rho, alpha, delta, theta, psi, tau;
|
||||
|
||||
alpha = 0.36;
|
||||
rho = 0.95;
|
||||
tau = 0.025;
|
||||
beta = 1/(1.03^0.25);
|
||||
delta = 0.025;
|
||||
psi = 0;
|
||||
theta = 2.95;
|
||||
|
||||
model;
|
||||
C*theta*H^(1+psi) = (1-alpha)*Y;
|
||||
beta*exp(B)*C/exp(B(1))/C(1)*
|
||||
(exp(B(1))*alpha*Y(1)/K(1)+1-delta) = 1;
|
||||
Y = exp(A)*K^alpha*H^(1-alpha);
|
||||
K = exp(B(-1))*(Y(-1)-C(-1)) + (1-delta)*K(-1);
|
||||
A = rho*A(-1) + tau*B(-1) + EPS;
|
||||
B = tau*A(-1) + rho*B(-1) + NU;
|
||||
end;
|
||||
|
||||
initval;
|
||||
A = 0;
|
||||
B = 0;
|
||||
H = ((1-alpha)/(theta*(1-(delta*alpha)/(1/beta-1+delta))))^(1/(1+psi));
|
||||
Y = (alpha/(1/beta-1+delta))^(alpha/(1-alpha))*H;
|
||||
K = alpha/(1/beta-1+delta)*Y;
|
||||
C = Y - delta*K;
|
||||
end;
|
||||
|
||||
vcov = [0.0002 0.00005;
|
||||
0.00005 0.0001
|
||||
];
|
||||
|
||||
order = 7;
|
|
@ -1,22 +1,22 @@
|
|||
/*
|
||||
* This file replicates the estimation of the cash in advance model (termed M1
|
||||
* in the paper) described in Frank Schorfheide (2000): "Loss function-based
|
||||
* This file replicates the estimation of the cash in advance model (termed M1
|
||||
* in the paper) described in Frank Schorfheide (2000): "Loss function-based
|
||||
* evaluation of DSGE models", Journal of Applied Econometrics, 15(6), 645-670.
|
||||
*
|
||||
* The data are taken from the replication package at
|
||||
* http://dx.doi.org/10.15456/jae.2022314.0708799949
|
||||
* The data are in file "fsdat_simul.m", and have been artificially generated.
|
||||
* They are therefore different from the original dataset used by Schorfheide.
|
||||
*
|
||||
* The prior distribution follows the one originally specified in Schorfheide's
|
||||
* paper. Note that the elicited beta prior for rho in the paper
|
||||
* paper, except for parameter rho. In the paper, the elicited beta prior for rho
|
||||
* implies an asymptote and corresponding prior mode at 0. It is generally
|
||||
* recommended to avoid this extreme type of prior.
|
||||
*
|
||||
* Because the data are already logged and we use the loglinear option to conduct
|
||||
* a full log-linearization, we need to use the logdata option.
|
||||
* recommended to avoid this extreme type of prior. Some optimizers, for instance
|
||||
* mode_compute=12 (Mathworks' particleswarm algorithm) may find a posterior mode
|
||||
* with rho equal to zero. We lowered the value of the prior standard deviation
|
||||
* (changing .223 to .100) to remove the asymptote.
|
||||
*
|
||||
* The equations are taken from J. Nason and T. Cogley (1994): "Testing the
|
||||
* implications of long-run neutrality for monetary business cycle models",
|
||||
* Journal of Applied Econometrics, 9, S37-S70, NC in the following.
|
||||
* Journal of Applied Econometrics, 9, S37-S70.
|
||||
* Note that there is an initial minus sign missing in equation (A1), p. S63.
|
||||
*
|
||||
* This implementation was originally written by Michel Juillard. Please note that the
|
||||
|
@ -25,7 +25,7 @@
|
|||
*/
|
||||
|
||||
/*
|
||||
* Copyright © 2004-2023 Dynare Team
|
||||
* Copyright © 2004-2017 Dynare Team
|
||||
*
|
||||
* This file is part of Dynare.
|
||||
*
|
||||
|
@ -43,71 +43,33 @@
|
|||
* along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
var m ${m}$ (long_name='money growth')
|
||||
P ${P}$ (long_name='Price level')
|
||||
c ${c}$ (long_name='consumption')
|
||||
e ${e}$ (long_name='capital stock')
|
||||
W ${W}$ (long_name='Wage rate')
|
||||
R ${R}$ (long_name='interest rate')
|
||||
k ${k}$ (long_name='capital stock')
|
||||
d ${d}$ (long_name='dividends')
|
||||
n ${n}$ (long_name='labor')
|
||||
l ${l}$ (long_name='loans')
|
||||
gy_obs ${\Delta \ln GDP}$ (long_name='detrended capital stock')
|
||||
gp_obs ${\Delta \ln P}$ (long_name='detrended capital stock')
|
||||
y ${y}$ (long_name='detrended output')
|
||||
dA ${\Delta A}$ (long_name='TFP growth')
|
||||
;
|
||||
varexo e_a ${\epsilon_A}$ (long_name='TFP shock')
|
||||
e_m ${\epsilon_M}$ (long_name='Money growth shock')
|
||||
;
|
||||
var m P c e W R k d n l gy_obs gp_obs y dA;
|
||||
varexo e_a e_m;
|
||||
|
||||
parameters alp ${\alpha}$ (long_name='capital share')
|
||||
bet ${\beta}$ (long_name='discount factor')
|
||||
gam ${\gamma}$ (long_name='long-run TFP growth')
|
||||
logmst ${\log(m^*)}$ (long_name='long-run money growth')
|
||||
rho ${\rho}$ (long_name='autocorrelation money growth')
|
||||
phi ${\phi}$ (long_name='labor weight in consumption')
|
||||
del ${\delta}$ (long_name='depreciation rate')
|
||||
;
|
||||
parameters alp bet gam mst rho psi del;
|
||||
|
||||
% roughly picked values to allow simulating the model before estimation
|
||||
alp = 0.33;
|
||||
bet = 0.99;
|
||||
gam = 0.003;
|
||||
logmst = log(1.011);
|
||||
mst = 1.011;
|
||||
rho = 0.7;
|
||||
phi = 0.787;
|
||||
psi = 0.787;
|
||||
del = 0.02;
|
||||
|
||||
model;
|
||||
[name='NC before eq. (1), TFP growth equation']
|
||||
dA = exp(gam+e_a);
|
||||
[name='NC eq. (2), money growth rate']
|
||||
log(m) = (1-rho)*logmst + rho*log(m(-1))+e_m;
|
||||
[name='NC eq. (A1), Euler equation']
|
||||
log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m;
|
||||
-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;
|
||||
[name='NC below eq. (A1), firm borrowing constraint']
|
||||
W = l/n;
|
||||
[name='NC eq. (A2), intratemporal labour market condition']
|
||||
-(phi/(1-phi))*(c*P/(1-n))+l/n = 0;
|
||||
[name='NC below eq. (A2), credit market clearing']
|
||||
-(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
|
||||
R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
|
||||
[name='NC eq. (A3), credit market optimality']
|
||||
1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
|
||||
[name='NC eq. (18), aggregate resource constraint']
|
||||
c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
|
||||
[name='NC eq. (19), money market condition']
|
||||
P*c = m;
|
||||
[name='NC eq. (20), credit market equilibrium condition']
|
||||
m-1+d = l;
|
||||
[name='Definition TFP shock']
|
||||
e = exp(e_a);
|
||||
[name='Implied by NC eq. (18), production function']
|
||||
y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
|
||||
[name='Observation equation GDP growth']
|
||||
gy_obs = dA*y/y(-1);
|
||||
[name='Observation equation price level']
|
||||
gp_obs = (P/P(-1))*m(-1)/dA;
|
||||
end;
|
||||
|
||||
|
@ -119,41 +81,40 @@ end;
|
|||
steady_state_model;
|
||||
dA = exp(gam);
|
||||
gst = 1/dA;
|
||||
m = exp(logmst);
|
||||
m = mst;
|
||||
khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
|
||||
xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/m )^(-1);
|
||||
nust = phi*m^2/( (1-alp)*(1-phi)*bet*gst^alp*khst^alp );
|
||||
xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
|
||||
nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
|
||||
n = xist/(nust+xist);
|
||||
P = xist + nust;
|
||||
k = khst*n;
|
||||
|
||||
l = phi*m*n/( (1-phi)*(1-n) );
|
||||
c = m/P;
|
||||
d = l - m + 1;
|
||||
l = psi*mst*n/( (1-psi)*(1-n) );
|
||||
c = mst/P;
|
||||
d = l - mst + 1;
|
||||
y = k^alp*n^(1-alp)*gst^alp;
|
||||
R = m/bet;
|
||||
R = mst/bet;
|
||||
W = l/n;
|
||||
ist = y-c;
|
||||
q = 1 - d;
|
||||
|
||||
e = 1;
|
||||
|
||||
|
||||
gp_obs = m/dA;
|
||||
gy_obs = dA;
|
||||
end;
|
||||
|
||||
|
||||
steady;
|
||||
|
||||
check;
|
||||
|
||||
% Table 1 of Schorfheide (2000)
|
||||
estimated_params;
|
||||
alp, beta_pdf, 0.356, 0.02;
|
||||
bet, beta_pdf, 0.993, 0.002;
|
||||
gam, normal_pdf, 0.0085, 0.003;
|
||||
logmst, normal_pdf, 0.0002, 0.007;
|
||||
rho, beta_pdf, 0.129, 0.223;
|
||||
phi, beta_pdf, 0.65, 0.05;
|
||||
mst, normal_pdf, 1.0002, 0.007;
|
||||
rho, beta_pdf, 0.129, 0.100;
|
||||
psi, beta_pdf, 0.65, 0.05;
|
||||
del, beta_pdf, 0.01, 0.005;
|
||||
stderr e_a, inv_gamma_pdf, 0.035449, inf;
|
||||
stderr e_m, inv_gamma_pdf, 0.008862, inf;
|
||||
|
@ -161,8 +122,14 @@ end;
|
|||
|
||||
varobs gp_obs gy_obs;
|
||||
|
||||
estimation(order=1, datafile=fs2000_data, loglinear,logdata, mode_compute=4, mh_replic=20000, nodiagnostic, mh_nblocks=2, mh_jscale=0.8, mode_check);
|
||||
estimation(order=1, datafile=fsdat_simul, nobs=192, loglinear, mh_replic=2000, mh_nblocks=2, mh_jscale=0.8, mode_check);
|
||||
|
||||
%uncomment the following lines to generate LaTeX-code of the model equations
|
||||
%write_latex_original_model(write_equation_tags);
|
||||
%collect_latex_files;
|
||||
|
||||
/*
|
||||
* The following lines were used to generate the data file. If you want to
|
||||
* generate another random data file, comment the "estimation" line and uncomment
|
||||
* the following lines.
|
||||
*/
|
||||
|
||||
//stoch_simul(periods=200, order=1);
|
||||
//datatomfile('fsdat_simul', {'gy_obs', 'gp_obs'});
|
||||
|
|
|
@ -1,215 +0,0 @@
|
|||
%This file is a direct Matlab implementation of the loaddata.g and data.prn files
|
||||
%of Schorfheide, Frank (2000): Loss function-based evaluation of DSGE models
|
||||
%(replication data). Version: 1. Journal of Applied Econometrics. Dataset.
|
||||
%http://dx.doi.org/10.15456/jae.2022314.0708799949
|
||||
% Copyright: 2000-2022 Frank Schorfheide
|
||||
% Copyright: 2023 Dynare Team
|
||||
|
||||
% License: CC BY 4.0
|
||||
% (https://creativecommons.org/licenses/by/4.0/legalcode)
|
||||
|
||||
% Time series, extracted 05/04/00
|
||||
% columms are quarterly data from 1949:IV to 1997:IV
|
||||
% 1: GDPD = GROSS DOMESTIC PRODUCT:IMPLICIT PRICE DEFLATOR (INDEX,92=100)(T7.1)
|
||||
% 2: GDPQ = GROSS DOMESTIC PRODUCT
|
||||
% 3: GPOP = POPULATION, NIPA basis (THOUS.,NSA)
|
||||
|
||||
data_q=[18.02 1474.5 150.2
|
||||
17.94 1538.2 150.9
|
||||
18.01 1584.5 151.4
|
||||
18.42 1644.1 152
|
||||
18.73 1678.6 152.7
|
||||
19.46 1693.1 153.3
|
||||
19.55 1724 153.9
|
||||
19.56 1758.2 154.7
|
||||
19.79 1760.6 155.4
|
||||
19.77 1779.2 156
|
||||
19.82 1778.8 156.6
|
||||
20.03 1790.9 157.3
|
||||
20.12 1846 158
|
||||
20.1 1882.6 158.6
|
||||
20.14 1897.3 159.2
|
||||
20.22 1887.4 160
|
||||
20.27 1858.2 160.7
|
||||
20.34 1849.9 161.4
|
||||
20.39 1848.5 162
|
||||
20.42 1868.9 162.8
|
||||
20.47 1905.6 163.6
|
||||
20.56 1959.6 164.3
|
||||
20.62 1994.4 164.9
|
||||
20.78 2020.1 165.7
|
||||
21 2030.5 166.5
|
||||
21.2 2023.6 167.2
|
||||
21.33 2037.7 167.9
|
||||
21.62 2033.4 168.7
|
||||
21.71 2066.2 169.5
|
||||
22.01 2077.5 170.2
|
||||
22.15 2071.9 170.9
|
||||
22.27 2094 171.7
|
||||
22.29 2070.8 172.5
|
||||
22.56 2012.6 173.1
|
||||
22.64 2024.7 173.8
|
||||
22.77 2072.3 174.5
|
||||
22.88 2120.6 175.3
|
||||
22.92 2165 176.045
|
||||
22.91 2223.3 176.727
|
||||
22.94 2221.4 177.481
|
||||
23.03 2230.95 178.268
|
||||
23.13 2279.22 179.694
|
||||
23.22 2265.48 180.335
|
||||
23.32 2268.29 181.094
|
||||
23.4 2238.57 181.915
|
||||
23.45 2251.68 182.634
|
||||
23.51 2292.02 183.337
|
||||
23.56 2332.61 184.103
|
||||
23.63 2381.01 184.894
|
||||
23.75 2422.59 185.553
|
||||
23.81 2448.01 186.203
|
||||
23.87 2471.86 186.926
|
||||
23.94 2476.67 187.68
|
||||
24 2508.7 188.299
|
||||
24.07 2538.05 188.906
|
||||
24.12 2586.26 189.631
|
||||
24.29 2604.62 190.362
|
||||
24.35 2666.69 190.954
|
||||
24.41 2697.54 191.56
|
||||
24.52 2729.63 192.256
|
||||
24.64 2739.75 192.938
|
||||
24.77 2808.88 193.467
|
||||
24.88 2846.34 193.994
|
||||
25.01 2898.79 194.647
|
||||
25.17 2970.48 195.279
|
||||
25.32 3042.35 195.763
|
||||
25.53 3055.53 196.277
|
||||
25.79 3076.51 196.877
|
||||
26.02 3102.36 197.481
|
||||
26.14 3127.15 197.967
|
||||
26.31 3129.53 198.455
|
||||
26.6 3154.19 199.012
|
||||
26.9 3177.98 199.572
|
||||
27.21 3236.18 199.995
|
||||
27.49 3292.07 200.452
|
||||
27.75 3316.11 200.997
|
||||
28.12 3331.22 201.538
|
||||
28.39 3381.86 201.955
|
||||
28.73 3390.23 202.419
|
||||
29.14 3409.65 202.986
|
||||
29.51 3392.6 203.584
|
||||
29.94 3386.49 204.086
|
||||
30.36 3391.61 204.721
|
||||
30.61 3422.95 205.419
|
||||
31.02 3389.36 206.13
|
||||
31.5 3481.4 206.763
|
||||
31.93 3500.95 207.362
|
||||
32.27 3523.8 208
|
||||
32.54 3533.79 208.642
|
||||
33.02 3604.73 209.142
|
||||
33.2 3687.9 209.637
|
||||
33.49 3726.18 210.181
|
||||
33.95 3790.44 210.737
|
||||
34.36 3892.22 211.192
|
||||
34.94 3919.01 211.663
|
||||
35.61 3907.08 212.191
|
||||
36.29 3947.11 212.708
|
||||
37.01 3908.15 213.144
|
||||
37.79 3922.57 213.602
|
||||
38.96 3879.98 214.147
|
||||
40.13 3854.13 214.7
|
||||
41.05 3800.93 215.135
|
||||
41.66 3835.21 215.652
|
||||
42.41 3907.02 216.289
|
||||
43.19 3952.48 216.848
|
||||
43.69 4044.59 217.314
|
||||
44.15 4072.19 217.776
|
||||
44.77 4088.49 218.338
|
||||
45.57 4126.39 218.917
|
||||
46.32 4176.28 219.427
|
||||
47.07 4260.08 219.956
|
||||
47.66 4329.46 220.573
|
||||
48.63 4328.33 221.201
|
||||
49.42 4345.51 221.719
|
||||
50.41 4510.73 222.281
|
||||
51.27 4552.14 222.933
|
||||
52.35 4603.65 223.583
|
||||
53.51 4605.65 224.152
|
||||
54.65 4615.64 224.737
|
||||
55.82 4644.93 225.418
|
||||
56.92 4656.23 226.117
|
||||
58.18 4678.96 226.754
|
||||
59.55 4566.62 227.389
|
||||
61.01 4562.25 228.07
|
||||
62.59 4651.86 228.689
|
||||
64.15 4739.16 229.155
|
||||
65.37 4696.82 229.674
|
||||
66.65 4753.02 230.301
|
||||
67.87 4693.76 230.903
|
||||
68.86 4615.89 231.395
|
||||
69.72 4634.88 231.906
|
||||
70.66 4612.08 232.498
|
||||
71.44 4618.26 233.074
|
||||
72.08 4662.97 233.546
|
||||
72.83 4763.57 234.028
|
||||
73.48 4849 234.603
|
||||
74.19 4939.23 235.153
|
||||
75.02 5053.56 235.605
|
||||
75.58 5132.87 236.082
|
||||
76.25 5170.34 236.657
|
||||
76.81 5203.68 237.232
|
||||
77.63 5257.26 237.673
|
||||
78.25 5283.73 238.176
|
||||
78.76 5359.6 238.789
|
||||
79.45 5393.57 239.387
|
||||
79.81 5460.83 239.861
|
||||
80.22 5466.95 240.368
|
||||
80.84 5496.29 240.962
|
||||
81.45 5526.77 241.539
|
||||
82.09 5561.8 242.009
|
||||
82.68 5618 242.52
|
||||
83.33 5667.39 243.12
|
||||
84.09 5750.57 243.721
|
||||
84.67 5785.29 244.208
|
||||
85.56 5844.05 244.716
|
||||
86.66 5878.7 245.354
|
||||
87.44 5952.83 245.966
|
||||
88.45 6010.96 246.46
|
||||
89.39 6055.61 247.017
|
||||
90.13 6087.96 247.698
|
||||
90.88 6093.51 248.374
|
||||
92 6152.59 248.928
|
||||
93.18 6171.57 249.564
|
||||
94.14 6142.1 250.299
|
||||
95.11 6078.96 251.031
|
||||
96.27 6047.49 251.65
|
||||
97 6074.66 252.295
|
||||
97.7 6090.14 253.033
|
||||
98.31 6105.25 253.743
|
||||
99.13 6175.69 254.338
|
||||
99.79 6214.22 255.032
|
||||
100.17 6260.74 255.815
|
||||
100.88 6327.12 256.543
|
||||
101.84 6327.93 257.151
|
||||
102.35 6359.9 257.785
|
||||
102.83 6393.5 258.516
|
||||
103.51 6476.86 259.191
|
||||
104.13 6524.5 259.738
|
||||
104.71 6600.31 260.351
|
||||
105.39 6629.47 261.04
|
||||
106.09 6688.61 261.692
|
||||
106.75 6717.46 262.236
|
||||
107.24 6724.2 262.847
|
||||
107.75 6779.53 263.527
|
||||
108.29 6825.8 264.169
|
||||
108.91 6882 264.681
|
||||
109.24 6983.91 265.258
|
||||
109.74 7020 265.887
|
||||
110.23 7093.12 266.491
|
||||
111 7166.68 266.987
|
||||
111.43 7236.5 267.545
|
||||
111.76 7311.24 268.171
|
||||
112.08 7364.63 268.815];
|
||||
|
||||
%Compute growth rates: from 1950:I to 1997:IV
|
||||
gy_obs=1000*data_q(:,2)./data_q(:,3); %real GDP per capita
|
||||
gy_obs=diff(log(gy_obs));
|
||||
|
||||
gp_obs = diff(log(data_q(:,1))); %GDP deflator inflation
|
|
@ -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)
|
142
license.txt
142
license.txt
|
@ -1,6 +1,6 @@
|
|||
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||
Upstream-Name: Dynare
|
||||
Upstream-Contact: Dynare Team, whose members in 2024 are:
|
||||
Upstream-Contact: Dynare Team, whose members in 2023 are:
|
||||
- Stéphane Adjemian <stephane.adjemian@univ-lemans.fr>
|
||||
- Michel Juillard <michel.juillard@mjui.fr>
|
||||
- Frédéric Karamé <frederic.karame@univ-lemans.fr>
|
||||
|
@ -23,7 +23,7 @@ Upstream-Contact: Dynare Team, whose members in 2024 are:
|
|||
Source: https://www.dynare.org
|
||||
|
||||
Files: *
|
||||
Copyright: 1996-2024 Dynare Team
|
||||
Copyright: 1996-2023 Dynare Team
|
||||
License: GPL-3+
|
||||
|
||||
Files: matlab/+occbin/IVF_core.m
|
||||
|
@ -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
|
||||
|
@ -113,7 +113,7 @@ Copyright: 1995 E.G.Tsionas
|
|||
2015-2017 Dynare Team
|
||||
License: GPL-3+
|
||||
|
||||
Files: matlab/estimation/endogenous_prior.m
|
||||
Files: matlab/endogenous_prior.m
|
||||
Copyright: 2011 Lawrence J. Christiano, Mathias Trabandt and Karl Walentin
|
||||
2013-2017 Dynare Team
|
||||
License: GPL-3+
|
||||
|
@ -123,17 +123,12 @@ 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
|
||||
License: GPL-3+
|
||||
|
||||
Files: matlab/+pruned_SS/commutation.m matlab/+pruned_SS/duplication.m
|
||||
Files: matlab/commutation.m matlab/duplication.m
|
||||
Copyright: 1997 Tom Minka <minka@microsoft.com>
|
||||
2019-2020 Dynare Team
|
||||
License: GPL-3+
|
||||
|
@ -146,7 +141,7 @@ Comment: The original author gave authorization to change
|
|||
the license from BSD-2-clause to GPL-3+ and redistribute
|
||||
it under GPL-3+ with Dynare.
|
||||
|
||||
Files: matlab/+pruned_SS/uperm.m
|
||||
Files: matlab/uperm.m
|
||||
Copyright: 2014 Bruno Luong <brunoluong@yahoo.com>
|
||||
2020 Dynare Team
|
||||
License: GPL-3+
|
||||
|
@ -154,9 +149,9 @@ Comment: The original author gave authorization to change
|
|||
the license from BSD-2-clause to GPL-3+ and redistribute
|
||||
it under GPL-3+ with Dynare.
|
||||
|
||||
Files: matlab/+pruned_SS/prodmom.m matlab/+pruned_SS/bivmom.m
|
||||
Files: matlab/prodmom.m matlab/bivmom.m
|
||||
Copyright: 2008-2015 Raymond Kan <kan@chass.utoronto.ca>
|
||||
2019-2023 Dynare Team
|
||||
2019-2020 Dynare Team
|
||||
License: GPL-3+
|
||||
Comment: The author gave authorization to redistribute
|
||||
these functions under GPL-3+ with Dynare and would
|
||||
|
@ -166,37 +161,57 @@ Comment: The author gave authorization to redistribute
|
|||
Journal of Multivariate Analysis, 2008, vol. 99, issue 3,
|
||||
pages 542-554.
|
||||
|
||||
Files: matlab/+gsa/Morris_Measure_Groups.m
|
||||
matlab/+gsa/Sampling_Function_2.m
|
||||
Files: matlab/gsa/Morris_Measure_Groups.m
|
||||
matlab/gsa/Sampling_Function_2.m
|
||||
Copyright: 2005 European Commission
|
||||
2012-2013 Dynare Team
|
||||
2012-2017 Dynare Team
|
||||
License: GPL-3+
|
||||
Comment: Written by Jessica Cariboni and Francesca Campolongo
|
||||
Joint Research Centre, The European Commission,
|
||||
|
||||
Files: matlab/+gsa/cumplot.m
|
||||
matlab/+gsa/monte_carlo_filtering.m
|
||||
matlab/+gsa/skewness.m
|
||||
matlab/+gsa/log_transform.m
|
||||
matlab/+gsa/map_calibration.m
|
||||
matlab/+gsa/map_identification.m
|
||||
matlab/+gsa/monte_carlo_filtering_analysis.m
|
||||
matlab/+gsa/boxplot.m
|
||||
matlab/+gsa/prior_draw.m
|
||||
matlab/+gsa/reduced_form_mapping.m
|
||||
matlab/+gsa/reduced_form_screening.m
|
||||
matlab/+gsa/scatter_mcf.m
|
||||
matlab/+gsa/smirnov_test.m
|
||||
matlab/+gsa/stability_mapping.m
|
||||
matlab/+gsa/stability_mapping_univariate.m
|
||||
matlab/+gsa/stability_mapping_bivariate.m
|
||||
matlab/+gsa/standardize_columns.m
|
||||
matlab/+gsa/tcrit.m
|
||||
matlab/+gsa/teff.m
|
||||
Files: matlab/gsa/cumplot.m
|
||||
matlab/gsa/filt_mc_.m
|
||||
matlab/gsa/gsa_plotmatrix.m
|
||||
matlab/gsa/gsa_skewness.m
|
||||
matlab/gsa/gsa_speed.m
|
||||
matlab/gsa/log_trans_.m
|
||||
matlab/gsa/map_calibration.m
|
||||
matlab/gsa/map_ident_.m
|
||||
matlab/gsa/mcf_analysis.m
|
||||
matlab/gsa/myboxplot.m
|
||||
matlab/gsa/myprctilecol.m
|
||||
matlab/gsa/prior_draw_gsa.m
|
||||
matlab/gsa/read_data.m
|
||||
matlab/gsa/redform_map.m
|
||||
matlab/gsa/redform_screen.m
|
||||
matlab/gsa/scatter_mcf.m
|
||||
matlab/gsa/smirnov.m
|
||||
matlab/gsa/stab_map_.m
|
||||
matlab/gsa/stab_map_1.m
|
||||
matlab/gsa/stab_map_2.m
|
||||
matlab/gsa/stand_.m
|
||||
matlab/gsa/tcrit.m
|
||||
matlab/gsa/teff.m
|
||||
matlab/gsa/trank.m
|
||||
Copyright: 2011-2018 European Commission
|
||||
2011-2023 Dynare Team
|
||||
2011-2018 Dynare Team
|
||||
License: GPL-3+
|
||||
|
||||
Files: matlab/gsa/pick.m
|
||||
Copyright: none
|
||||
License: public-domain-jrc
|
||||
This software has been developed at the Joint Research Centre of European Commission
|
||||
by officers in the course of their official duties. This software is not subject to copyright
|
||||
protection and is in the public domain. It is an experimental system. The Joint Research Centre
|
||||
of European Commission assumes no responsibility whatsoever for its use by other parties
|
||||
and makes no guarantees, expressed or implied, about its quality, reliability, or any other
|
||||
characteristic. We would appreciate acknowledgement if the software is used.
|
||||
Comment: This file is part of GLUEWIN.
|
||||
The program has been developed by M. Ratto, European Commission, Joint Research Centre,
|
||||
Institute for the Protection and Security of The Citizen, Technological and Economic Risk Management,
|
||||
Applied Statistics, as a deliverable of the IMPACT project
|
||||
(EC Fifth Framework Programme, SCA Project, IST-1999-11313, DG-INFSO).
|
||||
|
||||
Files: matlab/optimization/simpsa.m matlab/optimization/simpsaget.m matlab/optimization/simpsaset.m
|
||||
Copyright: 2005 Henning Schmidt, FCC, henning@fcc.chalmers.se
|
||||
2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be
|
||||
|
@ -247,14 +262,9 @@ License: BSD-2-clause
|
|||
|
||||
Files: matlab/utilities/graphics/colorspace.m
|
||||
Copyright: 2005-2010 Pascal Getreuer
|
||||
2017-2023 Dynare Team
|
||||
2017 Dynare Team
|
||||
License: BSD-2-clause
|
||||
|
||||
Files: examples/fs2000_data.m
|
||||
Copyright: 2000-2022 Frank Schorfheide
|
||||
2023 Dynare Team
|
||||
License: CC-BY-SA-4.0
|
||||
|
||||
Files: doc/*.rst doc/*.tex doc/*.svg doc/*.pdf doc/*.bib
|
||||
Copyright: 1996-2022 Dynare Team
|
||||
License: GFDL-NIV-1.3+
|
||||
|
@ -297,6 +307,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 +435,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
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
#!/usr/bin/env bash
|
||||
|
||||
# Copyright © 2019-2024 Dynare Team
|
||||
# Copyright © 2019-2023 Dynare Team
|
||||
#
|
||||
# This file is part of Dynare.
|
||||
#
|
||||
|
@ -37,6 +37,8 @@ else
|
|||
# Remove /opt/homebrew/bin from PATH, so it does not intervene with the x86_64 compilations
|
||||
path_remove PATH /opt/homebrew/bin
|
||||
MATLAB_ARCH=maci64
|
||||
# On x86_64 we need to differentiate between older and newer MATLAB versions
|
||||
OLD_MATLAB_PATH=/Applications/"$PKG_ARCH"/MATLAB_R2016b.app
|
||||
fi
|
||||
MATLAB_PATH=/Applications/"$PKG_ARCH"/MATLAB_R2023b.app
|
||||
|
||||
|
@ -54,7 +56,7 @@ LIB64="$ROOTDIR"/macOS/deps/"$PKG_ARCH"/lib64
|
|||
## - the macOS linker is different from GNU ld and does not have the equivalent of -Bstatic/-Bdynamic
|
||||
## - libgfortran.spec does not include --as-needed on macOS, hence it will link the library anyways
|
||||
## Also, it does not seem possible to override libgfortran.spec with the --specs option.
|
||||
GCC_VERSION=$(sed -En "/^c[[:space:]]*=/s/c[[:space:]]*=[[:space:]]*'.*gcc-([0-9]+)'/\1/p" "$ROOTDIR"/macOS/homebrew-native-"$PKG_ARCH".ini)
|
||||
GCC_VERSION=$(sed -En "/^c[[:space:]]*=/s/c[[:space:]]*=[[:space:]]*'.*gcc-([0-9]+)'/\1/p" "$ROOTDIR"/scripts/homebrew-native-"$PKG_ARCH".ini)
|
||||
|
||||
QUADMATH_DIR=$(mktemp -d)
|
||||
ln -s "$BREWDIR"/opt/gcc/lib/gcc/"$GCC_VERSION"/libquadmath.a "$QUADMATH_DIR"
|
||||
|
@ -67,12 +69,18 @@ cd "$ROOTDIR"
|
|||
# NB: the addition of -Wl,-ld_classic is a workaround for https://github.com/mesonbuild/meson/issues/12282 (see also the native file)
|
||||
common_meson_opts=(-Dbuild_for=matlab -Dbuildtype=release -Dprefer_static=true -Dfortran_args="[ '-B', '$LIB64/Slicot/' ]" \
|
||||
-Dc_link_args="[ '-Wl,-ld_classic', '-L$QUADMATH_DIR' ]" -Dcpp_link_args="[ '-Wl,-ld_classic', '-L$QUADMATH_DIR' ]" -Dfortran_link_args="[ '-Wl,-ld_classic', '-L$QUADMATH_DIR' ]" \
|
||||
--native-file macOS/homebrew-native-$PKG_ARCH.ini)
|
||||
--native-file scripts/homebrew-native-$PKG_ARCH.ini)
|
||||
|
||||
# Build for MATLAB ⩾ R2018b (x86_64) and MATLAB ⩾ R2023b (arm64)
|
||||
# Build for MATLAB ⩾ R2018a (x86_64) and MATLAB ⩾ R2023b (arm64)
|
||||
arch -"$PKG_ARCH" meson setup "${common_meson_opts[@]}" -Dmatlab_path="$MATLAB_PATH" build-matlab --wipe
|
||||
arch -"$PKG_ARCH" meson compile -v -C build-matlab
|
||||
|
||||
if [[ "$PKG_ARCH" == x86_64 ]]; then
|
||||
# Build for MATLAB < R2018a
|
||||
arch -"$PKG_ARCH" meson setup "${common_meson_opts[@]}" -Dmatlab_path="$OLD_MATLAB_PATH" build-old-matlab --wipe
|
||||
arch -"$PKG_ARCH" meson compile -v -C build-old-matlab
|
||||
fi
|
||||
|
||||
# If not in CI, build the docs
|
||||
if [[ -z $CI ]]; then
|
||||
arch -"$PKG_ARCH" meson compile -v -C build-matlab doc
|
||||
|
@ -117,7 +125,8 @@ mkdir -p \
|
|||
"$PKGFILES"/scripts \
|
||||
"$PKGFILES"/contrib/ms-sbvar/TZcode
|
||||
if [[ "$PKG_ARCH" == x86_64 ]]; then
|
||||
mkdir -p "$PKGFILES"/mex/matlab/"$MATLAB_ARCH"-9.5-23.2
|
||||
mkdir -p "$PKGFILES"/mex/matlab/"$MATLAB_ARCH"-8.3-9.3 \
|
||||
"$PKGFILES"/mex/matlab/"$MATLAB_ARCH"-9.4-23.2
|
||||
else
|
||||
mkdir -p "$PKGFILES"/mex/matlab/"$MATLAB_ARCH"-23.2
|
||||
fi
|
||||
|
@ -138,20 +147,22 @@ mkdir -p "$PKGFILES"
|
|||
ln -sf ../../preprocessor/dynare-preprocessor "$PKGFILES"/matlab/preprocessor64/dynare_m
|
||||
|
||||
if [[ "$PKG_ARCH" == x86_64 ]]; then
|
||||
cp -L "$ROOTDIR"/build-matlab/*.mex"$MATLAB_ARCH" "$PKGFILES"/mex/matlab/"$MATLAB_ARCH"-9.5-23.2
|
||||
cp -L "$ROOTDIR"/build-matlab/*.mex"$MATLAB_ARCH" "$PKGFILES"/mex/matlab/"$MATLAB_ARCH"-9.4-23.2
|
||||
cp -L "$ROOTDIR"/build-old-matlab/*.mex"$MATLAB_ARCH" "$PKGFILES"/mex/matlab/"$MATLAB_ARCH"-8.3-9.3
|
||||
else
|
||||
cp -L "$ROOTDIR"/build-matlab/*.mex"$MATLAB_ARCH" "$PKGFILES"/mex/matlab/"$MATLAB_ARCH"-23.2
|
||||
fi
|
||||
|
||||
cp -p "$ROOTDIR"/scripts/dynare.el "$PKGFILES"/scripts
|
||||
cp -pr "$ROOTDIR"/contrib/ms-sbvar/TZcode/MatlabFiles "$PKGFILES"/contrib/ms-sbvar/TZcode
|
||||
cp -pr "$ROOTDIR"/contrib/jsonlab "$PKGFILES"/contrib
|
||||
|
||||
cp "$ROOTDIR"/build-doc/*.pdf "$PKGFILES"/doc
|
||||
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
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# Copyright © 2019-2024 Dynare Team
|
||||
# Copyright © 2019-2023 Dynare Team
|
||||
#
|
||||
# This file is part of Dynare.
|
||||
#
|
||||
|
@ -22,7 +22,7 @@ DEPS_ARCH ?= x86_64 # use x86_64 by default
|
|||
|
||||
BREWDIR := $(if $(filter arm64,$(DEPS_ARCH)),/opt/homebrew,/usr/local)
|
||||
|
||||
GCC_VERSION = $(shell sed -En "/^c[[:space:]]*=/s/c[[:space:]]*=[[:space:]]*'.*gcc-([0-9]+)'/\1/p" ../homebrew-native-$(DEPS_ARCH).ini)
|
||||
GCC_VERSION = $(shell sed -En "/^c[[:space:]]*=/s/c[[:space:]]*=[[:space:]]*'.*gcc-([0-9]+)'/\1/p" ../../scripts/homebrew-native-$(DEPS_ARCH).ini)
|
||||
|
||||
ROOT_PATH = $(realpath .)
|
||||
|
||||
|
@ -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 $@
|
||||
|
|
|
@ -1,2 +1,2 @@
|
|||
SLICOT_VERSION = 5.9~20240205.gita037f7e
|
||||
SLICOT_VERSION = 5.0+20101122
|
||||
X13AS_VERSION = 1-1-b60
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
_mexFunction
|
|
@ -34,7 +34,7 @@ global oo_
|
|||
oo_.bvar.log_marginal_data_density=NaN(maxnlags,1);
|
||||
|
||||
for nlags = 1:maxnlags
|
||||
[ny, ~, posterior, prior] = bvar.toolbox(nlags);
|
||||
[ny, nx, posterior, prior] = bvar.toolbox(nlags);
|
||||
oo_.bvar.posterior{nlags}=posterior;
|
||||
oo_.bvar.prior{nlags}=prior;
|
||||
|
||||
|
@ -75,8 +75,8 @@ function w = matrictint(S, df, XXi)
|
|||
|
||||
k=size(XXi,1);
|
||||
ny=size(S,1);
|
||||
[cx,p] = chol(XXi); %second output required to prevent error
|
||||
[cs,p] = chol(S); %second output required to prevent error
|
||||
[cx,p]=chol(XXi);
|
||||
[cs,q]=chol(S);
|
||||
|
||||
if any(diag(cx)<100*eps)
|
||||
error('singular XXi')
|
||||
|
|
|
@ -33,7 +33,7 @@ global options_ oo_ M_
|
|||
if options_.forecast == 0
|
||||
error('bvar.forecast: you must specify "forecast" option')
|
||||
end
|
||||
[ny, nx, posterior, ~, forecast_data] = bvar.toolbox(nlags);
|
||||
[ny, nx, posterior, prior, forecast_data] = bvar.toolbox(nlags);
|
||||
|
||||
sims_no_shock = NaN(options_.forecast, ny, options_.bvar_replic);
|
||||
sims_with_shocks = NaN(options_.forecast, ny, options_.bvar_replic);
|
||||
|
@ -95,7 +95,7 @@ end
|
|||
|
||||
if p > 0
|
||||
skipline()
|
||||
disp('Some of the VAR models sampled from the posterior distribution')
|
||||
disp(['Some of the VAR models sampled from the posterior distribution'])
|
||||
disp(['were found to be explosive (' num2str(p/options_.bvar_replic) ' percent).'])
|
||||
skipline()
|
||||
end
|
||||
|
@ -119,7 +119,7 @@ OutputDirectoryName = CheckPath('graphs',M_.dname);
|
|||
dyn_graph=bvar.graph_init(sprintf('BVAR forecasts (nlags = %d)', nlags), ny, {'b-' 'g-' 'g-' 'r-' 'r-'});
|
||||
|
||||
for i = 1:ny
|
||||
dyn_graph=plot_graph(dyn_graph,[ sims_no_shock_median(:, i) ...
|
||||
dyn_graph=dynare_graph(dyn_graph,[ sims_no_shock_median(:, i) ...
|
||||
sims_no_shock_up_conf(:, i) sims_no_shock_down_conf(:, i) ...
|
||||
sims_with_shocks_up_conf(:, i) sims_with_shocks_down_conf(:, i) ], ...
|
||||
options_.varobs{i});
|
||||
|
@ -154,8 +154,8 @@ end
|
|||
% Store results
|
||||
|
||||
DirectoryName = [ M_.dname '/bvar_forecast' ];
|
||||
if ~isfolder(DirectoryName)
|
||||
if ~isfolder(M_.dname)
|
||||
if ~isdir(DirectoryName)
|
||||
if ~isdir(M_.dname)
|
||||
mkdir(M_.dname);
|
||||
end
|
||||
mkdir(DirectoryName);
|
||||
|
@ -183,31 +183,3 @@ for i = 1:length(options_.varobs)
|
|||
oo_.bvar.forecast.rmse.(name) = rmse(i);
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
function dyn_graph=plot_graph(dyn_graph,y,tit,x)
|
||||
% function plot_graph(dyn_graph, y,tit,x)
|
||||
|
||||
if nargin < 4
|
||||
x = (1:size(y,1))';
|
||||
end
|
||||
nplot = dyn_graph.plot_nbr + 1;
|
||||
if nplot > dyn_graph.max_nplot
|
||||
figure('Name',dyn_graph.figure_name);
|
||||
nplot = 1;
|
||||
end
|
||||
dyn_graph.plot_nbr = nplot;
|
||||
subplot(dyn_graph.nr,dyn_graph.nc,nplot);
|
||||
|
||||
line_types = dyn_graph.line_types;
|
||||
line_type = line_types{1};
|
||||
for i=1:size(y,2)
|
||||
if length(line_types) > 1
|
||||
line_type = line_types{i};
|
||||
end
|
||||
|
||||
plot(x,y(:,i),line_type);
|
||||
hold on
|
||||
end
|
||||
title(tit);
|
||||
hold off
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
function dyn_graph=graph_init(figure_name,nplot,line_types,line_width)
|
||||
% function graph_init(figure_name,colors)
|
||||
function dyn_graph=dynare_graph_init(figure_name,nplot,line_types,line_width)
|
||||
% function dynare_graph_init(figure_name,colors)
|
||||
% initializes set of graphs
|
||||
%
|
||||
% INPUTS:
|
||||
|
@ -12,7 +12,7 @@ function dyn_graph=graph_init(figure_name,nplot,line_types,line_width)
|
|||
% SPECIAL REQUIREMENT
|
||||
% none
|
||||
|
||||
% Copyright © 2006-2023 Dynare Team
|
||||
% Copyright © 2006-2017 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
%
|
||||
|
|
|
@ -35,7 +35,7 @@ if nargin==1
|
|||
identification = 'Cholesky';
|
||||
end
|
||||
|
||||
[ny, nx, posterior] = bvar.toolbox(nlags);
|
||||
[ny, nx, posterior, prior] = bvar.toolbox(nlags);
|
||||
|
||||
S_inv_upper_chol = chol(inv(posterior.S));
|
||||
|
||||
|
@ -96,7 +96,7 @@ end
|
|||
|
||||
if p > 0
|
||||
skipline()
|
||||
disp('Some of the VAR models sampled from the posterior distribution')
|
||||
disp(['Some of the VAR models sampled from the posterior distribution'])
|
||||
disp(['were found to be explosive (' int2str(p) ' samples).'])
|
||||
skipline()
|
||||
end
|
||||
|
@ -130,7 +130,7 @@ end
|
|||
|
||||
% Save intermediate results
|
||||
DirectoryName = [ M_.dname '/bvar_irf' ];
|
||||
if ~isfolder(DirectoryName)
|
||||
if ~isdir(DirectoryName)
|
||||
mkdir('.',DirectoryName);
|
||||
end
|
||||
save([ DirectoryName '/simulations.mat'], 'sampled_irfs');
|
||||
|
@ -146,4 +146,4 @@ for i=1:ny
|
|||
oo_.bvar.irf.Upper_bound.(variable_name).(shock_name) = posterior_up_conf_irfs(j,i,:);
|
||||
oo_.bvar.irf.Lower_bound.(variable_name).(shock_name) = posterior_down_conf_irfs(j,i,:);
|
||||
end
|
||||
end
|
||||
end
|
|
@ -1,5 +1,5 @@
|
|||
function [ny, nx, posterior, prior, forecast_data] = toolbox(nlags)
|
||||
%function [ny, nx, posterior, prior, forecast_data] = toolbox(nlags)
|
||||
function [ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags)
|
||||
%function [ny, nx, posterior, prior, forecast_data] = bvar_toolbox(nlags)
|
||||
% bvar_toolbox Routines shared between BVAR methods
|
||||
% Computes several things for the estimations of a BVAR(nlags)
|
||||
%
|
||||
|
@ -42,7 +42,7 @@ function [ny, nx, posterior, prior, forecast_data] = toolbox(nlags)
|
|||
% - bvar_prior_{tau,decay,lambda,mu,omega,flat,train}
|
||||
|
||||
% Copyright © 2003-2007 Christopher Sims
|
||||
% Copyright © 2007-2023 Dynare Team
|
||||
% Copyright © 2007-2017 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
%
|
||||
|
|
|
@ -28,7 +28,7 @@ function nls(eqname, params, data, range, optimizer, varargin)
|
|||
% equation must have NaN values in the object.
|
||||
% [4] It is assumed that the residual is additive.
|
||||
|
||||
% Copyright © 2021-2023 Dynare Team
|
||||
% Copyright © 2021-2022 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
%
|
||||
|
@ -179,6 +179,12 @@ write_residuals_routine(lhs, rhs, eqname, ipnames_, M_);
|
|||
% Create a routine for evaluating the sum of squared residuals of the nonlinear model
|
||||
write_ssr_routine(lhs, rhs, eqname, ipnames_, M_);
|
||||
|
||||
% Workaround for Octave bug https://savannah.gnu.org/bugs/?46282
|
||||
% Octave will randomly fail to read the ssr_* file generated in the +folder
|
||||
if isoctave && octave_ver_less_than('7')
|
||||
path(path)
|
||||
end
|
||||
|
||||
% Create a function handle returning the sum of square residuals for a given vector of parameters.
|
||||
ssrfun = @(p) feval([M_.fname '.ssr_' eqname], p, DATA, M_, oo_);
|
||||
|
||||
|
@ -292,23 +298,23 @@ end
|
|||
%
|
||||
|
||||
if is_gauss_newton
|
||||
[params1, SSR] = gauss_newton(resfun, params0);
|
||||
[params1, SSR, exitflag] = gauss_newton(resfun, params0);
|
||||
elseif is_lsqnonlin
|
||||
if ismember('levenberg-marquardt', varargin)
|
||||
% Levenberg Marquardt does not handle boundary constraints.
|
||||
[params1, SSR] = lsqnonlin(resfun, params0, [], [], optimset(varargin{:}));
|
||||
[params1, SSR, ~, exitflag] = lsqnonlin(resfun, params0, [], [], optimset(varargin{:}));
|
||||
else
|
||||
[params1, SSR] = lsqnonlin(resfun, params0, bounds(:,1), bounds(:,2), optimset(varargin{:}));
|
||||
[params1, SSR, ~, exitflag] = lsqnonlin(resfun, params0, bounds(:,1), bounds(:,2), optimset(varargin{:}));
|
||||
end
|
||||
else
|
||||
% Estimate the parameters by minimizing the sum of squared residuals.
|
||||
[params1, SSR] = dynare_minimize_objective(ssrfun, params0, ...
|
||||
minalgo, ...
|
||||
options_, ...
|
||||
bounds, ...
|
||||
parameter_names, ...
|
||||
[], ...
|
||||
[]);
|
||||
[params1, SSR, exitflag] = dynare_minimize_objective(ssrfun, params0, ...
|
||||
minalgo, ...
|
||||
options_, ...
|
||||
bounds, ...
|
||||
parameter_names, ...
|
||||
[], ...
|
||||
[]);
|
||||
end
|
||||
|
||||
% Revert local modifications to the options.
|
||||
|
|
|
@ -1,305 +0,0 @@
|
|||
function map_identification(OutputDirectoryName,opt_gsa,M_,oo_,options_,estim_params_,bayestopt_)
|
||||
% map_identification(OutputDirectoryName,opt_gsa,M_,oo_,options_,estim_params_,bayestopt_)
|
||||
% Inputs
|
||||
% - OutputDirectoryName [string] name of the output directory
|
||||
% - opt_gsa [structure] GSA options structure
|
||||
% - M_ [structure] Matlab's structure describing the model
|
||||
% - oo_ [structure] Matlab's structure describing the results
|
||||
% - options_ [structure] Matlab's structure describing the current options
|
||||
% - estim_params_ [structure] characterizing parameters to be estimated
|
||||
% - bayestopt_ [structure] describing the priors
|
||||
|
||||
% Written by Marco Ratto
|
||||
% Joint Research Centre, The European Commission,
|
||||
% marco.ratto@ec.europa.eu
|
||||
|
||||
% Copyright © 2012-2016 European Commission
|
||||
% Copyright © 2012-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/>.
|
||||
|
||||
fname_ = M_.fname;
|
||||
dr=oo_.dr;
|
||||
nliv = opt_gsa.morris_nliv;
|
||||
itrans = opt_gsa.trans_ident;
|
||||
|
||||
np = size(estim_params_.param_vals,1);
|
||||
|
||||
pnames = M_.param_names(estim_params_.param_vals(:,1));
|
||||
if opt_gsa.pprior
|
||||
filetoload=[OutputDirectoryName '/' fname_ '_prior'];
|
||||
else
|
||||
filetoload=[OutputDirectoryName '/' fname_ '_mc'];
|
||||
end
|
||||
load(filetoload,'lpmat','lpmat0','istable','T','yys')
|
||||
if ~isempty(lpmat0)
|
||||
lpmatx=lpmat0(istable,:);
|
||||
else
|
||||
lpmatx=[];
|
||||
end
|
||||
Nsam = size(lpmat,1);
|
||||
nshock = size(lpmat0,2);
|
||||
npT = np+nshock;
|
||||
|
||||
fname_ = M_.fname;
|
||||
|
||||
if opt_gsa.load_ident_files==0
|
||||
mss = yys(bayestopt_.mfys,:);
|
||||
mss = gsa.teff(mss(:,istable),Nsam,istable);
|
||||
yys = gsa.teff(yys(dr.order_var,istable),Nsam,istable);
|
||||
if exist('T','var')
|
||||
[vdec, cc, ac] = gsa.monte_carlo_moments(T, lpmatx, dr, M_, options_, estim_params_);
|
||||
else
|
||||
return
|
||||
end
|
||||
|
||||
if opt_gsa.morris==2
|
||||
pdraws = identification.run(M_,oo_,options_,bayestopt_,estim_params_,options_.options_ident,[lpmatx lpmat(istable,:)]);
|
||||
if ~isempty(pdraws) && max(max(abs(pdraws-[lpmatx lpmat(istable,:)])))==0
|
||||
disp(['Sample check OK. Largest difference: ', num2str(max(max(abs(pdraws-[lpmatx lpmat(istable,:)]))))]),
|
||||
clear pdraws;
|
||||
end
|
||||
clear GAM gas
|
||||
end
|
||||
if opt_gsa.morris~=1 && M_.exo_nbr>1
|
||||
ifig=0;
|
||||
for j=1:M_.exo_nbr
|
||||
if mod(j,6)==1
|
||||
hh_fig=dyn_figure(options_.nodisplay,'name','Variance decomposition shocks');
|
||||
ifig=ifig+1;
|
||||
iplo=0;
|
||||
end
|
||||
iplo=iplo+1;
|
||||
subplot(2,3,iplo)
|
||||
gsa.boxplot(squeeze(vdec(:,j,:))',[],'.',[],10)
|
||||
set(gca,'xticklabel',' ','fontsize',10,'xtick',1:size(options_.varobs,1))
|
||||
set(gca,'xlim',[0.5 size(options_.varobs,1)+0.5])
|
||||
set(gca,'ylim',[-2 102])
|
||||
for ip=1:size(options_.varobs,1)
|
||||
if options_.TeX
|
||||
text(ip,-4,deblank(opt_gsa.varobs_tex(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','latex')
|
||||
else
|
||||
text(ip,-4,deblank(options_.varobs(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
|
||||
end
|
||||
end
|
||||
xlabel(' ')
|
||||
ylabel(' ')
|
||||
title(M_.exo_names{j},'interpreter','none')
|
||||
if mod(j,6)==0 || j==M_.exo_nbr
|
||||
dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],options_.nodisplay,options_.graph_format);
|
||||
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],ifig,'Variance decomposition shocks','vdec_exo',options_.figures.textwidth*min(iplo/3,1))
|
||||
end
|
||||
end
|
||||
end
|
||||
for j=1:size(cc,1)
|
||||
cc(j,j,:)=gsa.standardize_columns(squeeze(log(cc(j,j,:))))./2;
|
||||
end
|
||||
[vdec, ~, ir_vdec, ic_vdec] = gsa.teff(vdec,Nsam,istable);
|
||||
[cc, ~, ir_cc, ic_cc] = gsa.teff(cc,Nsam,istable);
|
||||
[ac, ~, ir_ac, ic_ac] = gsa.teff(ac,Nsam,istable);
|
||||
|
||||
nc1= size(T,2);
|
||||
endo_nbr = M_.endo_nbr;
|
||||
nstatic = M_.nstatic;
|
||||
nspred = M_.nspred;
|
||||
iv = (1:endo_nbr)';
|
||||
ic = [ nstatic+(1:nspred) endo_nbr+(1:size(dr.ghx,2)-nspred) ]';
|
||||
|
||||
dr.ghx = T(:, 1:(nc1-M_.exo_nbr),1);
|
||||
dr.ghu = T(:, (nc1-M_.exo_nbr+1):end, 1);
|
||||
[Aa,Bb] = kalman_transition_matrix(dr,iv,ic);
|
||||
A = zeros(size(Aa,1),size(Aa,2)+size(Aa,1),length(istable));
|
||||
if ~isempty(lpmatx)
|
||||
M_=gsa.set_shocks_param(M_,estim_params_,lpmatx(1,:));
|
||||
end
|
||||
A(:,:,1)=[Aa, triu(Bb*M_.Sigma_e*Bb')];
|
||||
for j=2:length(istable)
|
||||
dr.ghx = T(:, 1:(nc1-M_.exo_nbr),j);
|
||||
dr.ghu = T(:, (nc1-M_.exo_nbr+1):end, j);
|
||||
[Aa,Bb] = kalman_transition_matrix(dr, iv, ic);
|
||||
if ~isempty(lpmatx)
|
||||
M_=gsa.set_shocks_param(M_,estim_params_,lpmatx(j,:));
|
||||
end
|
||||
A(:,:,j)=[Aa, triu(Bb*M_.Sigma_e*Bb')];
|
||||
end
|
||||
clear T
|
||||
clear lpmatx
|
||||
|
||||
[yt, j0]=gsa.teff(A,Nsam,istable);
|
||||
yt = [yys yt];
|
||||
if opt_gsa.morris==2
|
||||
clear TAU A
|
||||
else
|
||||
clear A
|
||||
end
|
||||
save([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss')
|
||||
else %load identification files
|
||||
load([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss')
|
||||
end
|
||||
|
||||
if opt_gsa.morris==1
|
||||
if ~isempty(vdec)
|
||||
if opt_gsa.load_ident_files==0
|
||||
SAMorris=NaN(npT,3,size(vdec,2));
|
||||
for i=1:size(vdec,2)
|
||||
[~, SAMorris(:,:,i)] = gsa.Morris_Measure_Groups(npT, [lpmat0 lpmat], vdec(:,i),nliv);
|
||||
end
|
||||
SAvdec = squeeze(SAMorris(:,1,:))';
|
||||
save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAvdec','vdec','ir_vdec','ic_vdec')
|
||||
else
|
||||
load([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAvdec')
|
||||
end
|
||||
|
||||
hh_fig = dyn_figure(options_.nodisplay,'name','Screening identification: variance decomposition');
|
||||
gsa.boxplot(SAvdec,[],'.',[],10)
|
||||
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
|
||||
if options_.TeX
|
||||
[~, param_name_tex_temp]= get_the_name(ip,options_.TeX,M_,estim_params_,options_.varobs);
|
||||
text(ip,-2,param_name_tex_temp,'rotation',90,'HorizontalAlignment','right','interpreter','latex')
|
||||
else
|
||||
text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
|
||||
end
|
||||
end
|
||||
xlabel(' ')
|
||||
title('Elementary effects variance decomposition')
|
||||
dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_morris_vdec'],options_.nodisplay,options_.graph_format);
|
||||
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_vdec'],1,'Screening identification: variance decomposition','morris_vdec',1)
|
||||
else
|
||||
save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'vdec')
|
||||
end
|
||||
|
||||
if opt_gsa.load_ident_files==0
|
||||
ccac = [mss cc ac];
|
||||
SAMorris=NaN(npT,3,size(ccac,2));
|
||||
for i=1:size(ccac,2)
|
||||
[~, SAMorris(:,:,i)] = gsa.Morris_Measure_Groups(npT, [lpmat0 lpmat], [ccac(:,i)],nliv);
|
||||
end
|
||||
SAcc = squeeze(SAMorris(:,1,:))';
|
||||
SAcc = SAcc./(max(SAcc,[],2)*ones(1,npT));
|
||||
save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAcc','cc','ir_cc','ic_cc','-append')
|
||||
save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'ac','ir_ac','ic_ac','-append')
|
||||
else
|
||||
load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAcc','cc','ir_cc','ic_cc')
|
||||
load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'ac','ir_ac','ic_ac')
|
||||
end
|
||||
|
||||
hh_fig=dyn_figure(options_.nodisplay,'name','Screening identification: theoretical moments');
|
||||
gsa.boxplot(SAcc,[],'.',[],10)
|
||||
set(gca,'xticklabel',' ','fontsize',10,'xtick',1:npT)
|
||||
set(gca,'xlim',[0.5 npT+0.5])
|
||||
set(gca,'ylim',[0 1])
|
||||
set(gca,'position',[0.13 0.2 0.775 0.7])
|
||||
for ip=1:npT
|
||||
if options_.TeX
|
||||
[~, param_name_tex_temp]= get_the_name(ip,options_.TeX,M_,estim_params_,options_.varobs);
|
||||
text(ip,-0.02,param_name_tex_temp,'rotation',90,'HorizontalAlignment','right','interpreter','latex')
|
||||
else
|
||||
text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
|
||||
end
|
||||
end
|
||||
xlabel(' ')
|
||||
title('Elementary effects in the moments')
|
||||
dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_morris_moments'],options_.nodisplay,options_.graph_format);
|
||||
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_moments'],1,'Screening identification: theoretical moments','morris_moments',1)
|
||||
|
||||
if opt_gsa.load_ident_files==0
|
||||
SAMorris=NaN(npT,3,j0);
|
||||
for j=1:j0
|
||||
[~, SAMorris(:,:,j)] = gsa.Morris_Measure_Groups(npT, [lpmat0 lpmat], yt(:,j),nliv);
|
||||
end
|
||||
|
||||
SAM = squeeze(SAMorris(1:end,1,:));
|
||||
SAnorm=NaN(npT,j0);
|
||||
irex=NaN(j0);
|
||||
for j=1:j0
|
||||
SAnorm(:,j)=SAM(:,j)./max(SAM(:,j));
|
||||
irex(j)=length(find(SAnorm(:,j)>0.01));
|
||||
end
|
||||
|
||||
SAMmu = squeeze(SAMorris(1:end,2,:));
|
||||
SAmunorm=NaN(npT,j0);
|
||||
for j=1:j0
|
||||
SAmunorm(:,j)=SAMmu(:,j)./max(SAM(:,j)); % normalised w.r.t. mu*
|
||||
end
|
||||
SAMsig = squeeze(SAMorris(1:end,3,:));
|
||||
SAsignorm=NaN(npT,j0);
|
||||
for j=1:j0
|
||||
SAsignorm(:,j)=SAMsig(:,j)./max(SAMsig(:,j));
|
||||
end
|
||||
save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAnorm','SAmunorm','SAsignorm','-append')
|
||||
else
|
||||
load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAnorm')
|
||||
end
|
||||
hh_fig=dyn_figure(options_.nodisplay,'name','Screening identification: model');
|
||||
gsa.boxplot(SAnorm',[],'.',[],10)
|
||||
set(gca,'xticklabel',' ','fontsize',10,'xtick',1:npT)
|
||||
set(gca,'xlim',[0.5 npT+0.5])
|
||||
set(gca,'ylim',[0 1])
|
||||
set(gca,'position',[0.13 0.2 0.775 0.7])
|
||||
xlabel(' ')
|
||||
for ip=1:npT
|
||||
if options_.TeX
|
||||
[~, param_name_tex_temp]= get_the_name(ip,options_.TeX,M_,estim_params_,options_.varobs);
|
||||
text(ip,-0.02,param_name_tex_temp,'rotation',90,'HorizontalAlignment','right','interpreter','latex')
|
||||
else
|
||||
text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
|
||||
end
|
||||
end
|
||||
xlabel(' ')
|
||||
title('Elementary effects in the model')
|
||||
dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_morris_par'],options_.nodisplay,options_.graph_format);
|
||||
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_par'],1,'Screening identification: model','morris_par',1)
|
||||
|
||||
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)
|
||||
end
|
||||
|
||||
function []=create_TeX_loader(options_,figpath,ifig_number,caption,label_name,scale_factor)
|
||||
if nargin<6
|
||||
scale_factor=1;
|
||||
end
|
||||
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
|
||||
fidTeX = fopen([figpath '.tex'],'w');
|
||||
fprintf(fidTeX,'%% TeX eps-loader file generated by map_ident_.m (Dynare).\n');
|
||||
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
|
||||
fprintf(fidTeX,'\\begin{figure}[H]\n');
|
||||
fprintf(fidTeX,'\\centering \n');
|
||||
fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s}\n',scale_factor,strrep(figpath,'\','/'));
|
||||
fprintf(fidTeX,'\\caption{%s.}',caption);
|
||||
fprintf(fidTeX,'\\label{Fig:%s:%u}\n',label_name,ifig_number);
|
||||
fprintf(fidTeX,'\\end{figure}\n\n');
|
||||
fprintf(fidTeX,'%% End Of TeX file. \n');
|
||||
fclose(fidTeX);
|
||||
end
|
||||
|
||||
|
||||
function yr = trank(y)
|
||||
% yr is the rank transformation of y
|
||||
yr=NaN(size(y));
|
||||
[nr, nc] = size(y);
|
||||
for j=1:nc
|
||||
[~, is]=sort(y(:,j));
|
||||
yr(is,j)=[1:nr]'./nr;
|
||||
end
|
|
@ -1,60 +0,0 @@
|
|||
function [vdec, cc, ac] = monte_carlo_moments(mm, ss, dr, M_, options_, estim_params_)
|
||||
% [vdec, cc, ac] = monte_carlo_moments(mm, ss, dr, M_, options_,estim_params_)
|
||||
% Conduct Monte Carlo simulation of second moments for GSA
|
||||
% Inputs:
|
||||
% - dr [structure] decision rules
|
||||
% - M_ [structure] model structure
|
||||
% - options_ [structure] Matlab's structure describing the current options
|
||||
% - estim_params_ [structure] characterizing parameters to be estimated
|
||||
%
|
||||
% Outputs:
|
||||
% - vdec [double] variance decomposition matrix
|
||||
% - cc [double] vector of unique elements of cross correlation matrix
|
||||
% - ac [cell] autocorrelation matrix
|
||||
|
||||
|
||||
% Copyright © 2012-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/>.
|
||||
|
||||
[~, nc1, nsam] = size(mm);
|
||||
nobs=length(options_.varobs);
|
||||
disp('monte_carlo_moments: Computing theoretical moments ...')
|
||||
h = dyn_waitbar(0,'Theoretical moments ...');
|
||||
vdec = zeros(nobs,M_.exo_nbr,nsam);
|
||||
cc = zeros(nobs,nobs,nsam);
|
||||
ac = zeros(nobs,nobs*options_.ar,nsam);
|
||||
|
||||
for j=1:nsam
|
||||
dr.ghx = mm(:, 1:(nc1-M_.exo_nbr),j);
|
||||
dr.ghu = mm(:, (nc1-M_.exo_nbr+1):end, j);
|
||||
if ~isempty(ss)
|
||||
M_=gsa.set_shocks_param(M_,estim_params_,ss(j,:));
|
||||
end
|
||||
[vdec(:,:,j), corr, autocorr] = gsa.th_moments(dr,options_,M_);
|
||||
cc(:,:,j)=triu(corr);
|
||||
dum=NaN(nobs,nobs*options_.ar);
|
||||
for i=1:options_.ar
|
||||
dum(:,(i-1)*nobs+1:i*nobs)=autocorr{i};
|
||||
end
|
||||
ac(:,:,j)=dum;
|
||||
if mod(j,3)==0
|
||||
dyn_waitbar(j/nsam,h)
|
||||
end
|
||||
end
|
||||
dyn_waitbar_close(h)
|
||||
skipline()
|
||||
disp('... done !')
|
|
@ -142,11 +142,11 @@ mapkeys = unique(cell2mat([keys(unanticipated_p_shocks) keys(unanticipated_t_sho
|
|||
|
||||
%% Simulation
|
||||
options_.periods = jm.periods;
|
||||
oo_=perfect_foresight_setup(M_, options_, oo_);
|
||||
perfect_foresight_setup;
|
||||
|
||||
% no surprise shocks present
|
||||
if isempty(mapkeys)
|
||||
oo_=perfect_foresight_solver(M_, options_, oo_);
|
||||
perfect_foresight_solver;
|
||||
return
|
||||
end
|
||||
|
||||
|
@ -161,7 +161,7 @@ end
|
|||
if mapkeys(1) ~= 1
|
||||
% if first unanticipated shock is not in period 1
|
||||
% simulate until first unanticipated shock and save
|
||||
oo_=perfect_foresight_solver(M_, options_, oo_);
|
||||
perfect_foresight_solver;
|
||||
yy = [yy oo_.endo_simul(:, 2:mapkeys(1)+1)];
|
||||
end
|
||||
|
||||
|
@ -203,7 +203,7 @@ for i = 1:length(mapkeys)
|
|||
last_period = this_period;
|
||||
assert(rows(oo_.exo_simul) == oo_exo_simul_rows, 'error encountered setting oo_.exo_simul');
|
||||
oo_.endo_simul(:, 1) = yy(:, end);
|
||||
oo_=perfect_foresight_solver(M_, options_, oo_);
|
||||
perfect_foresight_solver;
|
||||
if next_period > 0
|
||||
yy = [yy oo_.endo_simul(:, 2:next_period-this_period+1)];
|
||||
else
|
||||
|
|
|
@ -1,28 +1,22 @@
|
|||
function J_test = Jtest(xparam, objective_function, Q, model_moments, m_data, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
|
||||
% J_test = Jtest(xparam, objective_function, Q, model_moments, m_data, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
|
||||
% -------------------------------------------------------------------------
|
||||
% Computes the J-test statistic and p-value given a GMM/SMM estimation
|
||||
function oo_ = Jtest(xparam, objective_function, Woptflag, oo_, options_mom_, bayestopt_, Bounds, estim_params_, M_, nobs)
|
||||
% function oo_ = Jtest(xparam, objective_function, Woptflag, oo_, options_mom_, bayestopt_, Bounds, estim_params_, M_, nobs)
|
||||
% -------------------------------------------------------------------------
|
||||
% Computes the J-test statistic and p-value for a GMM/SMM estimation
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% xparam: [vector] estimated parameter vector
|
||||
% objective_function: [function handle] objective function
|
||||
% Q: [scalar] value of moments distance criterion
|
||||
% model_moments: [vector] model moments
|
||||
% m_data: [matrix] selected empirical moments at each point in time
|
||||
% data_moments: [vector] empirical moments
|
||||
% weighting_info: [struct] information on weighting matrix
|
||||
% options_mom_: [struct] options
|
||||
% M_: [struct] model information
|
||||
% estim_params_: [struct] estimated parameters
|
||||
% bayestopt_: [struct] info on prior distributions
|
||||
% BoundsInfo: [struct] info bounds on parameters
|
||||
% dr: [struct] reduced form model
|
||||
% endo_steady_state: [vector] steady state of endogenous variables (initval)
|
||||
% exo_steady_state: [vector] steady state of exogenous variables (initval)
|
||||
% exo_det_steady_state: [vector] steady state of deterministic exogenous variables (initval)
|
||||
% xparam: [vector] estimated parameter vector
|
||||
% objective_function: [function handle] objective function
|
||||
% Woptflag: [logical] flag if optimal weighting matrix has already been computed
|
||||
% oo_: [struct] results
|
||||
% options_mom_: [struct] options
|
||||
% bayestopt_: [struct] information on priors
|
||||
% Bounds: [struct] bounds on parameters
|
||||
% estim_params_: [struct] information on estimated parameters
|
||||
% M_: [struct] information on the model
|
||||
% nobs: [scalar] number of observations
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUT
|
||||
% J_test: [struct] results of J test
|
||||
% oo_: [struct] updated results
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
|
@ -30,8 +24,7 @@ function J_test = Jtest(xparam, objective_function, Q, model_moments, m_data, da
|
|||
% This function calls
|
||||
% o mom.objective_function
|
||||
% o mom.optimal_weighting_matrix
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% =========================================================================
|
||||
% Copyright © 2023 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -48,26 +41,27 @@ function J_test = Jtest(xparam, objective_function, Q, model_moments, m_data, da
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
% =========================================================================
|
||||
|
||||
if options_mom_.mom.mom_nbr > length(xparam)
|
||||
% Get optimal weighting matrix for J test, if necessary
|
||||
if ~weighting_info.Woptflag
|
||||
W_opt = mom.optimal_weighting_matrix(m_data, model_moments, options_mom_.mom.bartlett_kernel_lag);
|
||||
weighting_info.Sw = chol(W_opt);
|
||||
fval = feval(objective_function, xparam, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
|
||||
if ~Woptflag
|
||||
W_opt = mom.optimal_weighting_matrix(oo_.mom.m_data, oo_.mom.model_moments, options_mom_.mom.bartlett_kernel_lag);
|
||||
oo_J = oo_;
|
||||
oo_J.mom.Sw = chol(W_opt);
|
||||
fval = feval(objective_function, xparam, Bounds, oo_J, estim_params_, M_, options_mom_);
|
||||
else
|
||||
fval = Q;
|
||||
fval = oo_.mom.Q;
|
||||
end
|
||||
% Compute J statistic
|
||||
if strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
variance_correction_factor = options_mom_.mom.variance_correction_factor;
|
||||
Variance_correction_factor = options_mom_.mom.variance_correction_factor;
|
||||
elseif strcmp(options_mom_.mom.mom_method,'GMM')
|
||||
variance_correction_factor = 1;
|
||||
Variance_correction_factor = 1;
|
||||
end
|
||||
J_test.j_stat = options_mom_.nobs*variance_correction_factor*fval/options_mom_.mom.weighting_matrix_scaling_factor;
|
||||
J_test.degrees_freedom = length(model_moments)-length(xparam);
|
||||
J_test.p_val = 1-chi2cdf(J_test.j_stat, J_test.degrees_freedom);
|
||||
fprintf('\nValue of J-test statistic: %f\n',J_test.j_stat);
|
||||
fprintf('p-value of J-test statistic: %f\n',J_test.p_val);
|
||||
oo_.mom.J_test.j_stat = nobs*Variance_correction_factor*fval/options_mom_.mom.weighting_matrix_scaling_factor;
|
||||
oo_.mom.J_test.degrees_freedom = length(oo_.mom.model_moments)-length(xparam);
|
||||
oo_.mom.J_test.p_val = 1-chi2cdf(oo_.mom.J_test.j_stat, oo_.mom.J_test.degrees_freedom);
|
||||
fprintf('\nValue of J-test statistic: %f\n',oo_.mom.J_test.j_stat);
|
||||
fprintf('p-value of J-test statistic: %f\n',oo_.mom.J_test.p_val);
|
||||
end
|
|
@ -1,57 +0,0 @@
|
|||
function [irf_matching_file_name, irf_matching_file_path] = check_irf_matching_file(irf_matching_file)
|
||||
% [irf_matching_file_name, irf_matching_file_path] = check_irf_matching_file(irf_matching_file)
|
||||
% -------------------------------------------------------------------------
|
||||
% Check if the provided irf_matching_file is a valid MATLAB function with
|
||||
% .m extension and return name, path and extension of the file.
|
||||
% -------------------------------------------------------------------------
|
||||
% INPUTS
|
||||
% - irf_matching_file: [string] user provided name (with possible path and extension)
|
||||
% of the MATLAB function that transforms model IRFs
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUTS
|
||||
% - irf_matching_file_name: [string] name of the MATLAB function (without extension)
|
||||
% - irf_matching_file_path: [string] path to irf_matching_file_name
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% - mom.run
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% Copyright © 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 isempty(irf_matching_file)
|
||||
% no irf_matching_file provided, so no transformations will be done
|
||||
irf_matching_file_name = '';
|
||||
irf_matching_file_path = '';
|
||||
else
|
||||
[irf_matching_file_path, irf_matching_file_name, irf_matching_file_ext] = fileparts(irf_matching_file);
|
||||
% make sure file is a MATLAB function with .m extension
|
||||
if ~strcmp(irf_matching_file_ext,'.m')
|
||||
if strcmp(irf_matching_file_ext,'')
|
||||
irf_matching_file_ext = '.m';
|
||||
else
|
||||
error('method_of_moments: ''irf_matching_file'' needs to point towards a MATLAB function with extension ''.m''!');
|
||||
end
|
||||
end
|
||||
if isempty(irf_matching_file_path)
|
||||
irf_matching_file_path = '.';
|
||||
end
|
||||
if exist([irf_matching_file_path filesep irf_matching_file_name irf_matching_file_ext],'file') ~= 2
|
||||
error('method_of_moments: Could not find a ''irf_matching_file'' called ''%s''!',[irf_matching_file_path filesep irf_matching_file_name irf_matching_file_ext]);
|
||||
end
|
||||
end
|
|
@ -1,33 +1,33 @@
|
|||
function options_mom_ = default_option_mom_values(options_mom_, options_, dname, do_bayesian_estimation)
|
||||
% options_mom_ = default_option_mom_values(options_mom_, options_, dname, do_bayesian_estimation)
|
||||
% -------------------------------------------------------------------------
|
||||
% Returns structure containing the options for method_of_moments command.
|
||||
% Note 1: options_mom_ is local and contains default and user-specified
|
||||
% values for all settings needed for the method of moments estimation.
|
||||
% Some options, though, are set by the preprocessor into options_ and we
|
||||
% copy these over. The idea is to be independent of options_ and have full
|
||||
% control of the estimation instead of possibly having to deal with options
|
||||
% chosen somewhere else in the mod file.
|
||||
% Note 2: we call a "mode" the minimum of the objective function, i.e.
|
||||
% the parameter vector that minimizes the distance between the moments/IRFs
|
||||
% computed from the model and the moments/IRFs computed from the data.
|
||||
% -------------------------------------------------------------------------
|
||||
function options_mom_ = default_option_mom_values(options_mom_, options_, dname, doBayesianEstimation)
|
||||
% function options_mom_ = default_option_mom_values(options_mom_, options_, dname, doBayesianEstimation)
|
||||
|
||||
% Returns structure containing the options for method_of_moments command
|
||||
|
||||
% options_mom_ is local and contains default and user-specified values for
|
||||
% all settings needed for the method of moments estimation. Some options,
|
||||
% though, are set by the preprocessor into options_ and we copy these over.
|
||||
% The idea is to be independent of options_ and have full control of the
|
||||
% estimation instead of possibly having to deal with options chosen somewhere
|
||||
% else in the mod file.
|
||||
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% o options_mom_: [structure] all user-specified settings (from the method_of_moments command)
|
||||
% o options_: [structure] global options
|
||||
% o dname: [string] default name of directory to store results
|
||||
% o do_bayesian_estimation [boolean] indicator whether we do Bayesian estimation
|
||||
% o options_mom_: [structure] information about all (user-specified and updated) settings used in estimation (options_mom_)
|
||||
% o options_: [structure] information on global options
|
||||
% o dname: [string] name of directory to store results
|
||||
% o doBayesianEstimation [boolean] indicator whether we do Bayesian estimation
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUTS
|
||||
% o options_mom_: [structure] all user-specified and updated settings required for method_of_moments estimation
|
||||
% o oo_: [structure] storage for results (oo_)
|
||||
% o options_mom_: [structure] information about all (user-specified and updated) settings used in estimation (options_mom_)
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
% -------------------------------------------------------------------------
|
||||
% This function calls
|
||||
% o set_default_option
|
||||
% o user_has_matlab_license
|
||||
% o user_has_octave_forge_package
|
||||
% o set_default_option
|
||||
% o user_has_matlab_license
|
||||
% o user_has_octave_forge_package
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% Copyright © 2023 Dynare Team
|
||||
|
@ -46,43 +46,34 @@ function options_mom_ = default_option_mom_values(options_mom_, options_, dname,
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
% =========================================================================
|
||||
|
||||
|
||||
mom_method = options_mom_.mom.mom_method; % this is a required option
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% LIMITATIONS
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
if options_.logged_steady_state || options_.loglinear
|
||||
error('method_of_moments: The loglinear option is not supported. Please append the required logged variables as auxiliary equations.');
|
||||
error('method_of_moments: The loglinear option is not supported. Please append the required logged variables as auxiliary equations.')
|
||||
else
|
||||
options_mom_.logged_steady_state = 0;
|
||||
options_mom_.loglinear = false;
|
||||
end
|
||||
if isfield(options_mom_,'hessian') && options_mom_.hessian.use_penalized_objective
|
||||
warning('method_of_moments: The ''use_penalized_objective_for_hessian'' option is not supported yet and will be skipped.');
|
||||
end
|
||||
options_mom_.hessian.use_penalized_objective = false; % penalized objective not yet supported
|
||||
options_mom_.hessian.use_penalized_objective = false; % penalized objective not yet
|
||||
% options related to variable declarations
|
||||
if isfield(options_,'trend_coeffs')
|
||||
error('method_of_moments: %s does not allow for trend in data',mom_method);
|
||||
error('method_of_moments: %s does not allow for trend in data',mom_method)
|
||||
end
|
||||
% options related to endogenous prior restrictions are not supported
|
||||
if ~isempty(options_.endogenous_prior_restrictions.irf) && ~isempty(options_.endogenous_prior_restrictions.moment)
|
||||
warning('method_of_moments: Endogenous prior restrictions are not supported yet and will be skipped.');
|
||||
fprintf('method_of_moments: Endogenous prior restrictions are not supported yet and will be skipped.\n')
|
||||
end
|
||||
options_mom_.endogenous_prior_restrictions.irf = {};
|
||||
options_mom_.endogenous_prior_restrictions.moment = {};
|
||||
if isfield(options_mom_,'bayesian_irf') && options_mom_.bayesian_irf % do we need this at all??
|
||||
warning('method_of_moments: The ''bayesian_irf'' option is not supported yet and will be skipped.');
|
||||
end
|
||||
options_mom_.bayesian_irf = false;
|
||||
if strcmp(mom_method,'IRF_MATCHING')
|
||||
if isfield(options_mom_.mom,'penalized_estimator') && options_mom_.mom.penalized_estimator
|
||||
warning('method_of_moments: The ''penalized_estimator'' option is not supported yet for IRF_MATCHING and will be ignored.');
|
||||
end
|
||||
options_mom_.mom.penalized_estimator = false;
|
||||
end
|
||||
|
||||
options_mom_.mom.analytic_jacobian_optimizers = [1, 3, 4, 13, 101]; % these are currently supported optimizers that are able to use the analytical_jacobian option
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% OPTIONS POSSIBLY SET BY THE USER
|
||||
|
@ -96,7 +87,8 @@ options_mom_ = set_default_option(options_mom_,'nograph',false); % do no
|
|||
options_mom_ = set_default_option(options_mom_,'noprint',false); % do not print output to console
|
||||
options_mom_ = set_default_option(options_mom_,'TeX',false); % print TeX tables and graphics
|
||||
options_mom_.mom = set_default_option(options_mom_.mom,'verbose',false); % display and store intermediate estimation results
|
||||
if do_bayesian_estimation
|
||||
%options_mom_ = set_default_option(options_mom_,'verbosity',false); %
|
||||
if doBayesianEstimation
|
||||
options_mom_ = set_default_option(options_mom_,'plot_priors',true); % control plotting of priors
|
||||
options_mom_ = set_default_option(options_mom_,'prior_trunc',1e-10); % probability of extreme values of the prior density that is ignored when computing bounds for the parameters
|
||||
end
|
||||
|
@ -119,16 +111,6 @@ end
|
|||
if strcmp(mom_method,'GMM')
|
||||
options_mom_.mom = set_default_option(options_mom_.mom,'analytic_standard_errors',false); % compute standard errors numerically (0) or analytically (1). Analytical derivatives are only available for GMM.
|
||||
end
|
||||
if strcmp(mom_method,'IRF_MATCHING')
|
||||
if ~isfield(options_mom_.mom,'irf_matching_file')
|
||||
options_mom_.mom.irf_matching_file = []; % irf_matching file enables to transform model IRFs before matching them to data IRFs
|
||||
end
|
||||
options_mom_.mom.irf_matching_file = set_default_option(options_mom_.mom.irf_matching_file,'name','');
|
||||
options_mom_.mom = set_default_option(options_mom_.mom,'simulation_method','STOCH_SIMUL'); % simulation method used to compute IRFs
|
||||
options_mom_ = set_default_option(options_mom_,'add_tiny_number_to_cholesky',1e-14); % add tiny number to Cholesky factor to avoid numerical problems when computing IRFs
|
||||
options_mom_ = set_default_option(options_mom_,'drop',100); % truncation / burnin for order>1 irf simulations
|
||||
options_mom_ = set_default_option(options_mom_,'relative_irf',false); % requests the computation of normalized IRFs
|
||||
end
|
||||
|
||||
% data related options
|
||||
if strcmp(mom_method,'GMM') || strcmp(mom_method,'SMM')
|
||||
|
@ -141,14 +123,12 @@ if strcmp(mom_method,'GMM') || strcmp(mom_method,'SMM')
|
|||
end
|
||||
|
||||
% optimization related
|
||||
if strcmp(mom_method,'GMM') || strcmp(mom_method,'SMM')
|
||||
if (isoctave && user_has_octave_forge_package('optim')) || (~isoctave && user_has_matlab_license('optimization_toolbox'))
|
||||
if (isoctave && user_has_octave_forge_package('optim')) || (~isoctave && user_has_matlab_license('optimization_toolbox'))
|
||||
if strcmp(mom_method,'GMM') || strcmp(mom_method,'SMM')
|
||||
options_mom_ = set_default_option(options_mom_,'mode_compute',13); % specifies lsqnonlin as default optimizer for minimization
|
||||
else
|
||||
options_mom_ = set_default_option(options_mom_,'mode_compute',5); % specifies newrat as fallback default option for minimization
|
||||
end
|
||||
elseif strcmp(mom_method,'IRF_MATCHING')
|
||||
options_mom_ = set_default_option(options_mom_,'mode_compute',5); % specifies newrat as fallback default option for minimization
|
||||
else
|
||||
options_mom_ = set_default_option(options_mom_,'mode_compute',4); % specifies csminwel as fallback default option for minimization
|
||||
end
|
||||
options_mom_ = set_default_option(options_mom_,'additional_optimizer_steps',[]); % vector of additional mode-finders run after mode_compute
|
||||
options_mom_ = set_default_option(options_mom_,'optim_opt',[]); % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
|
||||
|
@ -156,20 +136,9 @@ options_mom_ = set_default_option(options_mom_,'silent_optimizer',false);
|
|||
options_mom_ = set_default_option(options_mom_,'huge_number',1e7); % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
|
||||
options_mom_.mom = set_default_option(options_mom_.mom,'analytic_jacobian',false); % use analytic Jacobian in optimization, only available for GMM and gradient-based optimizers
|
||||
options_mom_.optimizer_vec = [options_mom_.mode_compute;num2cell(options_mom_.additional_optimizer_steps)];
|
||||
options_mom_.mom.analytic_jacobian_optimizers = [1, 3, 4, 13, 101]; % these are currently supported optimizers that are able to use the analytic_jacobian option
|
||||
options_mom_.analytic_derivation = 0; % force to 0 as we check this seperately in dynare_minimize_objective.m
|
||||
options_mom_ = set_default_option(options_mom_,'mode_file',''); % name of the file containing initial values for the mode
|
||||
options_mom_ = set_default_option(options_mom_,'cova_compute',true); % 1: computed covariance via Hessian after the computation of the mode, 0: turn off computation of covariance matrix
|
||||
|
||||
% perturbation related
|
||||
options_mom_ = set_default_option(options_mom_,'order',1); % order of Taylor approximation in perturbation
|
||||
if strcmp(mom_method,'IRF_MATCHING') % number of simulated series used to compute IRFs
|
||||
if options_mom_.order == 1
|
||||
options_mom_ = set_default_option(options_mom_,'replic',1);
|
||||
else
|
||||
options_mom_ = set_default_option(options_mom_,'replic',50);
|
||||
end
|
||||
end
|
||||
options_mom_ = set_default_option(options_mom_,'pruning',false); % use pruned state space system at order>1
|
||||
options_mom_ = set_default_option(options_mom_,'aim_solver',false); % use AIM algorithm to compute perturbation approximation instead of mjdgges
|
||||
options_mom_ = set_default_option(options_mom_,'k_order_solver',false); % use k_order_perturbation instead of mjdgges
|
||||
|
@ -191,122 +160,15 @@ options_mom_ = set_default_option(options_mom_,'lyapunov_srs',false);
|
|||
options_mom_ = set_default_option(options_mom_,'lyapunov_complex_threshold',1e-15); % complex block threshold for the upper triangular matrix in symmetric Lyapunov equation solver
|
||||
options_mom_ = set_default_option(options_mom_,'lyapunov_fixed_point_tol',1e-10); % convergence criterion used in the fixed point Lyapunov solver
|
||||
options_mom_ = set_default_option(options_mom_,'lyapunov_doubling_tol',1e-16); % convergence criterion used in the doubling algorithm
|
||||
options_mom_ = set_default_option(options_mom_,'sylvester_fp',false); % determines whether to use fixed point algorihtm to solve Sylvester equation (gensylv_fp), faster for large scale models
|
||||
options_mom_ = set_default_option(options_mom_,'sylvester_fixed_point_tol',1e-12); % convergence criterion used in the fixed point Sylvester solver
|
||||
|
||||
% Bayesian MCMC related
|
||||
if do_bayesian_estimation
|
||||
options_mom_ = set_default_option(options_mom_,'mh_replic',0); % number of draws in Metropolis-Hastings and slice samplers
|
||||
options_mom_ = set_default_option(options_mom_,'mh_posterior_mode_estimation',false); % skip optimizer-based mode-finding and instead compute the mode based on a run of a MCMC
|
||||
options_mom_ = set_default_option(options_mom_,'load_mh_file',false); % add to previous Metropolis-Hastings or slice simulations instead of starting from scratch
|
||||
options_mom_ = set_default_option(options_mom_,'load_results_after_load_mh',false); % load the previously computed convergence diagnostics, marginal data density, and posterior statistics from an existing mom_results file instead of recomputing them
|
||||
|
||||
if options_mom_.mh_replic > 0 || options_mom_.load_mh_file
|
||||
options_mom_ = set_default_option(options_mom_,'sub_draws',[]);
|
||||
options_mom_ = set_default_option(options_mom_,'posterior_max_subsample_draws',1200);
|
||||
options_mom_ = set_default_option(options_mom_,'mh_nblck',2); % number of parallel chains for Metropolis-Hastings or slice algorithm
|
||||
options_mom_ = set_default_option(options_mom_,'mh_drop',0.5); % fraction of initially generated parameter vectors to be dropped as a burn-in before using posterior simulations
|
||||
options_mom_ = set_default_option(options_mom_,'mh_conf_sig',0.9); % confidence/HPD interval used for the computation of prior and posterior statistics
|
||||
options_mom_ = set_default_option(options_mom_,'mh_recover',false); % attempts to recover a Metropolis-Hastings simulation that crashed prematurely
|
||||
options_mom_ = set_default_option(options_mom_,'MCMC_jumping_covariance','hessian'); % which covariance to use for the proposal density of the MCMC sampler
|
||||
if ~isfield(options_mom_,'mh_initialize_from_previous_mcmc')
|
||||
options_mom_.mh_initialize_from_previous_mcmc.status = false; % pick initial values for new MCMC from a previous one
|
||||
end
|
||||
options_mom_.mh_initialize_from_previous_mcmc = set_default_option(options_mom_.mh_initialize_from_previous_mcmc,'directory',''); % pick initial values for new MCMC from a previous one: directory
|
||||
options_mom_.mh_initialize_from_previous_mcmc = set_default_option(options_mom_.mh_initialize_from_previous_mcmc,'record',''); % pick initial values for new MCMC from a previous one: record file name
|
||||
options_mom_.mh_initialize_from_previous_mcmc = set_default_option(options_mom_.mh_initialize_from_previous_mcmc,'prior',''); % pick initial values for new MCMC from a previous one: prior file name
|
||||
if ~isfield(options_mom_,'posterior_sampler_options')
|
||||
options_mom_.posterior_sampler_options = [];
|
||||
end
|
||||
options_mom_.posterior_sampler_options = set_default_option(options_mom_.posterior_sampler_options,'posterior_sampling_method','random_walk_metropolis_hastings'); % selects the sampler used to sample from the posterior distribution during Bayesian estimation
|
||||
options_mom_.posterior_sampler_options = set_default_option(options_mom_.posterior_sampler_options,'sampling_opt',[]); % used to set options for the posterior sampling methods
|
||||
switch options_mom_.posterior_sampler_options.posterior_sampling_method
|
||||
case 'random_walk_metropolis_hastings'
|
||||
if ~isfield(options_mom_.posterior_sampler_options,'rwmh')
|
||||
options_mom_.posterior_sampler_options.rwmh = [];
|
||||
end
|
||||
options_mom_.posterior_sampler_options.rwmh = set_default_option(options_mom_.posterior_sampler_options.rwmh,'proposal_distribution','rand_multivariate_normal');
|
||||
options_mom_.posterior_sampler_options.rwmh = set_default_option(options_mom_.posterior_sampler_options.rwmh,'student_degrees_of_freedom',3);
|
||||
options_mom_.posterior_sampler_options.rwmh = set_default_option(options_mom_.posterior_sampler_options.rwmh,'use_mh_covariance_matrix',false);
|
||||
options_mom_.posterior_sampler_options.rwmh = set_default_option(options_mom_.posterior_sampler_options.rwmh,'save_tmp_file',false);
|
||||
case 'tailored_random_block_metropolis_hastings'
|
||||
if ~isfield(options_mom_.posterior_sampler_options,'tarb')
|
||||
options_mom_.posterior_sampler_options.tarb = [];
|
||||
end
|
||||
options_mom_.posterior_sampler_options.tarb = set_default_option(options_mom_.posterior_sampler_options.tarb,'proposal_distribution','rand_multivariate_normal');
|
||||
options_mom_.posterior_sampler_options.tarb = set_default_option(options_mom_.posterior_sampler_options.tarb,'student_degrees_of_freedom',3);
|
||||
options_mom_.posterior_sampler_options.tarb = set_default_option(options_mom_.posterior_sampler_options.tarb,'mode_compute',4);
|
||||
options_mom_.posterior_sampler_options.tarb = set_default_option(options_mom_.posterior_sampler_options.tarb,'new_block_probability',0.25);
|
||||
options_mom_.posterior_sampler_options.tarb = set_default_option(options_mom_.posterior_sampler_options.tarb,'optim_opt','');
|
||||
options_mom_.posterior_sampler_options.tarb = set_default_option(options_mom_.posterior_sampler_options.tarb,'save_tmp_file',true);
|
||||
case 'slice'
|
||||
if ~isfield(options_mom_.posterior_sampler_options,'slice')
|
||||
options_mom_.posterior_sampler_options.slice = [];
|
||||
end
|
||||
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'proposal_distribution','');
|
||||
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'rotated',0);
|
||||
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'slice_initialize_with_mode',false); % must be used with rotated
|
||||
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'use_mh_covariance_matrix',false); % must be used with rotated
|
||||
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'WR',[]);
|
||||
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'mode_files',[]);
|
||||
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'mode',[]);
|
||||
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'initial_step_size',0.8);
|
||||
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'save_tmp_file',true);
|
||||
case 'independent_metropolis_hastings'
|
||||
if ~isfield(options_mom_.posterior_sampler_options,'imh')
|
||||
options_mom_.posterior_sampler_options.imh = [];
|
||||
end
|
||||
options_mom_.posterior_sampler_options.imh = set_default_option(options_mom_.posterior_sampler_options.imh,'proposal_distribution','rand_multivariate_normal');
|
||||
options_mom_.posterior_sampler_options.imh = set_default_option(options_mom_.posterior_sampler_options.imh,'use_mh_covariance_matrix',false);
|
||||
options_mom_.posterior_sampler_options.imh = set_default_option(options_mom_.posterior_sampler_options.imh,'save_tmp_file',false);
|
||||
end
|
||||
if ~strcmp(options_mom_.posterior_sampler_options.posterior_sampling_method,'slice')
|
||||
options_mom_ = set_default_option(options_mom_,'mh_init_scale_factor',2);
|
||||
options_mom_ = set_default_option(options_mom_,'mh_jscale',[]);
|
||||
end
|
||||
|
||||
% mh_tune_jscale options
|
||||
if strcmp(options_mom_.posterior_sampler_options.posterior_sampling_method,'random_walk_metropolis_hastings')
|
||||
if ~isfield(options_mom_,'mh_tune_jscale')
|
||||
options_mom_.mh_tune_jscale = [];
|
||||
end
|
||||
options_mom_.mh_tune_jscale = set_default_option(options_mom_.mh_tune_jscale,'status',false);
|
||||
options_mom_.mh_tune_jscale = set_default_option(options_mom_.mh_tune_jscale,'target',0.33);
|
||||
options_mom_.mh_tune_jscale = set_default_option(options_mom_.mh_tune_jscale,'guess',[]);
|
||||
options_mom_.mh_tune_jscale.maxiter = options_.mh_tune_jscale.maxiter;
|
||||
options_mom_.mh_tune_jscale.rho = options_.mh_tune_jscale.rho;
|
||||
options_mom_.mh_tune_jscale.stepsize = options_.mh_tune_jscale.stepsize;
|
||||
options_mom_.mh_tune_jscale.c1 = options_.mh_tune_jscale.c1;
|
||||
options_mom_.mh_tune_jscale.c2 = options_.mh_tune_jscale.c2;
|
||||
options_mom_.mh_tune_jscale.c3 = options_.mh_tune_jscale.c3;
|
||||
end
|
||||
|
||||
% convergence diagnostics
|
||||
options_mom_ = set_default_option(options_mom_,'nodiagnostic',false);
|
||||
if ~isfield(options_mom_,'convergence')
|
||||
options_mom_.convergence = [];
|
||||
end
|
||||
if ~isfield(options_mom_.convergence,'geweke')
|
||||
options_mom_.convergence.geweke = [];
|
||||
end
|
||||
if ~isfield(options_mom_.convergence,'rafterylewis')
|
||||
options_mom_.convergence.rafterylewis = [];
|
||||
end
|
||||
if ~isfield(options_mom_.convergence,'brooksgelman')
|
||||
options_mom_.convergence.brooksgelman = [];
|
||||
end
|
||||
options_mom_.convergence.geweke = set_default_option(options_mom_.convergence.geweke,'taper_steps', [4 8 15]);
|
||||
options_mom_.convergence.geweke = set_default_option(options_mom_.convergence.geweke,'geweke_interval', [0.2 0.5]);
|
||||
options_mom_.convergence.rafterylewis = set_default_option(options_mom_.convergence.rafterylewis,'indicator', false);
|
||||
options_mom_.convergence.rafterylewis = set_default_option(options_mom_.convergence.rafterylewis,'qrs', [0.025 0.005 0.95]);
|
||||
options_mom_.convergence.brooksgelman = set_default_option(options_mom_.convergence.brooksgelman,'plotrows',3);
|
||||
end
|
||||
end
|
||||
|
||||
% mode check plot options
|
||||
% mode check plot
|
||||
options_mom_.mode_check.nolik = false; % we don't do likelihood (also this initializes mode_check substructure)
|
||||
options_mom_.mode_check = set_default_option(options_mom_.mode_check,'status',false); % plot the target function for values around the computed mode for each estimated parameter in turn. This is helpful to diagnose problems with the optimizer.
|
||||
options_mom_.mode_check = set_default_option(options_mom_.mode_check,'neighbourhood_size',.5); % width of the window around the computed mode to be displayed on the diagnostic plots. This width is expressed in percentage deviation. The Inf value is allowed, and will trigger a plot over the entire domain
|
||||
options_mom_.mode_check = set_default_option(options_mom_.mode_check,'symmetric_plots',true); % ensure that the check plots are symmetric around the mode. A value of 0 allows to have asymmetric plots, which can be useful if the mode is close to a domain boundary, or in conjunction with neighbourhood_size = Inf when the domain is not the entire real line
|
||||
options_mom_.mode_check = set_default_option(options_mom_.mode_check,'number_of_points',20); % number of points around the mode where the target function is evaluated (for each parameter)
|
||||
options_mom_.mode_check = set_default_option(options_mom_.mode_check,'status',false); % plot the target function for values around the computed minimum for each estimated parameter in turn. This is helpful to diagnose problems with the optimizer.
|
||||
options_mom_.mode_check = set_default_option(options_mom_.mode_check,'neighbourhood_size',.5); % width of the window around the computed minimum to be displayed on the diagnostic plots. This width is expressed in percentage deviation. The Inf value is allowed, and will trigger a plot over the entire domain
|
||||
options_mom_.mode_check = set_default_option(options_mom_.mode_check,'symmetric_plots',true); % ensure that the check plots are symmetric around the minimum. A value of 0 allows to have asymmetric plots, which can be useful if the minimum is close to a domain boundary, or in conjunction with neighbourhood_size = Inf when the domain is not the entire real line
|
||||
options_mom_.mode_check = set_default_option(options_mom_.mode_check,'number_of_points',20); % number of points around the minimum where the target function is evaluated (for each parameter)
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
|
@ -320,12 +182,8 @@ options_mom_.obs_nbr = length(options_mom_.varobs); % number of observed variabl
|
|||
|
||||
% related to call of dynare
|
||||
options_mom_.console_mode = options_.console_mode;
|
||||
if options_mom_.console_mode
|
||||
options_mom_.nodisplay = true;
|
||||
end
|
||||
options_mom_.parallel = options_.parallel;
|
||||
options_mom_.parallel_info = options_.parallel_info;
|
||||
options_mom_.debug = options_.debug; % debug option is needed by some functions, e.g. check_plot
|
||||
|
||||
% related to estimated_params and estimated_params_init blocks
|
||||
options_mom_.use_calibration_initialization = options_.use_calibration_initialization;
|
||||
|
@ -394,82 +252,19 @@ end
|
|||
options_mom_.gstep = options_.gstep; % needed by hessian.m
|
||||
options_mom_.trust_region_initial_step_bound_factor = options_.trust_region_initial_step_bound_factor; % used in dynare_solve for trust_region
|
||||
|
||||
% miscellaneous
|
||||
options_mom_.threads = options_.threads;
|
||||
% other
|
||||
options_mom_.MaxNumberOfBytes = options_.MaxNumberOfBytes;
|
||||
options_mom_.marginal_data_density = options_.marginal_data_density;
|
||||
%options_mom_.MaximumNumberOfMegaBytes = options_.MaximumNumberOfMegaBytes;
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% DEFAULT VALUES
|
||||
% -------------------------------------------------------------------------
|
||||
options_mom_.mom.compute_derivs = false; % flag to compute derivs in objective function (might change for GMM with either analytic_standard_errors or analytic_jacobian (dependent on optimizer))
|
||||
options_mom_.mom.vector_output = false; % specifies whether the objective function returns a vector
|
||||
|
||||
options_mom_.analytic_derivation = 0;
|
||||
options_mom_.analytic_derivation_mode = 0; % needed by get_perturbation_params_derivs.m, ie use efficient sylvester equation method to compute analytical derivatives as in Ratto & Iskrev (2012)
|
||||
options_mom_.initialize_estimated_parameters_with_the_prior_mode = 0; % needed by set_prior.m
|
||||
options_mom_.figures = options_.figures; % needed by plot_priors.m
|
||||
options_mom_.ramsey_policy = false; % needed by evaluate_steady_state
|
||||
options_mom_.risky_steadystate = false; % needed by resol
|
||||
options_mom_.jacobian_flag = true; % needed by dynare_solve
|
||||
options_mom_.use_mh_covariance_matrix = false; % needed by posterior_sampler, get's overwritten by same option in options_mom_.posterior_sampler_options
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% CHECKS ON SETTINGS
|
||||
% -------------------------------------------------------------------------
|
||||
if strcmp(mom_method,'GMM') || strcmp(mom_method,'SMM')
|
||||
if numel(options_mom_.nobs) > 1
|
||||
error('method_of_moments: Recursive estimation is not supported. Please set an integer as ''nobs''!');
|
||||
end
|
||||
if numel(options_mom_.first_obs) > 1
|
||||
error('method_of_moments: Recursive estimation is not supported. Please set an integer as ''first_obs''!');
|
||||
end
|
||||
end
|
||||
if options_mom_.order < 1
|
||||
error('method_of_moments: The order of the Taylor approximation cannot be 0!')
|
||||
end
|
||||
if options_mom_.order > 2
|
||||
fprintf('Dynare will use ''k_order_solver'' as the order>2\n');
|
||||
options_mom_.k_order_solver = true;
|
||||
end
|
||||
if strcmp(mom_method,'SMM')
|
||||
if options_mom_.mom.simulation_multiple < 1
|
||||
fprintf('The simulation horizon is shorter than the data. Dynare resets the simulation_multiple to 7.\n')
|
||||
options_mom_.mom.simulation_multiple = 7;
|
||||
end
|
||||
end
|
||||
if strcmp(mom_method,'GMM')
|
||||
% require pruning with GMM at higher order
|
||||
if options_mom_.order > 1 && ~options_mom_.pruning
|
||||
fprintf('GMM at higher order only works with pruning, so we set pruning option to 1.\n');
|
||||
options_mom_.pruning = true;
|
||||
end
|
||||
if options_mom_.order > 3
|
||||
error('method_of_moments: Perturbation orders higher than 3 are not implemented for GMM estimation, try using SMM!');
|
||||
end
|
||||
end
|
||||
if strcmp(mom_method,'IRF_MATCHING') && do_bayesian_estimation
|
||||
if isfield(options_mom_,'mh_tune_jscale') && options_mom_.mh_tune_jscale.status && (options_mom_.mh_tune_jscale.maxiter<options_mom_.mh_tune_jscale.stepsize)
|
||||
warning('method_of_moments: You specified mh_tune_jscale, but the maximum number of iterations is smaller than the step size. No update will take place.')
|
||||
end
|
||||
if options_mom_.load_results_after_load_mh
|
||||
if ~exist([options_mom_.dirname filesep 'method_of_moments' filesep M_.fname '_mom_results.mat'],'file')
|
||||
fprintf('\nYou specified the ''load_results_after_load_mh'' option, but no ''%s_mom_results.mat'' file\n',M_.fname);
|
||||
fprintf('was found in the folder %s%smethod_of_moments.\n',options_mom_.dirname,filesep);
|
||||
fprintf('Results will be recomputed and option ''load_results_after_load_mh'' is reset to false.\n');
|
||||
options_mom_.load_results_after_load_mh = false;
|
||||
end
|
||||
end
|
||||
if options_mom_.mh_replic>0 && options_mom_.mh_nblck<1
|
||||
error('method_of_moments: Bayesian MCMC estimation cannot be conducted with ''mh_nblocks''=0!')
|
||||
end
|
||||
end
|
||||
if options_mom_.mom.analytic_jacobian && ~strcmp(mom_method,'GMM')
|
||||
options_mom_.mom.analytic_jacobian = false;
|
||||
fprintf('\n''analytic_jacobian'' option will be dismissed as it only works with GMM.\n');
|
||||
end
|
||||
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
|
||||
if any(cellfun(@(x) isnumeric(x) && any(x == 13), options_mom_.optimizer_vec))
|
||||
error('method_of_moments: lsqnonlin (mode_compute=13) is not yet supported for IRF matching!');
|
||||
end
|
||||
end
|
||||
options_mom_.figures = options_.figures; % needed by plot_priors.m
|
||||
options_mom_.ramsey_policy = false; % needed by evaluate_steady_state
|
||||
options_mom_.risky_steadystate = false; % needed by resol
|
||||
options_mom_.jacobian_flag = true; % needed by dynare_solve
|
|
@ -0,0 +1,74 @@
|
|||
function display_comparison_moments(M_, options_mom_, data_moments, model_moments)
|
||||
% function display_comparison_moments(M_, options_mom_, data_moments, model_moments)
|
||||
% -------------------------------------------------------------------------
|
||||
% Displays and saves to disk the comparison of the data moments and the model moments
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% M_: [structure] model information
|
||||
% options_mom_: [structure] method of moments options
|
||||
% data_moments: [vector] data moments
|
||||
% model_moments: [vector] model moments
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUT
|
||||
% No output, just displays and saves to disk the comparison of the data moments and the model moments
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
% -------------------------------------------------------------------------
|
||||
% This function calls
|
||||
% o dyn_latex_table
|
||||
% o dyntable
|
||||
% o cellofchararraymaxlength
|
||||
% =========================================================================
|
||||
% Copyright © 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/>.
|
||||
% =========================================================================
|
||||
|
||||
titl = ['Comparison of matched data moments and model moments (',options_mom_.mom.mom_method,')'];
|
||||
headers = {'Moment','Data','Model'};
|
||||
for jm = 1:size(M_.matched_moments,1)
|
||||
lables_tmp = 'E[';
|
||||
lables_tmp_tex = 'E \left[ ';
|
||||
for jvar = 1:length(M_.matched_moments{jm,1})
|
||||
lables_tmp = [lables_tmp M_.endo_names{M_.matched_moments{jm,1}(jvar)}];
|
||||
lables_tmp_tex = [lables_tmp_tex, '{', M_.endo_names_tex{M_.matched_moments{jm,1}(jvar)}, '}'];
|
||||
if M_.matched_moments{jm,2}(jvar) ~= 0
|
||||
lables_tmp = [lables_tmp, '(', num2str(M_.matched_moments{jm,2}(jvar)), ')'];
|
||||
lables_tmp_tex = [lables_tmp_tex, '_{t', num2str(M_.matched_moments{jm,2}(jvar)), '}'];
|
||||
else
|
||||
lables_tmp_tex = [lables_tmp_tex, '_{t}'];
|
||||
end
|
||||
if M_.matched_moments{jm,3}(jvar) > 1
|
||||
lables_tmp = [lables_tmp, '^', num2str(M_.matched_moments{jm,3}(jvar))];
|
||||
lables_tmp_tex = [lables_tmp_tex, '^{', num2str(M_.matched_moments{jm,3}(jvar)) '}'];
|
||||
end
|
||||
if jvar == length(M_.matched_moments{jm,1})
|
||||
lables_tmp = [lables_tmp, ']'];
|
||||
lables_tmp_tex = [lables_tmp_tex, ' \right]'];
|
||||
else
|
||||
lables_tmp = [lables_tmp, '*'];
|
||||
lables_tmp_tex = [lables_tmp_tex, ' \times '];
|
||||
end
|
||||
end
|
||||
labels{jm,1} = lables_tmp;
|
||||
labels_TeX{jm,1} = lables_tmp_tex;
|
||||
end
|
||||
data_mat = [data_moments model_moments];
|
||||
dyntable(options_mom_, titl, headers, labels, data_mat, cellofchararraymaxlength(labels)+2, 10, 7);
|
||||
if options_mom_.TeX
|
||||
dyn_latex_table(M_, options_mom_, titl, ['comparison_moments_', options_mom_.mom.mom_method], headers, labels_TeX, data_mat, cellofchararraymaxlength(labels)+2, 10, 7);
|
||||
end
|
|
@ -1,96 +0,0 @@
|
|||
function display_comparison_moments_irfs(M_, options_mom_, data_moments, model_moments)
|
||||
% display_comparison_moments_irfs(M_, options_mom_, data_moments, model_moments)
|
||||
% -------------------------------------------------------------------------
|
||||
% Displays and saves to disk the comparison of the data moments/IRFs and the model moments/IRFs
|
||||
% -------------------------------------------------------------------------
|
||||
% INPUTS
|
||||
% M_: [structure] model information
|
||||
% options_mom_: [structure] method of moments options
|
||||
% data_moments: [vector] data moments
|
||||
% model_moments: [vector] model moments
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUT
|
||||
% No output, just displays and saves to disk the comparison of the data moments and the model moments
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
% -------------------------------------------------------------------------
|
||||
% This function calls
|
||||
% o dyn_latex_table
|
||||
% o dyntable
|
||||
% o cellofchararraymaxlength
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% Copyright © 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 strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
|
||||
titl = upper('Comparison of matched data IRFs and model IRFs');
|
||||
headers = {'IRF','Data','Model'};
|
||||
idx = 1;
|
||||
for jj = 1:size(M_.matched_irfs,1)
|
||||
irf_varname = M_.matched_irfs{jj,1};
|
||||
irf_shockname = M_.matched_irfs{jj,2};
|
||||
% note that periods can span over multiple rows
|
||||
IRF_PERIODS = [];
|
||||
for kk = 1:size(M_.matched_irfs{jj,3},1)
|
||||
irf_periods = M_.matched_irfs{jj,3}{kk,1};
|
||||
IRF_PERIODS = [IRF_PERIODS; irf_periods(:)];
|
||||
end
|
||||
for hh = 1:length(IRF_PERIODS)
|
||||
labels{idx,1} = sprintf('%s %s (%u)',irf_varname,irf_shockname,IRF_PERIODS(hh));
|
||||
labels_TeX{idx,1} = sprintf('%s %s (%u)',M_.endo_names_tex{ismember(M_.endo_names,irf_varname)},M_.exo_names_tex{ismember(M_.exo_names,irf_shockname)},IRF_PERIODS(hh));
|
||||
idx = idx+1;
|
||||
end
|
||||
end
|
||||
else
|
||||
titl = ['Comparison of matched data moments and model moments (',options_mom_.mom.mom_method,')'];
|
||||
headers = {'Moment','Data','Model'};
|
||||
for jm = 1:size(M_.matched_moments,1)
|
||||
lables_tmp = 'E[';
|
||||
lables_tmp_tex = 'E \left[ ';
|
||||
for jvar = 1:length(M_.matched_moments{jm,1})
|
||||
lables_tmp = [lables_tmp M_.endo_names{M_.matched_moments{jm,1}(jvar)}];
|
||||
lables_tmp_tex = [lables_tmp_tex, '{', M_.endo_names_tex{M_.matched_moments{jm,1}(jvar)}, '}'];
|
||||
if M_.matched_moments{jm,2}(jvar) ~= 0
|
||||
lables_tmp = [lables_tmp, '(', num2str(M_.matched_moments{jm,2}(jvar)), ')'];
|
||||
lables_tmp_tex = [lables_tmp_tex, '_{t', num2str(M_.matched_moments{jm,2}(jvar)), '}'];
|
||||
else
|
||||
lables_tmp_tex = [lables_tmp_tex, '_{t}'];
|
||||
end
|
||||
if M_.matched_moments{jm,3}(jvar) > 1
|
||||
lables_tmp = [lables_tmp, '^', num2str(M_.matched_moments{jm,3}(jvar))];
|
||||
lables_tmp_tex = [lables_tmp_tex, '^{', num2str(M_.matched_moments{jm,3}(jvar)) '}'];
|
||||
end
|
||||
if jvar == length(M_.matched_moments{jm,1})
|
||||
lables_tmp = [lables_tmp, ']'];
|
||||
lables_tmp_tex = [lables_tmp_tex, ' \right]'];
|
||||
else
|
||||
lables_tmp = [lables_tmp, '*'];
|
||||
lables_tmp_tex = [lables_tmp_tex, ' \times '];
|
||||
end
|
||||
end
|
||||
labels{jm,1} = lables_tmp;
|
||||
labels_TeX{jm,1} = lables_tmp_tex;
|
||||
end
|
||||
end
|
||||
data_mat = [data_moments model_moments];
|
||||
dyntable(options_mom_, titl, headers, labels, data_mat, cellofchararraymaxlength(labels)+2, 10, 7);
|
||||
if options_mom_.TeX
|
||||
dyn_latex_table(M_, options_mom_, titl, ['comparison_moments_', options_mom_.mom.mom_method], headers, labels_TeX, data_mat, cellofchararraymaxlength(labels)+2, 10, 7);
|
||||
end
|
|
@ -1,8 +1,7 @@
|
|||
function [data_moments, m_data] = get_data_moments(data, obs_var, inv_order_var, matched_moments_, options_mom_)
|
||||
% [data_moments, m_data] = get_data_moments(data, obs_var, inv_order_var, matched_moments_, options_mom_)
|
||||
% -------------------------------------------------------------------------
|
||||
% Computes the user-selected empirical moments from data
|
||||
% -------------------------------------------------------------------------
|
||||
function [dataMoments, m_data] = get_data_moments(data, obs_var, inv_order_var, matched_moments_, options_mom_)
|
||||
% [dataMoments, m_data] = get_data_moments(data, obs_var, inv_order_var, matched_moments_, options_mom_)
|
||||
% This function computes the user-selected empirical moments from data
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% o data [T x varobs_nbr] data set
|
||||
% o obs_var: [integer] index of observables
|
||||
|
@ -11,14 +10,13 @@ function [data_moments, m_data] = get_data_moments(data, obs_var, inv_order_var,
|
|||
% o options_mom_: [structure] information about all settings (specified by the user, preprocessor, and taken from global options_)
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUTS
|
||||
% o data_moments [numMom x 1] mean of selected empirical moments
|
||||
% o dataMoments [numMom x 1] mean of selected empirical moments
|
||||
% o m_data [T x numMom] selected empirical moments at each point in time
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
% o mom.objective_function
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% =========================================================================
|
||||
% Copyright © 2020-2023 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -35,11 +33,15 @@ function [data_moments, m_data] = get_data_moments(data, obs_var, inv_order_var,
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% Author(s):
|
||||
% o Willi Mutschler (willi@mutschler.eu)
|
||||
% o Johannes Pfeifer (johannes.pfeifer@unibw.de)
|
||||
% =========================================================================
|
||||
|
||||
% Initialization
|
||||
T = size(data,1); % Number of observations (T)
|
||||
data_moments = NaN(options_mom_.mom.mom_nbr,1);
|
||||
dataMoments = NaN(options_mom_.mom.mom_nbr,1);
|
||||
m_data = NaN(T,options_mom_.mom.mom_nbr);
|
||||
% Product moment for each time period, i.e. each row t contains y_t1(l1)^p1*y_t2(l2)^p2*...
|
||||
% note that here we already are able to treat leads and lags and any power product moments
|
||||
|
@ -58,11 +60,11 @@ for jm = 1:options_mom_.mom.mom_nbr
|
|||
end
|
||||
end
|
||||
% We replace NaN (due to leads and lags and missing values) with the corresponding mean
|
||||
if isoctave && octave_ver_less_than('8')
|
||||
data_moments(jm,1) = nanmean(m_data_tmp);
|
||||
if isoctave || matlab_ver_less_than('8.5')
|
||||
dataMoments(jm,1) = nanmean(m_data_tmp);
|
||||
else
|
||||
data_moments(jm,1) = mean(m_data_tmp,'omitnan');
|
||||
dataMoments(jm,1) = mean(m_data_tmp,'omitnan');
|
||||
end
|
||||
m_data_tmp(isnan(m_data_tmp)) = data_moments(jm,1);
|
||||
m_data_tmp(isnan(m_data_tmp)) = dataMoments(jm,1);
|
||||
m_data(:,jm) = m_data_tmp;
|
||||
end
|
||||
end
|
|
@ -1,130 +0,0 @@
|
|||
function graph_comparison_irfs(matched_irfs,irf_model_varobs,varobs_id,irf_horizon,relative_irf,endo_names,endo_names_tex,exo_names,exo_names_tex,dname,fname,graph_format,TeX,nodisplay,figures_textwidth)
|
||||
% graph_comparison_irfs(matched_irfs,irf_model_varobs,varobs_id,irf_horizon,relative_irf,endo_names,endo_names_tex,exo_names,exo_names_tex,dname,fname,graph_format,TeX,nodisplay,figures_textwidth)
|
||||
% -------------------------------------------------------------------------
|
||||
% Plots and saves to disk the comparison of the selected data IRFs and corresponding model IRfs
|
||||
% -------------------------------------------------------------------------
|
||||
% INPUTS
|
||||
% matched_irfs: [matrix] information on matched data IRFs
|
||||
% irf_model_varobs: [matrix] model IRFs for observable variables
|
||||
% varobs_id: [vector] index for observable variables in endo_names
|
||||
% irf_horizon: [scalar] maximum horizon of IRFs
|
||||
% relative_irf: [boolean] if true, plots normalized IRFs
|
||||
% endo_names: [cell] names of endogenous variables
|
||||
% endo_names_tex: [cell] names of endogenous variables in latex
|
||||
% exo_names: [cell] names of exogenous variables
|
||||
% exo_names_tex: [cell] names of exogenous variables in latex
|
||||
% dname: [string] name of the directory where to save the graphs
|
||||
% fname: [string] name of the mod file
|
||||
% graph_format: [cell] format of the graphs
|
||||
% TeX: [boolean] if true, uses latex for plots
|
||||
% nodisplay: [boolean] if true, does not display the graphs
|
||||
% figures_textwidth: [scalar] textwidth used in plots
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUT
|
||||
% No output, just displays and saves to disk the graphs
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
% -------------------------------------------------------------------------
|
||||
% This function calls
|
||||
% o dyn_figure
|
||||
% o dyn_saveas
|
||||
% o remove_fractional_xticks
|
||||
% o CheckPath
|
||||
% o pltorg
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% Copyright © 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/>.
|
||||
|
||||
|
||||
graph_directory_name = CheckPath('graphs',dname);
|
||||
latex_directory_name = CheckPath('latex',dname);
|
||||
if TeX && any(strcmp('eps',cellstr(graph_format)))
|
||||
fid_TeX = fopen([latex_directory_name '/' fname '_irf_matching_plot.tex'],'w');
|
||||
fprintf(fid_TeX,'%% TeX eps-loader file generated by mom.run.m (Dynare).\n');
|
||||
fprintf(fid_TeX,['%% ' datestr(now,0) '\n']);
|
||||
fprintf(fid_TeX,' \n');
|
||||
end
|
||||
unique_shock_entries = unique(matched_irfs(:, 2));
|
||||
colDarkGrey = [0.3, 0.3, 0.3]; % dark grey
|
||||
for jexo = unique_shock_entries' % loop over cell with shock names
|
||||
unique_variables = unique(matched_irfs(ismember(matched_irfs(:, 2),jexo), 1));
|
||||
[nbplt,nr,nc,lr,lc,nstar] = pltorg(length(unique_variables));
|
||||
fig = 0;
|
||||
for jvar = 1:length(unique_variables)
|
||||
% get data points, note that periods and values can span over multiple rows
|
||||
jj = ismember(matched_irfs(:,1), unique_variables(jvar)) & ismember(matched_irfs(:,2), jexo);
|
||||
IRF_PERIODS = []; IRF_VALUES = [];
|
||||
for kk = 1:size(matched_irfs{jj,3},1)
|
||||
irf_periods = matched_irfs{jj,3}{kk,1};
|
||||
irf_values = matched_irfs{jj,3}{kk,2};
|
||||
if length(irf_values)==1
|
||||
irf_values = repmat(irf_values,length(irf_periods),1);
|
||||
end
|
||||
IRF_PERIODS = [IRF_PERIODS; irf_periods(:)];
|
||||
IRF_VALUES = [IRF_VALUES; irf_values(:)];
|
||||
end
|
||||
|
||||
if jvar==1 || ~( (fig-1)*nstar<jvar && jvar<=fig*nstar )
|
||||
fig = fig+1;
|
||||
fig_irf = dyn_figure(nodisplay,'Name',['IRF matching shock to ' jexo{:} ' figure ' int2str(fig)]);
|
||||
end
|
||||
plt = jvar-(fig-1)*nstar;
|
||||
if nbplt>1 && fig==nbplt
|
||||
subplot(lr,lc,plt);
|
||||
else
|
||||
subplot(nr,nc,plt);
|
||||
end
|
||||
plt_data = plot(IRF_PERIODS,IRF_VALUES,'h', 'MarkerEdgeColor',colDarkGrey,'MarkerFaceColor',colDarkGrey,'MarkerSize',8);
|
||||
hold on
|
||||
plt_model = plot(1:irf_horizon, irf_model_varobs(:,varobs_id==find(ismember(endo_names,unique_variables(jvar))) , ismember(exo_names,jexo)),'-k','linewidth',2);
|
||||
hold on
|
||||
plot([1 irf_horizon],[0 0],'-r','linewidth',1);
|
||||
hold off
|
||||
xlim([1 irf_horizon]);
|
||||
remove_fractional_xticks
|
||||
if TeX
|
||||
title(['$' endo_names_tex{ismember(endo_names,unique_variables(jvar))} '$'],'Interpreter','latex');
|
||||
else
|
||||
title(unique_variables{jvar},'Interpreter','none');
|
||||
end
|
||||
set(gca,'FontSize',12);
|
||||
if (plt==nstar) || jvar==length(unique_variables)
|
||||
% Adding a legend at the bottom
|
||||
axes('Position',[0, 0, 1, 1],'Visible','off');
|
||||
lgd = legend([plt_data,plt_model],{'Data', 'Model'}, 'Location', 'southeast','NumColumns',2,'FontSize',14);
|
||||
if ~isoctave
|
||||
lgd.Position = [0.37 0.01 lgd.Position(3) lgd.Position(4)];
|
||||
end
|
||||
dyn_saveas(fig_irf,[graph_directory_name filesep fname '_matched_irf_' jexo{:} int2str(fig)],nodisplay,graph_format);
|
||||
if TeX && any(strcmp('eps',cellstr(graph_format)))
|
||||
fprintf(fid_TeX,'\\begin{figure}[H]\n');
|
||||
fprintf(fid_TeX,'\\centering \n');
|
||||
fprintf(fid_TeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_matched_irf_%s%s}\n',figures_textwidth*min(plt/nc,1),[graph_directory_name '/' fname],jexo{:},int2str(fig));
|
||||
if relative_irf
|
||||
fprintf(fid_TeX,'\\caption{Relative impulse response functions (orthogonalized shock to $%s$).}', jexo{:});
|
||||
else
|
||||
fprintf(fid_TeX,'\\caption{Impulse response functions (orthogonalized shock to $%s$).}', jexo{:});
|
||||
end
|
||||
fprintf(fid_TeX,'\\label{Fig:MatchedIRF:%s:%s}\n', jexo{:},int2str(fig));
|
||||
fprintf(fid_TeX,'\\end{figure}\n');
|
||||
fprintf(fid_TeX,' \n');
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
|
@ -1,151 +0,0 @@
|
|||
function [data_irfs, weight_mat, irf_index, max_irf_horizon] = matched_irfs_blocks(matched_irfs, matched_irfs_weight, varobs_id, obs_nbr, exo_nbr, endo_names, exo_names)
|
||||
% [data_irfs, weight_mat, irf_index, max_irf_horizon] = matched_irfs_blocks(matched_irfs, matched_irfs_weight, varobs_id, obs_nbr, exo_nbr, endo_names, exo_names)
|
||||
% -------------------------------------------------------------------------
|
||||
% Checks and transforms matched_irfs and matched_irfs_weight blocks
|
||||
% for further use in the estimation.
|
||||
% -------------------------------------------------------------------------
|
||||
% INPUTS
|
||||
% matched_irfs: [cell array] original matched_irfs block
|
||||
% matched_irfs_weight: [cell array] original matched_irfs_weight block
|
||||
% varobs_id: [vector] index for observable variables in endo_names
|
||||
% obs_nbr: [scalar] number of observable variables
|
||||
% exo_nbr: [scalar] number of exogenous variables
|
||||
% endo_names: [cell array] names of endogenous variables
|
||||
% exo_names: [cell array] names of exogenous variables
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUT
|
||||
% data_irfs: [matrix] IRFs for VAROBS as declared in matched_irfs block
|
||||
% weight_mat: [matrix] weighting matrix for IRFs as declared in matched_irfs_weight block
|
||||
% irf_index: [vector] index for selecting specific IRFs from full IRF matrix of observables
|
||||
% max_irf_horizon: [scalar] maximum IRF horizon as declared in matched_irfs block
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% Copyright © 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/>.
|
||||
|
||||
% note matched_irfs block:
|
||||
% - each row in the cell contains a unique combination of var and varexo,
|
||||
% however the third column in each row is a nested cell with information
|
||||
% on periods, values and weights
|
||||
% - periods, values and weights can span several rows with different lengths of entries
|
||||
% - in some cases we need to duplicate values and/or weights
|
||||
% - at the end we want to have everything vectorized and the same length
|
||||
|
||||
% get maximum IRF horizons
|
||||
max_irf_horizon = [];
|
||||
for jj = 1:size(matched_irfs,1)
|
||||
max_irf_horizon = [max_irf_horizon; cell2mat(cellfun(@(c) c(:), matched_irfs{jj,3}(:,1), 'UniformOutput', false))];
|
||||
end
|
||||
max_irf_horizon = max(max_irf_horizon);
|
||||
|
||||
% create full matrix where 1st dimension are IRF periods, 2nd dimension are variables as declared in VAROBS, 3rd dimension are shocks
|
||||
% idea: overwrite NaN values if they are declared in matched_irfs block; at the end the remaining NaN values will be removed
|
||||
data_irfs = NaN(max_irf_horizon,obs_nbr,exo_nbr);
|
||||
% create full empirical weighting matrix, identity matrix by default, i.e. all IRFs are equally important
|
||||
% idea: first specify full matrix and then reduce it using only entries that are declared in matched_irfs block
|
||||
weight_mat = speye(max_irf_horizon*obs_nbr*exo_nbr);
|
||||
|
||||
for jj = 1:size(matched_irfs,1)
|
||||
id_var = find(ismember(endo_names,matched_irfs{jj,1}));
|
||||
id_varobs = find(varobs_id==id_var,1);
|
||||
id_shock = find(ismember(exo_names,matched_irfs{jj,2}));
|
||||
if isempty(id_varobs)
|
||||
skipline;
|
||||
error('method_of_moments: You specified an IRF matching involving variable %s, but it is not declared as a varobs!',endo_names{id_var})
|
||||
end
|
||||
IRF_PERIODS = []; IRF_VALUES = []; IRF_WEIGHTS = [];
|
||||
for kk = 1:size(matched_irfs{jj,3},1)
|
||||
irf_periods = matched_irfs{jj,3}{kk,1};
|
||||
if length(unique(irf_periods)) < length(irf_periods) % row-specific check for unique periods
|
||||
error('method_of_moments: You specified an IRF matching involving variable %s and shock %s, but there were duplicate ''periods'' in the specification!',endo_names{id_var},exo_names{id_shock});
|
||||
end
|
||||
irf_values = matched_irfs{jj,3}{kk,2};
|
||||
if length(irf_values)==1
|
||||
irf_values = repmat(irf_values,length(irf_periods),1);
|
||||
end
|
||||
if length(irf_periods) ~= length(irf_values) % row-specific check for enough values
|
||||
error('method_of_moments: You specified an IRF matching involving variable %s and shock %s, but the length of ''periods'' does not match the length of ''values''!',endo_names{id_var},exo_names{id_shock});
|
||||
end
|
||||
irf_weights = matched_irfs{jj,3}{kk,3};
|
||||
if length(irf_weights)==1
|
||||
irf_weights = repmat(irf_weights,length(irf_periods),1);
|
||||
end
|
||||
if length(irf_periods) ~= length(irf_weights) % row-specific check for enough weights
|
||||
error('method_of_moments: You specified an IRF matching involving variable %s and shock %s, but the length of ''periods'' does not match the length of ''weights''!',endo_names{id_var},exo_names{id_shock});
|
||||
end
|
||||
IRF_PERIODS = [IRF_PERIODS; irf_periods(:)];
|
||||
IRF_VALUES = [IRF_VALUES; irf_values(:)];
|
||||
IRF_WEIGHTS = [IRF_WEIGHTS; irf_weights(:)];
|
||||
end
|
||||
if length(unique(irf_periods)) < length(irf_periods) % overall check for unique periods
|
||||
error('method_of_moments: You specified an IRF matching involving variable %s and shock %s, but there were duplicate ''periods'' in the specification!',endo_names{id_var},exo_names{id_shock});
|
||||
end
|
||||
for hh = 1:length(IRF_PERIODS)
|
||||
data_irfs(IRF_PERIODS(hh),id_varobs,id_shock) = IRF_VALUES(hh);
|
||||
if IRF_WEIGHTS(hh) ~= 1
|
||||
idweight_mat = sub2ind(size(data_irfs),IRF_PERIODS(hh),id_varobs,id_shock);
|
||||
weight_mat(idweight_mat,idweight_mat) = IRF_WEIGHTS(hh);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
% fine-tune weighting matrix using matched_irfs_weights
|
||||
for jj = 1:size(matched_irfs_weight,1)
|
||||
id_var1 = find(ismember(endo_names,matched_irfs_weight{jj,1}));
|
||||
id_var2 = find(ismember(endo_names,matched_irfs_weight{jj,4}));
|
||||
id_varobs1 = find(varobs_id==id_var1,1);
|
||||
id_varobs2 = find(varobs_id==id_var2,1);
|
||||
if isempty(id_varobs1)
|
||||
skipline;
|
||||
error('method_of_moments: You specified a weight for an IRF matching involving variable %s, but it is not a varobs!',endo_names{id_var1})
|
||||
end
|
||||
if isempty(id_varobs2)
|
||||
skipline;
|
||||
error('method_of_moments: You specified a weight for an IRF matching involving variable %s, but it is not a varobs!',endo_names{id_var2})
|
||||
end
|
||||
id_shock1 = find(ismember(exo_names,matched_irfs_weight{jj,3}));
|
||||
id_shock2 = find(ismember(exo_names,matched_irfs_weight{jj,6}));
|
||||
irf_periods1 = matched_irfs_weight{jj,2};
|
||||
irf_periods2 = matched_irfs_weight{jj,5};
|
||||
if length(irf_periods1) ~= length(irf_periods2)
|
||||
error('method_of_moments: You specified a ''matched_irfs_weights'' entry for an IRF matching involving %s/%s and %s/%s,\n but the horizons do not have the same length!',endo_names{id_var1},exo_names{id_shock1},endo_names{id_var2},exo_names{id_shock2});
|
||||
end
|
||||
if max([irf_periods1(:);irf_periods2(:)]) > max_irf_horizon
|
||||
error('method_of_moments: You specified a ''matched_irfs_weights'' entry for an IRF matching involving %s/%s and %s/%s,\n but the horizon is larger than the maximum one declared in the ''matched_irfs'' block!',endo_names{id_var1},exo_names{id_shock1},endo_names{id_var2},exo_names{id_shock2});
|
||||
end
|
||||
weight_mat_values = matched_irfs_weight{jj,7};
|
||||
if length(weight_mat_values)==1 && length(irf_periods1)>1
|
||||
weight_mat_values = repmat(weight_mat_values,length(irf_periods1),1);
|
||||
end
|
||||
if length(weight_mat_values) ~= length(irf_periods1)
|
||||
error('method_of_moments: You specified a ''matched_irfs_weights'' entry for an IRF matching involving %s/%s and %s/%s,\n but the horizons do not match the length of ''weights''!',endo_names{id_var1},exo_names{id_shock1},endo_names{id_var2},exo_names{id_shock2});
|
||||
end
|
||||
for hh = 1:length(irf_periods1)
|
||||
idweight_mat1 = sub2ind(size(data_irfs),irf_periods1(hh),id_varobs1,id_shock1);
|
||||
idweight_mat2 = sub2ind(size(data_irfs),irf_periods2(hh),id_varobs2,id_shock2);
|
||||
weight_mat(idweight_mat1,idweight_mat2) = weight_mat_values(hh);
|
||||
weight_mat(idweight_mat2,idweight_mat1) = weight_mat_values(hh); % symmetry
|
||||
end
|
||||
end
|
||||
|
||||
% remove non-specified IRFs
|
||||
irf_index = find(~isnan(data_irfs));
|
||||
data_irfs = data_irfs(irf_index);
|
||||
weight_mat = weight_mat(irf_index,irf_index);
|
|
@ -1,8 +1,8 @@
|
|||
function matched_moments = matched_moments_block(matched_moments, mom_method)
|
||||
% matched_moments = matched_moments_block(matched_moments, mom_method)
|
||||
% -------------------------------------------------------------------------
|
||||
% Checks and transforms matched_moments block for further use in the estimation
|
||||
% function matched_moments = matched_moments_block(matched_moments, mom_method)
|
||||
% -------------------------------------------------------------------------
|
||||
% Checks and transforms matched_moments bock for further use in the estimation
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% matched_moments: [cell array] original matched_moments block
|
||||
% mom_method: [string] method of moments method (GMM or SMM)
|
||||
|
@ -12,8 +12,7 @@ function matched_moments = matched_moments_block(matched_moments, mom_method)
|
|||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% =========================================================================
|
||||
% Copyright © 2023 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -30,7 +29,7 @@ function matched_moments = matched_moments_block(matched_moments, mom_method)
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
% =========================================================================
|
||||
|
||||
matched_moments_orig = matched_moments;
|
||||
% higher-order product moments not supported yet for GMM
|
||||
|
@ -60,22 +59,22 @@ for jm = 1:size(matched_moments,1)
|
|||
end
|
||||
% find duplicate rows in cell array by making groups according to powers as we can then use cell2mat for the unique function
|
||||
powers = cellfun(@sum,matched_moments(:,3))';
|
||||
unique_mom_idx = [];
|
||||
UniqueMomIdx = [];
|
||||
for jpow = unique(powers)
|
||||
idx1 = find(powers==jpow);
|
||||
[~,idx2] = unique(cell2mat(matched_moments(idx1,:)),'rows');
|
||||
unique_mom_idx = [unique_mom_idx idx1(idx2)];
|
||||
UniqueMomIdx = [UniqueMomIdx idx1(idx2)];
|
||||
end
|
||||
% remove duplicate elements
|
||||
duplicate_moms = setdiff(1:size(matched_moments_orig,1),unique_mom_idx);
|
||||
if ~isempty(duplicate_moms)
|
||||
fprintf('Duplicate declared moments found and removed in ''matched_moments'' block in rows:\n %s.\n',num2str(duplicate_moms));
|
||||
DuplicateMoms = setdiff(1:size(matched_moments_orig,1),UniqueMomIdx);
|
||||
if ~isempty(DuplicateMoms)
|
||||
fprintf('Duplicate declared moments found and removed in ''matched_moments'' block in rows:\n %s.\n',num2str(DuplicateMoms))
|
||||
fprintf('Dynare will continue with remaining moment conditions\n');
|
||||
end
|
||||
if strcmp(mom_method, 'SMM')
|
||||
% for SMM: keep the original structure, but get rid of duplicate moments
|
||||
matched_moments = matched_moments_orig(sort(unique_mom_idx),:);
|
||||
matched_moments = matched_moments_orig(sort(UniqueMomIdx),:);
|
||||
elseif strcmp(mom_method, 'GMM')
|
||||
% for GMM we use the transformed matched_moments structure
|
||||
matched_moments = matched_moments(sort(unique_mom_idx),:);
|
||||
matched_moments = matched_moments(sort(UniqueMomIdx),:);
|
||||
end
|
|
@ -1,30 +1,25 @@
|
|||
function [xparam1, weighting_info, mom_verbose] = mode_compute_gmm_smm(xparam0, objective_function, m_data, data_moments, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
|
||||
% [xparam1, weighting_info, mom_verbose] = mode_compute_gmm_smm(xparam0, objective_function, m_data, data_moments, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
|
||||
function [xparam1, oo_, Woptflag] = mode_compute_gmm_smm(xparam0, objective_function, oo_, M_, options_mom_, estim_params_, bayestopt_, Bounds)
|
||||
% function [xparam1, oo_, Woptflag] = mode_compute_gmm_smm(xparam0, objective_function, oo_, M_, options_mom_, estim_params_, bayestopt_, Bounds)
|
||||
% -------------------------------------------------------------------------
|
||||
% Iterated method of moments for GMM and SMM, computes the minimum of the
|
||||
% objective function (distance between data moments and model moments)
|
||||
% for a sequence of optimizers and GMM/SMM iterations with different
|
||||
% weighting matrices.
|
||||
% -------------------------------------------------------------------------
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% xparam0: [vector] vector of initialized parameters
|
||||
% objective_function: [func handle] name of the objective function
|
||||
% m_data: [matrix] selected data moments at each point in time
|
||||
% data_moments: [vector] vector of data moments
|
||||
% options_mom_: [structure] options
|
||||
% M_: [structure] model information
|
||||
% estim_params_: [structure] information on estimated parameters
|
||||
% bayestopt_: [structure] information on priors
|
||||
% BoundsInfo: [structure] bounds for optimization
|
||||
% dr: [structure] reduced form model
|
||||
% endo_steady_state: [vector] steady state for endogenous variables (initval)
|
||||
% exo_steady_state: [vector] steady state for exogenous variables (initval)
|
||||
% exo_det_steady_state: [vector] steady state for exogenous deterministic variables (initval)
|
||||
% xparam0: [vector] vector of initialized parameters
|
||||
% objective_function: [func handle] name of the objective function
|
||||
% oo_: [structure] results
|
||||
% M_: [structure] model information
|
||||
% options_mom_: [structure] options
|
||||
% estim_params_: [structure] information on estimated parameters
|
||||
% bayestopt_: [structure] information on priors
|
||||
% Bounds: [structure] bounds for optimization
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUT
|
||||
% xparam1: [vector] mode of objective function
|
||||
% weighting_info: [structure] information on weighting matrix
|
||||
% mom_verbose: [structure] information on intermediate estimation results
|
||||
% xparam1: [vector] mode of objective function
|
||||
% oo_: [structure] updated results
|
||||
% Woptflag: [logical] true if optimal weighting matrix was computed
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
|
@ -34,9 +29,7 @@ function [xparam1, weighting_info, mom_verbose] = mode_compute_gmm_smm(xparam0,
|
|||
% o mom.display_estimation_results_table
|
||||
% o dynare_minimize_objective
|
||||
% o mom.objective_function
|
||||
% o prior_dist_names
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% =========================================================================
|
||||
% Copyright © 2023 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -53,16 +46,15 @@ function [xparam1, weighting_info, mom_verbose] = mode_compute_gmm_smm(xparam0,
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
% =========================================================================
|
||||
|
||||
|
||||
mom_verbose = [];
|
||||
if size(options_mom_.mom.weighting_matrix,1)>1 && ~(any(strcmpi('diagonal',options_mom_.mom.weighting_matrix)) || any(strcmpi('optimal',options_mom_.mom.weighting_matrix)))
|
||||
fprintf('\nYou did not specify the use of an optimal or diagonal weighting matrix. There is no point in running an iterated method of moments.\n');
|
||||
fprintf('\nYou did not specify the use of an optimal or diagonal weighting matrix. There is no point in running an iterated method of moments.\n')
|
||||
end
|
||||
|
||||
for stage_iter = 1:size(options_mom_.mom.weighting_matrix,1)
|
||||
fprintf('Estimation stage %u\n',stage_iter);
|
||||
weighting_info.Woptflag = false;
|
||||
Woptflag = false;
|
||||
switch lower(options_mom_.mom.weighting_matrix{stage_iter})
|
||||
case 'identity_matrix'
|
||||
fprintf(' - identity weighting matrix\n');
|
||||
|
@ -71,44 +63,44 @@ for stage_iter = 1:size(options_mom_.mom.weighting_matrix,1)
|
|||
fprintf(' - diagonal of optimal weighting matrix (Bartlett kernel with %d lags)\n', options_mom_.mom.bartlett_kernel_lag);
|
||||
if stage_iter == 1
|
||||
fprintf(' and using data-moments as initial estimate of model-moments\n');
|
||||
weighting_matrix = diag(diag( mom.optimal_weighting_matrix(m_data, data_moments, options_mom_.mom.bartlett_kernel_lag) ));
|
||||
weighting_matrix = diag(diag( mom.optimal_weighting_matrix(oo_.mom.m_data, oo_.mom.data_moments, options_mom_.mom.bartlett_kernel_lag) ));
|
||||
else
|
||||
fprintf(' and using previous stage estimate of model-moments\n');
|
||||
weighting_matrix = diag(diag( mom.optimal_weighting_matrix(m_data, model_moments, options_mom_.mom.bartlett_kernel_lag) ));
|
||||
weighting_matrix = diag(diag( mom.optimal_weighting_matrix(oo_.mom.m_data, oo_.mom.model_moments, options_mom_.mom.bartlett_kernel_lag) ));
|
||||
end
|
||||
case 'optimal'
|
||||
fprintf(' - optimal weighting matrix (Bartlett kernel with %d lags)\n', options_mom_.mom.bartlett_kernel_lag);
|
||||
if stage_iter == 1
|
||||
fprintf(' and using data-moments as initial estimate of model-moments\n');
|
||||
weighting_matrix = mom.optimal_weighting_matrix(m_data, data_moments, options_mom_.mom.bartlett_kernel_lag);
|
||||
weighting_matrix = mom.optimal_weighting_matrix(oo_.mom.m_data, oo_.mom.data_moments, options_mom_.mom.bartlett_kernel_lag);
|
||||
else
|
||||
fprintf(' and using previous stage estimate of model-moments\n');
|
||||
weighting_matrix = mom.optimal_weighting_matrix(m_data, model_moments, options_mom_.mom.bartlett_kernel_lag);
|
||||
weighting_info.Woptflag = true;
|
||||
weighting_matrix = mom.optimal_weighting_matrix(oo_.mom.m_data, oo_.mom.model_moments, options_mom_.mom.bartlett_kernel_lag);
|
||||
Woptflag = true;
|
||||
end
|
||||
otherwise % user specified matrix in file
|
||||
fprintf(' - user-specified weighting matrix\n');
|
||||
try
|
||||
load(options_mom_.mom.weighting_matrix{stage_iter},'weighting_matrix')
|
||||
catch
|
||||
error(['method_of_moments: No matrix named ''weighting_matrix'' could be found in ',options_mom_.mom.weighting_matrix{stage_iter},'.mat !']);
|
||||
error(['method_of_moments: No matrix named ''weighting_matrix'' could be found in ',options_mom_.mom.weighting_matrix{stage_iter},'.mat !'])
|
||||
end
|
||||
[nrow, ncol] = size(weighting_matrix);
|
||||
if ~isequal(nrow,ncol) || ~isequal(nrow,length(data_moments)) %check if square and right size
|
||||
error(['method_of_moments: ''weighting_matrix'' must be square and have ',num2str(length(data_moments)),' rows and columns!']);
|
||||
if ~isequal(nrow,ncol) || ~isequal(nrow,length(oo_.mom.data_moments)) %check if square and right size
|
||||
error(['method_of_moments: ''weighting_matrix'' must be square and have ',num2str(length(oo_.mom.data_moments)),' rows and columns!'])
|
||||
end
|
||||
end
|
||||
try % check for positive definiteness of weighting_matrix
|
||||
weighting_info.Sw = chol(weighting_matrix);
|
||||
oo_.mom.Sw = chol(weighting_matrix);
|
||||
catch
|
||||
error('method_of_moments: Specified ''weighting_matrix'' is not positive definite. Check whether your model implies stochastic singularity!');
|
||||
error('method_of_moments: Specified ''weighting_matrix'' is not positive definite. Check whether your model implies stochastic singularity!')
|
||||
end
|
||||
|
||||
for optim_iter = 1:length(options_mom_.optimizer_vec)
|
||||
options_mom_.current_optimizer = options_mom_.optimizer_vec{optim_iter};
|
||||
if options_mom_.optimizer_vec{optim_iter} == 0
|
||||
xparam1 = xparam0; % no minimization, evaluate objective at current values
|
||||
fval = feval(objective_function, xparam1, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
|
||||
xparam1 = xparam0; % no minimization, evaluate objective at current values
|
||||
fval = feval(objective_function, xparam1, Bounds, oo_, estim_params_, M_, options_mom_);
|
||||
else
|
||||
if options_mom_.optimizer_vec{optim_iter} == 13
|
||||
options_mom_.mom.vector_output = true;
|
||||
|
@ -120,22 +112,18 @@ for stage_iter = 1:size(options_mom_.mom.weighting_matrix,1)
|
|||
else
|
||||
options_mom_.mom.compute_derivs = false;
|
||||
end
|
||||
[xparam1, fval] = dynare_minimize_objective(objective_function, xparam0, options_mom_.optimizer_vec{optim_iter}, options_mom_, [BoundsInfo.lb BoundsInfo.ub], bayestopt_.name, bayestopt_, [],...
|
||||
data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
|
||||
[xparam1, fval, exitflag] = dynare_minimize_objective(objective_function, xparam0, options_mom_.optimizer_vec{optim_iter}, options_mom_, [Bounds.lb Bounds.ub], bayestopt_.name, bayestopt_, [],...
|
||||
Bounds, oo_, estim_params_, M_, options_mom_);
|
||||
if options_mom_.mom.vector_output
|
||||
fval = fval'*fval;
|
||||
end
|
||||
end
|
||||
fprintf('\nStage %d Iteration %d: Value of minimized moment distance objective function: %12.10f.\n',stage_iter,optim_iter,fval);
|
||||
fprintf('\nStage %d Iteration %d: Value of minimized moment distance objective function: %12.10f.\n',stage_iter,optim_iter,fval)
|
||||
if options_mom_.mom.verbose
|
||||
fprintf('\n''verbose'' option: ');
|
||||
std_via_invhessian_xparam1_iter = NaN(size(xparam1));
|
||||
tbl_title_iter = sprintf('FREQUENTIST %s (STAGE %d ITERATION %d) VERBOSE',options_mom_.mom.mom_method,stage_iter,optim_iter);
|
||||
field_name_iter = sprintf('%s_stage_%d_iter_%d',lower(options_mom_.mom.mom_method),stage_iter,optim_iter);
|
||||
mom_verbose.(field_name_iter) = display_estimation_results_table(xparam1,std_via_invhessian_xparam1_iter,M_,options_mom_,estim_params_,bayestopt_,[],prior_dist_names,tbl_title_iter,field_name_iter);
|
||||
oo_.mom = display_estimation_results_table(xparam1,NaN(size(xparam1)),M_,options_mom_,estim_params_,bayestopt_,oo_.mom,prior_dist_names,sprintf('%s (STAGE %d ITERATION %d) VERBOSE',options_mom_.mom.mom_method,stage_iter,optim_iter),sprintf('verbose_%s_stage_%d_iter_%d',lower(options_mom_.mom.mom_method),stage_iter,optim_iter));
|
||||
end
|
||||
xparam0 = xparam1;
|
||||
end
|
||||
options_mom_.vector_output = false;
|
||||
[~, ~, ~, ~, ~, ~, model_moments] = feval(objective_function, xparam1, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state); % get model_moments for iterated GMM/SMM to compute optimal weighting matrix
|
||||
end
|
||||
[~, ~, ~,~,~, oo_] = feval(objective_function, xparam1, Bounds, oo_, estim_params_, M_, options_mom_); % get oo_.mom.model_moments for iterated GMM/SMM to compute optimal weighting matrix
|
||||
end
|
|
@ -1,122 +0,0 @@
|
|||
function [xparam1, hessian_xparam1, fval, mom_verbose] = mode_compute_irf_matching(xparam0, hessian_xparam0, objective_function, doBayesianEstimation, weighting_info, data_moments, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
|
||||
% [xparam1, hessian_xparam1, fval, mom_verbose] = mode_compute_irf_matching(xparam0, hessian_xparam0, objective_function, doBayesianEstimation, weighting_info, data_moments, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
|
||||
% -------------------------------------------------------------------------
|
||||
% Computes the minimum of the objective function (distance between data IRFs
|
||||
% and model IRFs) for a sequence of optimizers.
|
||||
% Note that we call a "mode" the minimum of the objective function, i.e.
|
||||
% the parameter vector that minimizes the distance between the IRFs
|
||||
% computed from the model and the IRFs computed from the data.
|
||||
% -------------------------------------------------------------------------
|
||||
% INPUTS
|
||||
% xparam0: [vector] initialized parameters
|
||||
% hessian_xparam0: [matrix] initialized hessian at xparam0
|
||||
% objective_function: [func handle] name of the objective function
|
||||
% doBayesianEstimation: [logical] true if Bayesian estimation
|
||||
% weighting_info: [structure] information on weighting matrix
|
||||
% data_moments: [vector] data moments
|
||||
% options_mom_: [structure] options
|
||||
% M_: [structure] model information
|
||||
% estim_params_: [structure] information on estimated parameters
|
||||
% bayestopt_: [structure] information on priors
|
||||
% BoundsInfo: [structure] bounds for optimization
|
||||
% dr: [structure] information reduced-form model
|
||||
% endo_steady_state: [vector] steady state of endogenous variables (initval)
|
||||
% exo_steady_state: [vector] steady state of exogenous variables (initval)
|
||||
% exo_det_steady_state: [vector] steady state of deterministic exogenous variables (initval)
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUT
|
||||
% xparam1: [vector] mode of objective function
|
||||
% hessian_xparam1: [matrix] hessian at xparam1
|
||||
% fval: [double] function value at mode
|
||||
% mom_verbose: [structure] information on intermediate estimation results
|
||||
% Also saves the computed mode and hessian to a file.
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
% -------------------------------------------------------------------------
|
||||
% This function calls
|
||||
% o display_estimation_results_table
|
||||
% o dynare_minimize_objective
|
||||
% o hessian
|
||||
% o mom.objective_function
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% Copyright © 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/>.
|
||||
|
||||
|
||||
mom_verbose = [];
|
||||
for optim_iter = 1:length(options_mom_.optimizer_vec)
|
||||
options_mom_.current_optimizer = options_mom_.optimizer_vec{optim_iter};
|
||||
if options_mom_.optimizer_vec{optim_iter}==0
|
||||
% no minimization, evaluate objective at current values
|
||||
xparam1 = xparam0;
|
||||
hessian_xparam1 = hessian_xparam0;
|
||||
fval = feval(objective_function, xparam1, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
|
||||
else
|
||||
[xparam1, fval, exitflag, hessian_xparam1, options_mom_, Scale, new_rat_hess_info] = dynare_minimize_objective(objective_function, xparam0, options_mom_.optimizer_vec{optim_iter}, options_mom_, [BoundsInfo.lb BoundsInfo.ub], bayestopt_.name, bayestopt_, hessian_xparam0,...
|
||||
data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
|
||||
end
|
||||
fprintf('\nMode Compute Iteration %d: Value of minimized moment distance objective function: %12.10f.\n',optim_iter,fval);
|
||||
if options_mom_.mom.verbose
|
||||
fprintf('\n''verbose'' option: ');
|
||||
if options_mom_.cova_compute
|
||||
if options_mom_.optimizer_vec{optim_iter}==0
|
||||
hessian_xparam1_iter = hessian_xparam1;
|
||||
else
|
||||
fprintf('computing Hessian');
|
||||
hessian_xparam1_iter = hessian(objective_function, xparam1, options_mom_.gstep,...
|
||||
data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
|
||||
hessian_xparam1_iter = reshape(hessian_xparam1_iter, length(xparam1), length(xparam1));
|
||||
end
|
||||
hsd_iter = sqrt(diag(hessian_xparam1_iter));
|
||||
invhessian_xparam1_iter = inv(hessian_xparam1_iter./(hsd_iter*hsd_iter'))./(hsd_iter*hsd_iter');
|
||||
std_via_invhessian_xparam1_iter = sqrt(diag(invhessian_xparam1_iter));
|
||||
else
|
||||
std_via_invhessian_xparam1_iter = NaN(size(xparam1));
|
||||
end
|
||||
fprintf(' and displaying intermediate results.');
|
||||
if doBayesianEstimation
|
||||
tbl_title_iter = sprintf('BAYESIAN %s (OPTIM ITERATION %d) VERBOSE',strrep(options_mom_.mom.mom_method,'_',' '),optim_iter);
|
||||
field_name_iter = sprintf('posterior_iter_%d',optim_iter);
|
||||
else
|
||||
tbl_title_iter = sprintf('FREQUENTIST %s (OPTIM ITERATION %d) VERBOSE',strrep(options_mom_.mom.mom_method,'_',' '),optim_iter);
|
||||
field_name_iter = sprintf('iter_%d',optim_iter);
|
||||
end
|
||||
mom_verbose.(field_name_iter) = display_estimation_results_table(xparam1,std_via_invhessian_xparam1_iter,M_,options_mom_,estim_params_,bayestopt_,[],prior_dist_names,tbl_title_iter,field_name_iter);
|
||||
end
|
||||
xparam0 = xparam1;
|
||||
hessian_xparam0 = hessian_xparam1;
|
||||
end
|
||||
|
||||
if options_mom_.cova_compute
|
||||
if options_mom_.mom.verbose
|
||||
hessian_xparam1 = hessian_xparam1_iter;
|
||||
else
|
||||
fprintf('\nComputing Hessian at the mode.\n');
|
||||
hessian_xparam1 = hessian(objective_function, xparam1, options_mom_.gstep,...
|
||||
data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
|
||||
hessian_xparam1 = reshape(hessian_xparam1, length(xparam1), length(xparam1));
|
||||
end
|
||||
end
|
||||
parameter_names = bayestopt_.name;
|
||||
if options_mom_.cova_compute || options_mom_.mode_compute==5 || options_mom_.mode_compute==6
|
||||
hh = hessian_xparam1;
|
||||
save([M_.dname filesep 'method_of_moments' filesep M_.fname '_mode.mat'],'xparam1','hh','parameter_names','fval');
|
||||
else
|
||||
save([M_.dname filesep 'method_of_moments' filesep M_.fname '_mode.mat'],'xparam1','parameter_names','fval');
|
||||
end
|
|
@ -1,33 +1,27 @@
|
|||
function [fval, info, exit_flag, df, junk_hessian, Q, model_moments, model_moments_params_derivs, irf_model_varobs] = objective_function(xparam, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
|
||||
% [fval, info, exit_flag, df, junk_hessian, Q, model_moments, model_moments_params_derivs, irf_model_varobs] = objective_function(xparam, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
|
||||
function [fval, info, exit_flag, df, junkHessian, oo_, M_] = objective_function(xparam, Bounds, oo_, estim_params_, M_, options_mom_)
|
||||
% [fval, info, exit_flag, df, junk1, oo_, M_] = objective_function(xparam, Bounds, oo_, estim_params_, M_, options_mom_)
|
||||
% -------------------------------------------------------------------------
|
||||
% This function evaluates the objective function for method of moments estimation,
|
||||
% i.e. distance between model and data moments/IRFs, possibly augmented with priors.
|
||||
% -------------------------------------------------------------------------
|
||||
% INPUTS (same ones as in dsge_likelihood.m and dsge_var_likelihood.m)
|
||||
% - xparam: [vector] current value of estimated parameters as returned by set_prior()
|
||||
% - data_moments: [vector] data with moments/IRFs to match (corresponds to dataset_ in likelihood-based estimation)
|
||||
% - weighting_info: [structure] storing information on weighting matrices (corresponds to dataset_info in likelihood-based estimation)
|
||||
% - options_mom_: [structure] information about all settings (specified by the user, preprocessor, and taken from global options_)
|
||||
% - M_ [structure] model information
|
||||
% - estim_params_: [structure] information from estimated_params block
|
||||
% - bayestopt_: [structure] information on the prior distributions
|
||||
% - BoundsInfo: [structure] parameter bounds
|
||||
% - dr: [structure] reduced form model
|
||||
% - endo_steady_state: [vector] steady state value for endogenous variables (initval)
|
||||
% - exo_steady_state: [vector] steady state value for exogenous variables (initval)
|
||||
% - exo_det_steady_state: [vector] steady state value for exogenous deterministic variables (initval)
|
||||
% This function evaluates the objective function for method of moments estimation
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% o xparam: [vector] current value of estimated parameters as returned by set_prior()
|
||||
% o Bounds: [structure] containing parameter bounds
|
||||
% o oo_: [structure] for results
|
||||
% o estim_params_: [structure] describing the estimated_parameters
|
||||
% o M_ [structure] describing the model
|
||||
% o options_mom_: [structure] information about all settings (specified by the user, preprocessor, and taken from global options_)
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUTS
|
||||
% - fval: [double] value of the quadratic form of the moment difference (except for lsqnonlin, where this is done implicitly)
|
||||
% - info: [vector] information on error codes and penalties
|
||||
% - exit_flag: [double] flag for exit status (0 if error, 1 if no error)
|
||||
% - df: [matrix] analytical jacobian of the moment difference (wrt paramters), currently for GMM only
|
||||
% - junk_hessian: [matrix] empty matrix required for optimizer interface (Hessian would typically go here)
|
||||
% - Q: [double] value of the quadratic form of the moment difference
|
||||
% - model_moments: [vector] model moments
|
||||
% - model_moments_params_derivs: [matrix] analytical jacobian of the model moments wrt estimated parameters (currently for GMM only)
|
||||
% - irf_model_varobs: [matrix] model IRFs for observable variables (used for plotting matched IRfs in mom.run)
|
||||
% o fval: [double] value of the quadratic form of the moment difference (except for lsqnonlin, where this is done implicitly)
|
||||
% o info: [vector] information on error codes and penalties
|
||||
% o exit_flag: [double] flag for exit status (0 if error, 1 if no error)
|
||||
% o df: [matrix] analytical jacobian of the moment difference (wrt paramters), currently for GMM only
|
||||
% o junkHessian: [matrix] empty matrix required for optimizer interface (Hessian would typically go here)
|
||||
% o oo_: [structure] results with the following updated fields:
|
||||
% - oo_.mom.model_moments: [vector] model moments
|
||||
% - oo_.mom.Q: [double] value of the quadratic form of the moment difference
|
||||
% - oo_.mom.model_moments_params_derivs: [matrix] analytical jacobian of the model moments wrt estimated parameters (currently for GMM only)
|
||||
% o M_: [structure] updated model structure
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
|
@ -35,18 +29,13 @@ function [fval, info, exit_flag, df, junk_hessian, Q, model_moments, model_momen
|
|||
% -------------------------------------------------------------------------
|
||||
% This function calls
|
||||
% o check_bounds_and_definiteness_estimation
|
||||
% o get_lower_cholesky_covariance
|
||||
% o get_perturbation_params_derivs
|
||||
% o getIrfShocksIndx
|
||||
% o irf
|
||||
% o mom.get_data_moments
|
||||
% o priordens
|
||||
% o pruned_state_space_system
|
||||
% o resol
|
||||
% o set_all_parameters
|
||||
% o simult_
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% =========================================================================
|
||||
% Copyright © 2020-2023 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -63,27 +52,28 @@ function [fval, info, exit_flag, df, junk_hessian, Q, model_moments, model_momen
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
% =========================================================================
|
||||
|
||||
%% TO DO
|
||||
% check the info values and make use of meaningful penalties
|
||||
% how do we do the penalty for the prior??
|
||||
|
||||
|
||||
%------------------------------------------------------------------------------
|
||||
% Initialization of the returned variables and others...
|
||||
%------------------------------------------------------------------------------
|
||||
irf_model_varobs = [];
|
||||
model_moments_params_derivs = [];
|
||||
model_moments = [];
|
||||
Q = [];
|
||||
junk_hessian = [];
|
||||
junkHessian = [];
|
||||
df = []; % required to be empty by e.g. newrat
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_jacobian
|
||||
if options_mom_.mom.vector_output == 1
|
||||
if options_mom_.mom.penalized_estimator
|
||||
df = NaN(options_mom_.mom.mom_nbr+length(xparam),length(xparam));
|
||||
df = nan(size(oo_.mom.data_moments,1)+length(xparam),length(xparam));
|
||||
else
|
||||
df = NaN(options_mom_.mom.mom_nbr,length(xparam));
|
||||
df = nan(size(oo_.mom.data_moments,1),length(xparam));
|
||||
end
|
||||
else
|
||||
df = NaN(length(xparam),1);
|
||||
df = nan(length(xparam),1);
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -92,13 +82,14 @@ end
|
|||
%--------------------------------------------------------------------------
|
||||
% Get the structural parameters and define penalties
|
||||
%--------------------------------------------------------------------------
|
||||
|
||||
% Ensure that xparam1 is a column vector; particleswarm.m requires this.
|
||||
xparam = xparam(:);
|
||||
M_ = set_all_parameters(xparam, estim_params_, M_);
|
||||
[fval,info,exit_flag] = check_bounds_and_definiteness_estimation(xparam, M_, estim_params_, BoundsInfo);
|
||||
[fval,info,exit_flag] = check_bounds_and_definiteness_estimation(xparam, M_, estim_params_, Bounds);
|
||||
if info(1)
|
||||
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
|
||||
fval = ones(options_mom_.mom.mom_nbr,1)*options_mom_.huge_number;
|
||||
fval = ones(size(oo_.mom.data_moments,1),1)*options_mom_.huge_number;
|
||||
end
|
||||
return
|
||||
end
|
||||
|
@ -107,8 +98,9 @@ end
|
|||
%--------------------------------------------------------------------------
|
||||
% Call resol to compute steady state and model solution
|
||||
%--------------------------------------------------------------------------
|
||||
|
||||
% Compute linear approximation around the deterministic steady state
|
||||
[dr, info, M_.params] = resol(0, M_, options_mom_, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
|
||||
[oo_.dr, info, M_.params] = resol(0, M_, options_mom_, oo_.dr ,oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
|
||||
% Return, with endogenous penalty when possible, if resol issues an error code
|
||||
if info(1)
|
||||
if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 ||...
|
||||
|
@ -119,7 +111,7 @@ if info(1)
|
|||
info(4) = info(2);
|
||||
exit_flag = 0;
|
||||
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
|
||||
fval = ones(options_mom_.mom.mom_nbr,1)*options_mom_.huge_number;
|
||||
fval = ones(size(oo_.mom.data_moments,1),1)*options_mom_.huge_number;
|
||||
end
|
||||
return
|
||||
else
|
||||
|
@ -127,7 +119,7 @@ if info(1)
|
|||
info(4) = 0.1;
|
||||
exit_flag = 0;
|
||||
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
|
||||
fval = ones(options_mom_.mom.mom_nbr,1)*options_mom_.huge_number;
|
||||
fval = ones(size(oo_.mom.data_moments,1),1)*options_mom_.huge_number;
|
||||
end
|
||||
return
|
||||
end
|
||||
|
@ -152,44 +144,44 @@ if strcmp(options_mom_.mom.mom_method,'GMM')
|
|||
indpcorr = estim_params_.corrx(:,1:2); % values correspond to varexo declaration order, row number corresponds to order in estimated_params
|
||||
end
|
||||
if estim_params_.nvn || estim_params_.ncn % nvn is number of stderr parameters and ncn is number of corr parameters of measurement innovations as declared in estimated_params
|
||||
error('Analytic computation of standard errrors does not (yet) support measurement errors.\nInstead, define them explicitly as varexo and provide measurement equations in the model definition.\nAlternatively, use numerical standard errors.');
|
||||
error('Analytic computation of standard errrors does not (yet) support measurement errors.\nInstead, define them explicitly as varexo and provide measurement equations in the model definition.\nAlternatively, use numerical standard errors.')
|
||||
end
|
||||
modparam_nbr = estim_params_.np; % number of model parameters as declared in estimated_params
|
||||
stderrparam_nbr = estim_params_.nvx; % number of stderr parameters
|
||||
corrparam_nbr = estim_params_.ncx; % number of corr parameters
|
||||
totparam_nbr = stderrparam_nbr+corrparam_nbr+modparam_nbr;
|
||||
dr.derivs = identification.get_perturbation_params_derivs(M_, options_mom_, estim_params_, dr, endo_steady_state, exo_steady_state, exo_det_steady_state, indpmodel, indpstderr, indpcorr, 0); %analytic derivatives of perturbation matrices
|
||||
model_moments_params_derivs = NaN(options_mom_.mom.mom_nbr,totparam_nbr);
|
||||
pruned_state_space = pruned_SS.pruned_state_space_system(M_, options_mom_, dr, options_mom_.mom.obs_var, options_mom_.ar, 0, 1);
|
||||
oo_.dr.derivs = get_perturbation_params_derivs(M_, options_mom_, estim_params_, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state, indpmodel, indpstderr, indpcorr, 0); %analytic derivatives of perturbation matrices
|
||||
oo_.mom.model_moments_params_derivs = NaN(options_mom_.mom.mom_nbr,totparam_nbr);
|
||||
pruned_state_space = pruned_state_space_system(M_, options_mom_, oo_.dr, oo_.mom.obs_var, options_mom_.ar, 0, 1);
|
||||
else
|
||||
pruned_state_space = pruned_SS.pruned_state_space_system(M_, options_mom_, dr, options_mom_.mom.obs_var, options_mom_.ar, 0, 0);
|
||||
pruned_state_space = pruned_state_space_system(M_, options_mom_, oo_.dr, oo_.mom.obs_var, options_mom_.ar, 0, 0);
|
||||
end
|
||||
model_moments = NaN(options_mom_.mom.mom_nbr,1);
|
||||
oo_.mom.model_moments = NaN(options_mom_.mom.mom_nbr,1);
|
||||
for jm = 1:size(M_.matched_moments,1)
|
||||
% First moments
|
||||
if ~options_mom_.prefilter && (sum(M_.matched_moments{jm,3}) == 1)
|
||||
idx1 = (options_mom_.mom.obs_var == find(dr.order_var==M_.matched_moments{jm,1}) );
|
||||
model_moments(jm,1) = pruned_state_space.E_y(idx1);
|
||||
idx1 = (oo_.mom.obs_var == find(oo_.dr.order_var==M_.matched_moments{jm,1}) );
|
||||
oo_.mom.model_moments(jm,1) = pruned_state_space.E_y(idx1);
|
||||
if options_mom_.mom.compute_derivs && ( options_mom_.mom.analytic_standard_errors || options_mom_.mom.analytic_jacobian )
|
||||
model_moments_params_derivs(jm,:) = pruned_state_space.dE_y(idx1,:);
|
||||
oo_.mom.model_moments_params_derivs(jm,:) = pruned_state_space.dE_y(idx1,:);
|
||||
end
|
||||
end
|
||||
% second moments
|
||||
if (sum(M_.matched_moments{jm,3}) == 2)
|
||||
idx1 = (options_mom_.mom.obs_var == find(dr.order_var==M_.matched_moments{jm,1}(1)) );
|
||||
idx2 = (options_mom_.mom.obs_var == find(dr.order_var==M_.matched_moments{jm,1}(2)) );
|
||||
idx1 = (oo_.mom.obs_var == find(oo_.dr.order_var==M_.matched_moments{jm,1}(1)) );
|
||||
idx2 = (oo_.mom.obs_var == find(oo_.dr.order_var==M_.matched_moments{jm,1}(2)) );
|
||||
if nnz(M_.matched_moments{jm,2}) == 0
|
||||
% covariance
|
||||
if options_mom_.prefilter
|
||||
model_moments(jm,1) = pruned_state_space.Var_y(idx1,idx2);
|
||||
oo_.mom.model_moments(jm,1) = pruned_state_space.Var_y(idx1,idx2);
|
||||
if options_mom_.mom.compute_derivs && ( options_mom_.mom.analytic_standard_errors || options_mom_.mom.analytic_jacobian )
|
||||
model_moments_params_derivs(jm,:) = pruned_state_space.dVar_y(idx1,idx2,:);
|
||||
oo_.mom.model_moments_params_derivs(jm,:) = pruned_state_space.dVar_y(idx1,idx2,:);
|
||||
end
|
||||
else
|
||||
model_moments(jm,1) = pruned_state_space.Var_y(idx1,idx2) + pruned_state_space.E_y(idx1)*pruned_state_space.E_y(idx2)';
|
||||
oo_.mom.model_moments(jm,1) = pruned_state_space.Var_y(idx1,idx2) + pruned_state_space.E_y(idx1)*pruned_state_space.E_y(idx2)';
|
||||
if options_mom_.mom.compute_derivs && ( options_mom_.mom.analytic_standard_errors || options_mom_.mom.analytic_jacobian )
|
||||
for jp=1:totparam_nbr
|
||||
model_moments_params_derivs(jm,jp) = pruned_state_space.dVar_y(idx1,idx2,jp) + pruned_state_space.dE_y(idx1,jp)*pruned_state_space.E_y(idx2)' + pruned_state_space.E_y(idx1)*pruned_state_space.dE_y(idx2,jp)';
|
||||
oo_.mom.model_moments_params_derivs(jm,jp) = pruned_state_space.dVar_y(idx1,idx2,jp) + pruned_state_space.dE_y(idx1,jp)*pruned_state_space.E_y(idx2)' + pruned_state_space.E_y(idx1)*pruned_state_space.dE_y(idx2,jp)';
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -197,15 +189,15 @@ if strcmp(options_mom_.mom.mom_method,'GMM')
|
|||
% autocovariance
|
||||
lag = -M_.matched_moments{jm,2}(2); %note that leads/lags in M_.matched_moments are transformed such that first entry is always 0 and the second is a lag
|
||||
if options_mom_.prefilter
|
||||
model_moments(jm,1) = pruned_state_space.Var_yi(idx1,idx2,lag);
|
||||
oo_.mom.model_moments(jm,1) = pruned_state_space.Var_yi(idx1,idx2,lag);
|
||||
if options_mom_.mom.compute_derivs && ( options_mom_.mom.analytic_standard_errors || options_mom_.mom.analytic_jacobian )
|
||||
model_moments_params_derivs(jm,:) = pruned_state_space.dVar_yi(idx1,idx2,lag,:);
|
||||
oo_.mom.model_moments_params_derivs(jm,:) = pruned_state_space.dVar_yi(idx1,idx2,lag,:);
|
||||
end
|
||||
else
|
||||
model_moments(jm,1) = pruned_state_space.Var_yi(idx1,idx2,lag) + pruned_state_space.E_y(idx1)*pruned_state_space.E_y(idx2)';
|
||||
oo_.mom.model_moments(jm,1) = pruned_state_space.Var_yi(idx1,idx2,lag) + pruned_state_space.E_y(idx1)*pruned_state_space.E_y(idx2)';
|
||||
if options_mom_.mom.compute_derivs && ( options_mom_.mom.analytic_standard_errors || options_mom_.mom.analytic_jacobian )
|
||||
for jp=1:totparam_nbr
|
||||
model_moments_params_derivs(jm,jp) = vec( pruned_state_space.dVar_yi(idx1,idx2,lag,jp) + pruned_state_space.dE_y(idx1,jp)*pruned_state_space.E_y(idx2)' + pruned_state_space.E_y(idx1)*pruned_state_space.dE_y(idx2,jp)');
|
||||
oo_.mom.model_moments_params_derivs(jm,jp) = vec( pruned_state_space.dVar_yi(idx1,idx2,lag,jp) + pruned_state_space.dE_y(idx1,jp)*pruned_state_space.E_y(idx2)' + pruned_state_space.E_y(idx1)*pruned_state_space.dE_y(idx2,jp)');
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -225,22 +217,26 @@ if strcmp(options_mom_.mom.mom_method,'SMM')
|
|||
scaled_shock_series = zeros(size(options_mom_.mom.shock_series)); % initialize
|
||||
scaled_shock_series(:,i_exo_var) = options_mom_.mom.shock_series(:,i_exo_var)*chol_S; % set non-zero entries
|
||||
% simulate series
|
||||
y_sim = simult_(M_, options_mom_, dr.ys, dr, scaled_shock_series, options_mom_.order);
|
||||
% provide meaningful penalty if data is NaN or Inf
|
||||
y_sim = simult_(M_, options_mom_, oo_.dr.ys, oo_.dr, scaled_shock_series, options_mom_.order);
|
||||
% provide meaningful penalty if data is nan or inf
|
||||
if any(any(isnan(y_sim))) || any(any(isinf(y_sim)))
|
||||
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
|
||||
fval = Inf(size(oo_.mom.Sw,1),1);
|
||||
else
|
||||
fval = Inf;
|
||||
end
|
||||
info(1)=180;
|
||||
info(4) = 0.1;
|
||||
exit_flag = 0;
|
||||
fval = Inf;
|
||||
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
|
||||
fval = ones(options_mom_.mom.mom_nbr,1)*options_mom_.huge_number;
|
||||
fval = ones(size(oo_.mom.data_moments,1),1)*options_mom_.huge_number;
|
||||
end
|
||||
return
|
||||
end
|
||||
% remove burn-in and focus on observables (note that y_sim is in declaration order)
|
||||
y_sim = y_sim(dr.order_var(options_mom_.mom.obs_var) , end-options_mom_.mom.long+1:end)';
|
||||
y_sim = y_sim(oo_.dr.order_var(oo_.mom.obs_var) , end-options_mom_.mom.long+1:end)';
|
||||
if ~all(diag(M_.H)==0)
|
||||
i_ME = setdiff(1:size(M_.H,1),find(diag(M_.H) == 0)); % find ME with 0 variance
|
||||
i_ME = setdiff([1:size(M_.H,1)],find(diag(M_.H) == 0)); % find ME with 0 variance
|
||||
chol_S = chol(M_.H(i_ME,i_ME)); % decompose rest
|
||||
shock_mat=zeros(size(options_mom_.mom.ME_shock_series)); % initialize
|
||||
shock_mat(:,i_ME)=options_mom_.mom.ME_shock_series(:,i_ME)*chol_S;
|
||||
|
@ -250,119 +246,46 @@ if strcmp(options_mom_.mom.mom_method,'SMM')
|
|||
if options_mom_.prefilter
|
||||
y_sim = bsxfun(@minus, y_sim, mean(y_sim,1));
|
||||
end
|
||||
model_moments = mom.get_data_moments(y_sim, options_mom_.mom.obs_var, dr.inv_order_var, M_.matched_moments, options_mom_);
|
||||
end
|
||||
|
||||
|
||||
%------------------------------------------------------------------------------
|
||||
% IRF_MATCHING using STOCH_SIMUL: Compute IRFs given model solution and Cholesky
|
||||
% decomposition on shock covariance matrix; this resembles the core codes in
|
||||
% stoch_simul
|
||||
%------------------------------------------------------------------------------
|
||||
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING') && strcmp(options_mom_.mom.simulation_method,'STOCH_SIMUL')
|
||||
cs = get_lower_cholesky_covariance(M_.Sigma_e,options_mom_.add_tiny_number_to_cholesky);
|
||||
irf_shocks_indx = getIrfShocksIndx(M_, options_mom_);
|
||||
model_irf = NaN(options_mom_.irf,M_.endo_nbr,M_.exo_nbr);
|
||||
for i = irf_shocks_indx
|
||||
if options_mom_.order>1 && options_mom_.relative_irf % normalize shock to 0.01 before IRF generation for GIRFs; multiply with 100 later
|
||||
y_irf = irf(M_, options_mom_, dr, cs(:,i)./cs(i,i)/100, options_mom_.irf, options_mom_.drop, options_mom_.replic, options_mom_.order);
|
||||
else % for linear model, rescaling is done later
|
||||
y_irf = irf(M_, options_mom_, dr, cs(:,i), options_mom_.irf, options_mom_.drop, options_mom_.replic, options_mom_.order);
|
||||
end
|
||||
if any(any(isnan(y_irf))) && ~options_mom_.pruning && ~(options_mom_.order==1)
|
||||
info(1) = 181;
|
||||
info(4) = 0.1;
|
||||
fval = Inf;
|
||||
exit_flag = 0;
|
||||
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
|
||||
fval = ones(options_mom_.mom.mom_nbr,1)*options_mom_.huge_number;
|
||||
end
|
||||
message = get_error_message(info,options_mom_);
|
||||
fprintf('\n%s\n info = %d for shock %s.\n', message, info(1), M_.exo_names{i});
|
||||
return
|
||||
end
|
||||
if options_mom_.relative_irf
|
||||
if options_mom_.order==1 % multiply with 100 for backward compatibility
|
||||
y_irf = 100*y_irf/cs(i,i);
|
||||
end
|
||||
end
|
||||
model_irf(:,:,i) = transpose(y_irf);
|
||||
end
|
||||
% do transformations on model IRFs if irf_matching_file is provided
|
||||
if ~isempty(options_mom_.mom.irf_matching_file.name)
|
||||
[model_irf, check] = feval(str2func(options_mom_.mom.irf_matching_file.name), model_irf, M_, options_mom_, dr.ys);
|
||||
if check
|
||||
fval = Inf;
|
||||
info(1) = 180;
|
||||
info(4) = 0.1;
|
||||
exit_flag = 0;
|
||||
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
|
||||
fval = ones(options_mom_.mom.mom_nbr,1)*options_mom_.huge_number;
|
||||
end
|
||||
return
|
||||
end
|
||||
end
|
||||
irf_model_varobs = model_irf(:,options_mom_.varobs_id,:); % focus only on observables (this will be used later for plotting)
|
||||
model_moments = irf_model_varobs(options_mom_.mom.irfIndex); % focus only on selected IRF periods
|
||||
oo_.mom.model_moments = mom.get_data_moments(y_sim, oo_.mom.obs_var, oo_.dr.inv_order_var, M_.matched_moments, options_mom_);
|
||||
end
|
||||
|
||||
|
||||
%--------------------------------------------------------------------------
|
||||
% Compute quadratic target function
|
||||
%--------------------------------------------------------------------------
|
||||
moments_difference = data_moments - model_moments;
|
||||
moments_difference = oo_.mom.data_moments - oo_.mom.model_moments;
|
||||
|
||||
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
|
||||
Q = transpose(moments_difference)*weighting_info.W*moments_difference;
|
||||
% log-likelihood
|
||||
lnlik = options_mom_.mom.mom_nbr/2*log(1/2/pi) - 1/2*weighting_info.Winv_logdet - 1/2*Q;
|
||||
if isinf(lnlik)
|
||||
fval = Inf; info(1) = 50; info(4) = 0.1; exit_flag = 0;
|
||||
return
|
||||
end
|
||||
if isnan(lnlik)
|
||||
fval = Inf; info(1) = 45; info(4) = 0.1; exit_flag = 0;
|
||||
return
|
||||
end
|
||||
if imag(lnlik)~=0
|
||||
fval = Inf; info(1) = 46; info(4) = 0.1; exit_flag = 0;
|
||||
return
|
||||
end
|
||||
% add log prior if necessary
|
||||
lnprior = priordens(xparam,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
|
||||
fval = - (lnlik + lnprior);
|
||||
|
||||
elseif strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
residuals = sqrt(options_mom_.mom.weighting_matrix_scaling_factor)*weighting_info.Sw*moments_difference;
|
||||
Q = residuals'*residuals;
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
residuals = sqrt(options_mom_.mom.weighting_matrix_scaling_factor)*oo_.mom.Sw*moments_difference;
|
||||
oo_.mom.Q = residuals'*residuals;
|
||||
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
|
||||
fval = residuals;
|
||||
if options_mom_.mom.penalized_estimator
|
||||
fval=[fval;(xparam-bayestopt_.p1)./bayestopt_.p2];
|
||||
fval=[fval;(xparam-oo_.mom.prior.mean)./sqrt(diag(oo_.mom.prior.variance))];
|
||||
end
|
||||
else
|
||||
fval = Q;
|
||||
fval = oo_.mom.Q;
|
||||
if options_mom_.mom.penalized_estimator
|
||||
fval=fval+(xparam-bayestopt_.p1)'/(diag(bayestopt_.p2.^2))*(xparam-bayestopt_.p1);
|
||||
fval=fval+(xparam-oo_.mom.prior.mean)'/oo_.mom.prior.variance*(xparam-oo_.mom.prior.mean);
|
||||
end
|
||||
end
|
||||
if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_jacobian
|
||||
if options_mom_.mom.penalized_estimator
|
||||
dxparam = eye(length(xparam));
|
||||
dxparam1 = eye(length(xparam));
|
||||
end
|
||||
for jp=1:length(xparam)
|
||||
dmoments_difference = - model_moments_params_derivs(:,jp);
|
||||
dresiduals = sqrt(options_mom_.mom.weighting_matrix_scaling_factor)*weighting_info.Sw*dmoments_difference;
|
||||
dmoments_difference = - oo_.mom.model_moments_params_derivs(:,jp);
|
||||
dresiduals = sqrt(options_mom_.mom.weighting_matrix_scaling_factor)*oo_.mom.Sw*dmoments_difference;
|
||||
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
|
||||
if options_mom_.mom.penalized_estimator
|
||||
df(:,jp)=[dresiduals;dxparam(:,jp)./bayestopt_.p2];
|
||||
df(:,jp)=[dresiduals;dxparam1(:,jp)./sqrt(diag(oo_.mom.prior.variance))];
|
||||
else
|
||||
df(:,jp) = dresiduals;
|
||||
end
|
||||
else
|
||||
df(jp,1) = dresiduals'*residuals + residuals'*dresiduals;
|
||||
if options_mom_.mom.penalized_estimator
|
||||
df(jp,1)=df(jp,1)+(dxparam(:,jp))'/(diag(bayestopt_.p2.^2))*(xparam-bayestopt_.p1)+(xparam-bayestopt_.p1)'/(diag(bayestopt_.p2.^2))*(dxparam(:,jp));
|
||||
df(jp,1)=df(jp,1)+(dxparam1(:,jp))'/oo_.mom.prior.variance*(xparam-oo_.mom.prior.mean)+(xparam-oo_.mom.prior.mean)'/oo_.mom.prior.variance*(dxparam1(:,jp));
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -370,4 +293,5 @@ elseif strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_
|
|||
end
|
||||
|
||||
|
||||
end % main function end
|
||||
end % main function end
|
||||
|
||||
|
|
|
@ -2,10 +2,9 @@ function W_opt = optimal_weighting_matrix(m_data, moments, q_lag)
|
|||
% W_opt = optimal_weighting_matrix(m_data, moments, q_lag)
|
||||
% -------------------------------------------------------------------------
|
||||
% This function computes the optimal weigthing matrix by a Bartlett kernel with maximum lag q_lag
|
||||
% Adapted from replication codes of Andreasen, Fernández-Villaverde, 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.
|
||||
% -------------------------------------------------------------------------
|
||||
% Adapted from replication codes of
|
||||
% o Andreasen, Fernández-Villaverde, 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.
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% o m_data [T x numMom] selected data moments at each point in time
|
||||
% o moments [numMom x 1] selected estimated moments (either data_moments or estimated model_moments)
|
||||
|
@ -18,10 +17,9 @@ function W_opt = optimal_weighting_matrix(m_data, moments, q_lag)
|
|||
% o mom.run.m
|
||||
% -------------------------------------------------------------------------
|
||||
% This function calls:
|
||||
% o corr_matrix (embedded)
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% Copyright © 2020-2023 Dynare Team
|
||||
% o CorrMatrix (embedded)
|
||||
% =========================================================================
|
||||
% Copyright © 2020-2021 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
%
|
||||
|
@ -37,42 +35,46 @@ function W_opt = optimal_weighting_matrix(m_data, moments, q_lag)
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
% -------------------------------------------------------------------------
|
||||
% Author(s):
|
||||
% o Willi Mutschler (willi@mutschler.eu)
|
||||
% o Johannes Pfeifer (johannes.pfeifer@unibw.de)
|
||||
% =========================================================================
|
||||
|
||||
|
||||
% initialize
|
||||
[T,num_Mom] = size(m_data); % note that in m_data NaN values (due to leads or lags in matched_moments and missing data) were replaced by the mean
|
||||
% Initialize
|
||||
[T,num_Mom] = size(m_data); %note that in m_data NaN values (due to leads or lags in matched_moments and missing data) were replaced by the mean
|
||||
|
||||
% center around moments (could be either data_moments or model_moments)
|
||||
h_func = m_data - repmat(moments',T,1);
|
||||
h_Func = m_data - repmat(moments',T,1);
|
||||
|
||||
% the required correlation matrices
|
||||
gamma_array = zeros(num_Mom,num_Mom,q_lag);
|
||||
gamma0 = corr_matrix(h_func,T,num_Mom,0);
|
||||
% The required correlation matrices
|
||||
GAMA_array = zeros(num_Mom,num_Mom,q_lag);
|
||||
GAMA0 = Corr_Matrix(h_Func,T,num_Mom,0);
|
||||
if q_lag > 0
|
||||
for ii=1:q_lag
|
||||
gamma_array(:,:,ii) = corr_matrix(h_func,T,num_Mom,ii);
|
||||
GAMA_array(:,:,ii) = Corr_Matrix(h_Func,T,num_Mom,ii);
|
||||
end
|
||||
end
|
||||
|
||||
% the estimate of S
|
||||
S = gamma0;
|
||||
% The estimate of S
|
||||
S = GAMA0;
|
||||
if q_lag > 0
|
||||
for ii=1:q_lag
|
||||
S = S + (1-ii/(q_lag+1))*(gamma_array(:,:,ii) + gamma_array(:,:,ii)');
|
||||
S = S + (1-ii/(q_lag+1))*(GAMA_array(:,:,ii) + GAMA_array(:,:,ii)');
|
||||
end
|
||||
end
|
||||
|
||||
% the estimate of W
|
||||
% The estimate of W
|
||||
W_opt = S\eye(size(S,1));
|
||||
|
||||
W_opt = (W_opt+W_opt')/2; % ensure symmetry
|
||||
end % main function end
|
||||
W_opt=(W_opt+W_opt')/2; %assure symmetry
|
||||
end
|
||||
|
||||
% The correlation matrix
|
||||
function gamma_corr = corr_matrix(h_func,T,num_Mom,v)
|
||||
gamma_corr = zeros(num_Mom,num_Mom);
|
||||
function GAMA_corr = Corr_Matrix(h_Func,T,num_Mom,v)
|
||||
GAMA_corr = zeros(num_Mom,num_Mom);
|
||||
for t = 1+v:T
|
||||
gamma_corr = gamma_corr + h_func(t-v,:)'*h_func(t,:);
|
||||
GAMA_corr = GAMA_corr + h_Func(t-v,:)'*h_Func(t,:);
|
||||
end
|
||||
gamma_corr = gamma_corr/T;
|
||||
end % corr_matrix end
|
||||
GAMA_corr = GAMA_corr/T;
|
||||
end
|
||||
|
|
|
@ -1,12 +1,11 @@
|
|||
function print_info_on_estimation_settings(options_mom_, number_of_estimated_parameters, do_bayesian_estimation)
|
||||
% print_info_on_estimation_settings(options_mom_, number_of_estimated_parameters, do_bayesian_estimation)
|
||||
function print_info_on_estimation_settings(options_mom_, number_of_estimated_parameters)
|
||||
% function print_info_on_estimation_settings(options_mom_, number_of_estimated_parameters)
|
||||
% -------------------------------------------------------------------------
|
||||
% Print information on the method of moments estimation settings to the console
|
||||
% -------------------------------------------------------------------------
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% options_mom_ [struct] options for the method of moments estimation
|
||||
% number_of_estimated_parameters [integer] number of estimated parameters
|
||||
% do_bayesian_estimation [boolean] true if the estimation is Bayesian
|
||||
% options_mom_ [struct] Options for the method of moments estimation
|
||||
% number_of_estimated_parameters [integer] Number of estimated parameters
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUT
|
||||
% No output, just displays the chosen settings
|
||||
|
@ -16,8 +15,7 @@ function print_info_on_estimation_settings(options_mom_, number_of_estimated_par
|
|||
% -------------------------------------------------------------------------
|
||||
% This function calls
|
||||
% o skipline
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% =========================================================================
|
||||
% Copyright © 2023 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -34,8 +32,7 @@ function print_info_on_estimation_settings(options_mom_, number_of_estimated_par
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
% =========================================================================
|
||||
fprintf('\n---------------------------------------------------\n')
|
||||
if strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
fprintf('Simulated method of moments with');
|
||||
|
@ -52,16 +49,7 @@ if strcmp(options_mom_.mom.mom_method,'SMM') || strcmp(options_mom_.mom.mom_meth
|
|||
fprintf('\n - penalized estimation using deviation from prior mean and weighted with prior precision');
|
||||
end
|
||||
end
|
||||
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
|
||||
if do_bayesian_estimation
|
||||
fprintf('Bayesian Impulse Response Function Matching with');
|
||||
else
|
||||
fprintf('Frequentist Impulse Response Function Matching with');
|
||||
end
|
||||
if ~isempty(options_mom_.mom.irf_matching_file.name)
|
||||
fprintf('\n - irf_matching_file: %s',[options_mom_.mom.irf_matching_file.path filesep options_mom_.mom.irf_matching_file.name '.m']);
|
||||
end
|
||||
end
|
||||
|
||||
for i = 1:length(options_mom_.optimizer_vec)
|
||||
if i == 1
|
||||
str = '- optimizer (mode_compute';
|
||||
|
@ -130,8 +118,6 @@ if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_meth
|
|||
fprintf('\n - standard errors: numerical derivatives');
|
||||
end
|
||||
fprintf('\n - number of matched moments: %d', options_mom_.mom.mom_nbr);
|
||||
elseif strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
|
||||
fprintf('\n - number of matched IRFs: %d', options_mom_.mom.mom_nbr);
|
||||
end
|
||||
fprintf('\n - number of parameters: %d', number_of_estimated_parameters);
|
||||
fprintf('\n\n');
|
|
@ -6,47 +6,31 @@ function [oo_, options_mom_, M_] = run(bayestopt_, options_, oo_, estim_params_,
|
|||
% o Preparing local options_mom_ structure
|
||||
% o Checking the options and the compatibility of the settings
|
||||
% o Initializations of variables, orderings and state space representation
|
||||
% o Checks and transformations for matched_moments structure
|
||||
% o Checks and transformations for matched_irfs and matched_irfs_weights structure
|
||||
% o Checks and transformations for matched moments structure
|
||||
% o Checks and transformations for estimated parameters, priors, and bounds
|
||||
% o Checks and transformations for data
|
||||
% o Checks for objective function at initial parameters
|
||||
% o Mode computation: optimization
|
||||
% - GMM/SMM: iterated optimization
|
||||
% - IRF_MATCHING: optimization
|
||||
% o Bayesian MCMC estimation
|
||||
% o GMM/SMM: iterated method of moments estimation
|
||||
% o GMM/SMM: J-Test and fit of moments%
|
||||
% o Display of results
|
||||
% - GMM/SMM: J-Test and fit of moments
|
||||
% - IRF_MATCHING: fit of IRFs
|
||||
% o Clean up
|
||||
% -------------------------------------------------------------------------
|
||||
% Note that we call a "mode" the minimum of the objective function, i.e.
|
||||
% the parameter vector that minimizes the distance between the moments/IRFs
|
||||
% computed from the model and the moments/IRFs computed from the data.
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is inspired by replication codes accompanied to the following papers:
|
||||
% GMM/SMM:
|
||||
% o Andreasen, Fernández-Villaverde, 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.
|
||||
% o Born, Pfeifer (2014): "Risk Matters: Comment", American Economic Review, 104(12):4231-4239.
|
||||
% o Mutschler (2018): "Higher-order statistics for DSGE models", Econometrics and Statistics, 6:44-56.
|
||||
% o Ruge-Murcia (2007): "Methods to Estimate Dynamic Stochastic General Equilibrium Models", Journal of Economic Dynamics and Control, 31(8):2599-2636.
|
||||
% IRF MATCHING:
|
||||
% o Christiano, Trabandt, Walentin (2010): "DSGE Models for Monetary Policy Analysis." In Handbook of Monetary Economics, 3:285–367.
|
||||
% o Christiano, Eichenbaum, Trabandt (2016): "Unemployment and Business Cycles." Econometrica, 84: 1523-1569.
|
||||
% o Ruge-Murcia (2020): "Estimating Nonlinear Dynamic Equilibrium Models by Matching Impulse Responses", Economics Letters, 197.
|
||||
% -------------------------------------------------------------------------
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% o bayestopt_: [structure] information about priors
|
||||
% o options_: [structure] information about global options
|
||||
% o oo_: [structure] results
|
||||
% o oo_: [structure] storage for results
|
||||
% o estim_params_: [structure] information about estimated parameters
|
||||
% o M_: [structure] information about model with
|
||||
% o matched_moments: [cell] information about selected moments to match in GMM/SMM estimation
|
||||
% vars: matched_moments{:,1});
|
||||
% lead/lags: matched_moments{:,2};
|
||||
% powers: matched_moments{:,3};
|
||||
% o matched_irfs: [cell] information about selected IRFs to match in IRF_MATCHING estimation
|
||||
% o matched_irfs_weights: [cell] information about entries in weight matrix for an IRF_MATCHING estimation
|
||||
% o options_mom_: [structure] information about settings specified by the user
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUTS
|
||||
|
@ -58,26 +42,25 @@ function [oo_, options_mom_, M_] = run(bayestopt_, options_, oo_, estim_params_,
|
|||
% o driver.m
|
||||
% -------------------------------------------------------------------------
|
||||
% This function calls
|
||||
% o cellofchararraymaxlength
|
||||
% o check_for_calibrated_covariances
|
||||
% o check_mode_file
|
||||
% o check_posterior_sampler_options
|
||||
% o check_prior_bounds
|
||||
% o check_prior_stderr_corr
|
||||
% o check_steady_state_changes_parameters
|
||||
% o check_varobs_are_endo_and_declared_once
|
||||
% o check_hessian_at_the_mode
|
||||
% o display_estimation_results_table
|
||||
% o do_parameter_initialization
|
||||
% o dyn_latex_table
|
||||
% o dynare_minimize_objective
|
||||
% o dyntable
|
||||
% o get_all_parameters
|
||||
% o get_dynare_random_generator_state
|
||||
% o get_matrix_entries_for_psd_check
|
||||
% o M_.fname '_prior_restrictions'
|
||||
% o makedataset
|
||||
% o mode_check
|
||||
% o mom.check_irf_matching_file
|
||||
% o mom.check_plot
|
||||
% o mom.default_option_mom_values
|
||||
% o mom.get_data_moments
|
||||
% o mom.matched_irfs_blocks
|
||||
% o mom.matched_moments_block
|
||||
% o mom.objective_function
|
||||
% o mom.optimal_weighting_matrix
|
||||
|
@ -94,9 +77,8 @@ function [oo_, options_mom_, M_] = run(bayestopt_, options_, oo_, estim_params_,
|
|||
% o set_state_space
|
||||
% o skipline
|
||||
% o test_for_deep_parameters_calibration
|
||||
% o transform_prior_to_laplace_prior
|
||||
% o warning_config
|
||||
|
||||
% =========================================================================
|
||||
% Copyright © 2020-2023 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -113,8 +95,34 @@ function [oo_, options_mom_, M_] = run(bayestopt_, options_, oo_, estim_params_,
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
% -------------------------------------------------------------------------
|
||||
% Maintaining Author(s):
|
||||
% o Willi Mutschler (willi@mutschler.eu)
|
||||
% o Johannes Pfeifer (johannes.pfeifer@unibw.de)
|
||||
% =========================================================================
|
||||
|
||||
fprintf('\n==== Method of Moments Estimation (%s) ====\n\n',options_mom_.mom.mom_method);
|
||||
% -------------------------------------------------------------------------
|
||||
% TO DO LISTS
|
||||
% -------------------------------------------------------------------------
|
||||
% GENERAL
|
||||
% - document all options in manual
|
||||
% - document analytic_jacobian better
|
||||
% - make endogenous_prior_restrictions work
|
||||
% - dirname option to save output to different directory not yet implemented
|
||||
% - create test for prior restrictions file
|
||||
% - add mode_file option
|
||||
% - implement penalty objective
|
||||
% - test optimizers
|
||||
% GMM/SMM
|
||||
% - speed up pruned_state_space_system (by using doubling with old initial values, hardcoding zeros, other "tricks" used in e.g. nlma)
|
||||
% - add option to use autocorrelations (we have useautocorr in identification toolbox already)
|
||||
% - SMM with extended path
|
||||
% - deal with measurement errors (once @wmutschl has implemented this in identification toolbox)
|
||||
% - display scaled moments
|
||||
% - enable first moments despite prefilter
|
||||
% - do "true" Bayesian GMM and SMM not only penalized
|
||||
|
||||
fprintf('\n==== Method of Moments Estimation (%s) ====\n\n',options_mom_.mom.mom_method)
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
|
@ -122,33 +130,29 @@ fprintf('\n==== Method of Moments Estimation (%s) ====\n\n',options_mom_.mom.mom
|
|||
% -------------------------------------------------------------------------
|
||||
if isempty(estim_params_) % structure storing the info about estimated parameters in the estimated_params block
|
||||
if ~(isfield(estim_params_,'nvx') && (size(estim_params_.var_exo,1)+size(estim_params_.var_endo,1)+size(estim_params_.corrx,1)+size(estim_params_.corrn,1)+size(estim_params_.param_vals,1))==0)
|
||||
error('method_of_moments: You need to provide an ''estimated_params'' block!');
|
||||
error('method_of_moments: You need to provide an ''estimated_params'' block!')
|
||||
else
|
||||
error('method_of_moments: The ''estimated_params'' block must not be empty!');
|
||||
error('method_of_moments: The ''estimated_params'' block must not be empty!')
|
||||
end
|
||||
end
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
if ~isfield(M_,'matched_moments') || isempty(M_.matched_moments) % structure storing the moments used for GMM and SMM estimation
|
||||
error('method_of_moments: You need to provide a ''matched_moments'' block for ''mom_method=%s''!',options_mom_.mom.mom_method);
|
||||
end
|
||||
elseif strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
|
||||
if ~isfield(M_,'matched_irfs') || isempty(M_.matched_irfs) % structure storing the irfs used for matching
|
||||
error('method_of_moments: You need to provide a ''matched_irfs'' block for ''mom_method=%s''!',options_mom_.mom.mom_method);
|
||||
error('method_of_moments: You need to provide a ''matched_moments'' block for ''mom_method=%s''!',options_mom_.mom.mom_method)
|
||||
end
|
||||
end
|
||||
if (~isempty(estim_params_.var_endo) || ~isempty(estim_params_.corrn)) && strcmp(options_mom_.mom.mom_method, 'GMM')
|
||||
error('method_of_moments: GMM estimation does not support measurement error(s) yet. Please specify them as a structural shock!');
|
||||
error('method_of_moments: GMM estimation does not support measurement error(s) yet. Please specify them as a structural shock!')
|
||||
end
|
||||
do_bayesian_estimation = [estim_params_.var_exo(:,5); estim_params_.var_endo(:,5); estim_params_.corrx(:,6); estim_params_.corrn(:,6); estim_params_.param_vals(:,5)];
|
||||
if all(do_bayesian_estimation~=0)
|
||||
do_bayesian_estimation = true;
|
||||
elseif all(do_bayesian_estimation==0)
|
||||
do_bayesian_estimation = false;
|
||||
doBayesianEstimation = [estim_params_.var_exo(:,5); estim_params_.var_endo(:,5); estim_params_.corrx(:,6); estim_params_.corrn(:,6); estim_params_.param_vals(:,5)];
|
||||
if all(doBayesianEstimation~=0)
|
||||
doBayesianEstimation = true;
|
||||
elseif all(doBayesianEstimation==0)
|
||||
doBayesianEstimation = false;
|
||||
else
|
||||
error('method_of_moments: Estimation must be either fully Frequentist or fully Bayesian. Maybe you forgot to specify a prior distribution!');
|
||||
error('method_of_moments: Estimation must be either fully Frequentist or fully Bayesian. Maybe you forgot to specify a prior distribution!')
|
||||
end
|
||||
if ~isfield(options_,'varobs')
|
||||
error('method_of_moments: VAROBS statement is missing!');
|
||||
error('method_of_moments: VAROBS statement is missing!')
|
||||
end
|
||||
check_varobs_are_endo_and_declared_once(options_.varobs,M_.endo_names);
|
||||
|
||||
|
@ -162,12 +166,28 @@ check_varobs_are_endo_and_declared_once(options_.varobs,M_.endo_names);
|
|||
% The idea is to be independent of options_ and have full control of the
|
||||
% estimation instead of possibly having to deal with options chosen somewhere
|
||||
% else in the mod file.
|
||||
options_mom_ = mom.default_option_mom_values(options_mom_, options_, M_.dname, do_bayesian_estimation);
|
||||
options_mom_ = mom.default_option_mom_values(options_mom_, options_, M_.dname, doBayesianEstimation);
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% workarounds
|
||||
% -------------------------------------------------------------------------
|
||||
% The TeX option crashes MATLAB R2014a run with "-nodisplay" option
|
||||
% (as is done from the testsuite).
|
||||
% Since we can’t directly test whether "-nodisplay" has been passed,
|
||||
% we test for the "source_root" environment variable, which is set
|
||||
% by the testsuite.
|
||||
% Note that it was not tested whether the crash happens with more
|
||||
% recent MATLAB versions, so when OLD_MATLAB_VERSION is increased,
|
||||
% one should make a test before removing this workaround.
|
||||
if options_.TeX && ~isoctave && matlab_ver_less_than('8.4') && ~isempty(getenv('source_root'))
|
||||
warning('Disabling TeX option due to a bug in MATLAB R2014a with -nodisplay')
|
||||
options_.TeX = false;
|
||||
end
|
||||
if isfield(options_mom_, 'TeX') && options_mom_.TeX && ~isoctave && matlab_ver_less_than('8.4') && ~isempty(getenv('source_root'))
|
||||
warning('Disabling TeX option due to a bug in MATLAB R2014a with -nodisplay')
|
||||
options_mom_.TeX = false;
|
||||
end
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
% temporary workaround for https://git.dynare.org/Dynare/dseries/-/issues/51
|
||||
if options_mom_.xls_sheet~=1
|
||||
|
@ -179,27 +199,60 @@ if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_meth
|
|||
end
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% checks on settings
|
||||
% -------------------------------------------------------------------------
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
if numel(options_mom_.nobs) > 1
|
||||
error('method_of_moments: Recursive estimation and forecast for samples is not supported. Please set an integer as ''nobs''!');
|
||||
end
|
||||
if numel(options_mom_.first_obs) > 1
|
||||
error('method_of_moments: Recursive estimation and forecast for samples is not supported. Please set an integer as ''first_obs''!');
|
||||
end
|
||||
end
|
||||
if options_mom_.order < 1
|
||||
error('method_of_moments: The order of the Taylor approximation cannot be 0!')
|
||||
end
|
||||
if options_mom_.order > 2
|
||||
fprintf('Dynare will use ''k_order_solver'' as the order>2\n');
|
||||
options_mom_.k_order_solver = true;
|
||||
end
|
||||
if strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
if options_mom_.mom.simulation_multiple < 1
|
||||
fprintf('The simulation horizon is shorter than the data. Dynare resets the simulation_multiple to 7.\n')
|
||||
options_mom_.mom.simulation_multiple = 7;
|
||||
end
|
||||
end
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM')
|
||||
% require pruning with GMM at higher order
|
||||
if options_mom_.order > 1 && ~options_mom_.pruning
|
||||
fprintf('GMM at higher order only works with pruning, so we set pruning option to 1.\n');
|
||||
options_mom_.pruning = true;
|
||||
end
|
||||
if options_mom_.order > 3
|
||||
error('method_of_moments: Perturbation orders higher than 3 are not implemented for GMM estimation, try using SMM!');
|
||||
end
|
||||
end
|
||||
if options_mom_.mom.analytic_jacobian && ~strcmp(options_mom_.mom.mom_method,'GMM')
|
||||
options_mom_.mom.analytic_jacobian = false;
|
||||
fprintf('\n''analytic_jacobian'' option will be dismissed as it only works with GMM.\n');
|
||||
end
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% initializations
|
||||
% -------------------------------------------------------------------------
|
||||
% create output directories to store results
|
||||
M_.dname = options_mom_.dirname;
|
||||
CheckPath(M_.dname,'.');
|
||||
CheckPath('method_of_moments',M_.dname);
|
||||
CheckPath('graphs',M_.dname);
|
||||
|
||||
if do_bayesian_estimation
|
||||
oo_.mom.posterior.optimization.mode = [];
|
||||
oo_.mom.posterior.optimization.Variance = [];
|
||||
oo_.mom.posterior.optimization.log_density=[];
|
||||
end
|
||||
do_bayesian_estimation_mcmc = do_bayesian_estimation && ( (options_mom_.mh_replic>0) || options_mom_.load_mh_file );
|
||||
invhess = [];
|
||||
CheckPath('graphs',options_mom_.dirname);
|
||||
% initialize options that might change
|
||||
options_mom_.mom.compute_derivs = false; % flag to compute derivs in objective function (might change for GMM with either analytic_standard_errors or analytic_jacobian (dependent on optimizer))
|
||||
options_mom_.mom.vector_output = false; % specifies whether the objective function returns a vector
|
||||
% decision rule
|
||||
oo_.dr = set_state_space(oo_.dr,M_); % get state-space representation
|
||||
options_mom_.mom.obs_var = []; % create index of observed variables in DR order
|
||||
oo_.mom.obs_var = []; % create index of observed variables in DR order
|
||||
for i = 1:options_mom_.obs_nbr
|
||||
options_mom_.mom.obs_var = [options_mom_.mom.obs_var; find(strcmp(options_mom_.varobs{i}, M_.endo_names(oo_.dr.order_var)))];
|
||||
oo_.mom.obs_var = [oo_.mom.obs_var; find(strcmp(options_mom_.varobs{i}, M_.endo_names(oo_.dr.order_var)))];
|
||||
end
|
||||
|
||||
|
||||
|
@ -218,76 +271,37 @@ if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_meth
|
|||
% Get maximum lag number for autocovariances/autocorrelations
|
||||
options_mom_.ar = max(cellfun(@max,M_.matched_moments(:,2))) - min(cellfun(@min,M_.matched_moments(:,2)));
|
||||
% Check that only observed variables are involved in moments
|
||||
not_observed_variables=setdiff(oo_.dr.inv_order_var([M_.matched_moments{:,1}]),options_mom_.mom.obs_var);
|
||||
not_observed_variables=setdiff(oo_.dr.inv_order_var([M_.matched_moments{:,1}]),oo_.mom.obs_var);
|
||||
if ~isempty(not_observed_variables)
|
||||
skipline;
|
||||
error('method_of_moments: You specified moments involving %s, but it is not a varobs!',M_.endo_names{oo_.dr.order_var(not_observed_variables)});
|
||||
error('method_of_moments: You specified moments involving %s, but it is not a varobs!',M_.endo_names{oo_.dr.order_var(not_observed_variables)})
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% matched_irfs: checks and transformations
|
||||
% -------------------------------------------------------------------------
|
||||
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
|
||||
[oo_.mom.data_moments, oo_.mom.weighting_info.W, options_mom_.mom.irfIndex, options_mom_.irf] = mom.matched_irfs_blocks(M_.matched_irfs, M_.matched_irfs_weights, options_mom_.varobs_id, options_mom_.obs_nbr, M_.exo_nbr, M_.endo_names, M_.exo_names);
|
||||
% compute inverse of weighting matrix
|
||||
try
|
||||
oo_.mom.weighting_info.Winv = inv(oo_.mom.weighting_info.W);
|
||||
catch
|
||||
error('method_of_moments: Something wrong while computing inv(W), check your weighting matrix!');
|
||||
end
|
||||
if any(isnan(oo_.mom.weighting_info.Winv(:))) || any(isinf(oo_.mom.weighting_info.Winv(:)))
|
||||
error('method_of_moments: There are NaN or Inf values in inv(W), check your weighting matrix!');
|
||||
end
|
||||
% compute log determinant of inverse of weighting matrix in a robust way to avoid Inf or NaN
|
||||
try
|
||||
oo_.mom.weighting_info.Winv_logdet = 2*sum(log(diag(chol(oo_.mom.weighting_info.Winv))));
|
||||
catch
|
||||
error('method_of_moments: Something wrong while computing log(det(inv(W))), check your weighting matrix!');
|
||||
end
|
||||
if any(isnan(oo_.mom.weighting_info.Winv_logdet(:))) || any(isinf(oo_.mom.weighting_info.Winv_logdet(:)))
|
||||
error('method_of_moments: There are NaN or Inf values in log(det(inv(W))), check your weighting matrix!');
|
||||
end
|
||||
options_mom_.mom.mom_nbr = length(options_mom_.mom.irfIndex);
|
||||
end
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% irf_matching_file: checks and transformations
|
||||
% -------------------------------------------------------------------------
|
||||
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
|
||||
[options_mom_.mom.irf_matching_file.name, options_mom_.mom.irf_matching_file.path] = mom.check_irf_matching_file(options_mom_.mom.irf_matching_file.name);
|
||||
% check for irf_matching_file
|
||||
if ~( isempty(options_mom_.mom.irf_matching_file.path) || strcmp(options_mom_.mom.irf_matching_file.path,'.') )
|
||||
fprintf('\nAdding %s to MATLAB''s path.\n',options_mom_.mom.irf_matching_file.path);
|
||||
addpath(options_mom_.mom.irf_matching_file.path);
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% estimated parameters: checks and transformations on values, priors, bounds, posterior options
|
||||
% estimated parameters: checks and transformations on values, priors, bounds
|
||||
% -------------------------------------------------------------------------
|
||||
% set priors and bounds over the estimated parameters
|
||||
[xparam0, estim_params_, bayestopt_, lb, ub, M_] = set_prior(estim_params_, M_, options_mom_);
|
||||
number_of_estimated_parameters = length(xparam0);
|
||||
hessian_xparam0 = []; % initialize hessian
|
||||
|
||||
% check if enough moments for estimation
|
||||
if options_mom_.mom.mom_nbr < length(xparam0)
|
||||
skipline;
|
||||
error('method_of_moments: There must be at least as many moments as parameters for a %s estimation!',options_mom_.mom.mom_method);
|
||||
if strcmp(options_mom_.mom.mom_method, 'GMM') || strcmp(options_mom_.mom.mom_method, 'SMM')
|
||||
if options_mom_.mom.mom_nbr < length(xparam0)
|
||||
skipline;
|
||||
error('method_of_moments: There must be at least as many moments as parameters for a %s estimation!',options_mom_.mom.mom_method);
|
||||
end
|
||||
skipline(2);
|
||||
end
|
||||
skipline(2);
|
||||
|
||||
% check if a _prior_restrictions.m file exists
|
||||
if exist([M_.fname '_prior_restrictions.m'],'file')
|
||||
options_mom_.prior_restrictions.status = 1;
|
||||
options_mom_.prior_restrictions.routine = str2func([M_.fname '_prior_restrictions']);
|
||||
end
|
||||
% check that the provided mode_file is compatible with the current estimation settings
|
||||
if ~isempty(options_mom_.mode_file) && ( ~do_bayesian_estimation || (do_bayesian_estimation && ~options_mom_.mh_posterior_mode_estimation) )
|
||||
[xparam0, hessian_xparam0] = check_mode_file(xparam0, hessian_xparam0, options_mom_, bayestopt_);
|
||||
end
|
||||
|
||||
% check on specified priors and penalized estimation (which uses Laplace approximated priors)
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
bayestopt_orig = bayestopt_;
|
||||
|
@ -300,6 +314,7 @@ if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_meth
|
|||
bayestopt_ = mom.transform_prior_to_laplace_prior(bayestopt_);
|
||||
end
|
||||
end
|
||||
|
||||
% check for calibrated covariances before updating parameters
|
||||
estim_params_ = check_for_calibrated_covariances(estim_params_,M_);
|
||||
|
||||
|
@ -311,104 +326,89 @@ else
|
|||
estim_params_.full_calibration_detected = false;
|
||||
end
|
||||
if options_mom_.use_calibration_initialization % set calibration as starting values
|
||||
if ~isempty(bayestopt_) && ~do_bayesian_estimation && any(all(isnan([xparam_calib xparam0]),2))
|
||||
if ~isempty(bayestopt_) && ~doBayesianEstimation && any(all(isnan([xparam_calib xparam0]),2))
|
||||
error('method_of_moments: When using the use_calibration option with %s without prior, the parameters must be explicitly initialized!',options_mom_.mom.mom_method);
|
||||
else
|
||||
[xparam0,estim_params_] = do_parameter_initialization(estim_params_,xparam_calib,xparam0); % get explicitly initialized parameters that have precedence over calibrated values
|
||||
end
|
||||
end
|
||||
|
||||
% check initialization
|
||||
if ~isempty(bayestopt_) && ~do_bayesian_estimation && any(isnan(xparam0))
|
||||
if ~isempty(bayestopt_) && ~doBayesianEstimation && any(isnan(xparam0))
|
||||
error('method_of_moments: Frequentist %s requires all estimated parameters to be initialized, either in an estimated_params or estimated_params_init-block!',options_mom_.mom.mom_method);
|
||||
end
|
||||
|
||||
% set and check parameter bounds
|
||||
if ~isempty(bayestopt_) && do_bayesian_estimation
|
||||
if ~isempty(bayestopt_) && doBayesianEstimation
|
||||
% plot prior densities
|
||||
if ~options_mom_.nograph && options_mom_.plot_priors
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
plot_priors(bayestopt_orig,M_,estim_params_,options_mom_,'Original priors'); % only for visual inspection (not saved to disk, because overwritten in next call to plot_priors)
|
||||
plot_priors(bayestopt_,M_,estim_params_,options_mom_,'Laplace approximated priors');
|
||||
clear('bayestopt_orig'); % make sure stale structure cannot be used
|
||||
else
|
||||
plot_priors(bayestopt_,M_,estim_params_,options_mom_,'Priors');
|
||||
end
|
||||
end
|
||||
% set prior bounds
|
||||
BoundsInfo = prior_bounds(bayestopt_, options_mom_.prior_trunc);
|
||||
BoundsInfo.lb = max(BoundsInfo.lb,lb);
|
||||
BoundsInfo.ub = min(BoundsInfo.ub,ub);
|
||||
Bounds = prior_bounds(bayestopt_, options_mom_.prior_trunc);
|
||||
Bounds.lb = max(Bounds.lb,lb);
|
||||
Bounds.ub = min(Bounds.ub,ub);
|
||||
else
|
||||
% no priors are declared so Dynare will estimate the parameters with Frequentist methods using inequality constraints for the parameters
|
||||
BoundsInfo.lb = lb;
|
||||
BoundsInfo.ub = ub;
|
||||
if (strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')) && options_mom_.mom.penalized_estimator
|
||||
fprintf('Penalized estimation turned off as you did not declare priors\n');
|
||||
% no priors are declared so Dynare will estimate the parameters with
|
||||
% Frequentist methods using inequality constraints for the parameters
|
||||
Bounds.lb = lb;
|
||||
Bounds.ub = ub;
|
||||
if options_mom_.mom.penalized_estimator
|
||||
fprintf('Penalized estimation turned off as you did not declare priors\n')
|
||||
options_mom_.mom.penalized_estimator = 0;
|
||||
else
|
||||
if isfield(options_mom_,'mh_replic') && options_mom_.mh_replic > 0
|
||||
fprintf('Setting ''mh_replic=0'' as you did not declare priors.\n');
|
||||
options_mom_.mh_replic = 0;
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
% set correct bounds for standard deviations and correlations
|
||||
BoundsInfo = mom.set_correct_bounds_for_stderr_corr(estim_params_,BoundsInfo);
|
||||
Bounds = mom.set_correct_bounds_for_stderr_corr(estim_params_,Bounds);
|
||||
|
||||
% test if initial values of the estimated parameters are all between the prior lower and upper bounds
|
||||
if options_mom_.use_calibration_initialization
|
||||
try
|
||||
check_prior_bounds(xparam0,BoundsInfo,M_,estim_params_,options_mom_,bayestopt_);
|
||||
check_prior_bounds(xparam0,Bounds,M_,estim_params_,options_mom_,bayestopt_);
|
||||
catch last_error
|
||||
fprintf('Cannot use parameter values from calibration as they violate the prior bounds.');
|
||||
fprintf('Cannot use parameter values from calibration as they violate the prior bounds.')
|
||||
rethrow(last_error);
|
||||
end
|
||||
else
|
||||
check_prior_bounds(xparam0,BoundsInfo,M_,estim_params_,options_mom_,bayestopt_);
|
||||
check_prior_bounds(xparam0,Bounds,M_,estim_params_,options_mom_,bayestopt_);
|
||||
end
|
||||
|
||||
% check for positive definiteness
|
||||
estim_params_ = get_matrix_entries_for_psd_check(M_,estim_params_);
|
||||
|
||||
% set sigma_e_is_diagonal flag (needed if the shocks block is not declared in the mod file)
|
||||
M_.sigma_e_is_diagonal = true;
|
||||
if estim_params_.ncx || any(nnz(tril(M_.Correlation_matrix,-1))) || isfield(estim_params_,'calibrated_covariances')
|
||||
M_.sigma_e_is_diagonal = false;
|
||||
end
|
||||
% storing prior parameters in results structure
|
||||
if do_bayesian_estimation || ( (strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')) && options_mom_.mom.penalized_estimator)
|
||||
oo_.mom.prior.mean = bayestopt_.p1;
|
||||
oo_.mom.prior.mode = bayestopt_.p5;
|
||||
oo_.mom.prior.variance = diag(bayestopt_.p2.^2);
|
||||
oo_.mom.prior.hyperparameters.first = bayestopt_.p6;
|
||||
oo_.mom.prior.hyperparameters.second = bayestopt_.p7;
|
||||
end
|
||||
|
||||
% storing prior parameters in results
|
||||
oo_.mom.prior.mean = bayestopt_.p1;
|
||||
oo_.mom.prior.mode = bayestopt_.p5;
|
||||
oo_.mom.prior.variance = diag(bayestopt_.p2.^2);
|
||||
oo_.mom.prior.hyperparameters.first = bayestopt_.p6;
|
||||
oo_.mom.prior.hyperparameters.second = bayestopt_.p7;
|
||||
|
||||
% set all parameters
|
||||
M_ = set_all_parameters(xparam0,estim_params_,M_);
|
||||
|
||||
% provide warning if there is NaN in parameters
|
||||
test_for_deep_parameters_calibration(M_);
|
||||
% set jscale
|
||||
if do_bayesian_estimation_mcmc
|
||||
if ~strcmp(options_mom_.posterior_sampler_options.posterior_sampling_method,'slice')
|
||||
if isempty(options_mom_.mh_jscale)
|
||||
options_mom_.mh_jscale = 2.38/sqrt(number_of_estimated_parameters); % use optimal value for univariate normal distribution (check_posterior_sampler_options and mode_compute=6 may overwrite this setting)
|
||||
end
|
||||
bayestopt_.jscale(find(isnan(bayestopt_.jscale))) = options_mom_.mh_jscale;
|
||||
end
|
||||
end
|
||||
% initialization of posterior sampler options
|
||||
if do_bayesian_estimation_mcmc
|
||||
[current_options, options_mom_, bayestopt_] = check_posterior_sampler_options([], M_.fname, M_.dname, options_mom_, BoundsInfo, bayestopt_);
|
||||
options_mom_.posterior_sampler_options.current_options = current_options;
|
||||
if strcmp(current_options.posterior_sampling_method,'slice') && current_options.use_mh_covariance_matrix && ~current_options.rotated
|
||||
error('method_of_moments: Using the slice sampler with the ''use_mh_covariance_matrix'' option requires also setting the ''rotated'' option!');
|
||||
end
|
||||
end
|
||||
% warning if prior allows that stderr parameters are negative or corr parameters are outside the unit circle
|
||||
if do_bayesian_estimation
|
||||
|
||||
if doBayesianEstimation
|
||||
% warning if prior allows that stderr parameters are negative or corr parameters are outside the unit circle
|
||||
check_prior_stderr_corr(estim_params_,bayestopt_);
|
||||
|
||||
% check value of prior density
|
||||
[~,~,~,info] = priordens(xparam0,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
|
||||
[~,~,~,info]= priordens(xparam0,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
|
||||
if any(info)
|
||||
fprintf('The prior density evaluated at the initial values is Inf for the following parameters: %s\n',bayestopt_.name{info,1});
|
||||
error('The initial value of the prior is -Inf!');
|
||||
fprintf('The prior density evaluated at the initial values is Inf for the following parameters: %s\n',bayestopt_.name{info,1})
|
||||
error('The initial value of the prior is -Inf!')
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -416,34 +416,34 @@ end
|
|||
% -------------------------------------------------------------------------
|
||||
% datafile: checks and transformations
|
||||
% -------------------------------------------------------------------------
|
||||
% build dataset
|
||||
% Build dataset
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
% check if datafile has same name as mod file
|
||||
[~,name] = fileparts(options_mom_.datafile);
|
||||
% Check if datafile has same name as mod file
|
||||
[~,name,~] = fileparts(options_mom_.datafile);
|
||||
if strcmp(name,M_.fname)
|
||||
error('method_of_moments: ''datafile'' and mod file are not allowed to have the same name; change the name of the ''datafile''!');
|
||||
error('method_of_moments: ''datafile'' and mod file are not allowed to have the same name; change the name of the ''datafile''!')
|
||||
end
|
||||
dataset_ = makedataset(options_mom_);
|
||||
% set options for old interface from the ones for new interface
|
||||
if ~isempty(dataset_)
|
||||
options_mom_.nobs = dataset_.nobs;
|
||||
end
|
||||
% check length of data for estimation of second moments
|
||||
% Check length of data for estimation of second moments
|
||||
if options_mom_.ar > options_mom_.nobs+1
|
||||
error('method_of_moments: Dataset is too short to compute higher than first moments!');
|
||||
end
|
||||
% provide info on data moments handling
|
||||
% Provide info on data moments handling
|
||||
fprintf('Computing data moments. Note that NaN values in the moments (due to leads and lags or missing data) are replaced by the mean of the corresponding moment.\n');
|
||||
% get data moments for the method of moments
|
||||
[oo_.mom.data_moments, oo_.mom.m_data] = mom.get_data_moments(dataset_.data, options_mom_.mom.obs_var, oo_.dr.inv_order_var, M_.matched_moments, options_mom_);
|
||||
% Get data moments for the method of moments
|
||||
[oo_.mom.data_moments, oo_.mom.m_data] = mom.get_data_moments(dataset_.data, oo_.mom.obs_var, oo_.dr.inv_order_var, M_.matched_moments, options_mom_);
|
||||
if ~isreal(dataset_.data)
|
||||
error('method_of_moments: The data moments contain complex values!');
|
||||
error('method_of_moments: The data moments contain complex values!')
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% SMM: Get shock series and set variance correction factor
|
||||
% SMM: Get shock series fand set variance correction factor
|
||||
% -------------------------------------------------------------------------
|
||||
if strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
options_mom_.mom.long = round(options_mom_.mom.simulation_multiple*options_mom_.nobs);
|
||||
|
@ -477,6 +477,7 @@ end
|
|||
% -------------------------------------------------------------------------
|
||||
% checks for steady state at initial parameters
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% check if steady state solves static model and if steady-state changes estimated parameters
|
||||
if options_mom_.steadystate.nocheck
|
||||
steadystate_check_flag_vec = [0 1];
|
||||
|
@ -485,7 +486,7 @@ else
|
|||
end
|
||||
[oo_.steady_state, info, steady_state_changes_parameters] = check_steady_state_changes_parameters(M_, estim_params_, oo_, options_mom_, steadystate_check_flag_vec);
|
||||
if info(1)
|
||||
fprintf('\nThe steady state at the initial parameters cannot be computed.\n');
|
||||
fprintf('\nThe steady state at the initial parameters cannot be computed.\n')
|
||||
print_info(info, 0, options_mom_);
|
||||
end
|
||||
if steady_state_changes_parameters && strcmp(options_mom_.mom.mom_method,'GMM') && options_mom_.mom.analytic_standard_errors
|
||||
|
@ -493,6 +494,7 @@ if steady_state_changes_parameters && strcmp(options_mom_.mom.mom_method,'GMM')
|
|||
fprintf('because the steady-state changes estimated parameters. Option ''analytic_derivation_mode'' reset to -2.');
|
||||
options_mom_.analytic_derivation_mode = -2;
|
||||
end
|
||||
|
||||
% display warning if some parameters are still NaN
|
||||
test_for_deep_parameters_calibration(M_);
|
||||
|
||||
|
@ -502,25 +504,17 @@ test_for_deep_parameters_calibration(M_);
|
|||
% -------------------------------------------------------------------------
|
||||
objective_function = str2func('mom.objective_function');
|
||||
try
|
||||
% check for NaN or complex values of moment-distance-funtion evaluated at initial parameters
|
||||
% Check for NaN or complex values of moment-distance-funtion evaluated at initial parameters
|
||||
if strcmp(options_mom_.mom.mom_method,'SMM') || strcmp(options_mom_.mom.mom_method,'GMM')
|
||||
oo_.mom.weighting_info.Sw = eye(options_mom_.mom.mom_nbr); % initialize with identity weighting matrix
|
||||
oo_.mom.Sw = eye(options_mom_.mom.mom_nbr); % initialize with identity weighting matrix
|
||||
end
|
||||
tic_id = tic;
|
||||
[fval, info] = feval(objective_function, xparam0, oo_.mom.data_moments, oo_.mom.weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
|
||||
[fval, info, ~, ~, ~, oo_, M_] = feval(objective_function, xparam0, Bounds, oo_, estim_params_, M_, options_mom_);
|
||||
elapsed_time = toc(tic_id);
|
||||
if isnan(fval)
|
||||
if strcmp(options_mom_.mom.mom_method,'SMM') || strcmp(options_mom_.mom.mom_method,'GMM')
|
||||
error('method_of_moments: The initial value of the objective function with identity weighting matrix is NaN!');
|
||||
else
|
||||
error('method_of_moments: The initial value of the objective function is NaN!');
|
||||
end
|
||||
error('method_of_moments: The initial value of the objective function with identity weighting matrix is NaN!')
|
||||
elseif imag(fval)
|
||||
if strcmp(options_mom_.mom.mom_method,'SMM') || strcmp(options_mom_.mom.mom_method,'GMM')
|
||||
error('method_of_moments: The initial value of the objective function with identity weighting matrix is complex!');
|
||||
else
|
||||
error('method_of_moments: The initial value of the objective function is complex!');
|
||||
end
|
||||
error('method_of_moments: The initial value of the objective function with identity weighting matrix is complex!')
|
||||
end
|
||||
if info(1) > 0
|
||||
disp('method_of_moments: Error in computing the objective function for initial parameter values')
|
||||
|
@ -535,10 +529,10 @@ try
|
|||
catch last_error % if check fails, provide info on using calibration if present
|
||||
if estim_params_.full_calibration_detected %calibrated model present and no explicit starting values
|
||||
skipline(1);
|
||||
fprintf('There was an error in computing the moments for initial parameter values.\n');
|
||||
fprintf('If this is not a problem with the setting of options (check the error message below),\n');
|
||||
fprintf('you should try using the calibrated version of the model as starting values. To do\n');
|
||||
fprintf('this, add an empty estimated_params_init-block with use_calibration option immediately before the estimation\n');
|
||||
fprintf('There was an error in computing the moments for initial parameter values.\n')
|
||||
fprintf('If this is not a problem with the setting of options (check the error message below),\n')
|
||||
fprintf('you should try using the calibrated version of the model as starting values. To do\n')
|
||||
fprintf('this, add an empty estimated_params_init-block with use_calibration option immediately before the estimation\n')
|
||||
fprintf('command (and after the estimated_params-block so that it does not get overwritten):\n');
|
||||
skipline(2);
|
||||
end
|
||||
|
@ -549,281 +543,60 @@ end
|
|||
% -------------------------------------------------------------------------
|
||||
% print some info to console
|
||||
% -------------------------------------------------------------------------
|
||||
mom.print_info_on_estimation_settings(options_mom_, number_of_estimated_parameters, do_bayesian_estimation);
|
||||
mom.print_info_on_estimation_settings(options_mom_, number_of_estimated_parameters);
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% compute mode for GMM/SMM
|
||||
% -------------------------------------------------------------------------
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
[xparam1, oo_.mom.weighting_info, oo_.mom.verbose] = mom.mode_compute_gmm_smm(xparam0, objective_function, oo_.mom.m_data, oo_.mom.data_moments, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
|
||||
end
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% compute mode for IRF matching
|
||||
% -------------------------------------------------------------------------
|
||||
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
|
||||
if ~do_bayesian_estimation || (do_bayesian_estimation && ~options_mom_.mh_posterior_mode_estimation)
|
||||
[xparam1, hessian_xparam1, fval, oo_.mom.verbose] = mom.mode_compute_irf_matching(xparam0, hessian_xparam0, objective_function, do_bayesian_estimation, oo_.mom.weighting_info, oo_.mom.data_moments, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
|
||||
else
|
||||
xparam1 = xparam0;
|
||||
hessian_xparam1 = hessian_xparam0;
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% compute standard errors and initialize covariance of the proposal distribution
|
||||
% GMM/SMM: iterated estimation
|
||||
% -------------------------------------------------------------------------
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
|
||||
% compute mode
|
||||
[xparam1, oo_, Woptflag] = mom.mode_compute_gmm_smm(xparam0, objective_function, oo_, M_, options_mom_, estim_params_, bayestopt_, Bounds);
|
||||
% compute standard errors at mode
|
||||
options_mom_.mom.vector_output = false; % make sure flag is reset
|
||||
M_ = set_all_parameters(xparam1,estim_params_,M_); % update M_ and oo_ (in particular to get oo_.mom.model_moments)
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM') && options_mom_.mom.analytic_standard_errors
|
||||
options_mom_.mom.compute_derivs = true; % for GMM we compute derivatives analytically in the objective function with this flag
|
||||
end
|
||||
[~, ~, ~, ~, ~, oo_.mom.Q, oo_.mom.model_moments, oo_.mom.model_moments_params_derivs] = feval(objective_function, xparam1, oo_.mom.data_moments, oo_.mom.weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
|
||||
[~, ~, ~,~,~, oo_] = feval(objective_function, xparam1, Bounds, oo_, estim_params_, M_, options_mom_); % compute model moments and oo_.mom.model_moments_params_derivs
|
||||
options_mom_.mom.compute_derivs = false; % reset to not compute derivatives in objective function during optimization
|
||||
[stdh, invhess] = mom.standard_errors(xparam1, objective_function, oo_.mom.model_moments, oo_.mom.model_moments_params_derivs, oo_.mom.m_data, oo_.mom.data_moments, oo_.mom.weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
|
||||
if options_mom_.cova_compute
|
||||
hessian_xparam1 = inv(invhess);
|
||||
end
|
||||
else
|
||||
if ~do_bayesian_estimation || ~options_mom_.mh_posterior_mode_estimation
|
||||
if do_bayesian_estimation
|
||||
oo_.mom.posterior.optimization.mode = xparam1;
|
||||
if exist('fval','var')
|
||||
oo_.mom.posterior.optimization.log_density = -fval;
|
||||
end
|
||||
end
|
||||
if options_mom_.cova_compute
|
||||
hsd = sqrt(diag(hessian_xparam1)); % represent the curvature (or second derivatives) of the likelihood with respect to each parameter being estimated.
|
||||
invhess = inv(hessian_xparam1./(hsd*hsd'))./(hsd*hsd'); % before taking the inverse scale the Hessian matrix by dividing each of its elements by the outer product of hsd such that the diagonal of the resulting matrix is approximately 1. This kind of scaling can help in regularizing the matrix and potentially improves its condition number, which in turn can make the matrix inversion more stable.
|
||||
stdh = sqrt(diag(invhess));
|
||||
if do_bayesian_estimation
|
||||
oo_.mom.posterior.optimization.Variance = invhess;
|
||||
end
|
||||
end
|
||||
else
|
||||
variances = bayestopt_.p2.*bayestopt_.p2;
|
||||
id_Inf = isinf(variances);
|
||||
variances(id_Inf) = 1;
|
||||
invhess = options_mom_.mh_posterior_mode_estimation*diag(variances);
|
||||
xparam1 = bayestopt_.p5;
|
||||
id_NaN = isnan(xparam1);
|
||||
xparam1(id_NaN) = bayestopt_.p1(id_NaN);
|
||||
outside_bound_pars=find(xparam1 < BoundsInfo.lb | xparam1 > BoundsInfo.ub);
|
||||
xparam1(outside_bound_pars) = bayestopt_.p1(outside_bound_pars);
|
||||
end
|
||||
if ~options_mom_.cova_compute
|
||||
stdh = NaN(length(xparam1),1);
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% display estimation results at mode
|
||||
% -------------------------------------------------------------------------
|
||||
if do_bayesian_estimation && ~options_mom_.mom.penalized_estimator && ~options_mom_.mh_posterior_mode_estimation
|
||||
% display table with Bayesian mode estimation results and store parameter estimates and standard errors in oo_
|
||||
oo_.mom = display_estimation_results_table(xparam1, stdh, M_, options_mom_, estim_params_, bayestopt_, oo_.mom, prior_dist_names, 'Posterior', 'posterior');
|
||||
% Laplace approximation to the marginal log density
|
||||
if options_mom_.cova_compute
|
||||
estim_params_nbr = size(xparam1,1);
|
||||
if ispd(invhess)
|
||||
log_det_invhess = log(det(invhess./(stdh*stdh')))+2*sum(log(stdh));
|
||||
likelihood = feval(objective_function, xparam1, oo_.mom.data_moments, oo_.mom.weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
|
||||
oo_.mom.MarginalDensity.LaplaceApproximation = .5*estim_params_nbr*log(2*pi) + .5*log_det_invhess - likelihood;
|
||||
else
|
||||
oo_.mom.MarginalDensity.LaplaceApproximation = NaN;
|
||||
end
|
||||
fprintf('\nLog data density [Laplace approximation] is %f.\n',oo_.mom.MarginalDensity.LaplaceApproximation);
|
||||
end
|
||||
elseif ~do_bayesian_estimation || (do_bayesian_estimation && options_mom_.mom.penalized_estimator)
|
||||
% display table with Frequentist estimation results and store parameter estimates and standard errors in oo_
|
||||
oo_.mom = display_estimation_results_table(xparam1, stdh, M_, options_mom_, estim_params_, bayestopt_, oo_.mom, prior_dist_names, options_mom_.mom.mom_method, lower(options_mom_.mom.mom_method));
|
||||
[stdh,hessian_xparam1] = mom.standard_errors(xparam1, objective_function, Bounds, oo_, estim_params_, M_, options_mom_, Woptflag);
|
||||
end
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% checks for mode and hessian at the mode
|
||||
% -------------------------------------------------------------------------
|
||||
if (~do_bayesian_estimation && options_mom_.cova_compute) || (do_bayesian_estimation && ~options_mom_.mh_posterior_mode_estimation && options_mom_.cova_compute)
|
||||
check_hessian_at_the_mode(hessian_xparam1, xparam1, M_, estim_params_, options_, BoundsInfo);
|
||||
end
|
||||
if options_mom_.mode_check.status
|
||||
if ~do_bayesian_estimation || (do_bayesian_estimation && ~options_mom_.mh_posterior_mode_estimation)
|
||||
mode_check(objective_function, xparam1, diag(stdh), options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, true,... % use diag(stdh) instead of hessian_xparam1 as mode_check uses diagonal elements
|
||||
oo_.mom.data_moments, oo_.mom.weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
|
||||
end
|
||||
end
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% Bayesian MCMC estimation
|
||||
% -------------------------------------------------------------------------
|
||||
if do_bayesian_estimation_mcmc
|
||||
invhess = set_mcmc_jumping_covariance(invhess, length(xparam1), options_mom_.MCMC_jumping_covariance, bayestopt_, 'method_of_moments');
|
||||
% reset bounds as lb and ub must only be operational during mode-finding
|
||||
BoundsInfo = set_mcmc_prior_bounds(xparam1, bayestopt_, options_mom_, 'method_of_moments');
|
||||
% tunes the jumping distribution's scale parameter
|
||||
if isfield(options_mom_,'mh_tune_jscale') && options_mom_.mh_tune_jscale.status
|
||||
if strcmp(options_mom_.posterior_sampler_options.posterior_sampling_method, 'random_walk_metropolis_hastings')
|
||||
options_mom_.mh_jscale = tune_mcmc_mh_jscale_wrapper(invhess, options_mom_, M_, objective_function, xparam1, BoundsInfo,...
|
||||
oo_.mom.data_moments, oo_.mom.weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
|
||||
bayestopt_.jscale(:) = options_mom_.mh_jscale;
|
||||
fprintf('mh_tune_jscale: mh_jscale has been set equal to %s.\n', num2str(options_mom_.mh_jscale));
|
||||
else
|
||||
warning('mh_tune_jscale is only available with ''random_walk_metropolis_hastings''!')
|
||||
end
|
||||
end
|
||||
% run MCMC sampling
|
||||
posterior_sampler_options = options_mom_.posterior_sampler_options.current_options;
|
||||
posterior_sampler_options.invhess = invhess;
|
||||
[posterior_sampler_options, options_mom_, bayestopt_] = check_posterior_sampler_options(posterior_sampler_options, M_.fname, M_.dname, options_mom_, BoundsInfo, bayestopt_,'method_of_moments');
|
||||
options_mom_.posterior_sampler_options.current_options = posterior_sampler_options; % store current options
|
||||
if options_mom_.mh_replic>0
|
||||
posterior_sampler(objective_function,posterior_sampler_options.proposal_distribution,xparam1,posterior_sampler_options,BoundsInfo,oo_.mom.data_moments,oo_.mom.weighting_info,options_mom_,M_,estim_params_,bayestopt_,oo_,'method_of_moments::mcmc');
|
||||
end
|
||||
CutSample(M_, options_mom_, 'method_of_moments::mcmc'); % discard first mh_drop percent of the draws
|
||||
if options_mom_.mh_posterior_mode_estimation
|
||||
% skip optimizer-based mode-finding and instead compute the mode based on a run of a MCMC
|
||||
[~,~,posterior_mode,~] = compute_mh_covariance_matrix(bayestopt_,M_.fname,M_.dname,'method_of_moments');
|
||||
oo_.mom = fill_mh_mode(posterior_mode',NaN(length(posterior_mode),1),M_,options_mom_,estim_params_,bayestopt_,oo_.mom,'posterior');
|
||||
return
|
||||
else
|
||||
% get stored results if required
|
||||
if options_mom_.load_mh_file && options_mom_.load_results_after_load_mh
|
||||
oo_load_mh = load([M_.dname filesep 'method_of_moments' filesep M_.fname '_mom_results'],'oo_');
|
||||
end
|
||||
% convergence diagnostics
|
||||
if ~options_mom_.nodiagnostic
|
||||
if (options_mom_.mh_replic>0 || (options_mom_.load_mh_file && ~options_mom_.load_results_after_load_mh))
|
||||
oo_.mom = mcmc_diagnostics(options_mom_, estim_params_, M_, oo_.mom);
|
||||
elseif options_mom_.load_mh_file && options_mom_.load_results_after_load_mh
|
||||
if isfield(oo_load_mh.oo_.mom,'convergence')
|
||||
oo_.mom.convergence = oo_load_mh.oo_.mom.convergence;
|
||||
end
|
||||
end
|
||||
end
|
||||
% statistics and plots for posterior draws
|
||||
if options_mom_.mh_replic || (options_mom_.load_mh_file && ~options_mom_.load_results_after_load_mh)
|
||||
[~,oo_.mom] = marginal_density(M_, options_mom_, estim_params_, oo_.mom, bayestopt_, 'method_of_moments');
|
||||
oo_.mom = GetPosteriorParametersStatistics(estim_params_, M_, options_mom_, bayestopt_, oo_.mom, prior_dist_names);
|
||||
if ~options_mom_.nograph
|
||||
oo_.mom = PlotPosteriorDistributions(estim_params_, M_, options_mom_, bayestopt_, oo_.mom);
|
||||
end
|
||||
[oo_.mom.posterior.metropolis.mean,oo_.mom.posterior.metropolis.Variance] = GetPosteriorMeanVariance(options_mom_,M_);
|
||||
elseif options_mom_.load_mh_file && options_mom_.load_results_after_load_mh
|
||||
% load fields from previous MCMC run stored in results-file
|
||||
field_names={'posterior_mode','posterior_std_at_mode',...% fields set by marginal_density
|
||||
'posterior_mean','posterior_hpdinf','posterior_hpdsup','posterior_median','posterior_variance','posterior_std','posterior_deciles','posterior_density',...% fields set by GetPosteriorParametersStatistics
|
||||
'prior_density',...% fields set by PlotPosteriorDistributions
|
||||
};
|
||||
for field_iter=1:size(field_names,2)
|
||||
if isfield(oo_load_mh.oo_.mom,field_names{1,field_iter})
|
||||
oo_.mom.(field_names{1,field_iter}) = oo_load_mh.oo_.mom.(field_names{1,field_iter});
|
||||
end
|
||||
end
|
||||
if isfield(oo_load_mh.oo_.mom,'MarginalDensity') && isfield(oo_load_mh.oo_.mom.MarginalDensity,'ModifiedHarmonicMean') % field set by marginal_density
|
||||
oo_.mom.MarginalDensity.ModifiedHarmonicMean = oo_load_mh.oo_.mom.MarginalDensity.ModifiedHarmonicMean;
|
||||
end
|
||||
if isfield(oo_load_mh.oo_.mom,'posterior') && isfield(oo_load_mh.oo_.mom.posterior,'metropolis') % field set by GetPosteriorMeanVariance
|
||||
oo_.mom.posterior.metropolis = oo_load_mh.oo_.mom.posterior.metropolis;
|
||||
end
|
||||
end
|
||||
[error_flag,~,options_mom_]= metropolis_draw(1,options_mom_,estim_params_,M_);
|
||||
if ~(~isempty(options_mom_.sub_draws) && options_mom_.sub_draws==0)
|
||||
% THIS IS PROBABLY NOT USEFUL HERE AND CAN BE REMOVED (PREPROCESSOR: REMOVE bayesian_irf, moments_varendo)
|
||||
%if options_mom_.bayesian_irf
|
||||
% if error_flag
|
||||
% error('method_of_moments: Cannot compute the posterior IRFs!');
|
||||
% end
|
||||
% PosteriorIRF('posterior','method_of_moments::mcmc');
|
||||
%end
|
||||
% if options_mom_.moments_varendo
|
||||
% if error_flag
|
||||
% error('method_of_moments: Cannot compute the posterior moments for the endogenous variables!');
|
||||
% end
|
||||
% if options_mom_.load_mh_file && options_mom_.mh_replic==0 %user wants to recompute results
|
||||
% [MetropolisFolder, info] = CheckPath('metropolis',options_mom_.dirname);
|
||||
% 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
|
||||
% end
|
||||
% oo_ = compute_moments_varendo('posterior',options_,M_,oo_,var_list_);
|
||||
% end
|
||||
else
|
||||
fprintf('''sub_draws'' was set to 0. Skipping posterior computations.');
|
||||
end
|
||||
xparam1 = get_posterior_parameters('mean',M_,estim_params_,oo_.mom,options_);
|
||||
end
|
||||
% MAYBE USEFUL????
|
||||
% % Posterior correlations
|
||||
% extreme_corr_bound = 0.7;
|
||||
% if ~isnan(extreme_corr_bound)
|
||||
% tril_para_correlation_matrix=tril(para_correlation_matrix,-1);
|
||||
% [row_index,col_index]=find(abs(tril_para_correlation_matrix)>extreme_corr_bound);
|
||||
% extreme_corr_params=cell(length(row_index),3);
|
||||
% for i=1:length(row_index)
|
||||
% extreme_corr_params{i,1}=char(parameter_names(row_index(i),:));
|
||||
% extreme_corr_params{i,2}=char(parameter_names(col_index(i),:));
|
||||
% extreme_corr_params{i,3}=tril_para_correlation_matrix(row_index(i),col_index(i));
|
||||
% end
|
||||
% end
|
||||
% disp(' ');
|
||||
% disp(['Correlations of Parameters (at Posterior Mode) > ',num2str(extreme_corr_bound)]);
|
||||
% disp(extreme_corr_params)
|
||||
mode_check(objective_function, xparam1, hessian_xparam1, options_mom_, M_, estim_params_, bayestopt_, Bounds, true,...
|
||||
Bounds, oo_, estim_params_, M_, options_mom_);
|
||||
end
|
||||
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% display final estimation results
|
||||
% -------------------------------------------------------------------------
|
||||
M_ = set_all_parameters(xparam1,estim_params_,M_); % update parameters
|
||||
[~, ~, ~, ~, ~, oo_.mom.Q, oo_.mom.model_moments, oo_.mom.model_moments_params_derivs, oo_.mom.irf_model_varobs] = objective_function(xparam1, oo_.mom.data_moments, oo_.mom.weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state); % store final results in oo_.mom
|
||||
if strcmp(options_mom_.mom.mom_method,'SMM') || strcmp(options_mom_.mom.mom_method,'GMM')
|
||||
% Store results in output structure
|
||||
oo_.mom = display_estimation_results_table(xparam1,stdh,M_,options_mom_,estim_params_,bayestopt_,oo_.mom,prior_dist_names,options_mom_.mom.mom_method,lower(options_mom_.mom.mom_method));
|
||||
% J test
|
||||
oo_.mom.J_test = mom.Jtest(xparam1, objective_function, oo_.mom.Q, oo_.mom.model_moments, oo_.mom.m_data, oo_.mom.data_moments, oo_.mom.weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
|
||||
elseif strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
|
||||
if ~options_mom_.nograph
|
||||
mom.graph_comparison_irfs(M_.matched_irfs,oo_.mom.irf_model_varobs,options_mom_.varobs_id,options_mom_.irf,options_mom_.relative_irf,M_.endo_names,M_.endo_names_tex,M_.exo_names,M_.exo_names_tex,M_.dname,M_.fname,options_mom_.graph_format,options_mom_.TeX,options_mom_.nodisplay,options_mom_.figures.textwidth)
|
||||
end
|
||||
oo_ = mom.Jtest(xparam1, objective_function, Woptflag, oo_, options_mom_, bayestopt_, Bounds, estim_params_, M_, dataset_.nobs);
|
||||
% display comparison of model moments and data moments
|
||||
mom.display_comparison_moments(M_, options_mom_, oo_.mom.data_moments, oo_.mom.model_moments);
|
||||
end
|
||||
% display comparison of model moments/IRFs and data moments/IRFs
|
||||
mom.display_comparison_moments_irfs(M_, options_mom_, oo_.mom.data_moments, oo_.mom.model_moments);
|
||||
% save results to _mom_results.mat
|
||||
save([M_.dname filesep 'method_of_moments' filesep M_.fname '_mom_results.mat'], 'oo_', 'options_mom_', 'M_', 'estim_params_', 'bayestopt_');
|
||||
|
||||
fprintf('\n==== Method of Moments Estimation (%s) Completed ====\n\n',options_mom_.mom.mom_method);
|
||||
|
||||
% -------------------------------------------------------------------------
|
||||
% clean up
|
||||
% -------------------------------------------------------------------------
|
||||
warning_config; %reset warning state
|
||||
fprintf('\n==== Method of Moments Estimation (%s) Completed ====\n\n',options_mom_.mom.mom_method)
|
||||
|
||||
%reset warning state
|
||||
warning_config;
|
||||
|
||||
if isoctave && isfield(options_mom_, 'prior_restrictions') && ...
|
||||
isfield(options_mom_.prior_restrictions, 'routine')
|
||||
% Octave crashes if it tries to save function handles (to the _results.mat file)
|
||||
% See https://savannah.gnu.org/bugs/?43215
|
||||
options_mom_.prior_restrictions.routine = [];
|
||||
end
|
||||
if strcmp(options_mom_.mom.mom_method,'SMM') || strcmp(options_mom_.mom.mom_method,'GMM')
|
||||
if isfield(oo_.mom,'irf_model_varobs') && isempty(oo_.mom.irf_model_varobs)
|
||||
oo_.mom = rmfield(oo_.mom,'irf_model_varobs'); % remove empty field
|
||||
end
|
||||
end
|
||||
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING') && ~isempty(options_mom_.mom.irf_matching_file.path) && ~strcmp(options_mom_.mom.irf_matching_file.path,'.')
|
||||
rmpath(options_mom_.irf_matching_file.path); % remove path to irf_matching_file
|
||||
end
|
|
@ -1,19 +1,18 @@
|
|||
function BoundsInfo = set_correct_bounds_for_stderr_corr(estim_params_,BoundsInfo)
|
||||
% BoundsInfo = set_correct_bounds_for_stderr_corr(estim_params_,BoundsInfo)
|
||||
function Bounds = set_correct_bounds_for_stderr_corr(estim_params_,Bounds)
|
||||
% function Bounds = set_correct_bounds_for_stderr_corr(estim_params_,Bounds)
|
||||
% -------------------------------------------------------------------------
|
||||
% Set correct bounds for standard deviation and corrrelation parameters
|
||||
% -------------------------------------------------------------------------
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% o estim_params_ [struct] information on estimated parameters
|
||||
% o BoundsInfo [struct] information on bounds
|
||||
% o Bounds [struct] information on bounds
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUT
|
||||
% o BoundsInfo [struct] updated bounds
|
||||
% o Bounds [struct] updated bounds
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% =========================================================================
|
||||
% Copyright © 2023 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -30,15 +29,15 @@ function BoundsInfo = set_correct_bounds_for_stderr_corr(estim_params_,BoundsInf
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
% =========================================================================
|
||||
|
||||
number_of_estimated_parameters = estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn+estim_params_.np;
|
||||
% set correct bounds for standard deviations and corrrelations
|
||||
param_of_interest = (1:number_of_estimated_parameters)'<=estim_params_.nvx+estim_params_.nvn;
|
||||
LB_below_0 = (BoundsInfo.lb<0 & param_of_interest);
|
||||
BoundsInfo.lb(LB_below_0) = 0;
|
||||
LB_below_0 = (Bounds.lb<0 & param_of_interest);
|
||||
Bounds.lb(LB_below_0) = 0;
|
||||
param_of_interest = (1:number_of_estimated_parameters)'> estim_params_.nvx+estim_params_.nvn & (1:number_of_estimated_parameters)'<estim_params_.nvx+estim_params_.nvn +estim_params_.ncx + estim_params_.ncn;
|
||||
LB_below_minus_1 = (BoundsInfo.lb<-1 & param_of_interest);
|
||||
UB_above_1 = (BoundsInfo.ub>1 & param_of_interest);
|
||||
BoundsInfo.lb(LB_below_minus_1) = -1;
|
||||
BoundsInfo.ub(UB_above_1) = 1;
|
||||
LB_below_minus_1 = (Bounds.lb<-1 & param_of_interest);
|
||||
UB_above_1 = (Bounds.ub>1 & param_of_interest);
|
||||
Bounds.lb(LB_below_minus_1) = -1;
|
||||
Bounds.ub(UB_above_1) = 1;
|
|
@ -1,32 +1,23 @@
|
|||
function [stderr_values, asympt_cov_mat] = standard_errors(xparam, objective_function, model_moments, model_moments_params_derivs, m_data, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
|
||||
% [stderr_values, asympt_cov_mat] = standard_errors(xparam, objective_function, model_moments, model_moments_params_derivs, m_data, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
|
||||
function [SE_values, Asympt_Var] = standard_errors(xparam, objective_function, Bounds, oo_, estim_params_, M_, options_mom_, Wopt_flag)
|
||||
% [SE_values, Asympt_Var] = standard_errors(xparam, objective_function, Bounds, oo_, estim_params_, M_, options_mom_, Wopt_flag)
|
||||
% -------------------------------------------------------------------------
|
||||
% This function computes standard errors to the method of moments estimates
|
||||
% Adapted from replication codes of Andreasen, Fernández-Villaverde, 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.
|
||||
% -------------------------------------------------------------------------
|
||||
% Adapted from replication codes of
|
||||
% o Andreasen, Fernández-Villaverde, 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.
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% - xparam: [vector] value of estimated parameters as returned by set_prior()
|
||||
% - objective_function [func] function handle with string of objective function
|
||||
% - model_moments: [vector] model moments
|
||||
% - model_moments_params_derivs: [matrix] analytical jacobian of the model moments wrt estimated parameters (currently for GMM only)
|
||||
% - m_data [matrix] selected empirical moments at each point in time
|
||||
% - data_moments: [vector] data with moments/IRFs to match
|
||||
% - weighting_info: [structure] storing information on weighting matrices
|
||||
% - options_mom_: [structure] information about all settings (specified by the user, preprocessor, and taken from global options_)
|
||||
% - M_ [structure] model information
|
||||
% - estim_params_: [structure] information from estimated_params block
|
||||
% - bayestopt_: [structure] information on the prior distributions
|
||||
% - BoundsInfo: [structure] parameter bounds
|
||||
% - dr: [structure] reduced form model
|
||||
% - endo_steady_state: [vector] steady state value for endogenous variables (initval)
|
||||
% - exo_steady_state: [vector] steady state value for exogenous variables (initval)
|
||||
% - exo_det_steady_state: [vector] steady state value for exogenous deterministic variables (initval)
|
||||
% o xparam: value of estimated parameters as returned by set_prior()
|
||||
% o objective_function string of objective function
|
||||
% o Bounds: structure containing parameter bounds
|
||||
% o oo_: structure for results
|
||||
% o estim_params_: structure describing the estimated_parameters
|
||||
% o M_ structure describing the model
|
||||
% o options_mom_: structure information about all settings (specified by the user, preprocessor, and taken from global options_)
|
||||
% o Wopt_flag: indicator whether the optimal weighting is actually used
|
||||
% -------------------------------------------------------------------------
|
||||
% OUTPUTS
|
||||
% o stderr_values [nparam x 1] vector of standard errors
|
||||
% o asympt_cov_mat [nparam x nparam] asymptotic covariance matrix
|
||||
% o SE_values [nparam x 1] vector of standard errors
|
||||
% o Asympt_Var [nparam x nparam] asymptotic covariance matrix
|
||||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run.m
|
||||
|
@ -35,10 +26,9 @@ function [stderr_values, asympt_cov_mat] = standard_errors(xparam, objective_fun
|
|||
% o get_the_name
|
||||
% o get_error_message
|
||||
% o mom.objective_function
|
||||
% o mom.optimal_weighting_matrix
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% Copyright © 2020-2023 Dynare Team
|
||||
% o mom.optimal_weighting_matrix
|
||||
% =========================================================================
|
||||
% Copyright © 2020-2021 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
%
|
||||
|
@ -54,74 +44,84 @@ function [stderr_values, asympt_cov_mat] = standard_errors(xparam, objective_fun
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
% -------------------------------------------------------------------------
|
||||
% Author(s):
|
||||
% o Willi Mutschler (willi@mutschler.eu)
|
||||
% o Johannes Pfeifer (johannes.pfeifer@unibw.de)
|
||||
% =========================================================================
|
||||
|
||||
% Some dimensions
|
||||
num_mom = size(model_moments,1);
|
||||
num_mom = size(oo_.mom.model_moments,1);
|
||||
dim_params = size(xparam,1);
|
||||
D = zeros(num_mom,dim_params);
|
||||
eps_value = options_mom_.mom.se_tolx;
|
||||
|
||||
if strcmp(options_mom_.mom.mom_method,'GMM') && options_mom_.mom.analytic_standard_errors
|
||||
fprintf('\nComputing standard errors using analytical derivatives of moments\n');
|
||||
D = model_moments_params_derivs; % already computed in objective function via get_perturbation_params.m
|
||||
D = oo_.mom.model_moments_params_derivs; %already computed in objective function via get_perturbation_params.m
|
||||
idx_nan = find(any(isnan(D)));
|
||||
if any(idx_nan)
|
||||
for i = idx_nan
|
||||
fprintf('No standard errors available for parameter %s\n',get_the_name(i,options_mom_.TeX, M_, estim_params_, options_mom_.varobs))
|
||||
fprintf('No standard errors available for parameter %s\n',get_the_name(i,options_mom_.TeX, M_, estim_params_, options_mom_))
|
||||
end
|
||||
warning('There are NaN in the analytical Jacobian of Moments. Check your bounds and/or priors, or use a different optimizer.')
|
||||
asympt_cov_mat = NaN(length(xparam),length(xparam));
|
||||
stderr_values = NaN(length(xparam),1);
|
||||
Asympt_Var = NaN(length(xparam),length(xparam));
|
||||
SE_values = NaN(length(xparam),1);
|
||||
return
|
||||
end
|
||||
else
|
||||
fprintf('\nComputing standard errors using numerical derivatives of moments\n');
|
||||
for i=1:dim_params
|
||||
% positive step
|
||||
%Positive step
|
||||
xparam_eps_p = xparam;
|
||||
xparam_eps_p(i,1) = xparam_eps_p(i) + eps_value;
|
||||
[~, info_p, ~, ~, ~, ~, model_moments_p] = feval(objective_function, xparam_eps_p, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
|
||||
% negative step
|
||||
xparam_eps_p(i,1) = xparam_eps_p(i) + eps_value;
|
||||
[~, info_p, ~, ~,~, oo__p] = feval(objective_function, xparam_eps_p, Bounds, oo_, estim_params_, M_, options_mom_);
|
||||
|
||||
% Negative step
|
||||
xparam_eps_m = xparam;
|
||||
xparam_eps_m(i,1) = xparam_eps_m(i) - eps_value;
|
||||
[~, info_m, ~, ~, ~, ~, model_moments_m] = feval(objective_function, xparam_eps_m, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
|
||||
% the Jacobian
|
||||
xparam_eps_m(i,1) = xparam_eps_m(i) - eps_value;
|
||||
[~, info_m, ~, ~,~, oo__m] = feval(objective_function, xparam_eps_m, Bounds, oo_, estim_params_, M_, options_mom_);
|
||||
|
||||
% The Jacobian:
|
||||
if nnz(info_p)==0 && nnz(info_m)==0
|
||||
D(:,i) = (model_moments_p - model_moments_m)/(2*eps_value);
|
||||
D(:,i) = (oo__p.mom.model_moments - oo__m.mom.model_moments)/(2*eps_value);
|
||||
else
|
||||
problematic_parameter = get_the_name(i,options_mom_.TeX, M_, estim_params_, options_mom_.varobs);
|
||||
problpar = get_the_name(i,options_mom_.TeX, M_, estim_params_, options_mom_);
|
||||
if info_p(1)==42
|
||||
warning('method_of_moments:info','Cannot compute the Jacobian using finite differences for parameter %s due to hitting the upper bound - no standard errors available.\n',problematic_parameter)
|
||||
warning('method_of_moments:info','Cannot compute the Jacobian using finite differences for parameter %s due to hitting the upper bound - no standard errors available.\n',problpar)
|
||||
else
|
||||
message_p = get_error_message(info_p, options_mom_);
|
||||
end
|
||||
if info_m(1)==41
|
||||
warning('method_of_moments:info','Cannot compute the Jacobian using finite differences for parameter %s due to hitting the lower bound - no standard errors available.\n',problematic_parameter)
|
||||
warning('method_of_moments:info','Cannot compute the Jacobian using finite differences for parameter %s due to hitting the lower bound - no standard errors available.\n',problpar)
|
||||
else
|
||||
message_m = get_error_message(info_m, options_mom_);
|
||||
message_m = get_error_message(info_m, options_mom_);
|
||||
end
|
||||
if info_m(1)~=41 && info_p(1)~=42
|
||||
warning('method_of_moments:info','Cannot compute the Jacobian using finite differences for parameter %s - no standard errors available\n %s %s\nCheck your priors or use a different optimizer.\n',problematic_parameter, message_p, message_m)
|
||||
warning('method_of_moments:info','Cannot compute the Jacobian using finite differences for parameter %s - no standard errors available\n %s %s\nCheck your priors or use a different optimizer.\n',problpar, message_p, message_m)
|
||||
end
|
||||
asympt_cov_mat = NaN(length(xparam),length(xparam));
|
||||
stderr_values = NaN(length(xparam),1);
|
||||
Asympt_Var = NaN(length(xparam),length(xparam));
|
||||
SE_values = NaN(length(xparam),1);
|
||||
return
|
||||
end
|
||||
end
|
||||
end
|
||||
T = options_mom_.nobs;
|
||||
|
||||
T = options_mom_.nobs; %Number of observations
|
||||
if isfield(options_mom_,'variance_correction_factor')
|
||||
T = T*options_mom_.variance_correction_factor;
|
||||
end
|
||||
WW = weighting_info.Sw'*weighting_info.Sw;
|
||||
if weighting_info.Woptflag
|
||||
% we already have the optimal weighting matrix
|
||||
asympt_cov_mat = 1/T*((D'*WW*D)\eye(dim_params));
|
||||
|
||||
WW = oo_.mom.Sw'*oo_.mom.Sw;
|
||||
if Wopt_flag
|
||||
% We have the optimal weighting matrix
|
||||
Asympt_Var = 1/T*((D'*WW*D)\eye(dim_params));
|
||||
else
|
||||
% we do not have the optimal weighting matrix yet
|
||||
WWopt = mom.optimal_weighting_matrix(m_data, model_moments, options_mom_.mom.bartlett_kernel_lag);
|
||||
% We do not have the optimal weighting matrix yet
|
||||
WWopt = mom.optimal_weighting_matrix(oo_.mom.m_data, oo_.mom.model_moments, options_mom_.mom.bartlett_kernel_lag);
|
||||
S = WWopt\eye(size(WWopt,1));
|
||||
AA = (D'*WW*D)\eye(dim_params);
|
||||
asympt_cov_mat = 1/T*AA*D'*WW*S*WW*D*AA;
|
||||
Asympt_Var = 1/T*AA*D'*WW*S*WW*D*AA;
|
||||
end
|
||||
stderr_values = sqrt(diag(asympt_cov_mat));
|
||||
|
||||
SE_values = sqrt(diag(Asympt_Var));
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
function bayestopt_ = transform_prior_to_laplace_prior(bayestopt_)
|
||||
% bayestopt_ = transform_prior_to_laplace_prior(bayestopt_)
|
||||
% function bayestopt_ = transform_prior_to_laplace_prior(bayestopt_)
|
||||
% -------------------------------------------------------------------------
|
||||
% Transforms the prior specification to a Laplace type of approximation:
|
||||
% only the prior mean and standard deviation are relevant, all other shape
|
||||
% information, except for the parameter bounds, is ignored.
|
||||
% -------------------------------------------------------------------------
|
||||
% =========================================================================
|
||||
% INPUTS
|
||||
% bayestopt_ [structure] prior information
|
||||
% -------------------------------------------------------------------------
|
||||
|
@ -13,8 +13,7 @@ function bayestopt_ = transform_prior_to_laplace_prior(bayestopt_)
|
|||
% -------------------------------------------------------------------------
|
||||
% This function is called by
|
||||
% o mom.run
|
||||
% -------------------------------------------------------------------------
|
||||
|
||||
% =========================================================================
|
||||
% Copyright © 2023 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
|
@ -31,7 +30,7 @@ function bayestopt_ = transform_prior_to_laplace_prior(bayestopt_)
|
|||
%
|
||||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
% =========================================================================
|
||||
if any(setdiff([0;bayestopt_.pshape],[0,3]))
|
||||
fprintf('\nNon-normal priors specified. Penalized estimation uses a Laplace type of approximation:');
|
||||
fprintf('\nOnly the prior mean and standard deviation are relevant, all other shape information, except for the parameter bounds, is ignored.\n\n');
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
function [alphahat,etahat,epsilonhat,ahat0,SteadyState,trend_coeff,aKK,T0,R0,P,PKK,decomp,Trend,state_uncertainty,oo_,bayestopt_,alphahat0,state_uncertainty0] = DSGE_smoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_,dataset_, dataset_info)
|
||||
% [alphahat,etahat,epsilonhat,ahat0,SteadyState,trend_coeff,aKK,T0,R0,P,PKK,decomp,Trend,state_uncertainty,oo_,bayestopt_,alphahat0,state_uncertainty0] = DSGE_smoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_,dataset_, dataset_info)
|
||||
%function [alphahat,etahat,epsilonhat,ahat0,SteadyState,trend_coeff,aKK,T0,R0,P,PKK,decomp,Trend,state_uncertainty,M_,oo_,bayestopt_] = DSGE_smoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_,dataset_, dataset_info)
|
||||
% Runs a DSGE smoother with occasionally binding constraints
|
||||
%
|
||||
% INPUTS
|
||||
|
@ -65,10 +65,8 @@ regime_history=[];
|
|||
if options_.occbin.smoother.linear_smoother && nargin==12
|
||||
%% linear smoother
|
||||
options_.occbin.smoother.status=false;
|
||||
[alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T0,R0,P,PK,decomp,Trend,state_uncertainty,oo_,bayestopt_,alphahat0,state_uncertainty0] = ...
|
||||
DsgeSmoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_);
|
||||
tmp_smoother=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,...
|
||||
aK,P,PK,decomp,Trend,state_uncertainty);
|
||||
[alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T0,R0,P,PK,decomp,Trend,state_uncertainty,oo_,bayestopt_] = DsgeSmoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_);
|
||||
tmp_smoother=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,P,PK,decomp,Trend,state_uncertainty);
|
||||
for jf=1:length(smoother_field_list)
|
||||
oo_.occbin.linear_smoother.(smoother_field_list{jf}) = tmp_smoother.(smoother_field_list{jf});
|
||||
end
|
||||
|
@ -82,9 +80,7 @@ if options_.occbin.smoother.linear_smoother && nargin==12
|
|||
oo_.occbin.linear_smoother.T0=T0;
|
||||
oo_.occbin.linear_smoother.R0=R0;
|
||||
oo_.occbin.linear_smoother.decomp=decomp;
|
||||
oo_.occbin.linear_smoother.alphahat0=alphahat0;
|
||||
oo_.occbin.linear_smoother.state_uncertainty0=state_uncertainty0;
|
||||
|
||||
|
||||
fprintf('\nOccbin: linear smoother done.\n')
|
||||
options_.occbin.smoother.status=true;
|
||||
end
|
||||
|
@ -116,46 +112,15 @@ opts_simul.max_check_ahead_periods = options_.occbin.smoother.max_check_ahead_pe
|
|||
opts_simul.periodic_solution = options_.occbin.smoother.periodic_solution;
|
||||
opts_simul.full_output = options_.occbin.smoother.full_output;
|
||||
opts_simul.piecewise_only = options_.occbin.smoother.piecewise_only;
|
||||
% init_mode = options_.occbin.smoother.init_mode; % 0 = standard; 1 = unconditional frcsts zero shocks+smoothed states in each period
|
||||
% init_mode = 0;
|
||||
occbin_options = struct();
|
||||
|
||||
occbin_options.first_period_occbin_update = options_.occbin.smoother.first_period_occbin_update;
|
||||
occbin_options.opts_simul = opts_simul; % this builds the opts_simul options field needed by occbin.solver
|
||||
occbin_options.opts_regime.binding_indicator = options_.occbin.smoother.init_binding_indicator;
|
||||
occbin_options.opts_regime.regime_history=options_.occbin.smoother.init_regime_history;
|
||||
|
||||
error_indicator=false;
|
||||
try
|
||||
%blanket try-catch should be replaced be proper error handling, see https://git.dynare.org/Dynare/dynare/-/merge_requests/2226#note_20318
|
||||
[alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T0,R0,P,PK,decomp,Trend,state_uncertainty,oo_,bayestopt_,alphahat0,state_uncertainty0] = DsgeSmoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_,occbin_options);% T1=TT;
|
||||
catch ME
|
||||
error_indicator=true;
|
||||
disp(ME.message)
|
||||
for iter = 1:numel(ME.stack)
|
||||
ME.stack(iter)
|
||||
end
|
||||
end
|
||||
if error_indicator || isempty(alphahat0)
|
||||
etahat= oo_.occbin.linear_smoother.etahat;
|
||||
alphahat0= oo_.occbin.linear_smoother.alphahat0;
|
||||
base_regime = struct();
|
||||
if M_.occbin.constraint_nbr==1
|
||||
base_regime.regime = 0;
|
||||
base_regime.regimestart = 1;
|
||||
else
|
||||
base_regime.regime1 = 0;
|
||||
base_regime.regimestart1 = 1;
|
||||
base_regime.regime2 = 0;
|
||||
base_regime.regimestart2 = 1;
|
||||
end
|
||||
oo_.occbin.smoother.regime_history = [];
|
||||
for jper=1:size(alphahat,2)+1
|
||||
if jper == 1
|
||||
oo_.occbin.smoother.regime_history = base_regime;
|
||||
else
|
||||
oo_.occbin.smoother.regime_history(jper) = base_regime;
|
||||
end
|
||||
end
|
||||
end
|
||||
occbin_options.opts_regime = opts_simul; % this builds the opts_simul options field needed by occbin.solver
|
||||
occbin_options.opts_regime.binding_indicator = options_.occbin.likelihood.init_binding_indicator;
|
||||
occbin_options.opts_regime.regime_history=options_.occbin.likelihood.init_regime_history;
|
||||
[alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T0,R0,P,PK,decomp,Trend,state_uncertainty,oo_,bayestopt_,alphahat0,state_uncertainty0, diffuse_steps] = DsgeSmoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_,occbin_options);% T1=TT;
|
||||
|
||||
oo_.occbin.smoother.realtime_regime_history = oo_.occbin.smoother.regime_history;
|
||||
regime_history = oo_.occbin.smoother.regime_history;
|
||||
|
@ -176,7 +141,6 @@ opts_simul.SHOCKS = [etahat(:,1:end)'; zeros(1,M_.exo_nbr)];
|
|||
opts_simul.exo_pos = 1:M_.exo_nbr;
|
||||
opts_simul.endo_init = alphahat0(oo_.dr.inv_order_var,1);
|
||||
opts_simul.init_regime=regime_history; % use realtime regime for guess, to avoid multiple solution issues!
|
||||
opts_simul.periods = size(opts_simul.SHOCKS,1);
|
||||
options_.occbin.simul=opts_simul;
|
||||
options_.noprint = true;
|
||||
[~, out, ss] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
|
||||
|
@ -192,10 +156,15 @@ if options_.smoother_redux
|
|||
[T0,R0] = dynare_resolve(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
|
||||
oo_.occbin.linear_smoother.T0=T0;
|
||||
oo_.occbin.linear_smoother.R0=R0;
|
||||
% oo_.occbin.linear_smoother.T0=ss.T(oo_.dr.order_var,oo_.dr.order_var,1);
|
||||
% oo_.occbin.linear_smoother.R0=ss.R(oo_.dr.order_var,:,1);
|
||||
end
|
||||
TT = ss.T(oo_.dr.order_var,oo_.dr.order_var,:);
|
||||
RR = ss.R(oo_.dr.order_var,:,:);
|
||||
CC = ss.C(oo_.dr.order_var,:);
|
||||
% TT = cat(3,TT(:,:,1),TT);
|
||||
% RR = cat(3,RR(:,:,1),RR);
|
||||
% CC = cat(2,CC(:,1),CC);
|
||||
|
||||
opts_regime.regime_history = regime_history;
|
||||
opts_regime.binding_indicator = [];
|
||||
|
@ -217,7 +186,6 @@ sto_etahat={etahat};
|
|||
sto_CC = CC;
|
||||
sto_RR = RR;
|
||||
sto_TT = TT;
|
||||
sto_eee=NaN(size(TT,1),size(TT,3));
|
||||
for k=1:size(TT,3)
|
||||
sto_eee(:,k) = eig(TT(:,:,k));
|
||||
end
|
||||
|
@ -227,12 +195,11 @@ while is_changed && maxiter>iter && ~is_periodic
|
|||
iter=iter+1;
|
||||
fprintf('Occbin smoother iteration %u.\n', iter)
|
||||
occbin_options.opts_regime.regime_history=regime_history;
|
||||
[alphahat,etahat,epsilonhat,~,SteadyState,trend_coeff,~,T0,R0,P,~,decomp,Trend,state_uncertainty,oo_,bayestopt_,alphahat0,state_uncertainty0]...
|
||||
= DsgeSmoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_,occbin_options,TT,RR,CC);
|
||||
[alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T0,R0,P,PK,decomp,Trend,state_uncertainty,oo_,bayestopt_,alphahat0,state_uncertainty0, diffuse_steps] = DsgeSmoother(xparam1,gend,Y,data_index,missing_value,M_,oo_,options_,bayestopt_,estim_params_,occbin_options,TT,RR,CC);% T1=TT;
|
||||
sto_etahat(iter)={etahat};
|
||||
regime_history0(iter,:) = regime_history;
|
||||
if occbin_smoother_debug
|
||||
save('Occbin_smoother_debug_regime_history','regime_history0');
|
||||
save('info1','regime_history0');
|
||||
end
|
||||
|
||||
sto_CC = CC;
|
||||
|
@ -253,13 +220,13 @@ while is_changed && maxiter>iter && ~is_periodic
|
|||
TT = ss.T(oo_.dr.order_var,oo_.dr.order_var,:);
|
||||
RR = ss.R(oo_.dr.order_var,:,:);
|
||||
CC = ss.C(oo_.dr.order_var,:);
|
||||
% TT = cat(3,TT(:,:,1),TT);
|
||||
% RR = cat(3,RR(:,:,1),RR);
|
||||
% CC = cat(2,CC(:,1),CC);
|
||||
|
||||
opts_regime.regime_history = regime_history;
|
||||
[TT, RR, CC, regime_history] = occbin.check_regimes(TT, RR, CC, opts_regime, M_, options_ , oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);
|
||||
is_changed = ~isequal(regime_history0(iter,:),regime_history);
|
||||
isdiff_regime=NaN(size(regime_history0,2),M_.occbin.constraint_nbr);
|
||||
isdiff_start=NaN(size(isdiff_regime));
|
||||
isdiff_=NaN(size(isdiff_regime));
|
||||
if M_.occbin.constraint_nbr==2
|
||||
for k=1:size(regime_history0,2)
|
||||
isdiff_regime(k,1) = ~isequal(regime_history0(end,k).regime1,regime_history(k).regime1);
|
||||
|
@ -269,16 +236,16 @@ while is_changed && maxiter>iter && ~is_periodic
|
|||
isdiff_start(k,2) = ~isequal(regime_history0(end,k).regimestart2,regime_history(k).regimestart2);
|
||||
isdiff_(k,2) = isdiff_regime(k,2) || isdiff_start(k,2);
|
||||
end
|
||||
is_changed_regime = any(isdiff_regime(:,1)) || any(isdiff_regime(:,2));
|
||||
is_changed_start = any(isdiff_start(:,1)) || any(isdiff_start(:,2));
|
||||
is_changed_regime = ~isempty(find(isdiff_regime(:,1))) || ~isempty(find(isdiff_regime(:,2)));
|
||||
is_changed_start = ~isempty(find(isdiff_start(:,1))) || ~isempty(find(isdiff_start(:,2)));
|
||||
else
|
||||
for k=1:size(regime_history0,2)
|
||||
isdiff_regime(k,1) = ~isequal(regime_history0(end,k).regime,regime_history(k).regime);
|
||||
isdiff_start(k,1) = ~isequal(regime_history0(end,k).regimestart,regime_history(k).regimestart);
|
||||
isdiff_(k,1) = isdiff_regime(k,1) || isdiff_start(k,1);
|
||||
end
|
||||
is_changed_regime = any(isdiff_regime(:,1));
|
||||
is_changed_start = any(isdiff_start(:,1));
|
||||
is_changed_regime = ~isempty(find(isdiff_regime(:,1)));
|
||||
is_changed_start = ~isempty(find(isdiff_start(:,1)));
|
||||
end
|
||||
if occbin_smoother_fast
|
||||
is_changed = is_changed_regime;
|
||||
|
@ -294,11 +261,9 @@ while is_changed && maxiter>iter && ~is_periodic
|
|||
end
|
||||
|
||||
if is_changed
|
||||
eee=NaN(size(TT,1),size(TT,3));
|
||||
for k=1:size(TT,3)
|
||||
eee(:,k) = eig(TT(:,:,k));
|
||||
end
|
||||
if options_.debug
|
||||
err_eig(iter-1) = max(max(abs(sort(eee)-sort(sto_eee))));
|
||||
err_alphahat(iter-1) = max(max(max(abs(alphahat-sto_alphahat))));
|
||||
err_etahat(iter-1) = max(max(max(abs(etahat-sto_etahat{iter-1}))));
|
||||
|
@ -306,7 +271,6 @@ while is_changed && maxiter>iter && ~is_periodic
|
|||
err_RR(iter-1) = max(max(max(abs(RR-sto_RR))));
|
||||
err_TT(iter-1) = max(max(max(abs(TT-sto_TT))));
|
||||
end
|
||||
end
|
||||
|
||||
if occbin_smoother_debug || is_periodic
|
||||
regime_ = cell(0);
|
||||
|
@ -386,7 +350,7 @@ regime_history0(max(iter+1,1),:) = regime_history;
|
|||
oo_.occbin.smoother.regime_history=regime_history0(end,:);
|
||||
oo_.occbin.smoother.regime_history_iter=regime_history0;
|
||||
if occbin_smoother_debug
|
||||
save('Occbin_smoother_debug_regime_history','regime_history0')
|
||||
save('info1','regime_history0')
|
||||
end
|
||||
|
||||
if (maxiter==iter && is_changed) || is_periodic
|
||||
|
@ -429,24 +393,12 @@ if (~is_changed || occbin_smoother_debug) && nargin==12
|
|||
oo_.occbin.smoother.T0=TT;
|
||||
oo_.occbin.smoother.R0=RR;
|
||||
oo_.occbin.smoother.C0=CC;
|
||||
oo_.occbin.smoother.simul.piecewise = out.piecewise(1:end-1,:);
|
||||
if ~options_.occbin.simul.piecewise_only
|
||||
oo_.occbin.smoother.simul.linear = out.linear(1:end-1,:);
|
||||
end
|
||||
if options_.occbin.smoother.plot
|
||||
GraphDirectoryName = CheckPath('graphs',M_.fname);
|
||||
latexFolder = CheckPath('latex',M_.dname);
|
||||
|
||||
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
|
||||
fidTeX = fopen([latexFolder filesep M_.fname '_OccBin_smoother_plots.tex'],'w');
|
||||
fprintf(fidTeX,'%% TeX eps-loader file generated by occbin.DSGE_smoother.m (Dynare).\n');
|
||||
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
|
||||
fprintf(fidTeX,' \n');
|
||||
end
|
||||
j1=0;
|
||||
ifig=0;
|
||||
for j=1:M_.exo_nbr
|
||||
if max(abs(oo_.occbin.smoother.etahat(j,:)))>1.e-8
|
||||
if M_.Sigma_e(j,j)
|
||||
j1=j1+1;
|
||||
if mod(j1,9)==1
|
||||
hh_fig = dyn_figure(options_.nodisplay,'name','Occbin smoothed shocks');
|
||||
|
@ -462,49 +414,23 @@ if (~is_changed || occbin_smoother_debug) && nargin==12
|
|||
plot(oo_.occbin.smoother.etahat(j,:)','r--','linewidth',2)
|
||||
hold on, plot([0 options_.nobs],[0 0],'k--')
|
||||
set(gca,'xlim',[0 options_.nobs])
|
||||
if options_.TeX
|
||||
title(['$' M_.exo_names_tex{j,:} '$'],'interpreter','latex')
|
||||
else
|
||||
title(M_.exo_names{j,:},'interpreter','none')
|
||||
end
|
||||
|
||||
title(deblank(M_.exo_names(j,:)),'interpreter','none')
|
||||
if mod(j1,9)==0
|
||||
if options_.occbin.smoother.linear_smoother
|
||||
annotation('textbox', [0.1,0,0.35,0.05],'String', 'Linear','Color','Blue','horizontalalignment','center','interpreter','none');
|
||||
end
|
||||
annotation('textbox', [0.55,0,0.35,0.05],'String', 'Piecewise','Color','Red','horizontalalignment','center','interpreter','none');
|
||||
dyn_saveas(gcf,[GraphDirectoryName filesep M_.fname,'_smoothedshocks_occbin',int2str(ifig)],options_.nodisplay,options_.graph_format);
|
||||
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
|
||||
% TeX eps loader file
|
||||
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,'\\label{Fig:smoothedshocks_occbin:%s}\n',int2str(ifig));
|
||||
fprintf(fidTeX,'\\end{figure}\n');
|
||||
fprintf(fidTeX,' \n');
|
||||
end
|
||||
end
|
||||
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);
|
||||
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
|
||||
% TeX eps loader file
|
||||
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,'\\label{Fig:smoothedshocks_occbin:%s}\n',int2str(ifig));
|
||||
fprintf(fidTeX,'\\end{figure}\n');
|
||||
fprintf(fidTeX,' \n');
|
||||
end
|
||||
end
|
||||
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
|
||||
fclose(fidTeX);
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
|
|
|
@ -71,7 +71,7 @@ end
|
|||
|
||||
if ~isempty(xparam1)
|
||||
M_ = set_all_parameters(xparam1,estim_params_,M_);
|
||||
[fval,info,exit_flag]=check_bounds_and_definiteness_estimation(xparam1, M_, estim_params_, BoundsInfo);
|
||||
[fval,info,exit_flag,Q,H]=check_bounds_and_definiteness_estimation(xparam1, M_, estim_params_, BoundsInfo);
|
||||
if info(1)
|
||||
return
|
||||
end
|
||||
|
@ -81,7 +81,7 @@ err_index=options_.occbin.likelihood.IVF_shock_observable_mapping; % err_index=
|
|||
COVMAT1 = M_.Sigma_e(err_index,err_index);
|
||||
|
||||
% Linearize the model around the deterministic steady state and extract the matrices of the state equation (T and R).
|
||||
[~,~,SteadyState,info,dr, M_.params] = dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state,'restrict');
|
||||
[T,R,SteadyState,info,dr, M_.params] = dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state,'restrict');
|
||||
|
||||
% Return, with endogenous penalty when possible, if dynare_resolve issues an error code (defined in resol).
|
||||
if info(1)
|
||||
|
@ -195,4 +195,4 @@ end
|
|||
|
||||
% remember that the likelihood has already been multiplied by -1
|
||||
% hence, posterior is -1 times the log of the prior
|
||||
fval = like+prior;
|
||||
fval = like+prior;
|
|
@ -1,87 +0,0 @@
|
|||
function [binding_indicator, A, regime_string] = backward_map_regime(regime, regime_start)
|
||||
% [binding_indicator, A, regime_string] = backward_map_regime(regime, regime_start)
|
||||
% Map regime information into regime indicator
|
||||
%
|
||||
% Inputs:
|
||||
% - regime [integer] [1 by n_transitions] vector of regime number indices
|
||||
% - regime_start [integer] [1 by n_transitions] vectors with period numbers in which regime starts
|
||||
%
|
||||
% Outputs:
|
||||
% - binding_indicator [integer] [nperiods by 1] vector of regime indices
|
||||
% - A [bin] binary representation of binding indicator
|
||||
% - error_flag [boolean] 1 if regime never leaves 1 or is still there at the end of nperiods
|
||||
% 0 otherwise
|
||||
|
||||
% Copyright © 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
|
||||
|
||||
if nargin ==1
|
||||
% polymorphism
|
||||
if ~isstruct(regime)
|
||||
disp('error::backward_map_regime')
|
||||
disp('input arguments may be 1 structure with regime info')
|
||||
disp('or two arrays: regime and regimestart ')
|
||||
error('wrong input')
|
||||
end
|
||||
|
||||
fnam = fieldnames(regime);
|
||||
if length(fnam) == 2
|
||||
[binding_indicator, A, regime_string] = occbin.backward_map_regime(regime.regime, regime.regimestart);
|
||||
else
|
||||
for k=1:2
|
||||
nperiods(k) = regime.(['regimestart' int2str(k)])(end);
|
||||
number_of_binary_tokens(k) = ceil((nperiods(k)-1)/50);
|
||||
end
|
||||
binding_indicator = false(max(nperiods),2);
|
||||
A = int64(zeros(max(number_of_binary_tokens),2));
|
||||
|
||||
for k=1:2
|
||||
[binding_indicator(1:nperiods(k),k), A(1:number_of_binary_tokens(k),k), tmp{k}] = ...
|
||||
occbin.backward_map_regime(regime.(['regime' int2str(k)]), regime.(['regimestart' int2str(k)]));
|
||||
end
|
||||
regime_string = char(tmp{1},tmp{2});
|
||||
end
|
||||
|
||||
return
|
||||
else
|
||||
if isstruct(regime)
|
||||
disp('error::backward_map_regime')
|
||||
disp('input arguments may be ONE structure with regime info')
|
||||
disp('or TWO arrays: regime and regimestart ')
|
||||
error('wrong input')
|
||||
end
|
||||
end
|
||||
|
||||
regime_string = char(mat2str(double(regime)),mat2str(regime_start));
|
||||
|
||||
nperiods_0 = regime_start(end);
|
||||
number_of_binary_tokens = max(1,ceil((nperiods_0-1)/50));
|
||||
A = int64(zeros(number_of_binary_tokens,1));
|
||||
binding_indicator = false(nperiods_0,1);
|
||||
if length(regime)>1
|
||||
for ir=1:length(regime)-1
|
||||
binding_indicator(regime_start(ir):regime_start(ir+1)-1,1) = regime(ir);
|
||||
for k=regime_start(ir):regime_start(ir+1)-1
|
||||
this_token = ceil(k/50);
|
||||
A(this_token) = int64(bitset(A(this_token),k-50*(this_token-1),regime(ir)));
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
binding_indicator = logical(binding_indicator);
|
||||
% to convert regime in a readable string array
|
||||
% a = dec2bin(A);
|
||||
% bindicator = [a(end:-1:1) '0'];
|
|
@ -1,50 +0,0 @@
|
|||
function [cost, out] = cost_function(err_0, current_obs, weights, opts_simul,...
|
||||
M_, dr,endo_steady_state,exo_steady_state,exo_det_steady_state, options_)
|
||||
% [cost, out] = cost_function(err_0, current_obs, opts_simul,...
|
||||
% M_, dr,endo_steady_state,exo_steady_state,exo_det_steady_state, options_)
|
||||
% Outputs:
|
||||
% - cost [double] penalty
|
||||
% - out [structure] Occbin's results structure
|
||||
%
|
||||
% Inputs
|
||||
% - err_0 [double] value of shocks
|
||||
% - current_obs [double] [1 by n_obs] current value of observables
|
||||
% - weights [double] [1 by n_obs] variance of observables,
|
||||
% - opts_simul [structure] Structure with simulation options
|
||||
% used in cost function
|
||||
% - M_ [structure] Matlab's structure describing the model (M_).
|
||||
% - dr_ [structure] model information structure
|
||||
% - endo_steady_state [vector] steady state value for endogenous variables
|
||||
% - exo_steady_state [vector] steady state value for exogenous variables
|
||||
% - exo_det_steady_state [vector] steady state value for exogenous deterministic variables
|
||||
% - options_ [structure] Matlab's structure describing the current options (options_).
|
||||
|
||||
% Copyright © 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
|
||||
|
||||
|
||||
opts_simul.SHOCKS = err_0';
|
||||
options_.occbin.simul=opts_simul;
|
||||
options_.occbin.simul.full_output=1;
|
||||
options_.noprint = 1;
|
||||
[~, out] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
|
||||
cost = 0;
|
||||
if ~out.error_flag
|
||||
cost = mean((out.piecewise(1,opts_simul.varobs_id)'-current_obs').^2./weights);
|
||||
else
|
||||
cost = cost+1.e10;
|
||||
end
|
|
@ -1,63 +0,0 @@
|
|||
function [y, out, cost] = findmin(d_index, a0, P1, Qt, Y, ZZ, opts_simul,M_, dr,endo_steady_state,exo_steady_state,exo_det_steady_state, options_)
|
||||
% [y, out, cost] = findmin(d_index, a0, P1, Qt, Y, ZZ, opts_simul,M_, dr,endo_steady_state,exo_steady_state,exo_det_steady_state, options_)
|
||||
% Outputs:
|
||||
% - cost [double] penalty
|
||||
% - out [structure] Occbin's results structure
|
||||
%
|
||||
% Inputs
|
||||
% - opts_simul [structure] Structure with simulation options
|
||||
% used in cost function
|
||||
% - M_ [structure] Matlab's structure describing the model (M_).
|
||||
% - dr_ [structure] model information structure
|
||||
% - endo_steady_state [vector] steady state value for endogenous variables
|
||||
% - exo_steady_state [vector] steady state value for exogenous variables
|
||||
% - exo_det_steady_state [vector] steady state value for exogenous deterministic variables
|
||||
% - options_ [structure] Matlab's structure describing the current options (options_).
|
||||
|
||||
% Copyright © 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
|
||||
|
||||
current_obs = Y(d_index,2)'+dr.ys(options_.varobs_id(d_index))';
|
||||
err_index = find(diag(Qt(:,:,2))~=0);
|
||||
F = ZZ(d_index,:)*P1(:,:,2)*ZZ(d_index,:)' ;
|
||||
|
||||
weights=diag(F);
|
||||
|
||||
filtered_errs_init = zeros(1,length(err_index));
|
||||
opts_simul.varobs_id=options_.varobs_id(d_index)';
|
||||
opts_simul.exo_pos=err_index; %err_index is predefined mapping from observables to shocks
|
||||
opts_simul.SHOCKS = filtered_errs_init;
|
||||
if opts_simul.restrict_state_space
|
||||
tmp=zeros(M_.endo_nbr,1);
|
||||
tmp(dr.restrict_var_list,1)=a0(:,1); %updated state
|
||||
opts_simul.endo_init = tmp(dr.inv_order_var,1);
|
||||
else
|
||||
opts_simul.endo_init = a0(dr.inv_order_var,1);
|
||||
end
|
||||
|
||||
|
||||
[y] = fminsearch(@cost_function,filtered_errs_init');
|
||||
|
||||
[cost, out] = occbin.cost_function(y, current_obs, weights, opts_simul,...
|
||||
M_, dr,endo_steady_state,exo_steady_state,exo_det_steady_state, options_);
|
||||
|
||||
function cost = cost_function(x)
|
||||
cost = occbin.cost_function(x, current_obs, weights, opts_simul,...
|
||||
M_, dr,endo_steady_state,exo_steady_state,exo_det_steady_state, options_);
|
||||
end
|
||||
|
||||
|
||||
end
|
|
@ -1,169 +0,0 @@
|
|||
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/>.
|
||||
|
||||
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
|
||||
end
|
||||
elseif isreal(shocks_input)
|
||||
shock_mat=shocks_input;
|
||||
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
|
||||
[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);
|
||||
else
|
||||
SHOCKS_add = randn(forecast_horizon*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);
|
||||
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')
|
||||
end
|
||||
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
|
||||
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);
|
||||
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;
|
||||
end
|
||||
|
||||
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);
|
||||
end
|
||||
end
|
||||
|
||||
forecast.regimes=frcst_regime_history;
|
|
@ -109,7 +109,7 @@ for fig = 1:nbplt
|
|||
if ndim==2
|
||||
legend([h1,h2],legend_list,'box','off')
|
||||
else
|
||||
legend(h1,legend_list,'box','off')
|
||||
legend([h1],legend_list,'box','off')
|
||||
end
|
||||
end
|
||||
if options_.TeX
|
||||
|
|
|
@ -1,124 +0,0 @@
|
|||
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/>.
|
||||
|
||||
shocknames = options_.occbin.irf.exo_names;
|
||||
shocksigns = options_.occbin.irf.shocksigns; %'pos','neg'
|
||||
shocksize = options_.occbin.irf.shocksize;
|
||||
t_0 = options_.occbin.irf.t0;
|
||||
|
||||
%% set simulation options based on IRF options
|
||||
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);
|
||||
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);
|
||||
end
|
||||
options_.occbin.simul.SHOCKS=shocks_base;
|
||||
|
||||
[~, 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
|
||||
|
||||
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');
|
||||
end
|
||||
|
||||
% cs=get_lower_cholesky_covariance(M_.Sigma_e,options_.add_tiny_number_to_cholesky);
|
||||
% irf_shocks_indx = getIrfShocksIndx(M_, options_);
|
||||
|
||||
% Set shock size
|
||||
if isempty(shocksize)
|
||||
shocksize = sqrt(diag(M_.Sigma_e(exo_index,exo_index)));
|
||||
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
|
||||
options_.occbin.simul.endo_init = [];
|
||||
else
|
||||
options_.occbin.simul.endo_init = oo_.occbin.smoother.alphahat(oo_.dr.inv_order_var,t_0);
|
||||
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
|
||||
end
|
||||
% 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
|
||||
end
|
||||
end
|
|
@ -1,4 +1,4 @@
|
|||
function [a, a1, P, P1, v, T, R, C, regimes_, error_flag, M_, lik, etahat, alphahat, V] = kalman_update_algo_1(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,T0,R0,TT,RR,CC,regimes0,M_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state,options_,occbin_options)
|
||||
function [a, a1, P, P1, v, T, R, C, regimes_, error_flag, M_, lik, etahat] = kalman_update_algo_1(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,T0,R0,TT,RR,CC,regimes0,M_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state,options_,occbin_options)
|
||||
% function [a, a1, P, P1, v, T, R, C, regimes_, error_flag, M_, lik, etahat] = kalman_update_algo_1(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,T0,R0,TT,RR,CC,regimes0,M_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state,options_,occbin_options)
|
||||
% INPUTS
|
||||
% - a [N by 1] t-1's state estimate
|
||||
|
@ -86,8 +86,6 @@ else
|
|||
base_regime.regimestart2 = 1;
|
||||
end
|
||||
regimes_ = [base_regime base_regime base_regime];
|
||||
opts_simul = occbin_options.opts_simul;
|
||||
options_.occbin.simul=opts_simul;
|
||||
|
||||
mm=size(a,1);
|
||||
%% store info in t=1
|
||||
|
@ -105,46 +103,16 @@ PZI = P1(:,:,t)*ZZ'*iF(di,di,t);
|
|||
% L(:,:,t) = T-K(:,di,t)*ZZ;
|
||||
L(:,:,t) = eye(mm)-PZI*ZZ;
|
||||
|
||||
if ~isempty(fieldnames(regimes0))
|
||||
if options_.occbin.filter.guess_regime
|
||||
[~,~,~,~,~,~, TTx, RRx, CCx] ...
|
||||
= occbin.dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state, regimes0(1),'reduced_state_space',T0,R0);
|
||||
if M_.occbin.constraint_nbr==1
|
||||
bindx = occbin.backward_map_regime(regimes0(1).regime, regimes0(1).regimestart);
|
||||
bindx = bindx(2:end);
|
||||
[regimes0(2).regime, regimes0(2).regimestart, error_flag]=occbin.map_regime(bindx);
|
||||
bindx = bindx(2:end);
|
||||
[regimes0(3).regime, regimes0(3).regimestart, error_flag]=occbin.map_regime(bindx);
|
||||
else
|
||||
bindx1 = occbin.backward_map_regime(regimes0(1).regime1, regimes0(1).regimestart1);
|
||||
bindx2 = occbin.backward_map_regime(regimes0(1).regime2, regimes0(1).regimestart2);
|
||||
bindx1 = bindx1(2:end);
|
||||
bindx2 = bindx2(2:end);
|
||||
[regimes0(2).regime1, regimes0(2).regimestart1, error_flag]=occbin.map_regime(bindx1);
|
||||
[regimes0(2).regime2, regimes0(2).regimestart2, error_flag]=occbin.map_regime(bindx2);
|
||||
bindx1 = bindx1(2:end);
|
||||
bindx2 = bindx2(2:end);
|
||||
[regimes0(3).regime1, regimes0(3).regimestart1, error_flag]=occbin.map_regime(bindx1);
|
||||
[regimes0(3).regime2, regimes0(3).regimestart2, error_flag]=occbin.map_regime(bindx2);
|
||||
end
|
||||
% regimes0=[regimes0 base_regime base_regime];
|
||||
TT(:,:,2) = TTx(:,:,end);
|
||||
RR(:,:,2) = RRx(:,:,end);
|
||||
CC(:,2) = CCx(:,end);
|
||||
end
|
||||
[a, a1, P, P1, v, alphahat, etahat, lik, V, error_flag] = occbin_kalman_update0(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,iF,L,mm, options_.rescale_prediction_error_covariance, options_.occbin.likelihood.IF_likelihood, options_.occbin.filter.state_covariance);
|
||||
if ~options_.occbin.filter.use_relaxation
|
||||
[a, a1, P, P1, v, alphahat, etahat, lik, error_flag] = occbin_kalman_update0(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,iF,L,mm, options_.rescale_prediction_error_covariance, options_.occbin.likelihood.IF_likelihood);
|
||||
else
|
||||
[~,~,~,~,~,~, TTx, RRx, CCx] ...
|
||||
= occbin.dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state, base_regime,'reduced_state_space',T0,R0);
|
||||
if isempty(fieldnames(regimes0))
|
||||
regimes0 = regimes_;
|
||||
else
|
||||
regimes0(1)=base_regime;
|
||||
end
|
||||
regimes0(1)=base_regime;
|
||||
TT(:,:,2) = TTx(:,:,end);
|
||||
RR(:,:,2) = RRx(:,:,end);
|
||||
CC(:,2) = CCx(:,end);
|
||||
[a, a1, P, P1, v, alphahat, etahat, lik, V, error_flag] = occbin_kalman_update0(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,iF,L,mm, options_.rescale_prediction_error_covariance, options_.occbin.likelihood.IF_likelihood, options_.occbin.filter.state_covariance);
|
||||
[a, a1, P, P1, v, alphahat, etahat, lik, error_flag] = occbin_kalman_update0(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,iF,L,mm, options_.rescale_prediction_error_covariance, options_.occbin.likelihood.IF_likelihood);
|
||||
end
|
||||
if error_flag
|
||||
etahat=NaN(size(QQQ,1),1);
|
||||
|
@ -152,6 +120,7 @@ if error_flag
|
|||
end
|
||||
|
||||
%% run here the occbin simul
|
||||
opts_simul = occbin_options.opts_simul;
|
||||
opts_simul.SHOCKS = zeros(3,M_.exo_nbr);
|
||||
opts_simul.exo_pos=1:M_.exo_nbr;
|
||||
opts_simul.SHOCKS(1,:) = etahat(:,2)';
|
||||
|
@ -165,24 +134,14 @@ else
|
|||
my_order_var = dr.order_var;
|
||||
end
|
||||
options_.occbin.simul=opts_simul;
|
||||
if options_.occbin.filter.guess_regime
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
if out.error_flag
|
||||
options_.occbin.simul.init_regime=regimes0;
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
if out.error_flag
|
||||
options_.occbin.simul=opts_simul;
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
end
|
||||
else
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
if out.error_flag
|
||||
options_.occbin.simul.init_regime=regimes0;
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
end
|
||||
end
|
||||
if out.error_flag
|
||||
error_flag = out.error_flag;
|
||||
etahat=etahat(:,2);
|
||||
lik=inf;
|
||||
return;
|
||||
end
|
||||
|
||||
|
@ -200,18 +159,53 @@ end
|
|||
lik_hist=lik;
|
||||
niter=1;
|
||||
is_periodic=0;
|
||||
if options_.occbin.filter.use_relaxation || isequal(regimes0(1),base_regime)
|
||||
nguess=1;
|
||||
else
|
||||
nguess=0;
|
||||
end
|
||||
newguess=0;
|
||||
|
||||
if any(myregime) || ~isequal(regimes_(1),regimes0(1))
|
||||
while ~isequal(regimes_(1),regimes0(1)) && ~is_periodic && ~out.error_flag && niter<=options_.occbin.likelihood.max_number_of_iterations
|
||||
niter=niter+1;
|
||||
TT(:,:,2)=ss.T(my_order_var,my_order_var,1);
|
||||
RR(:,:,2)=ss.R(my_order_var,:,1);
|
||||
CC(:,2)=ss.C(my_order_var,1);
|
||||
oldstart=1;
|
||||
if M_.occbin.constraint_nbr==1 && length(regimes0(1).regimestart)>1
|
||||
oldstart = regimes0(1).regimestart(end);
|
||||
end
|
||||
newstart=1;
|
||||
if M_.occbin.constraint_nbr==1 && length(regimes_(1).regimestart)>1
|
||||
newstart = regimes_(1).regimestart(end);
|
||||
end
|
||||
if M_.occbin.constraint_nbr==1 && (newstart-oldstart)>2 && options_.occbin.filter.use_relaxation
|
||||
regimestart = max(oldstart+2,round(0.5*(newstart+oldstart)));
|
||||
regimestart = min(regimestart,oldstart+4);
|
||||
if regimestart<=regimes_(1).regimestart(end-1)
|
||||
if length(regimes_(1).regimestart)<=3
|
||||
regimestart = max(regimestart, min(regimes_(1).regimestart(end-1)+2,newstart));
|
||||
else
|
||||
regimes_(1).regime = regimes_(1).regime(1:end-2);
|
||||
regimes_(1).regimestart = regimes_(1).regimestart(1:end-2);
|
||||
regimestart = max(regimestart, regimes_(1).regimestart(end-1)+1);
|
||||
end
|
||||
end
|
||||
regimes_(1).regimestart(end)=regimestart;
|
||||
[~,~,~,~,~,~, TTx, RRx, CCx] ...
|
||||
= occbin.dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state, [base_regime regimes_(1)],'reduced_state_space', T0, R0);
|
||||
TT(:,:,2) = TTx(:,:,end);
|
||||
RR(:,:,2) = RRx(:,:,end);
|
||||
CC(:,2) = CCx(:,end);
|
||||
elseif newguess==0
|
||||
TT(:,:,2)=ss.T(my_order_var,my_order_var,1);
|
||||
RR(:,:,2)=ss.R(my_order_var,:,1);
|
||||
CC(:,2)=ss.C(my_order_var,1);
|
||||
end
|
||||
newguess=0;
|
||||
regime_hist(niter) = {regimes_(1)};
|
||||
if M_.occbin.constraint_nbr==1
|
||||
regime_end(niter) = regimes_(1).regimestart(end);
|
||||
end
|
||||
[a, a1, P, P1, v, alphahat, etahat, lik, V] = occbin_kalman_update0(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,iF,L,mm, options_.rescale_prediction_error_covariance, options_.occbin.likelihood.IF_likelihood, options_.occbin.filter.state_covariance);
|
||||
[a, a1, P, P1, v, alphahat, etahat, lik] = occbin_kalman_update0(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,iF,L,mm, options_.rescale_prediction_error_covariance, options_.occbin.likelihood.IF_likelihood);
|
||||
etahat_hist(niter) = {etahat};
|
||||
lik_hist(niter) = lik;
|
||||
opts_simul.SHOCKS(1,:) = etahat(:,2)';
|
||||
|
@ -222,7 +216,9 @@ if any(myregime) || ~isequal(regimes_(1),regimes0(1))
|
|||
else
|
||||
opts_simul.endo_init = alphahat(dr.inv_order_var,1);
|
||||
end
|
||||
opts_simul.init_regime=regimes_(1);
|
||||
if not(options_.occbin.filter.use_relaxation)
|
||||
opts_simul.init_regime=regimes_(1);
|
||||
end
|
||||
if M_.occbin.constraint_nbr==1
|
||||
myregimestart = [regimes_.regimestart];
|
||||
else
|
||||
|
@ -231,14 +227,9 @@ if any(myregime) || ~isequal(regimes_(1),regimes0(1))
|
|||
opts_simul.periods = max(opts_simul.periods,max(myregimestart));
|
||||
options_.occbin.simul=opts_simul;
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
if out.error_flag
|
||||
options_.occbin.simul.init_regime=[];
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
end
|
||||
if out.error_flag
|
||||
error_flag = out.error_flag;
|
||||
etahat=etahat(:,2);
|
||||
lik=inf;
|
||||
return;
|
||||
end
|
||||
regimes0=regimes_;
|
||||
|
@ -247,14 +238,36 @@ if any(myregime) || ~isequal(regimes_(1),regimes0(1))
|
|||
for kiter=1:niter-1
|
||||
is_periodic(kiter) = isequal(regime_hist{kiter}, regimes_(1));
|
||||
end
|
||||
is_periodic_iter = find(is_periodic);
|
||||
is_periodic = any(is_periodic);
|
||||
if is_periodic
|
||||
% re-set to previous regime
|
||||
if options_.occbin.filter.periodic_solution
|
||||
% force projection conditional on most likely regime
|
||||
[m, im]=min(lik_hist(is_periodic_iter:end));
|
||||
opts_simul.init_regime=regime_hist{is_periodic_iter+im-1};
|
||||
if nguess<3 && M_.occbin.constraint_nbr==1
|
||||
newguess=1;
|
||||
is_periodic=0;
|
||||
nguess=nguess+1;
|
||||
if nguess==1
|
||||
% change starting regime
|
||||
regimes_(1).regime=0;
|
||||
regimes_(1).regimestart=1;
|
||||
elseif nguess==2
|
||||
% change starting regime
|
||||
regimes_(1).regime=[0 1 0];
|
||||
regimes_(1).regimestart=[1 2 3];
|
||||
else
|
||||
regimes_(1).regime=[1 0];
|
||||
regimes_(1).regimestart=[1 2];
|
||||
end
|
||||
[~,~,~,~,~,~, TTx, RRx, CCx] ...
|
||||
= occbin.dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state, [base_regime regimes_(1)],'reduced_state_space',T0,R0);
|
||||
TT(:,:,2) = TTx(:,:,end);
|
||||
RR(:,:,2) = RRx(:,:,end);
|
||||
CC(:,2) = CCx(:,end);
|
||||
regime_hist = regime_hist(1);
|
||||
niter=1;
|
||||
else
|
||||
% re-set to previous regime
|
||||
regimes_ = regimes0;
|
||||
% force projection conditional on previous regime
|
||||
opts_simul.init_regime=regimes0(1);
|
||||
if M_.occbin.constraint_nbr==1
|
||||
myregimestart = [regimes0.regimestart];
|
||||
else
|
||||
|
@ -267,20 +280,8 @@ if any(myregime) || ~isequal(regimes_(1),regimes0(1))
|
|||
if out.error_flag
|
||||
error_flag = out.error_flag;
|
||||
etahat=etahat(:,2);
|
||||
lik=inf;
|
||||
return;
|
||||
else
|
||||
regimes_ = out.regime_history;
|
||||
TT(:,:,2)=ss.T(my_order_var,my_order_var,1);
|
||||
RR(:,:,2)=ss.R(my_order_var,:,1);
|
||||
CC(:,2)=ss.C(my_order_var,1);
|
||||
[a, a1, P, P1, v, alphahat, etahat, lik, V] = occbin_kalman_update0(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,iF,L,mm, options_.rescale_prediction_error_covariance, options_.occbin.likelihood.IF_likelihood, options_.occbin.filter.state_covariance);
|
||||
end
|
||||
else
|
||||
error_flag = 330;
|
||||
etahat=etahat(:,2);
|
||||
lik=inf;
|
||||
return;
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -290,6 +291,62 @@ end
|
|||
error_flag = out.error_flag;
|
||||
if ~error_flag && niter>options_.occbin.likelihood.max_number_of_iterations && ~isequal(regimes_(1),regimes0(1))
|
||||
error_flag = 1;
|
||||
if M_.occbin.constraint_nbr==1 % try some other regime
|
||||
[ll, il]=sort(lik_hist);
|
||||
[ll, il]=sort(regime_end);
|
||||
rr=regime_hist(il(2:3));
|
||||
newstart=1;
|
||||
if length(rr{1}.regimestart)>1
|
||||
newstart = rr{1}.regimestart(end)-rr{1}.regimestart(end-1)+1;
|
||||
end
|
||||
oldstart=1;
|
||||
if length(rr{2}.regimestart)>1
|
||||
oldstart = rr{2}.regimestart(end)-rr{2}.regimestart(end-1)+1;
|
||||
end
|
||||
nstart=sort([newstart oldstart]);
|
||||
regimes_=rr{1}(1);
|
||||
for k=(nstart(1)+1):(nstart(2)-1)
|
||||
niter=niter+1;
|
||||
regimes_(1).regimestart(end)=k;
|
||||
|
||||
[~,~,~,~,~,~, TTx, RRx, CCx] ...
|
||||
= occbin.dynare_resolve(M_,options_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state, [base_regime regimes_(1)],'reduced_state_space',T0,R0);
|
||||
TT(:,:,2) = TTx(:,:,end);
|
||||
RR(:,:,2) = RRx(:,:,end);
|
||||
CC(:,2) = CCx(:,end);
|
||||
[a, a1, P, P1, v, alphahat, etahat, lik] = occbin_kalman_update0(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,iF,L,mm, options_.rescale_prediction_error_covariance, options_.occbin.likelihood.IF_likelihood);
|
||||
etahat_hist(niter) = {etahat};
|
||||
lik_hist(niter) = lik;
|
||||
regime_hist(niter) = {regimes_(1)};
|
||||
opts_simul.SHOCKS(1,:) = etahat(:,2)';
|
||||
if opts_simul.restrict_state_space
|
||||
tmp=zeros(M_.endo_nbr,1);
|
||||
tmp(dr.restrict_var_list,1)=alphahat(:,1);
|
||||
opts_simul.endo_init = tmp(dr.inv_order_var,1);
|
||||
else
|
||||
opts_simul.endo_init = alphahat(dr.inv_order_var,1);
|
||||
end
|
||||
% opts_simul.init_regime=regimes_(1);
|
||||
if M_.occbin.constraint_nbr==1
|
||||
myregimestart = [regimes_.regimestart];
|
||||
else
|
||||
myregimestart = [regimes_.regimestart1 regimes_.regimestart2];
|
||||
end
|
||||
opts_simul.periods = max(opts_simul.periods,max(myregimestart));
|
||||
options_.occbin.simul=opts_simul;
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
if out.error_flag
|
||||
error_flag = out.error_flag;
|
||||
etahat=etahat(:,2);
|
||||
return;
|
||||
end
|
||||
if isequal(out.regime_history(1),regimes_(1))
|
||||
error_flag=0;
|
||||
break
|
||||
end
|
||||
end
|
||||
regimes_ = out.regime_history;
|
||||
end
|
||||
end
|
||||
|
||||
if ~error_flag
|
||||
|
@ -302,26 +359,17 @@ C = ss.C(my_order_var,1:2);
|
|||
QQ = R(:,:,2)*QQQ(:,:,3)*transpose(R(:,:,2));
|
||||
P(:,:,1) = P(:,:,2);
|
||||
P(:,:,2) = T(:,:,2)*P(:,:,1)*transpose(T(:,:,2))+QQ;
|
||||
if nargout>=13
|
||||
etahat=etahat(:,2);
|
||||
end
|
||||
etahat=etahat(:,2);
|
||||
|
||||
warning_config;
|
||||
end
|
||||
|
||||
function [a, a1, P, P1, v, alphahat, etahat, lik, V, error_flag] = occbin_kalman_update0(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,iF,L,mm, rescale_prediction_error_covariance, IF_likelihood, state_uncertainty_flag)
|
||||
function [a, a1, P, P1, v, alphahat, etahat, lik, error_flag] = occbin_kalman_update0(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,iF,L,mm, rescale_prediction_error_covariance, IF_likelihood)
|
||||
alphahat=NaN(size(a));
|
||||
etahat=NaN(size(QQQ,1),2);
|
||||
lik=Inf;
|
||||
error_flag=0;
|
||||
|
||||
if state_uncertainty_flag
|
||||
V = zeros(mm,mm,2);
|
||||
N = zeros(mm,mm,3);
|
||||
else
|
||||
V=[];
|
||||
end
|
||||
|
||||
warning off
|
||||
if nargin<18
|
||||
IF_likelihood=0;
|
||||
|
@ -397,15 +445,9 @@ while t > 1
|
|||
if isempty(di)
|
||||
% in this case, L is simply T due to Z=0, so that DK (2012), eq. 4.93 obtains
|
||||
r(:,t) = L(:,:,t)'*r(:,t+1); %compute r_{t-1}, DK (2012), eq. 4.38 with Z=0
|
||||
if state_uncertainty_flag
|
||||
N(:,:,t)=L(:,:,t)'*N(:,:,t+1)*L(:,:,t); %compute N_{t-1}, DK (2012), eq. 4.42 with Z=0
|
||||
end
|
||||
else
|
||||
ZZ = Z(di,:);
|
||||
r(:,t) = ZZ'*iF(di,di,t)*v(di,t) + L(:,:,t)'*r(:,t+1); %compute r_{t-1}, DK (2012), eq. 4.38
|
||||
if state_uncertainty_flag
|
||||
N(:,:,t)=ZZ'*iF(di,di,t)*ZZ+L(:,:,t)'*N(:,:,t+1)*L(:,:,t); %compute N_{t-1}, DK (2012), eq. 4.42
|
||||
end
|
||||
end
|
||||
Q=QQQ(:,:,t);
|
||||
QRt = Q*transpose(RR(:,:,t));
|
||||
|
@ -413,10 +455,6 @@ while t > 1
|
|||
alphahat(:,t) = a1(:,t) + P1(:,:,t)*r(:,t); %DK (2012), eq. 4.35
|
||||
etahat(:,t) = QRt*r(:,t); %DK (2012), eq. 4.63
|
||||
r(:,t) = T'*r(:,t); % KD (2003), eq. (23), equation for r_{t-1,p_{t-1}}
|
||||
if state_uncertainty_flag
|
||||
V(:,:,t) = P1(:,:,t)-P1(:,:,t)*N(:,:,t)*P1(:,:,t); %DK (2012), eq. 4.43
|
||||
N(:,:,t) = T'*N(:,:,t)*T; %DK (2012), eq. 4.43
|
||||
end
|
||||
|
||||
if IF_likelihood && t==2 && not(isempty(di))
|
||||
ishocks = any(ZZ*RR(:,:,t));
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
function [a, a1, P, P1, v, Fi, Ki, T, R, C, regimes_, error_flag, M_, lik, alphahat, etahat, TT, RR, CC] = kalman_update_algo_3(a,a1,P,P1,data_index,Z,v,Fi,Ki,Y,H,QQQ,T0,R0,TT,RR,CC,regimes0,M_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state,options_,occbin_options,kalman_tol,nk)
|
||||
function [a, a1, P, P1, v, Fi, Ki, T, R, C, regimes_, error_flag, M_, alphahat, etahat, TT, RR, CC] = kalman_update_algo_3(a,a1,P,P1,data_index,Z,v,Fi,Ki,Y,H,QQQ,T0,R0,TT,RR,CC,regimes0,M_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state,options_,occbin_options,kalman_tol,nk)
|
||||
% function [a, a1, P, P1, v, Fi, Ki, T, R, C, regimes_, error_flag, M_, alphahat, etahat, TT, RR, CC] = kalman_update_algo_3(a,a1,P,P1,data_index,Z,v,Fi,Ki,Y,H,QQQ,T0,R0,TT,RR,CC,regimes0,M_,dr, endo_steady_state, exo_steady_state, exo_det_steady_state,options_,occbin_options,kalman_tol,nk)
|
||||
%
|
||||
% INPUTS
|
||||
|
@ -85,8 +85,7 @@ if isempty(nk)
|
|||
end
|
||||
nk=max(nk,1);
|
||||
|
||||
opts_simul = occbin_options.opts_simul;
|
||||
options_.occbin.simul=opts_simul;
|
||||
opts_simul = occbin_options.opts_regime;
|
||||
base_regime = struct();
|
||||
if M_.occbin.constraint_nbr==1
|
||||
base_regime.regime = 0;
|
||||
|
@ -97,7 +96,6 @@ else
|
|||
base_regime.regime2 = 0;
|
||||
base_regime.regimestart2 = 1;
|
||||
end
|
||||
regimes_ = [base_regime base_regime base_regime];
|
||||
myrestrict=[];
|
||||
if options_.smoother_redux
|
||||
opts_simul.restrict_state_space =1;
|
||||
|
@ -105,46 +103,15 @@ if options_.smoother_redux
|
|||
end
|
||||
|
||||
mm=size(a,1);
|
||||
if ~isempty(fieldnames(regimes0))
|
||||
if options_.occbin.filter.guess_regime
|
||||
[~,~,~,~,~,~, TTx, RRx, CCx] ...
|
||||
= occbin.dynare_resolve(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state, regimes0(1),myrestrict,T0,R0);
|
||||
if M_.occbin.constraint_nbr==1
|
||||
bindx = occbin.backward_map_regime(regimes0(1).regime, regimes0(1).regimestart);
|
||||
bindx = bindx(2:end);
|
||||
[regimes0(2).regime, regimes0(2).regimestart, error_flag]=occbin.map_regime(bindx);
|
||||
bindx = bindx(2:end);
|
||||
[regimes0(3).regime, regimes0(3).regimestart, error_flag]=occbin.map_regime(bindx);
|
||||
else
|
||||
bindx1 = occbin.backward_map_regime(regimes0(1).regime1, regimes0(1).regimestart1);
|
||||
bindx2 = occbin.backward_map_regime(regimes0(1).regime2, regimes0(1).regimestart2);
|
||||
bindx1 = bindx1(2:end);
|
||||
bindx2 = bindx2(2:end);
|
||||
[regimes0(2).regime1, regimes0(2).regimestart1, error_flag]=occbin.map_regime(bindx1);
|
||||
[regimes0(2).regime2, regimes0(2).regimestart2, error_flag]=occbin.map_regime(bindx2);
|
||||
bindx1 = bindx1(2:end);
|
||||
bindx2 = bindx2(2:end);
|
||||
[regimes0(3).regime1, regimes0(3).regimestart1, error_flag]=occbin.map_regime(bindx1);
|
||||
[regimes0(3).regime2, regimes0(3).regimestart2, error_flag]=occbin.map_regime(bindx2);
|
||||
end
|
||||
% regimes0=[regimes0 base_regime base_regime];
|
||||
TT(:,:,2) = TTx(:,:,end);
|
||||
RR(:,:,2) = RRx(:,:,end);
|
||||
CC(:,2) = CCx(:,end);
|
||||
end
|
||||
[a, a1, P, P1, v, Fi, Ki, alphahat, etahat, lik] = occbin_kalman_update(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,Ki,Fi,mm,kalman_tol);
|
||||
if ~options_.occbin.filter.use_relaxation
|
||||
[a, a1, P, P1, v, Fi, Ki, alphahat, etahat] = occbin_kalman_update(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,Ki,Fi,mm,kalman_tol);
|
||||
else
|
||||
[~,~,~,~,~,~, TTx, RRx, CCx] ...
|
||||
= occbin.dynare_resolve(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state, base_regime,myrestrict,T0,R0);
|
||||
if isempty(fieldnames(regimes0))
|
||||
regimes0 = regimes_;
|
||||
else
|
||||
regimes0(1)=base_regime;
|
||||
end
|
||||
TT(:,:,2) = TTx(:,:,end);
|
||||
RR(:,:,2) = RRx(:,:,end);
|
||||
CC(:,2) = CCx(:,end);
|
||||
[a, a1, P, P1, v, Fi, Ki, alphahat, etahat, lik] = occbin_kalman_update(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,Ki,Fi,mm,kalman_tol);
|
||||
[a, a1, P, P1, v, Fi, Ki, alphahat, etahat] = occbin_kalman_update(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,Ki,Fi,mm,kalman_tol);
|
||||
regimes0(1)=base_regime;
|
||||
end
|
||||
|
||||
|
@ -165,23 +132,9 @@ else
|
|||
end
|
||||
|
||||
options_.occbin.simul=opts_simul;
|
||||
if options_.occbin.filter.guess_regime
|
||||
options_.occbin.simul.init_regime=regimes0;
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
if out.error_flag
|
||||
options_.occbin.simul=opts_simul;
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
end
|
||||
else
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
if out.error_flag
|
||||
options_.occbin.simul.init_regime=regimes0;
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
end
|
||||
end
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
if out.error_flag
|
||||
error_flag = out.error_flag;
|
||||
etahat=etahat(:,2);
|
||||
return;
|
||||
end
|
||||
|
||||
|
@ -195,23 +148,65 @@ regime_hist = {regimes0(1)};
|
|||
if M_.occbin.constraint_nbr==1
|
||||
regime_end = regimes0(1).regimestart(end);
|
||||
end
|
||||
lik_hist=lik;
|
||||
niter=1;
|
||||
is_periodic=0;
|
||||
if options_.occbin.filter.use_relaxation || isequal(regimes0(1),base_regime)
|
||||
nguess=1;
|
||||
else
|
||||
nguess=0;
|
||||
end
|
||||
newguess=0;
|
||||
|
||||
if any(myregime) || ~isequal(regimes_(1),regimes0(1))
|
||||
while ~isequal(regimes_(1),regimes0(1)) && ~is_periodic && ~out.error_flag && niter<=options_.occbin.likelihood.max_number_of_iterations
|
||||
niter=niter+1;
|
||||
TT(:,:,2)=ss.T(my_order_var,my_order_var,1);
|
||||
RR(:,:,2)=ss.R(my_order_var,:,1);
|
||||
CC(:,2)=ss.C(my_order_var,1);
|
||||
newstart=1;
|
||||
if M_.occbin.constraint_nbr==1 && length(regimes_(1).regimestart)>1
|
||||
newstart = regimes_(1).regimestart(end);
|
||||
end
|
||||
oldstart=1;
|
||||
if M_.occbin.constraint_nbr==1 && length(regimes0(1).regimestart)>1
|
||||
oldstart = regimes0(1).regimestart(end);
|
||||
end
|
||||
if M_.occbin.constraint_nbr==1 && (newstart-oldstart)>2 && options_.occbin.filter.use_relaxation
|
||||
regimestart = max(oldstart+2,round(0.5*(newstart+oldstart)));
|
||||
regimestart = min(regimestart,oldstart+4);
|
||||
if regimestart<=regimes_(1).regimestart(end-1)
|
||||
if length(regimes_(1).regimestart)<=3
|
||||
regimestart = max(regimestart, min(regimes_(1).regimestart(end-1)+2,newstart));
|
||||
else
|
||||
regimes_(1).regime = regimes_(1).regime(1:end-2);
|
||||
regimes_(1).regimestart = regimes_(1).regimestart(1:end-2);
|
||||
regimestart = max(regimestart, regimes_(1).regimestart(end-1)+1);
|
||||
end
|
||||
end
|
||||
|
||||
% % if (newstart-oldstart)>3
|
||||
% % regimestart = regimes_(1).regimestart(end-1)+oldstart+2;
|
||||
% % % regimestart = regimes_(1).regimestart(end-1)+round(0.5*(newstart+oldstart))-1;
|
||||
regimes_(1).regimestart(end)=regimestart;
|
||||
[~,~,~,~,~,~, TTx, RRx, CCx] ...
|
||||
= occbin.dynare_resolve(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state, [base_regime regimes_(1)],myrestrict,T0,R0);
|
||||
TT(:,:,2) = TTx(:,:,end);
|
||||
RR(:,:,2) = RRx(:,:,end);
|
||||
CC(:,2) = CCx(:,end);
|
||||
elseif newguess==0
|
||||
TT(:,:,2)=ss.T(my_order_var,my_order_var,1);
|
||||
RR(:,:,2)=ss.R(my_order_var,:,1);
|
||||
CC(:,2)=ss.C(my_order_var,1);
|
||||
end
|
||||
newguess=0;
|
||||
regime_hist(niter) = {regimes_(1)};
|
||||
if M_.occbin.constraint_nbr==1
|
||||
regime_end(niter) = regimes_(1).regimestart(end);
|
||||
end
|
||||
[a, a1, P, P1, v, Fi, Ki, alphahat, etahat, lik] = occbin_kalman_update(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,Ki,Fi,mm,kalman_tol);
|
||||
lik_hist(niter) = lik;
|
||||
[a, a1, P, P1, v, Fi, Ki, alphahat, etahat] = occbin_kalman_update(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,Ki,Fi,mm,kalman_tol);
|
||||
opts_simul.SHOCKS(1,:) = etahat(:,2)';
|
||||
% if opts_simul.restrict_state_space
|
||||
% tmp=zeros(M_.endo_nbr,1);
|
||||
% tmp(dr.restrict_var_list,1)=alphahat(:,1);
|
||||
% opts_simul.endo_init = tmp(dr.inv_order_var,1);
|
||||
% else
|
||||
if opts_simul.restrict_state_space
|
||||
tmp=zeros(M_.endo_nbr,1);
|
||||
tmp(dr.restrict_var_list,1)=alphahat(:,1);
|
||||
|
@ -219,7 +214,10 @@ if any(myregime) || ~isequal(regimes_(1),regimes0(1))
|
|||
else
|
||||
opts_simul.endo_init = alphahat(dr.inv_order_var,1);
|
||||
end
|
||||
opts_simul.init_regime=regimes_(1);
|
||||
% end
|
||||
if not(options_.occbin.filter.use_relaxation)
|
||||
opts_simul.init_regime=regimes_(1);
|
||||
end
|
||||
if M_.occbin.constraint_nbr==1
|
||||
myregimestart = [regimes_.regimestart];
|
||||
else
|
||||
|
@ -230,8 +228,6 @@ if any(myregime) || ~isequal(regimes_(1),regimes0(1))
|
|||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
if out.error_flag
|
||||
error_flag = out.error_flag;
|
||||
etahat=etahat(:,2);
|
||||
lik=inf;
|
||||
return;
|
||||
end
|
||||
regimes0=regimes_;
|
||||
|
@ -240,14 +236,36 @@ if any(myregime) || ~isequal(regimes_(1),regimes0(1))
|
|||
for kiter=1:niter-1
|
||||
is_periodic(kiter) = isequal(regime_hist{kiter}, regimes_(1));
|
||||
end
|
||||
is_periodic_iter = find(is_periodic);
|
||||
is_periodic = any(is_periodic);
|
||||
if is_periodic
|
||||
if nguess<3 && M_.occbin.constraint_nbr==1
|
||||
newguess=1;
|
||||
is_periodic=0;
|
||||
nguess=nguess+1;
|
||||
if nguess==1
|
||||
% change starting regime
|
||||
regimes_(1).regime=0;
|
||||
regimes_(1).regimestart=1;
|
||||
elseif nguess==2
|
||||
% change starting regime
|
||||
regimes_(1).regime=[0 1 0];
|
||||
regimes_(1).regimestart=[1 2 3];
|
||||
else
|
||||
regimes_(1).regime=[1 0];
|
||||
regimes_(1).regimestart=[1 2];
|
||||
end
|
||||
[~,~,~,~,~,~, TTx, RRx, CCx] ...
|
||||
= occbin.dynare_resolve(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state, [base_regime regimes_(1)],myrestrict,T0,R0);
|
||||
TT(:,:,2) = TTx(:,:,end);
|
||||
RR(:,:,2) = RRx(:,:,end);
|
||||
CC(:,2) = CCx(:,end);
|
||||
regime_hist = regime_hist(1);
|
||||
niter=1;
|
||||
else
|
||||
% re-set to previous regime
|
||||
if options_.occbin.filter.periodic_solution
|
||||
% force projection conditional on most likely regime
|
||||
[m, im]=min(lik_hist(is_periodic_iter:end));
|
||||
opts_simul.init_regime=regime_hist{is_periodic_iter+im-1};
|
||||
regimes_ = regimes0;
|
||||
% force projection conditional on previous regime
|
||||
opts_simul.init_regime=regimes0(1);
|
||||
if M_.occbin.constraint_nbr==1
|
||||
myregimestart = [regimes0.regimestart];
|
||||
else
|
||||
|
@ -256,39 +274,68 @@ if any(myregime) || ~isequal(regimes_(1),regimes0(1))
|
|||
opts_simul.periods = max(opts_simul.periods,max(myregimestart));
|
||||
opts_simul.maxit=1;
|
||||
options_.occbin.simul=opts_simul;
|
||||
[~, out, ss] = occbin.solver(M_,oo_,options_);
|
||||
if out.error_flag
|
||||
error_flag = out.error_flag;
|
||||
etahat=etahat(:,2);
|
||||
lik=inf;
|
||||
return;
|
||||
else
|
||||
regimes_ = out.regime_history;
|
||||
TT(:,:,2)=ss.T(my_order_var,my_order_var,1);
|
||||
RR(:,:,2)=ss.R(my_order_var,:,1);
|
||||
CC(:,2)=ss.C(my_order_var,1);
|
||||
[a, a1, P, P1, v, Fi, Ki, alphahat, etahat, lik] = occbin_kalman_update(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,Ki,Fi,mm,kalman_tol);
|
||||
end
|
||||
else
|
||||
error_flag = 330;
|
||||
etahat=etahat(:,2);
|
||||
lik=inf;
|
||||
return;
|
||||
end
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
error_flag = out.error_flag;
|
||||
if ~error_flag && niter>options_.occbin.likelihood.max_number_of_iterations && ~isequal(regimes_(1),regimes0(1)) %fixed point algorithm did not converge
|
||||
if error_flag==0 && niter>options_.occbin.likelihood.max_number_of_iterations && ~isequal(regimes_(1),regimes0(1)) %fixed point algorithm did not converge
|
||||
error_flag = 1;
|
||||
|
||||
if M_.occbin.constraint_nbr==1
|
||||
% try some other regime before giving up
|
||||
[ll, il]=sort(regime_end);
|
||||
rr=regime_hist(il(2:3));
|
||||
newstart=1;
|
||||
if length(rr{1}(1).regimestart)>1
|
||||
newstart = rr{1}(1).regimestart(end)-rr{1}(1).regimestart(end-1)+1;
|
||||
end
|
||||
oldstart=1;
|
||||
if length(rr{2}(1).regimestart)>1
|
||||
oldstart = rr{2}(1).regimestart(end)-rr{2}(1).regimestart(end-1)+1;
|
||||
end
|
||||
nstart=sort([newstart oldstart]);
|
||||
regimes_=rr{1}(1);
|
||||
for k=(nstart(1)+1):(nstart(2)-1)
|
||||
niter=niter+1;
|
||||
regimes_(1).regimestart(end)=k;
|
||||
|
||||
[~,~,~,~,~,~, TTx, RRx, CCx] ...
|
||||
= occbin.dynare_resolve(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state, [base_regime regimes_(1)],myrestrict,T0,R0);
|
||||
TT(:,:,2) = TTx(:,:,end);
|
||||
RR(:,:,2) = RRx(:,:,end);
|
||||
CC(:,2) = CCx(:,end);
|
||||
[a, a1, P, P1, v, Fi, Ki, alphahat, etahat] = occbin_kalman_update(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,Ki,Fi,mm,kalman_tol);
|
||||
opts_simul.SHOCKS(1,:) = etahat(:,2)';
|
||||
if opts_simul.restrict_state_space
|
||||
tmp=zeros(M_.endo_nbr,1);
|
||||
tmp(dr.restrict_var_list,1)=alphahat(:,1);
|
||||
opts_simul.endo_init = tmp(dr.inv_order_var,1);
|
||||
else
|
||||
opts_simul.endo_init = alphahat(dr.inv_order_var,1);
|
||||
end
|
||||
if M_.occbin.constraint_nbr==1
|
||||
myregimestart = [regimes_.regimestart];
|
||||
else
|
||||
myregimestart = [regimes_.regimestart1 regimes_.regimestart2];
|
||||
end
|
||||
opts_simul.periods = max(opts_simul.periods,max(myregimestart));
|
||||
options_.occbin.simul=opts_simul;
|
||||
[~, out, ss] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
|
||||
if isequal(out.regime_history(1),regimes_(1))
|
||||
error_flag=0;
|
||||
break
|
||||
end
|
||||
end
|
||||
regimes_ = out.regime_history;
|
||||
end
|
||||
end
|
||||
|
||||
if ~error_flag
|
||||
a = out.piecewise(1:nk+1,my_order_var)' - repmat(out.ys(my_order_var),1,nk+1);
|
||||
regimes_=regimes_(1:3);
|
||||
end
|
||||
regimes_=regimes_(1:3);
|
||||
a = out.piecewise(1:nk+1,my_order_var)' - repmat(out.ys(my_order_var),1,nk+1);
|
||||
T = ss.T(my_order_var,my_order_var,:);
|
||||
R = ss.R(my_order_var,:,:);
|
||||
C = ss.C(my_order_var,:);
|
||||
|
@ -305,7 +352,7 @@ end
|
|||
|
||||
end
|
||||
|
||||
function [a, a1, P, P1, v, Fi, Ki, alphahat, etahat, lik] = occbin_kalman_update(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,Ki,Fi,mm,kalman_tol)
|
||||
function [a, a1, P, P1, v, Fi, Ki, alphahat, etahat] = occbin_kalman_update(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,Ki,Fi,mm,kalman_tol)
|
||||
% [a, a1, P, P1, v, Fi, Ki, alphahat, etahat] = occbin_kalman_update(a,a1,P,P1,data_index,Z,v,Y,H,QQQ,TT,RR,CC,Ki,Fi,mm,kalman_tol)
|
||||
% - a
|
||||
% - a1
|
||||
|
@ -330,18 +377,9 @@ a(:,t) = a1(:,t);
|
|||
P1(:,:,t) = T*P(:,:,t-1)*T' + QQ; %transition according to (6.14) in DK (2012)
|
||||
P(:,:,t) = P1(:,:,t);
|
||||
di = data_index{t}';
|
||||
% store info for lik
|
||||
if not(isempty(di))
|
||||
vv = Y(di,t) - Z(di,:)*a(:,t);
|
||||
F = Z(di,:)*P(:,:,t)*Z(di,:)' + diag(H(di));
|
||||
sig=sqrt(diag(F));
|
||||
lik=inf;
|
||||
end
|
||||
|
||||
if isempty(di)
|
||||
Fi(:,t) = 0;
|
||||
Ki(:,:,t) = 0;
|
||||
lik =0;
|
||||
end
|
||||
for i=di
|
||||
Zi = Z(i,:);
|
||||
|
@ -356,11 +394,6 @@ for i=di
|
|||
% p. 157, DK (2012)
|
||||
end
|
||||
end
|
||||
if not(isempty(di))
|
||||
log_dF = log(det(F./(sig*sig')))+2*sum(log(sig));
|
||||
iF = inv(F./(sig*sig'))./(sig*sig');
|
||||
lik = log_dF + transpose(vv)*iF*vv + length(di)*log(2*pi);
|
||||
end
|
||||
|
||||
%% do backward pass
|
||||
ri=zeros(mm,1);
|
||||
|
@ -383,4 +416,4 @@ while t > 1
|
|||
ri = T'*ri; % KD (2003), eq. (23), equation for r_{t-1,p_{t-1}}
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
|
|
|
@ -1,331 +0,0 @@
|
|||
function [ax, a1x, Px, P1x, vx, Tx, Rx, Cx, regx, info, M_, likx, etahat, alphahat, V, Fix, Kix, TTx,RRx,CCx] = ...
|
||||
kalman_update_engine(a0,a1,P0,P1,t,data_index,Z,vv,Y,H,Qt,T0,R0,TT,RR,CC,regimes_,base_regime,d_index,M_,...
|
||||
dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options, Fi,Ki,kalman_tol,nk)
|
||||
% [ax, a1x, Px, P1x, vx, Tx, Rx, Cx, regx, info, M_, likx, etahat, alphahat, V, Fix, Kix, TTx,RRx,CCx] = kalman_update_engine(
|
||||
% a0,a1,P0,P1,t,data_index,Z,vv,Y,H,Qt,T0,R0,TT,RR,CC,regimes_,base_regime,d_index,M_,
|
||||
% dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options, Fi,Ki,kalman_tol,nk)
|
||||
|
||||
% Copyright © 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
|
||||
|
||||
is_multivariate = true;
|
||||
Fix=[];
|
||||
Kix=[];
|
||||
TTx=[];
|
||||
RRx=[];
|
||||
CCx=[];
|
||||
V=[];
|
||||
if nargin>26
|
||||
is_multivariate = false;
|
||||
end
|
||||
|
||||
use_relaxation = false;
|
||||
|
||||
if is_multivariate
|
||||
[ax, a1x, Px, P1x, vx, Tx, Rx, Cx, regx, info, M_, likx, etahat, alphahat, V] = occbin.kalman_update_algo_1(a0,a1,P0,P1,data_index,Z,vv,Y,H,Qt,T0,R0,TT,RR,CC,struct(),M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options);
|
||||
else
|
||||
[ax, a1x, Px, P1x, vx, Fix, Kix, Tx, Rx, Cx, regx, info, M_, likx, alphahat, etahat,TTx,RRx,CCx] = occbin.kalman_update_algo_3(a0,a1,P0,P1,data_index,Z,vv,Fi,Ki,Y,H,Qt,T0,R0,TT,RR,CC,struct(),M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options,kalman_tol,nk);
|
||||
end
|
||||
info0=info;
|
||||
if info
|
||||
if ~isequal(regimes_(1:2),[base_regime base_regime])
|
||||
if is_multivariate
|
||||
[ax, a1x, Px, P1x, vx, Tx, Rx, Cx, regx, info, M_, likx, etahat, alphahat, V] = occbin.kalman_update_algo_1(a0,a1,P0,P1,data_index,Z,vv,Y,H,Qt,T0,R0,TT,RR,CC,regimes_(1:2),M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options);
|
||||
else
|
||||
[ax, a1x, Px, P1x, vx, Fix, Kix, Tx, Rx, Cx, regx, info, M_, likx, alphahat, etahat,TTx,RRx,CCx] = occbin.kalman_update_algo_3(a0,a1,P0,P1,data_index,Z,vv,Fi,Ki,Y,H,Qt,T0,R0,TT,RR,CC,regimes_(1:2),M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options,kalman_tol,nk);
|
||||
end
|
||||
end
|
||||
info1=info;
|
||||
else
|
||||
if ~isequal(regimes_(1:2),[base_regime base_regime])
|
||||
if is_multivariate
|
||||
[ax1, a1x1, Px1, P1x1, vx1, Tx1, Rx1, Cx1, regx1, info1, M_1, likx1, etahat1, alphahat1, V1] = occbin.kalman_update_algo_1(a0,a1,P0,P1,data_index,Z,vv,Y,H,Qt,T0,R0,TT,RR,CC,regimes_(1:2),M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options);
|
||||
else
|
||||
[ax1, a1x1, Px1, P1x1, vx1, Fix1, Kix1, Tx1, Rx1, Cx1, regx1, info1, M_1, likx1, alphahat1, etahat1,TTx1,RRx1,CCx1] = occbin.kalman_update_algo_3(a0,a1,P0,P1,data_index,Z,vv,Fi,Ki,Y,H,Qt,T0,R0,TT,RR,CC,regimes_(1:2),M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options,kalman_tol,nk);
|
||||
end
|
||||
if info1==0 && likx1<likx
|
||||
ax=ax1;
|
||||
a1x=a1x1;
|
||||
Px=Px1;
|
||||
P1x=P1x1;
|
||||
vx=vx1;
|
||||
Tx=Tx1;
|
||||
Rx=Rx1;
|
||||
Cx=Cx1;
|
||||
regx=regx1;
|
||||
info=info1;
|
||||
M_= M_1;
|
||||
likx=likx1;
|
||||
etahat=etahat1;
|
||||
alphahat=alphahat1;
|
||||
if is_multivariate
|
||||
V=V1;
|
||||
else
|
||||
Fix = Fix1;
|
||||
Kix = Kix1;
|
||||
TTx = TTx1;
|
||||
RRx = RRx1;
|
||||
CCx = CCx1;
|
||||
end
|
||||
end
|
||||
else
|
||||
if t>options_.occbin.likelihood.number_of_initial_periods_with_extra_regime_guess
|
||||
info1=0;
|
||||
else
|
||||
% may help in first 2 periods to try some other guess regime, due to
|
||||
% larger state uncertainty
|
||||
info1=1;
|
||||
options_.occbin.likelihood.brute_force_regime_guess = true;
|
||||
options_.occbin.likelihood.loss_function_regime_guess = true;
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
diffstart=0;
|
||||
if info==0
|
||||
if M_.occbin.constraint_nbr==1
|
||||
oldstart = regimes_(1).regimestart(end);
|
||||
newstart = regx(1).regimestart(end);
|
||||
diffstart = newstart-oldstart;
|
||||
else
|
||||
newstart1 = regx(1).regimestart1(end);
|
||||
newstart2 = regx(1).regimestart2(end);
|
||||
oldstart1 = regimes_(1).regimestart1(end);
|
||||
oldstart2 = regimes_(1).regimestart2(end);
|
||||
diffstart = max(newstart1-oldstart1,newstart2-oldstart2);
|
||||
end
|
||||
end
|
||||
|
||||
if options_.occbin.filter.use_relaxation && diffstart>2
|
||||
if info0==0
|
||||
% make sure we match criteria to enter further solution attempts
|
||||
info1=1;
|
||||
end
|
||||
options_.occbin.likelihood.brute_force_regime_guess = true;
|
||||
options_.occbin.likelihood.loss_function_regime_guess = true;
|
||||
use_relaxation = true;
|
||||
end
|
||||
|
||||
if options_.occbin.likelihood.brute_force_regime_guess && (info0 || info1) %|| (info==0 && ~isequal(regx(1),base_regime))
|
||||
|
||||
guess_regime = [base_regime base_regime];
|
||||
options_.occbin.filter.guess_regime = true;
|
||||
|
||||
use_index = 0;
|
||||
if M_.occbin.constraint_nbr==1
|
||||
for k=1:5
|
||||
guess_regime(1).regimestart=[1 5 5+4*k];
|
||||
guess_regime(1).regime=[0 1 0];
|
||||
if is_multivariate
|
||||
[ax2{1}, a1x2{1}, Px2{1}, P1x2{1}, vx2{1}, Tx2{1}, Rx2{1}, Cx2{1}, regx2{1}, info2, M_2{1}, likx2{1}, etahat2{1}, alphahat2{1}, V2{1}] = occbin.kalman_update_algo_1(a0,a1,P0,P1,data_index,Z,vv,Y,H,Qt,T0,R0,TT,RR,CC,guess_regime,M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options);
|
||||
else
|
||||
[ax2{1}, a1x2{1}, Px2{1}, P1x2{1}, vx2{1}, Fix2{1}, Kix2{1}, Tx2{1}, Rx2{1}, Cx2{1}, regx2{1}, info2, M_2{1}, likx2{1}, alphahat2{1}, etahat2{1},TTx2{1},RRx2{1},CCx2{1}] = occbin.kalman_update_algo_3(a0,a1,P0,P1,data_index,Z,vv,Fi,Ki,Y,H,Qt,T0,R0,TT,RR,CC,guess_regime,M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options,kalman_tol,nk);
|
||||
end
|
||||
if info2==0
|
||||
use_index= 1;
|
||||
if not(info==0 && isequal(regx2{1},regx)) && not(use_relaxation && likx2{1}>=likx)
|
||||
% found a solution, different from previous or
|
||||
% use_relaxation and likelihood is better
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
guess_regime(1).regimestart=[1 1+4*k];
|
||||
guess_regime(1).regime=[1 0];
|
||||
if is_multivariate
|
||||
[ax2{2}, a1x2{2}, Px2{2}, P1x2{2}, vx2{2}, Tx2{2}, Rx2{2}, Cx2{2}, regx2{2}, info2, M_2{2}, likx2{2}, etahat2{2}, alphahat2{2}, V2{2}] = occbin.kalman_update_algo_1(a0,a1,P0,P1,data_index,Z,vv,Y,H,Qt,T0,R0,TT,RR,CC,guess_regime,M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options);
|
||||
else
|
||||
[ax2{2}, a1x2{2}, Px2{2}, P1x2{2}, vx2{2}, Fix2{2}, Kix2{2}, Tx2{2}, Rx2{2}, Cx2{2}, regx2{2}, info2, M_2{2}, likx2{2}, alphahat2{2}, etahat2{2},TTx2{2},RRx2{2},CCx2{2}] = occbin.kalman_update_algo_3(a0,a1,P0,P1,data_index,Z,vv,Fi,Ki,Y,H,Qt,T0,R0,TT,RR,CC,guess_regime,M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options,kalman_tol,nk);
|
||||
end
|
||||
if info2==0
|
||||
use_index = 2;
|
||||
% if use_relaxation and we are here, previous guess did not
|
||||
% improve solution, so we test for this one
|
||||
end
|
||||
|
||||
if use_index
|
||||
% in case the second guess does not find a solution!
|
||||
info2=0;
|
||||
% a solution was found
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if M_.occbin.constraint_nbr==2
|
||||
for jk=0:1 % loop over other regime duration. this loop is shorter for parsimony. one may add an option ...
|
||||
for k=1:5 % loop over current regime duration
|
||||
gindex = 0;
|
||||
for jr=1:2 % loop over current regime 1 or 2
|
||||
if jr==1
|
||||
regstart1 = 'regimestart1';
|
||||
reg1 = 'regime1';
|
||||
regstart2 = 'regimestart2';
|
||||
reg2 = 'regime2';
|
||||
else
|
||||
regstart1 = 'regimestart2';
|
||||
reg1 = 'regime2';
|
||||
regstart2 = 'regimestart1';
|
||||
reg2 = 'regime1';
|
||||
end
|
||||
for kk=1:2 % loop over current regime binding in expectation vs binding in current period
|
||||
if kk==1
|
||||
guess_regime(1).(regstart1)=[1 5 5+4*k];
|
||||
guess_regime(1).(reg1)=[0 1 0];
|
||||
else
|
||||
guess_regime(1).(regstart1)=[1 1+4*k];
|
||||
guess_regime(1).(reg1)=[1 0];
|
||||
end
|
||||
for kj=1:1+1*(jk>0)
|
||||
% loop over other regime slack or binding in current period or binding in
|
||||
% expectation
|
||||
if jk==0
|
||||
% other regime is slack
|
||||
guess_regime(1).(regstart2) = 1;
|
||||
guess_regime(1).(reg2) = 0;
|
||||
else % jk>0
|
||||
if kj==1
|
||||
% other regime binding in current period
|
||||
guess_regime(1).(regstart2)=[1 1+4*jk];
|
||||
guess_regime(1).(reg2) = [1 0];
|
||||
else
|
||||
% other regime binding in expectation
|
||||
guess_regime(1).(regstart2)=[1 5 5+4*jk];
|
||||
guess_regime(1).(reg2) = [0 1 0];
|
||||
end
|
||||
end
|
||||
gindex = gindex+1;
|
||||
if is_multivariate
|
||||
[ax2{gindex}, a1x2{gindex}, Px2{gindex}, P1x2{gindex}, vx2{gindex}, Tx2{gindex}, Rx2{gindex}, Cx2{gindex}, regx2{gindex}, info2, M_2{gindex}, likx2{gindex}, etahat2{gindex}, alphahat2{gindex}, V2{gindex}] = occbin.kalman_update_algo_1(a0,a1,P0,P1,data_index,Z,vv,Y,H,Qt,T0,R0,TT,RR,CC,guess_regime,M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options);
|
||||
else
|
||||
[ax2{gindex}, a1x2{gindex}, Px2{gindex}, P1x2{gindex}, vx2{gindex}, Fix2{gindex}, Kix2{gindex}, Tx2{gindex}, Rx2{gindex}, Cx2{gindex}, regx2{gindex}, info2, M_2{gindex}, likx2{gindex}, alphahat2{gindex}, etahat2{gindex},TTx2{gindex},RRx2{gindex},CCx2{gindex}] = occbin.kalman_update_algo_3(a0,a1,P0,P1,data_index,Z,vv,Fi,Ki,Y,H,Qt,T0,R0,TT,RR,CC,guess_regime,M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options,kalman_tol,nk);
|
||||
end
|
||||
if info2==0
|
||||
use_index= gindex;
|
||||
if not(info==0 && isequal(regx2{gindex},regx)) && not(use_relaxation && likx2{gindex}>=likx)
|
||||
% found a solution, different from previous one
|
||||
% use_relaxation and likelihood improves
|
||||
break
|
||||
end
|
||||
end
|
||||
end % loop over other regime slack, binding in expectation or binding in current period
|
||||
|
||||
if info2==0
|
||||
if not(info==0 && isequal(regx2{gindex},regx)) && not(use_relaxation && likx2{gindex}>=likx)
|
||||
% found a solution, different from previous one
|
||||
% use_relaxation and likelihood improves
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
end % loop over current regime binding in expectation vs binding in current period
|
||||
|
||||
if info2==0
|
||||
if not(info==0 && isequal(regx2{gindex},regx)) && not(use_relaxation && likx2{gindex}>=likx)
|
||||
% found a solution, different from previous one
|
||||
% use_relaxation and likelihood improves
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
end % loop over current regime 1 or 2
|
||||
|
||||
if use_index
|
||||
info2=0;
|
||||
break
|
||||
end
|
||||
end % loop over current regime duration
|
||||
|
||||
if use_index
|
||||
break
|
||||
end
|
||||
end % loop over other regime duration
|
||||
end % 2 constraints
|
||||
|
||||
|
||||
if info2==0
|
||||
% so that we DO NOT enter IVF step
|
||||
info0=0;
|
||||
info1=0;
|
||||
end
|
||||
if info2==0 && likx2{use_index}<likx
|
||||
ax=ax2{use_index};
|
||||
a1x=a1x2{use_index};
|
||||
Px=Px2{use_index};
|
||||
P1x=P1x2{use_index};
|
||||
vx=vx2{use_index};
|
||||
Tx=Tx2{use_index};
|
||||
Rx=Rx2{use_index};
|
||||
Cx=Cx2{use_index};
|
||||
regx=regx2{use_index};
|
||||
info=info2;
|
||||
M_= M_2{use_index};
|
||||
likx=likx2{use_index};
|
||||
etahat=etahat2{use_index};
|
||||
alphahat=alphahat2{use_index};
|
||||
if is_multivariate
|
||||
V=V2{use_index};
|
||||
else
|
||||
Fix = Fix2{use_index};
|
||||
Kix = Kix2{use_index};
|
||||
TTx = TTx2{use_index};
|
||||
RRx = RRx2{use_index};
|
||||
CCx = CCx2{use_index};
|
||||
end
|
||||
end
|
||||
options_.occbin.filter.guess_regime = false;
|
||||
end
|
||||
if options_.occbin.likelihood.loss_function_regime_guess && (info0 || info1) %|| (info==0 && ~isequal(regx(1),base_regime))
|
||||
[~, out] = occbin.findmin(d_index, a0, P1, Qt, Y, Z, occbin_options.opts_simul,M_, dr,endo_steady_state,exo_steady_state,exo_det_steady_state, options_);
|
||||
if out.error_flag==0
|
||||
options_.occbin.filter.guess_regime = true;
|
||||
guess_regime=out.regime_history;
|
||||
guess_regime = [guess_regime base_regime];
|
||||
if is_multivariate
|
||||
[ax2, a1x2, Px2, P1x2, vx2, Tx2, Rx2, Cx2, regx2, info2, M_2, likx2, etahat2, alphahat2, V2] = occbin.kalman_update_algo_1(a0,a1,P0,P1,data_index,Z,vv,Y,H,Qt,T0,R0,TT,RR,CC,guess_regime,M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options);
|
||||
else
|
||||
[ax2, a1x2, Px2, P1x2, vx2, Fix2, Kix2, Tx2, Rx2, Cx2, regx2, info2, M_2, likx2, alphahat2, etahat2,TTx2,RRx2,CCx2] = occbin.kalman_update_algo_3(a0,a1,P0,P1,data_index,Z,vv,Fi,Ki,Y,H,Qt,T0,R0,TT,RR,CC,guess_regime,M_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state,options_,occbin_options,kalman_tol,nk);
|
||||
end
|
||||
options_.occbin.filter.guess_regime = false;
|
||||
if info2==0 && likx2<likx
|
||||
ax=ax2;
|
||||
a1x=a1x2;
|
||||
Px=Px2;
|
||||
P1x=P1x2;
|
||||
vx=vx2;
|
||||
Tx=Tx2;
|
||||
Rx=Rx2;
|
||||
Cx=Cx2;
|
||||
regx=regx2;
|
||||
info=info2;
|
||||
likx=likx2;
|
||||
M_= M_2;
|
||||
etahat=etahat2;
|
||||
alphahat=alphahat2;
|
||||
if is_multivariate
|
||||
V=V2;
|
||||
else
|
||||
Fix = Fix2;
|
||||
Kix = Kix2;
|
||||
TTx = TTx2;
|
||||
RRx = RRx2;
|
||||
CCx = CCx2;
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
|
@ -26,9 +26,6 @@ function [regime, regime_start, error_flag]=map_regime(binding_indicator,debug_s
|
|||
% Journal of Monetary Economics 70, 22-38
|
||||
|
||||
error_flag=0;
|
||||
if isempty(binding_indicator)
|
||||
binding_indicator = false;
|
||||
end
|
||||
% analyse violvec and isolate contiguous periods in the other regime.
|
||||
regime(1) = binding_indicator(1);
|
||||
regime_index = 1;
|
||||
|
|
|
@ -98,7 +98,11 @@ if T_max > 0
|
|||
% check if last binding regime was already stored
|
||||
tmp = 0*binding_indicator;
|
||||
tmp(1:end-T_max+1,:) = binding_indicator(T_max:end,:);
|
||||
itmp = find(~any(dictionary.binding_indicator(1:length(tmp)*2,:)-tmp(:)));
|
||||
if ~isoctave && matlab_ver_less_than('9.1') % Automatic broadcasting was introduced in MATLAB R2016b
|
||||
itmp = find(~any(bsxfun(@minus, dictionary.binding_indicator(1:length(tmp)*2,:), tmp(:))));
|
||||
else
|
||||
itmp = find(~any(dictionary.binding_indicator(1:length(tmp)*2,:)-tmp(:)));
|
||||
end
|
||||
if ~isempty(itmp)
|
||||
ireg(T_max) = itmp;
|
||||
else
|
||||
|
@ -130,7 +134,11 @@ if T_max > 0
|
|||
for i = T_max-1:-1:1
|
||||
tmp = 0*binding_indicator;
|
||||
tmp(1:end-i+1,:) = binding_indicator(i:end,:);
|
||||
itmp = find(~any(dictionary.binding_indicator(1:length(tmp)*2,:)-tmp(:)));
|
||||
if ~isoctave && matlab_ver_less_than('9.1') % Automatic broadcasting was introduced in MATLAB R2016b
|
||||
itmp = find(~any(bsxfun(@minus, dictionary.binding_indicator(1:length(tmp)*2,:), tmp(:))));
|
||||
else
|
||||
itmp = find(~any(dictionary.binding_indicator(1:length(tmp)*2,:)-tmp(:)));
|
||||
end
|
||||
if ~isempty(itmp)
|
||||
ireg(i) = itmp;
|
||||
else
|
||||
|
|
|
@ -89,7 +89,11 @@ if T_max > 0
|
|||
|
||||
tmp = 0*binding_indicator;
|
||||
tmp(1:end-i+1) = binding_indicator(i:end);
|
||||
itmp = find(~any(dictionary.binding_indicator-tmp));
|
||||
if ~isoctave && matlab_ver_less_than('9.1') % Automatic broadcasting was introduced in MATLAB R2016b
|
||||
itmp = find(~any(bsxfun(@minus, dictionary.binding_indicator, tmp)));
|
||||
else
|
||||
itmp = find(~any(dictionary.binding_indicator-tmp));
|
||||
end
|
||||
if ~isempty(itmp)
|
||||
ireg(i) = itmp;
|
||||
else
|
||||
|
|
|
@ -1,179 +0,0 @@
|
|||
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.
|
||||
|
||||
% 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;
|
||||
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);
|
||||
|
||||
endo_scaling_factor = options_.occbin.plot_irf.endo_scaling_factor;
|
||||
length_irf = options_.irf;
|
||||
|
||||
steps_irf = 1;
|
||||
|
||||
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');
|
||||
if isempty(itemp)
|
||||
error(['Shock ',shock_names{var_iter},' is not defined!'])
|
||||
else
|
||||
iexo=[iexo, itemp];
|
||||
end
|
||||
end
|
||||
|
||||
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;
|
||||
|
||||
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)
|
||||
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)]);
|
||||
ifig=ifig+1;
|
||||
isub=0;
|
||||
end
|
||||
isub=isub+1;
|
||||
if isempty(endo_scaling_factor)
|
||||
exofactor = 1;
|
||||
else
|
||||
exofactor = endo_scaling_factor{var_iter};
|
||||
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
|
||||
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);
|
||||
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
|
||||
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
|
||||
% Annotation Box + save figure
|
||||
% ----------------------
|
||||
if mod(j1,npan)==0 || (mod(j1,npan)~=0 && var_iter==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
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
|
||||
fprintf(fidTeX,'%% End Of TeX file.');
|
||||
fclose(fidTeX);
|
||||
end
|
|
@ -1,86 +0,0 @@
|
|||
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;
|
||||
if nconstr ==1
|
||||
regime(1) = {'regime'};
|
||||
regimestart(1) = {'regimestart'};
|
||||
else
|
||||
regime(1) = {'regime1'};
|
||||
regimestart(1) = {'regimestart1'};
|
||||
regime(2) = {'regime2'};
|
||||
regimestart(2) = {'regimestart2'};
|
||||
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
|
||||
|
||||
for k=1:nconstr
|
||||
subplot(nconstr,1,k)
|
||||
for t=1:nperiods
|
||||
nregimes_in_t = length(regimes(t).(regime{k}));
|
||||
start_periods = regimes(t).(regimestart{k});
|
||||
start_periods = [start_periods max(start_periods)];
|
||||
for r=1:nregimes_in_t
|
||||
isconstrained = regimes(t).(regime{k})(r);
|
||||
if isconstrained
|
||||
plot(t,start_periods(r),'*r')
|
||||
hold all,
|
||||
plot([t t],start_periods(r:r+1),'-r')
|
||||
else
|
||||
plot(t,start_periods(r),'ob')
|
||||
hold all,
|
||||
plot([t t],start_periods(r:r+1),'-b')
|
||||
end
|
||||
end
|
||||
end
|
||||
xlim([1 nperiods])
|
||||
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');
|
||||
|
||||
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
|
|
@ -42,35 +42,30 @@ if ismember(flag,{'all'})
|
|||
end
|
||||
|
||||
if ismember(flag,{'filter','all'})
|
||||
options_occbin_.filter.state_covariance = false;
|
||||
options_occbin_.filter.guess_regime = false;
|
||||
options_occbin_.filter.periodic_solution = true;
|
||||
options_occbin_.filter.use_relaxation = false;
|
||||
end
|
||||
|
||||
if ismember(flag,{'forecast','all'})
|
||||
options_occbin_.forecast.check_ahead_periods=30;
|
||||
options_occbin_.forecast.debug_flag=false;
|
||||
options_occbin_.forecast.frcst_regimes=[];
|
||||
options_occbin_.forecast.maxit=30;
|
||||
options_occbin_.forecast.periods=30;
|
||||
options_occbin_.forecast.qmc=0;
|
||||
options_occbin_.forecast.replic=0;
|
||||
options_occbin_.forecast.SHOCKS0=[];
|
||||
options_occbin_.forecast.treepath=1; % number of branches
|
||||
end
|
||||
|
||||
if ismember(flag,{'irf','all'})
|
||||
options_occbin_.irf.check_ahead_periods=30;
|
||||
options_occbin_.irf.exo_names=M_.exo_names;
|
||||
if ismember(flag,{'irf','all'})
|
||||
options_occbin_.irf.init_regime=[];
|
||||
options_occbin_.irf.maxit=30;
|
||||
options_occbin_.irf.threshold = 10^-6;
|
||||
% options_occbin_.irf.periods=options_.irf;
|
||||
options_occbin_.irf.shocksize=[];
|
||||
options_occbin_.irf.shocksigns = {'pos','neg'};
|
||||
options_occbin_.irf.t0=0;
|
||||
options_occbin_.irf.shocksigns = {'1','_1'};
|
||||
end
|
||||
|
||||
if ismember(flag,{'likelihood','all'})
|
||||
options_occbin_.likelihood.brute_force_regime_guess = true;
|
||||
options_occbin_.likelihood.curb_retrench = false;
|
||||
options_occbin_.likelihood.first_period_occbin_update = 1;
|
||||
options_occbin_.likelihood.full_output = false;
|
||||
|
@ -79,12 +74,10 @@ if ismember(flag,{'likelihood','all'})
|
|||
options_occbin_.likelihood.init_binding_indicator = false(0);
|
||||
options_occbin_.likelihood.inversion_filter = false;
|
||||
options_occbin_.likelihood.IVF_shock_observable_mapping = [];
|
||||
options_occbin_.likelihood.loss_function_regime_guess = false;
|
||||
options_occbin_.likelihood.maxit = 30; % this is for occbin solver algo
|
||||
options_occbin_.likelihood.max_number_of_iterations = 10; % this is for occbin_kalman_update loop
|
||||
options_occbin_.likelihood.max_check_ahead_periods=inf;
|
||||
options_occbin_.likelihood.number_of_initial_periods_with_extra_regime_guess=0;
|
||||
options_occbin_.likelihood.periods = 3;
|
||||
options_occbin_.likelihood.periods = 100;
|
||||
options_occbin_.likelihood.check_ahead_periods=200;
|
||||
options_occbin_.likelihood.periodic_solution=false;
|
||||
options_occbin_.likelihood.piecewise_only = true;
|
||||
|
@ -94,16 +87,6 @@ if ismember(flag,{'likelihood','all'})
|
|||
options_occbin_.likelihood.waitbar=false;
|
||||
end
|
||||
|
||||
if ismember(flag,{'plot_irf','all'})
|
||||
options_occbin_.plot_irf.add_steadystate = 0;
|
||||
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='';
|
||||
end
|
||||
|
||||
if ismember(flag,{'plot_shock_decomp','all'})
|
||||
options_occbin_.plot_shock_decomp.add_steadystate = false;
|
||||
options_occbin_.plot_shock_decomp.add_zero_line = false;
|
||||
|
@ -192,8 +175,6 @@ if ismember(flag,{'simul','all'})
|
|||
options_occbin_.simul.periods=100;
|
||||
options_occbin_.simul.check_ahead_periods=200;
|
||||
options_occbin_.simul.periodic_solution=false;
|
||||
options_occbin_.simul.periodic_solution_threshold=1;
|
||||
options_occbin_.simul.periodic_solution_strict=true;
|
||||
options_occbin_.simul.piecewise_only = false;
|
||||
options_occbin_.simul.reset_check_ahead_periods_in_new_period = false;
|
||||
options_occbin_.simul.reset_regime_in_new_period = false;
|
||||
|
@ -216,7 +197,7 @@ if ismember(flag,{'smoother','all'})
|
|||
options_occbin_.smoother.maxit = 30; % this is for occbin solver algo
|
||||
options_occbin_.smoother.max_check_ahead_periods=inf;
|
||||
options_occbin_.smoother.max_number_of_iterations = 10; % this is for smoother loop
|
||||
options_occbin_.smoother.periods = 3;
|
||||
options_occbin_.smoother.periods = 100;
|
||||
options_occbin_.smoother.check_ahead_periods=200;
|
||||
options_occbin_.smoother.periodic_solution=false;
|
||||
options_occbin_.smoother.piecewise_only = true;
|
||||
|
|
|
@ -136,8 +136,6 @@ for shock_period = 1:n_shocks_periods
|
|||
binding_indicator_history={};
|
||||
max_err = NaN(max_iter,1);
|
||||
regime_violates_constraint_in_expectation = false(max_iter,1);
|
||||
number_of_periods_with_violations = zeros(max_iter,1);
|
||||
regime_exit_period = ones(max_iter,1);
|
||||
|
||||
while (regime_change_this_iteration && iter<max_iter && ~is_periodic && ~is_periodic_loop)
|
||||
iter = iter +1;
|
||||
|
@ -196,11 +194,9 @@ for shock_period = 1:n_shocks_periods
|
|||
if ~isinf(opts_simul_.max_check_ahead_periods) && opts_simul_.max_check_ahead_periods<length(binding_indicator)
|
||||
end_periods = opts_simul_.max_check_ahead_periods;
|
||||
last_indicator = false(length(binding_indicator)-end_periods,1);
|
||||
regime_violates_constraint_in_last_period(iter) = any(binding.constraint_1(end_periods+1:end));
|
||||
else
|
||||
end_periods = length(binding_indicator);
|
||||
last_indicator = false(0);
|
||||
regime_violates_constraint_in_last_period(iter) = binding.constraint_1(end_periods);
|
||||
end
|
||||
% check if changes to the hypothesis of the duration for each
|
||||
% regime
|
||||
|
@ -219,9 +215,6 @@ for shock_period = 1:n_shocks_periods
|
|||
% if max_check_ahead_periods<inf, enforce unconstrained regime for period larger than max_check_ahead_periods
|
||||
binding_constraint_new=[binding.constraint_1(1:end_periods);last_indicator];
|
||||
relaxed_constraint_new = [relax.constraint_1(1:end_periods);not(last_indicator)];
|
||||
number_of_periods_with_violations(iter) = sum(binding_indicator -((binding_indicator | binding_constraint_new) & ~(binding_indicator & relaxed_constraint_new)));
|
||||
regime_exit_period(iter) = max(regime_history(shock_period).regimestart);
|
||||
|
||||
if curb_retrench % apply Gauss-Seidel idea of slowing down the change in the guess
|
||||
% for the constraint -- only relax one
|
||||
% period at a time starting from the last
|
||||
|
@ -259,35 +252,20 @@ for shock_period = 1:n_shocks_periods
|
|||
if size(binding_indicator,1)== size(binding_indicator_history{kiter},1)
|
||||
% vvv = [binding_indicator_history{kiter}; false(size(binding_indicator,1)- size(binding_indicator_history{kiter},1), 1)];
|
||||
% is_periodic(kiter) = isequal(vvv, binding_indicator);
|
||||
is_periodic(kiter) = isequal(binding_indicator_history{kiter}, binding_indicator) && sum(binding_indicator_history{iter}-binding_indicator)<=opts_simul_.periodic_solution_threshold;
|
||||
is_periodic(kiter) = isequal(binding_indicator_history{kiter}, binding_indicator) && length(find(binding_indicator_history{iter}-binding_indicator))==1;
|
||||
else
|
||||
is_periodic(kiter)=false;
|
||||
end
|
||||
end
|
||||
is_periodic_all =is_periodic;
|
||||
is_periodic = any(is_periodic);
|
||||
is_periodic_strict = is_periodic;
|
||||
|
||||
if is_periodic_loop && ~is_periodic
|
||||
if ~opts_simul_.periodic_solution_strict && any(number_of_periods_with_violations(~regime_violates_constraint_in_expectation(1:iter))<=opts_simul_.periodic_solution_threshold)
|
||||
is_periodic=true;
|
||||
is_periodic_all=false(size(is_periodic_loop_all));
|
||||
is_periodic_all(1) = true; % here we consider all guesses and pick the best one according to the criteria below
|
||||
else
|
||||
do_nothing=true;
|
||||
end
|
||||
end
|
||||
if is_periodic && periodic_solution
|
||||
inx = find(is_periodic_all,1):iter;
|
||||
inx1 = inx(find(~regime_violates_constraint_in_expectation(inx)));
|
||||
if not(isempty(inx1))
|
||||
inx=inx1;
|
||||
end
|
||||
if is_periodic_strict || isempty(inx1)
|
||||
[merr,imerr]=min(max_err(inx));
|
||||
else
|
||||
[merr,imerr]=min(number_of_periods_with_violations(inx));
|
||||
end
|
||||
[merr,imerr]=min(max_err(inx));
|
||||
inx = inx(imerr);
|
||||
binding_indicator=binding_indicator_history{inx};
|
||||
if inx<iter
|
||||
|
|
|
@ -228,7 +228,7 @@ for shock_period = 1:n_shocks_periods
|
|||
|
||||
err_binding_constraint_new = [err.binding_constraint_1(1:end_periods); err.binding_constraint_2(1:end_periods)];
|
||||
err_relaxed_constraint_new = [err.relax_constraint_1(1:end_periods); err.relax_constraint_2(1:end_periods)];
|
||||
|
||||
|
||||
% check if changes_
|
||||
if any(binding_constraint_new & ~my_binding_indicator(:)) || any(relaxed_constraint_new & my_binding_indicator(:))
|
||||
err_violation = err_binding_constraint_new(binding_constraint_new & ~my_binding_indicator(:));
|
||||
|
@ -243,11 +243,6 @@ for shock_period = 1:n_shocks_periods
|
|||
|
||||
binding_constraint_new=[binding.constraint_1(1:end_periods);last_indicator; binding.constraint_2(1:end_periods);last_indicator];
|
||||
relaxed_constraint_new = [relax.constraint_1(1:end_periods);not(last_indicator); relax.constraint_2(1:end_periods);not(last_indicator)];
|
||||
tmp_nper(1) = sum(binding_indicator(:,1) - (binding_indicator(:,1) | [binding.constraint_1(1:end_periods);last_indicator]) & ~(binding_indicator(:,1) & [relax.constraint_1(1:end_periods);not(last_indicator)]));
|
||||
tmp_nper(2) = sum(binding_indicator(:,2) - (binding_indicator(:,2) | [binding.constraint_2(1:end_periods);last_indicator]) & ~(binding_indicator(:,2) & [relax.constraint_2(1:end_periods);not(last_indicator)]));
|
||||
number_of_periods_with_violations(iter) = max(tmp_nper);
|
||||
regime_exit_period(iter,1) = max(regime_history(shock_period).regimestart1);
|
||||
regime_exit_period(iter,2) = max(regime_history(shock_period).regimestart2);
|
||||
if curb_retrench % apply Gauss-Seidel idea of slowing down the change in the guess
|
||||
% for the constraint -- only relax one
|
||||
% period at a time starting from the last
|
||||
|
@ -281,7 +276,7 @@ for shock_period = 1:n_shocks_periods
|
|||
is_periodic_loop(kiter) = false;
|
||||
end
|
||||
end
|
||||
is_periodic_loop_all =is_periodic_loop;
|
||||
% is_periodic_loop_all =is_periodic_loop;
|
||||
is_periodic_loop = any(is_periodic_loop);
|
||||
% only accept periodicity where regimes differ by one
|
||||
% period!
|
||||
|
@ -290,35 +285,20 @@ for shock_period = 1:n_shocks_periods
|
|||
if size(binding_indicator,1)== size(binding_indicator_history{kiter},1)
|
||||
% vvv = [binding_indicator_history{kiter}; false(size(binding_indicator,1)- size(binding_indicator_history{kiter},1), 1)];
|
||||
% is_periodic(kiter) = isequal(vvv, binding_indicator);
|
||||
is_periodic(kiter) = isequal(binding_indicator_history{kiter}, binding_indicator) && sum(binding_indicator_history{iter}(:,1)-binding_indicator(:,1))<=opts_simul_.periodic_solution_threshold && sum(binding_indicator_history{iter}(:,2)-binding_indicator(:,2))<=opts_simul_.periodic_solution_threshold;
|
||||
is_periodic(kiter) = isequal(binding_indicator_history{kiter}, binding_indicator) && length(find(binding_indicator_history{iter}(:,1)-binding_indicator(:,1)))<=1 && length(find(binding_indicator_history{iter}(:,2)-binding_indicator(:,2)))<=1;
|
||||
else
|
||||
is_periodic(kiter)=false;
|
||||
end
|
||||
end
|
||||
is_periodic_all = is_periodic;
|
||||
is_periodic = any(is_periodic);
|
||||
is_periodic_strict = is_periodic;
|
||||
|
||||
if is_periodic_loop && ~is_periodic
|
||||
if ~opts_simul_.periodic_solution_strict && any(number_of_periods_with_violations(~regime_violates_constraint_in_expectation(1:iter))<opts_simul_.periodic_solution_threshold)
|
||||
is_periodic=true;
|
||||
is_periodic_all=false(size(is_periodic_loop_all));
|
||||
is_periodic_all(1) = true; % here we consider all guesses and pick the best one according to the criteria below
|
||||
else
|
||||
do_nothing=true;
|
||||
end
|
||||
end
|
||||
if is_periodic && periodic_solution
|
||||
inx = find(is_periodic_all,1):iter;
|
||||
inx1 = inx(find(~regime_violates_constraint_in_expectation(inx)));
|
||||
if not(isempty(inx1))
|
||||
inx=inx1;
|
||||
end
|
||||
if is_periodic_strict || isempty(inx1)
|
||||
[min_err,index_min_err]=min(max_err(inx));
|
||||
else
|
||||
[min_err,index_min_err]=min(number_of_periods_with_violations(inx));
|
||||
end
|
||||
[min_err,index_min_err]=min(max_err(inx));
|
||||
inx = inx(index_min_err);
|
||||
binding_indicator=binding_indicator_history{inx}; %select regime history with same result, but smallest error
|
||||
if inx<iter %update if needed
|
||||
|
|
|
@ -1,28 +1,25 @@
|
|||
function [dr, out, ss] = solver(M_, options_, dr ,steady_state, exo_steady_state, exo_det_steady_state)
|
||||
% [dr, out, ss] = solver(M_,oo_,options_, dr ,steady_state, exo_steady_state, exo_det_steady_state
|
||||
% function [oo_, out, ss] = solver(M_,oo_,options_, dr ,steady_state, exo_steady_state, exo_det_steady_state
|
||||
% Solves the model with an OBC and produces simulations/IRFs
|
||||
%
|
||||
% INPUT:
|
||||
% - M_ [structure] Matlab's structure describing the model
|
||||
% - options_ [structure] Matlab's structure containing the options
|
||||
% - dr [structure] model information structure
|
||||
% - endo_steady_state [vector] steady state value for endogenous variables
|
||||
% - exo_steady_state [vector] steady state value for exogenous variables
|
||||
% - exo_det_steady_state [vector] steady state value for exogenous deterministic variables
|
||||
% - M_ [structure] Matlab's structure describing the model
|
||||
% - oo_ [structure] Matlab's structure containing the results
|
||||
% - options_ [structure] Matlab's structure containing the options
|
||||
%
|
||||
% OUTPUT:
|
||||
% - dr [structure] decision rules
|
||||
% - out [structure] simulation result containing fields:
|
||||
% - linear: paths for endogenous variables ignoring OBC (linear solution)
|
||||
% - piecewise: paths for endogenous variables satisfying the OBC (occbin/piecewise solution)
|
||||
% - ys: vector of steady state values
|
||||
% - regime_history: information on number and time of regime transitions
|
||||
% - ss [structure] State space solution
|
||||
% - T: [n_vars by n_vars by n_shock_period] array of transition matrices
|
||||
% - R: [n_vars by n_exo by n_shock_period] array of shock response matrices
|
||||
% - C: [n_vars by n_shock_period] array of constants
|
||||
% - oo_ [structure] Matlab's structure containing the results
|
||||
% - out [structure] simulation result containing fields:
|
||||
% - linear: paths for endogenous variables ignoring OBC (linear solution)
|
||||
% - piecewise: paths for endogenous variables satisfying the OBC (occbin/piecewise solution)
|
||||
% - ys: vector of steady state values
|
||||
% - regime_history: information on number and time of regime transitions
|
||||
% - ss [structure] State space solution
|
||||
% - T: [n_vars by n_vars by n_shock_period] array of transition matrices
|
||||
% - R: [n_vars by n_exo by n_shock_period] array of shock response matrices
|
||||
% - C: [n_vars by n_shock_period] array of constants
|
||||
|
||||
% Copyright © 2021-2023 Dynare Team
|
||||
% Copyright © 2021 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
%
|
||||
|
@ -53,7 +50,6 @@ else
|
|||
end
|
||||
end
|
||||
|
||||
ss=struct();
|
||||
if solve_dr
|
||||
if isempty(options_.qz_criterium)
|
||||
options_.qz_criterium = 1+1e-6;
|
||||
|
@ -94,7 +90,15 @@ end
|
|||
|
||||
% add back steady state
|
||||
if ~options_.occbin.simul.piecewise_only
|
||||
out.linear = out.linear + out.ys';
|
||||
if ~isoctave && matlab_ver_less_than('9.1') % Automatic broadcasting was introduced in MATLAB R2016b
|
||||
out.linear = bsxfun(@plus, out.linear, out.ys');
|
||||
else
|
||||
out.linear = out.linear + out.ys';
|
||||
end
|
||||
end
|
||||
out.piecewise = out.piecewise + out.ys';
|
||||
out.exo_pos = options_.occbin.simul.exo_pos;
|
||||
if ~isoctave && matlab_ver_less_than('9.1') % Automatic broadcasting was introduced in MATLAB R2016b
|
||||
out.piecewise = bsxfun(@plus, out.piecewise, out.ys');
|
||||
else
|
||||
out.piecewise = out.piecewise + out.ys';
|
||||
end
|
||||
out.exo_pos = options_.occbin.simul.exo_pos;
|
|
@ -1,44 +0,0 @@
|
|||
function [oo_,options_] = squeeze_shock_decomposition(M_,oo_,options_, sd_vlist)
|
||||
|
||||
if isstruct(options_.plot_shock_decomp.q2a)
|
||||
|
||||
avname=char({options_.plot_shock_decomp.q2a.qname});
|
||||
sda = options_.plot_shock_decomp.q2a(ismember(avname,sd_vlist,'rows'));
|
||||
for k=1:length(sda)
|
||||
if isstruct(sda(k).aux)
|
||||
sd_vlist = [sd_vlist; cellstr(sda(k).aux.y)];
|
||||
end
|
||||
end
|
||||
end
|
||||
i_var = varlist_indices(sd_vlist,M_.endo_names);
|
||||
sd_vlist = M_.endo_names(i_var);
|
||||
% first we squeeze usual fields
|
||||
oo_ = squeeze_shock_decomposition(M_,oo_,options_,sd_vlist);
|
||||
i_var = oo_.shock_decomposition_info.i_var;
|
||||
sd_vlist = M_.endo_names(i_var);
|
||||
|
||||
% now we check for occbin SDs
|
||||
options_.occbin.shock_decomp.i_var = i_var;
|
||||
if isfield (oo_.occbin.smoother,'decomp')
|
||||
oo_.occbin.smoother.decomp = oo_.occbin.smoother.decomp(i_var,:,:);
|
||||
oo_.occbin.smoother.wdecomp = oo_.occbin.smoother.wdecomp(i_var,:,:);
|
||||
end
|
||||
|
||||
if isfield(oo_.occbin,'shock_decomp')
|
||||
fnames = fieldnames(oo_.occbin.shock_decomp);
|
||||
for k=1:length(fnames)
|
||||
nendo = numel(oo_.occbin.shock_decomp.(fnames{k}).vname);
|
||||
tmp_i_var = varlist_indices(sd_vlist,char(oo_.occbin.shock_decomp.(fnames{k}).vname));
|
||||
oo_.occbin.shock_decomp.(fnames{k}).vname = cellstr(sd_vlist);
|
||||
tmpnames = fieldnames(oo_.occbin.shock_decomp.(fnames{k}));
|
||||
for t=1:length(tmpnames)
|
||||
if size(oo_.occbin.shock_decomp.(fnames{k}).(tmpnames{t}),3)==nendo
|
||||
oo_.occbin.shock_decomp.(fnames{k}).(tmpnames{t})= oo_.occbin.shock_decomp.(fnames{k}).(tmpnames{t})(:,:,tmp_i_var);
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
|
|
@ -7,7 +7,7 @@ function write_regimes_to_xls(occbin_struct,M_,options_)
|
|||
% - M_ [struct] Matlab's structure describing the model
|
||||
% - options_ [struct] Matlab's structure describing the current options
|
||||
|
||||
% Copyright © 2021-2023 Dynare Team
|
||||
% Copyright © 2021 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
%
|
||||
|
@ -62,7 +62,14 @@ else
|
|||
end
|
||||
end
|
||||
|
||||
filename=[OutputDirectoryName filesep xls_filename '.xls'];
|
||||
if ~ispc && ~isoctave && matlab_ver_less_than('9.0')
|
||||
% On GNU/Linux and macOS, with MATLAB < R2016a, “writeable” can’t write Excel files
|
||||
% (and “xlswrite” can’t either)
|
||||
warning('This version of MATLAB is too old and cannot create Excel files. The Occbin regimes will rather be written to a CSV file.')
|
||||
filename=[OutputDirectoryName filesep xls_filename '.csv'];
|
||||
else
|
||||
filename=[OutputDirectoryName filesep xls_filename '.xls'];
|
||||
end
|
||||
|
||||
if isfile(filename)
|
||||
delete(filename)
|
||||
|
@ -74,6 +81,10 @@ if isoctave
|
|||
error('The io package is required to write XLS files from Octave')
|
||||
end
|
||||
xlswrite(filename, vertcat(Header, xlsmat));
|
||||
elseif ~ispc && matlab_ver_less_than('9.0')
|
||||
% Use a CSV file. See the comment above about filename.
|
||||
% We don’t use xlswrite because its CSV fallback does not support cell-arrays.
|
||||
writetable(array2table(xlsmat,'VariableNames',Header), filename);
|
||||
else
|
||||
writetable(array2table(xlsmat,'VariableNames',Header), filename, 'Sheet', 'Regimes');
|
||||
end
|
||||
|
|
|
@ -64,9 +64,9 @@ if ~options_.analytic_derivation
|
|||
loss = full(weights(:)'*vx(:));
|
||||
else
|
||||
totparam_nbr=length(i_params);
|
||||
oo_.dr.derivs = identification.get_perturbation_params_derivs(M_, options_, [], oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state, i_params, [], [], 0); %analytic derivatives of perturbation matrices
|
||||
oo_.dr.derivs = get_perturbation_params_derivs(M_, options_, [], oo_.dr, oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state, i_params, [], [], 0); %analytic derivatives of perturbation matrices
|
||||
|
||||
pruned_state_space = pruned_SS.pruned_state_space_system(M_, options_, oo_.dr, i_var, 0, 0, 1);
|
||||
pruned_state_space = pruned_state_space_system(M_, options_, oo_.dr, i_var, 0, 0, 1);
|
||||
vx = pruned_state_space.Var_y + pruned_state_space.E_y*pruned_state_space.E_y';
|
||||
dE_yy = pruned_state_space.dVar_y;
|
||||
for jp=1:length(i_params)
|
||||
|
|
|
@ -18,7 +18,7 @@ function [pacmodl, lhs, rhs, pnames, enames, xnames, rname, pid, eid, xid, pname
|
|||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
% Get the original equation to be estimated
|
||||
[~, RHS] = get_lhs_and_rhs(eqname, M_, true);
|
||||
[LHS, RHS] = get_lhs_and_rhs(eqname, M_, true);
|
||||
|
||||
% Check that the equation has a PAC expectation term.
|
||||
if ~contains(RHS, 'pac_expectation', 'IgnoreCase', true)
|
||||
|
|
|
@ -41,7 +41,7 @@ function iterative_ols(eqname, params, data, range)
|
|||
|
||||
global M_ oo_ options_
|
||||
|
||||
[pacmodl, ~, rhs, ~, ~, ~, rname, ~, ~, ~, ~, ipnames_, params, data] = ...
|
||||
[pacmodl, ~, rhs, ~, ~, ~, rname, ~, ~, ~, ~, ipnames_, params, data, ~] = ...
|
||||
pac.estimate.init(M_, oo_, eqname, params, data, range);
|
||||
|
||||
% Set initial condition.
|
||||
|
|
|
@ -42,7 +42,7 @@ function nls(eqname, params, data, range, optimizer, varargin)
|
|||
% is available only if the matylab optimization toolbox is installed), the
|
||||
% remaining inputs are the options (key/value) passed to the optimizers.
|
||||
|
||||
% Copyright © 2018-2023 Dynare Team
|
||||
% Copyright © 2018-2022 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
%
|
||||
|
@ -96,6 +96,12 @@ write_residuals_routine(lhs, rhs, eqname, ipnames_, M_, pacmodl);
|
|||
% Create a routine for evaluating the sum of squared residuals of the nonlinear model
|
||||
write_ssr_routine(lhs, rhs, eqname, ipnames_, M_, pacmodl);
|
||||
|
||||
% Workaround for Octave bug https://savannah.gnu.org/bugs/?46282
|
||||
% Octave will randomly fail to read the ssr_* file generated in the +folder
|
||||
if isoctave && octave_ver_less_than('7')
|
||||
path(path)
|
||||
end
|
||||
|
||||
% Copy (sub)sample data in a matrix.
|
||||
DATA = data([range(1)-1, range]).data;
|
||||
|
||||
|
@ -200,23 +206,23 @@ if isnan(ssr0) || isinf(ssr0) || ~isreal(ssr0)
|
|||
end
|
||||
|
||||
if is_gauss_newton
|
||||
[params1, SSR] = gauss_newton(resfun, params0);
|
||||
[params1, SSR, exitflag] = gauss_newton(resfun, params0);
|
||||
elseif is_lsqnonlin
|
||||
if ismember('levenberg-marquardt', varargin)
|
||||
% Levenberg Marquardt does not handle boundary constraints.
|
||||
[params1, SSR] = lsqnonlin(resfun, params0, [], [], optimset(varargin{:}));
|
||||
[params1, SSR, ~, exitflag] = lsqnonlin(resfun, params0, [], [], optimset(varargin{:}));
|
||||
else
|
||||
[params1, SSR] = lsqnonlin(resfun, params0, bounds(:,1), bounds(:,2), optimset(varargin{:}));
|
||||
[params1, SSR, ~, exitflag] = lsqnonlin(resfun, params0, bounds(:,1), bounds(:,2), optimset(varargin{:}));
|
||||
end
|
||||
else
|
||||
% Estimate the parameters by minimizing the sum of squared residuals.
|
||||
[params1, SSR] = dynare_minimize_objective(ssrfun, params0, ...
|
||||
minalgo, ...
|
||||
options_, ...
|
||||
bounds, ...
|
||||
parameter_names, ...
|
||||
[], ...
|
||||
[]);
|
||||
[params1, SSR, exitflag] = dynare_minimize_objective(ssrfun, params0, ...
|
||||
minalgo, ...
|
||||
options_, ...
|
||||
bounds, ...
|
||||
parameter_names, ...
|
||||
[], ...
|
||||
[]);
|
||||
end
|
||||
|
||||
% Revert local modifications to the options.
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -40,7 +40,7 @@ end
|
|||
errorcode = 0;
|
||||
|
||||
% Get the original equation to be estimated
|
||||
[~, RHS] = get_lhs_and_rhs(eqname, M_, true);
|
||||
[LHS, RHS] = get_lhs_and_rhs(eqname, M_, true);
|
||||
|
||||
% Check that the equation has a PAC expectation term.
|
||||
if ~contains(RHS, 'pac_expectation', 'IgnoreCase', true)
|
||||
|
|
|
@ -49,7 +49,7 @@ for i1=1:p
|
|||
for i4=i3:p
|
||||
for i5=i4:p
|
||||
for i6=i5:p
|
||||
idx = pruned_SS.uperm([i6 i5 i4 i3 i2 i1]);
|
||||
idx = uperm([i6 i5 i4 i3 i2 i1]);
|
||||
for r = 1:size(idx,1)
|
||||
ii1 = idx(r,1); ii2= idx(r,2); ii3=idx(r,3); ii4=idx(r,4); ii5=idx(r,5); ii6=idx(r,6);
|
||||
n = ii1 + (ii2-1)*p + (ii3-1)*p^2 + (ii4-1)*p^3 + (ii5-1)*p^4 + (ii6-1)*p^5;
|
||||
|
|
|
@ -78,14 +78,14 @@ end
|
|||
Counter(0);
|
||||
|
||||
switch L1ops
|
||||
case {'==' '='}
|
||||
case {'==' '='},
|
||||
if isnan(MaxCounter)
|
||||
% return the number of solutions
|
||||
v = nchoosek(n+L1-1,L1); % nchoosek(n+L1-1,n-1)
|
||||
else
|
||||
v = allVL1eq(n, L1);
|
||||
end
|
||||
case '<=' % call allVL1eq for various sum targets
|
||||
case '<=', % call allVL1eq for various sum targets
|
||||
if isnan(MaxCounter)
|
||||
% return the number of solutions
|
||||
%v = nchoosek(n+L1,L1)*factorial(n-L1); BUG <- 16/Sep/2009:
|
||||
|
@ -99,7 +99,7 @@ switch L1ops
|
|||
v = cell2mat(arrayfun(@(j) allVL1eq(n, j), (0:L1)', ...
|
||||
'UniformOutput', false));
|
||||
end
|
||||
case '<'
|
||||
case '<',
|
||||
v = allVL1(n, L1-1, '<=', MaxCounter);
|
||||
otherwise
|
||||
error('allVL1: unknown L1ops')
|
||||
|
|
|
@ -76,8 +76,8 @@ if odd
|
|||
end
|
||||
y = y*rho;
|
||||
end
|
||||
y = prod(1:2:s1)*prod(1:2:s2)*y;
|
||||
y = prod([1:2:s1])*prod([1:2:s2])*y;
|
||||
if nargout > 1
|
||||
dy = prod(1:2:s1)*prod(1:2:s2)*dy;
|
||||
dy = prod([1:2:s1])*prod([1:2:s2])*dy;
|
||||
end
|
||||
|
||||
|
|
|
@ -21,7 +21,7 @@
|
|||
% Multivariate Analysis, 2008, vol. 99, issue 3, pages 542-554.
|
||||
% =========================================================================
|
||||
% Copyright © 2008-2015 Raymond Kan <kan@chass.utoronto.ca>
|
||||
% Copyright © 2019-2023 Dynare Team
|
||||
% Copyright © 2019-2020 Dynare Team
|
||||
%
|
||||
% This file is part of Dynare.
|
||||
%
|
||||
|
@ -38,7 +38,7 @@
|
|||
% You should have received a copy of the GNU General Public License
|
||||
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
|
||||
% =========================================================================
|
||||
function y = prodmom(V,ii,nu)
|
||||
function y = prodmom(V,ii,nu);
|
||||
if nargin<3
|
||||
nu = ones(size(ii));
|
||||
end
|
||||
|
@ -61,7 +61,7 @@ s2 = s/2;
|
|||
% Use univariate normal results
|
||||
%
|
||||
if m==1
|
||||
y = V^s2*prod(1:2:s-1);
|
||||
y = V^s2*prod([1:2:s-1]);
|
||||
return
|
||||
end
|
||||
%
|
||||
|
@ -104,4 +104,4 @@ for i=1:fix(prod(nu+1)/2)
|
|||
end
|
||||
end
|
||||
end
|
||||
y = y/prod(1:s2);
|
||||
y = y/prod([1:s2]);
|
|
@ -82,9 +82,9 @@ s2 = s/2;
|
|||
% Use univariate normal results
|
||||
%
|
||||
if m==1
|
||||
y = V^s2*prod(1:2:s-1);
|
||||
y = V^s2*prod([1:2:s-1]);
|
||||
if nargout > 1
|
||||
dy = s2*V^(s2-1)*dV*prod(1:2:s-1);
|
||||
dy = s2*V^(s2-1)*dV*prod([1:2:s-1]);
|
||||
dy = reshape(dy,1,size(dV,3));
|
||||
end
|
||||
return
|
||||
|
@ -169,8 +169,8 @@ for i=1:fix(prod(nu+1)/2)
|
|||
end
|
||||
end
|
||||
end
|
||||
y = y/prod(1:s2);
|
||||
y = y/prod([1:s2]);
|
||||
if nargout > 1
|
||||
dy = dy/prod(1:s2);
|
||||
dy = dy/prod([1:s2]);
|
||||
dy = reshape(dy,1,size(dV,3));
|
||||
end
|
|
@ -49,7 +49,7 @@ for l=1:p
|
|||
for k=l:p
|
||||
for j=k:p
|
||||
for i=j:p
|
||||
idx = pruned_SS.uperm([i j k l]);
|
||||
idx = uperm([i j k l]);
|
||||
for r = 1:size(idx,1)
|
||||
ii = idx(r,1); jj= idx(r,2); kk=idx(r,3); ll=idx(r,4);
|
||||
n = ii + (jj-1)*p + (kk-1)*p^2 + (ll-1)*p^3;
|
||||
|
|
|
@ -1,146 +0,0 @@
|
|||
function b = admissible(o, d)
|
||||
|
||||
% Return true iff d is an admissible draw in a distribution characterized by o.
|
||||
%
|
||||
% INPUTS
|
||||
% - o [dprior] Distribution specification for a n×1 vector of independent continuous random variables
|
||||
% - d [double] n×1 vector.
|
||||
%
|
||||
% OUTPUTS
|
||||
% - b [logical] scalar.
|
||||
%
|
||||
% REMARKS
|
||||
% None.
|
||||
%
|
||||
% EXAMPLE
|
||||
%
|
||||
% >> Prior = dprior(bayestopt_, options_.prior_trunc);
|
||||
% >> d = Prior.draw()
|
||||
% >> Prior.admissible(d)
|
||||
% ans =
|
||||
%
|
||||
% logical
|
||||
%
|
||||
% 1
|
||||
|
||||
% Copyright © 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/>.
|
||||
|
||||
b = false;
|
||||
|
||||
if ~isequal(length(d), length(o.lb))
|
||||
return
|
||||
end
|
||||
|
||||
if all(d>=o.lb & d<=o.ub)
|
||||
b = true;
|
||||
end
|
||||
|
||||
return % --*-- Unit tests --*--
|
||||
|
||||
%@test:1
|
||||
% Fill global structures with required fields...
|
||||
prior_trunc = 1e-10;
|
||||
p0 = repmat([1; 2; 3; 4; 5; 6; 8], 2, 1); % Prior shape
|
||||
p1 = .4*ones(14,1); % Prior mean
|
||||
p2 = .2*ones(14,1); % Prior std.
|
||||
p3 = NaN(14,1);
|
||||
p4 = NaN(14,1);
|
||||
p5 = NaN(14,1);
|
||||
p6 = NaN(14,1);
|
||||
p7 = NaN(14,1);
|
||||
|
||||
for i=1:14
|
||||
switch p0(i)
|
||||
case 1
|
||||
% Beta distribution
|
||||
p3(i) = 0;
|
||||
p4(i) = 1;
|
||||
[p6(i), p7(i)] = beta_specification(p1(i), p2(i)^2, p3(i), p4(i));
|
||||
p5(i) = compute_prior_mode([p6(i) p7(i)], 1);
|
||||
case 2
|
||||
% Gamma distribution
|
||||
p3(i) = 0;
|
||||
p4(i) = Inf;
|
||||
[p6(i), p7(i)] = gamma_specification(p1(i), p2(i)^2, p3(i), p4(i));
|
||||
p5(i) = compute_prior_mode([p6(i) p7(i)], 2);
|
||||
case 3
|
||||
% Normal distribution
|
||||
p3(i) = -Inf;
|
||||
p4(i) = Inf;
|
||||
p6(i) = p1(i);
|
||||
p7(i) = p2(i);
|
||||
p5(i) = p1(i);
|
||||
case 4
|
||||
% Inverse Gamma (type I) distribution
|
||||
p3(i) = 0;
|
||||
p4(i) = Inf;
|
||||
[p6(i), p7(i)] = inverse_gamma_specification(p1(i), p2(i)^2, p3(i), 1, false);
|
||||
p5(i) = compute_prior_mode([p6(i) p7(i)], 4);
|
||||
case 5
|
||||
% Uniform distribution
|
||||
[p1(i), p2(i), p6(i), p7(i)] = uniform_specification(p1(i), p2(i), p3(i), p4(i));
|
||||
p3(i) = p6(i);
|
||||
p4(i) = p7(i);
|
||||
p5(i) = compute_prior_mode([p6(i) p7(i)], 5);
|
||||
case 6
|
||||
% Inverse Gamma (type II) distribution
|
||||
p3(i) = 0;
|
||||
p4(i) = Inf;
|
||||
[p6(i), p7(i)] = inverse_gamma_specification(p1(i), p2(i)^2, p3(i), 2, false);
|
||||
p5(i) = compute_prior_mode([p6(i) p7(i)], 6);
|
||||
case 8
|
||||
% Weibull distribution
|
||||
p3(i) = 0;
|
||||
p4(i) = Inf;
|
||||
[p6(i), p7(i)] = weibull_specification(p1(i), p2(i)^2, p3(i));
|
||||
p5(i) = compute_prior_mode([p6(i) p7(i)], 8);
|
||||
otherwise
|
||||
error('This density is not implemented!')
|
||||
end
|
||||
end
|
||||
|
||||
BayesInfo.pshape = p0;
|
||||
BayesInfo.p1 = p1;
|
||||
BayesInfo.p2 = p2;
|
||||
BayesInfo.p3 = p3;
|
||||
BayesInfo.p4 = p4;
|
||||
BayesInfo.p5 = p5;
|
||||
BayesInfo.p6 = p6;
|
||||
BayesInfo.p7 = p7;
|
||||
|
||||
ndraws = 10;
|
||||
|
||||
% Call the tested routine
|
||||
try
|
||||
% Instantiate dprior object
|
||||
o = dprior(BayesInfo, prior_trunc, false);
|
||||
% Do simulations in a loop and estimate recursively the mean and the variance.
|
||||
for i = 1:ndraws
|
||||
draw = o.draw();
|
||||
if ~o.admissible(draw)
|
||||
error()
|
||||
end
|
||||
end
|
||||
t(1) = true;
|
||||
catch
|
||||
t(1) = false;
|
||||
end
|
||||
|
||||
T = all(t);
|
||||
|
||||
%@eof:1
|
|
@ -23,9 +23,9 @@ switch S(1).type
|
|||
case '.'
|
||||
if ismember(S(1).subs, {'p1','p2','p3','p4','p5','p6','p7','lb','ub'})
|
||||
p = builtin('subsref', o, S(1));
|
||||
elseif ismember(S(1).subs, {'draw','length'})
|
||||
elseif ismember(S(1).subs, {'draw'})
|
||||
p = feval(S(1).subs, o);
|
||||
elseif ismember(S(1).subs, {'draws', 'density', 'densities', 'moments', 'admissible'})
|
||||
elseif ismember(S(1).subs, {'draws', 'density', 'densities', 'moments'})
|
||||
p = feval(S(1).subs, o , S(2).subs{:});
|
||||
elseif ismember(S(1).subs, {'mean', 'median', 'variance', 'mode'})
|
||||
if (length(S)==2 && isempty(S(2).subs)) || length(S)==1
|
||||
|
|
|
@ -0,0 +1,152 @@
|
|||
function [AHess, DLIK, LIK] = AHessian(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,kalman_tol,riccati_tol)
|
||||
% function [AHess, DLIK, LIK] = AHessian(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,kalman_tol,riccati_tol)
|
||||
%
|
||||
% computes the asymptotic hessian matrix of the log-likelihood function of
|
||||
% a state space model (notation as in kalman_filter.m in DYNARE
|
||||
% Thanks to Nikolai Iskrev
|
||||
%
|
||||
% NOTE: the derivative matrices (DT,DR ...) are 3-dim. arrays with last
|
||||
% dimension equal to the number of structural parameters
|
||||
|
||||
% Copyright © 2011-2017 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/>.
|
||||
|
||||
|
||||
k = size(DT,3); % number of structural parameters
|
||||
smpl = size(Y,2); % Sample size.
|
||||
pp = size(Y,1); % Maximum number of observed variables.
|
||||
mm = size(T,2); % Number of state variables.
|
||||
a = zeros(mm,1); % State vector.
|
||||
Om = R*Q*transpose(R); % Variance of R times the vector of structural innovations.
|
||||
t = 0; % Initialization of the time index.
|
||||
oldK = 0;
|
||||
notsteady = 1; % Steady state flag.
|
||||
F_singular = 1;
|
||||
|
||||
lik = zeros(smpl,1); % Initialization of the vector gathering the densities.
|
||||
LIK = Inf; % Default value of the log likelihood.
|
||||
if nargout > 1
|
||||
DLIK = zeros(k,1); % Initialization of the score.
|
||||
end
|
||||
AHess = zeros(k,k); % Initialization of the Hessian
|
||||
Da = zeros(mm,k); % State vector.
|
||||
Dv = zeros(length(mf),k);
|
||||
|
||||
% for ii = 1:k
|
||||
% DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii));
|
||||
% end
|
||||
|
||||
while notsteady && t<smpl
|
||||
t = t+1;
|
||||
v = Y(:,t)-a(mf);
|
||||
F = P(mf,mf) + H;
|
||||
if rcond(F) < kalman_tol
|
||||
if ~all(abs(F(:))<kalman_tol)
|
||||
return
|
||||
else
|
||||
a = T*a;
|
||||
P = T*P*transpose(T)+Om;
|
||||
end
|
||||
else
|
||||
F_singular = 0;
|
||||
iF = inv(F);
|
||||
K = P(:,mf)*iF;
|
||||
lik(t) = log(det(F))+transpose(v)*iF*v;
|
||||
|
||||
[DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K);
|
||||
|
||||
for ii = 1:k
|
||||
Dv(:,ii) = -Da(mf,ii) - DYss(mf,ii);
|
||||
Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
|
||||
if t>=start && nargout > 1
|
||||
DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
|
||||
end
|
||||
end
|
||||
vecDPmf = reshape(DP(mf,mf,:),[],k);
|
||||
% iPmf = inv(P(mf,mf));
|
||||
if t>=start
|
||||
AHess = AHess + Dv'*iF*Dv + .5*(vecDPmf' * kron(iF,iF) * vecDPmf);
|
||||
end
|
||||
a = T*(a+K*v);
|
||||
P = T*(P-K*P(mf,:))*transpose(T)+Om;
|
||||
DP = DP1;
|
||||
end
|
||||
notsteady = max(max(abs(K-oldK))) > riccati_tol;
|
||||
oldK = K;
|
||||
end
|
||||
|
||||
if F_singular
|
||||
error('The variance of the forecast error remains singular until the end of the sample')
|
||||
end
|
||||
|
||||
|
||||
if t < smpl
|
||||
t0 = t+1;
|
||||
while t < smpl
|
||||
t = t+1;
|
||||
v = Y(:,t)-a(mf);
|
||||
for ii = 1:k
|
||||
Dv(:,ii) = -Da(mf,ii)-DYss(mf,ii);
|
||||
Da(:,ii) = DT(:,:,ii)*(a+K*v) + T*(Da(:,ii)+DK(:,:,ii)*v + K*Dv(:,ii));
|
||||
if t>=start && nargout >1
|
||||
DLIK(ii,1) = DLIK(ii,1) + trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
|
||||
end
|
||||
end
|
||||
if t>=start
|
||||
AHess = AHess + Dv'*iF*Dv;
|
||||
end
|
||||
a = T*(a+K*v);
|
||||
lik(t) = transpose(v)*iF*v;
|
||||
end
|
||||
AHess = AHess + .5*(smpl-t0+1)*(vecDPmf' * kron(iF,iF) * vecDPmf);
|
||||
if nargout > 1
|
||||
for ii = 1:k
|
||||
% DLIK(ii,1) = DLIK(ii,1) + (smpl-t0+1)*trace( iF*DF(:,:,ii) );
|
||||
end
|
||||
end
|
||||
lik(t0:smpl) = lik(t0:smpl) + log(det(F));
|
||||
% for ii = 1:k;
|
||||
% for jj = 1:ii
|
||||
% H(ii,jj) = trace(iPmf*(.5*DP(mf,mf,ii)*iPmf*DP(mf,mf,jj) + Dv(:,ii)*Dv(:,jj)'));
|
||||
% end
|
||||
% end
|
||||
end
|
||||
|
||||
AHess = -AHess;
|
||||
if nargout > 1
|
||||
DLIK = DLIK/2;
|
||||
end
|
||||
% adding log-likelihhod constants
|
||||
lik = (lik + pp*log(2*pi))/2;
|
||||
|
||||
LIK = sum(lik(start:end)); % Minus the log-likelihood.
|
||||
% end of main function
|
||||
|
||||
function [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,mf,iF,K)
|
||||
|
||||
k = size(DT,3);
|
||||
tmp = P-K*P(mf,:);
|
||||
|
||||
for ii = 1:k
|
||||
DF(:,:,ii) = DP(mf,mf,ii) + DH(:,:,ii);
|
||||
DiF(:,:,ii) = -iF*DF(:,:,ii)*iF;
|
||||
DK(:,:,ii) = DP(:,mf,ii)*iF + P(:,mf)*DiF(:,:,ii);
|
||||
Dtmp = DP(:,:,ii) - DK(:,:,ii)*P(mf,:) - K*DP(mf,:,ii);
|
||||
DP1(:,:,ii) = DT(:,:,ii)*tmp*T' + T*Dtmp*T' + T*tmp*DT(:,:,ii)' + DOm(:,:,ii);
|
||||
end
|
||||
|
||||
% end of computeDKalman
|
|
@ -89,7 +89,7 @@ if leads ==0
|
|||
end
|
||||
%disp('gensysToAMA:running ama');
|
||||
try % try to run AIM
|
||||
[bb,rts,~,~,~,~,aimcode] =...
|
||||
[bb,rts,ia,nexact,nnumeric,lgroots,aimcode] =...
|
||||
SPAmalg(theAIM_H,neq, lags,leads,condn,uprbnd);
|
||||
catch
|
||||
err = lasterror;
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue