Compare commits

...

68 Commits
master ... 6.x

Author SHA1 Message Date
Johannes Pfeifer 779b45fd13
SMC: gracefully exit with unsupported options
(cherry picked from commit 5d47ac2aa9)
2024-02-20 08:51:42 +01:00
Sébastien Villemot 9a179a3949
🐛 Steady state computation with bytecode + Ramsey policy was broken
(cherry picked from commit 1ce40d4df5)
2024-02-16 19:00:02 +01:00
Sébastien Villemot b7540c40e3
Manual: cosmetics
(cherry picked from commit 3000e6d691)
2024-02-16 14:08:46 +01:00
Johannes Pfeifer 94b8204711
solve_block_decomposed_problem.m: add missing semicolon
(cherry picked from commit 73d54cea04)
2024-02-16 14:08:46 +01:00
Willi Mutschler edca9c8f45
Update Dockerfile and instructions for new meson build systems
[skip ci]
This creates the Docker containers for 5.5 and 6.0

(cherry picked from commit 1b3c1c33ce)
2024-02-16 14:08:46 +01:00
Johannes Pfeifer 862261c9b9
gsa: update documentation
(cherry picked from commit 4a2724959d)
2024-02-14 14:08:08 +01:00
Johannes Pfeifer 711ff0e573
selec_posterior_draws.m: fix bug introduced when removing oo_ as an input
Thanks to Francesco Turino

(cherry picked from commit 6975aaef43)
2024-02-12 16:59:46 +01:00
Sébastien Villemot 76538d894a
Cosmetics
[skip ci]

(cherry picked from commit ec48980e1e)
2024-02-07 13:58:01 +01:00
Sébastien Villemot deab8ab5e4
Bump version number
[skip ci]
2024-02-05 16:10:30 +01:00
Sébastien Villemot 4111b88b89
CI: fix job for deploying manual
[skip ci]
2024-02-05 15:39:09 +01:00
Sébastien Villemot b654d2fdc2
NEWS.md: announcement for version 6.0
[skip ci]

(cherry picked from commit ebfd2aa0a1)
2024-02-02 18:33:37 +01:00
Sébastien Villemot 41dde2259c
Manual: update citation of reference manual working paper
(cherry picked from commit 433f00e224)
2024-02-02 18:33:36 +01:00
Sébastien Villemot 164eb44f6a
Manual: add missing options to occbin_solver
(cherry picked from commit d61cb124ba)
2024-02-02 18:33:36 +01:00
Sébastien Villemot 95492c418b
Manual: better documentation of solve_algo=12,14
(cherry picked from commit 05d82796c2)
2024-02-02 18:33:36 +01:00
Sébastien Villemot 1c19965cda
Manual: typos and cosmetics
(cherry picked from commit cfa978b39e)
2024-02-02 18:33:36 +01:00
Sébastien Villemot cc0b041e18
Manual: fix capitalization of Dynare Team on front page of PDF
(cherry picked from commit 99883d4ca6)
2024-02-01 21:53:04 +01:00
Sébastien Villemot edc81dd79e
Preprocessor: fix prototype of sparse {static,dynamic}_gN_tt.m for N⩾2 2024-01-31 18:16:52 +01:00
Johannes Pfeifer 2427888879
manual: clarify that search requires json
(cherry picked from commit a40b0c146d)
2024-01-30 11:18:28 +01:00
Johannes Pfeifer 45f838b559
manual: fix description of conditional likelihood
(cherry picked from commit 8e91841a39)
2024-01-30 11:18:28 +01:00
Johannes Pfeifer 943461a02f
annualized_shock_decomposition.m: fix bug introduced in 735bd66d
Use dedicated indicator instead of nargout to only request decomposition; closes #1919

(cherry picked from commit 2ed416532b)
2024-01-30 11:18:28 +01:00
Stéphane Adjemian (Argos) bd4357266a
Document dplot Matlab command.
(cherry picked from commit f5a5ebb910)
2024-01-29 20:58:59 +01:00
Sébastien Villemot a7d816cf99
Windows and macOS packages: fix installation path of x13as
The binary location had not been updated following the move of the dseries
submodule (commit e962cb4dba).

(cherry picked from commit 60e3b6a19f)
2024-01-29 16:33:02 +01:00
Stéphane Adjemian (Argos) 3a3d1db710
Add example for PAC equation (with estimation).
(cherry picked from commit 415a86d1d9)
2024-01-29 15:27:51 +01:00
Stéphane Adjemian (Argos) 50c1fb3597
Document composite targets in PAC equation.
(cherry picked from commit 8eab48aa5e)
2024-01-29 15:27:29 +01:00
Stéphane Adjemian (Argos) c8dd3045c9
Throw an error if composite PAC target ∧ trend_component aux. model.
(cherry picked from commit 9f9f4a99ba)
2024-01-29 15:27:09 +01:00
Stéphane Adjemian (Argos) c365f53e5c
Bug fix (wrong condition).
Also add comments about the choice for the definition of the linear
combination of the VAR companion variables.

We should test the numbe of output arguments, not the number of input
arguments. This was bug was probably not affecting the outcomes since
the number of input arguments is always greater than 1.

(cherry picked from commit a48a03bc67)
2024-01-29 15:26:49 +01:00
Stéphane Adjemian (Argos) 66c7e53ff2
Cosmetic changes.
(cherry picked from commit 942d8846e4)
2024-01-29 15:26:28 +01:00
Sébastien Villemot 0803119de4
README.md: fix testsuite documentation for running a whole directory of tests
[skip ci]
2024-01-29 13:59:57 +01:00
Sébastien Villemot 800da740dc
Occbin: add various consistency checks for bind/relax tags
In particular, emit more explicit error messages in the presence of
inconsistencies.

Closes: #103
2024-01-26 20:34:03 +01:00
Sébastien Villemot 4f4e5b8680
Bytecode: error out when using det_cond_forecast with perfect_foresight shocks
They’re not implemented in bytecode.

Closes: #1884
(cherry picked from commit 8954a682c7)
2024-01-26 10:19:11 +01:00
Sébastien Villemot 0149af67b7
Preprocessor / dseries: fix handling of monthly dates for months 10-12
Closes: #1918

(manually cherry picked from commit 6a0ee900a4)
2024-01-26 10:18:57 +01:00
Johannes Pfeifer 7e5888485b
gsa: add proper check for correctness of qz_criterium with unit roots
Critical for stability mapping

(cherry picked from commit b1cb309a73)
2024-01-22 19:06:01 +01:00
Sébastien Villemot ca0823fee4
Build system: workaround for Meson bug, needed for building MATLAB Online package
(cherry picked from commit 330542a79f)
2024-01-22 19:06:01 +01:00
Sébastien Villemot 052bb135c3
MATLAB Online package: update build script for meson
Also, use the local git checkout instead of downloading a source tarball from
the website.

(cherry picked from commit b2f603091a)
2024-01-22 19:06:01 +01:00
Sébastien Villemot c54cb4d29c
Build system: under Linux, do not try to statically link libgomp even with -Dprefer_static=true
Under Debian 12, it fails with:
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/12/libgomp.a(team.o): réadressage R_X86_64_TPOFF32 vers symbole caché « gomp_tls_data » ne peut pas être utilisé en créant un objet partagé

(cherry picked from commit 88236b1cc0)
2024-01-22 19:06:01 +01:00
Johannes Pfeifer 57e8c52ef9
GSA_recursive: make sure nobs is correctly set before checking for recursive estimation
Closes #1611

(cherry picked from commit 619de017d6)
2024-01-17 21:31:08 +01:00
Sébastien Villemot 510ba16601
Manual: do not add parentheses to synopsis of functions without arguments
Closes: #1707
(cherry picked from commit 85c637d3d1)
2024-01-17 21:31:08 +01:00
Sébastien Villemot c87c82c5a4
Remove remnants of workaround for incorrect display of macro-directives without arguments
This workaround was implemented in cd195279e9.
The zero-width spaces were inadvertently removed in
248ad18846.

Ref. #1707

(cherry picked from commit 6fe43545d8)
2024-01-17 21:31:08 +01:00
Sébastien Villemot c7d0f29dba
Manual: minor fixes to function synopses
(cherry picked from commit 6b6b648255)
2024-01-17 21:31:08 +01:00
Johannes Pfeifer 0ed937b833
Add display_parameter_values.m utility
(cherry picked from commit 28df34df06)
2024-01-17 14:38:21 +01:00
Johannes Pfeifer 2e237900aa
Tag Dynare figures and add utility for moving figures to uitabgroup
(cherry picked from commit 0187ebe0a2)
2024-01-17 14:38:11 +01:00
Johannes Pfeifer 695a55739c
compute_variance_decomposition.m: only print warning if absolute difference is meaningful
Prevents warnings if relative difference involves division by almost 0

(cherry picked from commit 6ff924550c)
2024-01-17 14:37:56 +01:00
Johannes Pfeifer df49b9f56c
occbin.DSGE_smoother.m: correct figure caption
(cherry picked from commit 248d8ae84f)
2024-01-15 12:18:13 +01:00
Johannes Pfeifer e3b60a1c1f
OccBin tools: rework codes
(cherry picked from commit 1b181fca57)
2024-01-15 11:39:51 +01:00
Johannes Pfeifer af0aa63d8c
🐛 model_info.m: fix display of lagged states
preprocessor increments lags/leads always only by lead_lag

(cherry picked from commit 45e8ab14dc)
2024-01-15 11:39:51 +01:00
Johannes Pfeifer 54268629bd
simulated_moment_uncertainty.m: remove evalin following removal of globals
transformed steady state is not passed back anymore

(cherry picked from commit 23225aca1b)
2024-01-15 11:39:51 +01:00
Sébastien Villemot 7f5c433382
Manual: update Normann’s affiliation
(cherry picked from commit 5d169d658e)

[skip ci]
2024-01-10 11:05:37 +01:00
Sébastien Villemot 9f1270b24d
Forbid alternative 1st order solvers with k_order_solver option
(cherry picked from commit cc02690acf)
2024-01-05 20:27:53 +01:00
Sébastien Villemot 8c8b9e0d67
Improve naming and description of various stack_solve_algo values
Also minor improvements to solve_algo description.

(cherry picked from commit ffb578276e)
2024-01-05 20:27:53 +01:00
Johannes Pfeifer f69a1483de
windows installer: add json-file
(cherry picked from commit 4a7851b069)
2024-01-05 20:27:53 +01:00
Johannes Pfeifer a94803ff29
send_endogenous_variables_to_workspace.m and friends: output column instead of row vectors
(cherry picked from commit 46d7e155d9)
2024-01-05 20:27:53 +01:00
Sébastien Villemot c19a4b14dd
Build system: don’t try to create TAGS file when not in a git working directory
(cherry picked from commit f9cd465fea)
2024-01-03 18:35:47 +01:00
Sébastien Villemot bb7648ad63
license.txt: fix various issues detected by lintian
(cherry picked from commit 53d8278d8a)
2024-01-03 18:35:46 +01:00
Sébastien Villemot 875437a221
Build system: install preprocessor symlink under libdir
(cherry picked from commit 049006a1bf)
2024-01-03 18:35:46 +01:00
Sébastien Villemot 0325d811b1
Build system: install .m files for MS-SBVAR
(cherry picked from commit e7cd6eb408)
2024-01-03 18:35:46 +01:00
Sébastien Villemot 093e9f348e
Build system: update list of ignored files under matlab/
(cherry picked from commit 0679da4cba)
2024-01-03 18:35:46 +01:00
Sébastien Villemot a910701699
Windows package: use our own mirror for the MSYS2 packages
Packages are removed from msys2.org after 21 months. Since the 6.x branch may
have a longer lifetime, it is safer to have our own mirror for the specific
packages that we need.
2024-01-03 10:44:43 +01:00
Sébastien Villemot d4e8d6d30d
Windows package: add missing rule for creating tarballs directory
[skip ci]

(cherry picked from commit a99beac083)
2024-01-03 10:25:02 +01:00
Johannes Pfeifer 4e125d6432
forecast_graphs.m: fix wrong naming
Also removes eval

(cherry picked from commit 02d1e8d3ed)
2024-01-03 10:14:23 +01:00
Johannes Pfeifer f53b6cc6fb
🐛 makedataset.m: correct error message with first_obs specified
(cherry picked from commit 8f07f37138)
2024-01-03 10:14:23 +01:00
Sébastien Villemot 6cae83f2f7
Update copyright years
(cherry picked from commit 8a7440c6ac)
2024-01-03 10:14:23 +01:00
Stéphane Adjemian (Guts) eb2c7cf101
Remove reference to dsmh in reference manual.
[skip ci]
2023-12-22 13:25:46 +01:00
Stéphane Adjemian (Guts) 9fd0dacf8a
Drop Dynamic Striated Metropolis-Hastings.
Will be part of dynare 7.x.
2023-12-22 13:18:29 +01:00
Sébastien Villemot f392c78644
Drop unused riccati_update MEX 2023-12-22 10:22:52 +01:00
Willi Mutschler fbb89dc190
Fixes for CET tests on Octave
- the mode file was previously saved as '-v7.3', now it is '-v6'
- mode_compute=1 and additional_optimizer=1 do not work under Octave

(cherry picked from commit ee2545f84d)
2023-12-22 10:18:48 +01:00
Johannes Pfeifer 0eedd5b46f
graph_comparison_irfs.m: compatibility fix for Octave
(cherry picked from commit 9c28f5feaf)
2023-12-22 10:18:47 +01:00
Sébastien Villemot 5acd6d1207
CI: adapt jobs for stable branch 2023-12-21 16:21:55 +01:00
Sébastien Villemot 6723a147ca
Bump version number 2023-12-21 16:06:00 +01:00
64 changed files with 1883 additions and 1402 deletions

View File

@ -11,12 +11,10 @@ variables:
# - 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 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=6-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'
@ -162,7 +160,6 @@ test_old_matlab:
paths:
- build-old-matlab/meson-logs/testlog.txt
when: always
when: manual
test_octave:
stage: test
@ -175,7 +172,6 @@ test_octave:
- build-octave/meson-logs/testlog.txt
when: always
needs: [ "build_octave" ]
when: manual
test_clang_format:
stage: test
@ -191,7 +187,7 @@ test_clang_format:
sign_windows:
stage: sign
rules:
- if: '$CI_PROJECT_NAMESPACE == "Dynare" && $CI_COMMIT_REF_NAME == "master"'
- if: '$CI_PROJECT_NAMESPACE == "Dynare" && $CI_COMMIT_TAG =~ /^6/'
when: on_success
- when: never
tags:
@ -205,10 +201,10 @@ sign_windows:
- windows/exe-signed/*
expire_in: 3 days
deploy_manual_unstable:
deploy_manual_stable:
stage: deploy
rules:
- if: '$CI_PROJECT_NAMESPACE == "Dynare" && $CI_COMMIT_REF_NAME == "master"'
- if: '$CI_PROJECT_NAMESPACE == "Dynare" && $CI_COMMIT_TAG =~ /^6\.[0-9]+$/'
when: on_success
- when: never
tags:
@ -216,12 +212,13 @@ deploy_manual_unstable:
dependencies:
- build_doc
script:
- rsync --recursive --links --delete build-doc/dynare-manual.html/ /srv/www.dynare.org/manual-unstable/
- rsync --recursive --links --delete build-doc/dynare-manual.html/ /srv/www.dynare.org/manual/
- cp build-doc/dynare-manual.pdf /srv/www.dynare.org/manual.pdf
deploy_snapshot_unstable:
deploy_release_stable:
stage: deploy
rules:
- if: '$CI_PROJECT_NAMESPACE == "Dynare" && $CI_COMMIT_REF_NAME == "master"'
- if: '$CI_PROJECT_NAMESPACE == "Dynare" && $CI_COMMIT_TAG =~ /^6\.[0-9]+$/'
when: on_success
- when: never
tags:
@ -233,11 +230,33 @@ deploy_snapshot_unstable:
- pkg_macOS_arm64
- pkg_macOS_x86_64
script:
- cp build-src/meson-dist/*.tar.xz /srv/www.dynare.org/snapshot/source/ && ln -sf *.tar.xz /srv/www.dynare.org/snapshot/source/dynare-latest-src.tar.xz
- f=(windows/exe-signed/*) && cp ${f[0]} /srv/www.dynare.org/snapshot/windows/ && ln -sf ${f[0]##*/} /srv/www.dynare.org/snapshot/windows/dynare-latest-win.exe
- f=(windows/7z/*) && cp ${f[0]} /srv/www.dynare.org/snapshot/windows-7z/ && ln -sf ${f[0]##*/} /srv/www.dynare.org/snapshot/windows-7z/dynare-latest-win.7z
- f=(windows/zip/*) && cp ${f[0]} /srv/www.dynare.org/snapshot/windows-zip/ && ln -sf ${f[0]##*/} /srv/www.dynare.org/snapshot/windows-zip/dynare-latest-win.zip
- f=(macOS/pkg/*-arm64.pkg) && cp ${f[0]} /srv/www.dynare.org/snapshot/macos-arm64/ && ln -sf ${f[0]##*/} /srv/www.dynare.org/snapshot/macos-arm64/dynare-latest-macos-arm64.pkg
- f=(macOS/pkg/*-x86_64.pkg) && cp ${f[0]} /srv/www.dynare.org/snapshot/macos-x86_64/ && ln -sf ${f[0]##*/} /srv/www.dynare.org/snapshot/macos-x86_64/dynare-latest-macos-x86_64.pkg
- ~/update-snapshot-list.sh
- cp build-src/meson-dist/*.tar.xz /srv/www.dynare.org/release/source/
- cp windows/exe-signed/* /srv/www.dynare.org/release/windows/
- cp windows/7z/* /srv/www.dynare.org/release/windows-7z/
- cp windows/zip/* /srv/www.dynare.org/release/windows-zip/
- cp macOS/pkg/*-arm64.pkg /srv/www.dynare.org/release/macos-arm64/
- cp macOS/pkg/*-x86_64.pkg /srv/www.dynare.org/release/macos-x86_64/
- ~/update-release-list.sh
- curl -X POST -F token="$WEBSITE_PIPELINE_TRIGGER_TOKEN" -F ref=master https://git.dynare.org/api/v4/projects/40/trigger/pipeline
deploy_beta_stable:
stage: deploy
rules:
- if: '$CI_PROJECT_NAMESPACE == "Dynare" && $CI_COMMIT_TAG =~ /^6(\.[0-9]+)?-(beta|rc)[0-9]+$/'
when: on_success
- when: never
tags:
- deploy
dependencies:
- pkg_source
- pkg_windows
- sign_windows
- pkg_macOS_arm64
- pkg_macOS_x86_64
script:
- cp build-src/meson-dist/*.tar.xz /srv/www.dynare.org/beta/source/
- cp windows/exe-signed/* /srv/www.dynare.org/beta/windows/
- cp windows/7z/* /srv/www.dynare.org/beta/windows-7z/
- cp windows/zip/* /srv/www.dynare.org/beta/windows-zip/
- cp macOS/pkg/*-arm64.pkg /srv/www.dynare.org/beta/macos-arm64/
- cp macOS/pkg/*-x86_64.pkg /srv/www.dynare.org/beta/macos-x86_64/

402
NEWS.md
View File

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

View File

@ -149,9 +149,10 @@ 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> deterministic_simulations
meson test -C <builddir> --suite deterministic_simulations
```
This will run all the integration tests in `tests/deterministic_simulations`.
This syntax also works with a nested directory (e.g. `--suite deterministic_simulations/purely_forward`).
Finally if you want to run a single integration test, e.g. `deterministic_simulations/lbj/rbc.mod`:
```sh

View File

@ -22,7 +22,7 @@
\begin{document}
% ----------------------------------------------------------------
\title{Sensitivity Analysis Toolbox for DYNARE\thanks{Copyright \copyright~2012 Dynare
\title{Sensitivity Analysis Toolbox for Dynare\thanks{Copyright \copyright~2012-2024 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 \\
TP361, IPSC, \\21027 Ispra
TP581\\21027 Ispra
(VA) Italy\\
\texttt{marco.ratto@jrc.ec.europa.eu}
\texttt{Marco.Ratto@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 v4 environment.
the Dynare 6 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,20 +81,18 @@ 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"dynare_sensitivity(option1=<opt1_val>,option2=<opt2_val>,...)"
\verb"sensitivity(option1=<opt1_val>,option2=<opt2_val>,...)"
\vspace{0.5cm} \noindent with a list of options described in the
next section.
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
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
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
@ -208,16 +206,17 @@ 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. requires an estimation step beforehand!
The use of cases 2. and 3. require an estimation step beforehand!
To facilitate the sensitivity analysis after estimation, the
\verb"dynare_sensitivity" command also allows to indicate some
options of \verb"dynare_estimation". These are:
\verb"sensitivity" command also allows to indicate some
options of \verb"estimation". These are:
\begin{itemize}
\item \verb"datafile"
\item \verb"diffuse_filter"
\item \verb"mode_file"
\item \verb"first_obs"
\item \verb"lik_init"
@ -278,10 +277,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"dynare_sensitivity(identification=1, morris=2);"
\noindent\verb"sensitivity(identification=1, morris=2);"
\vspace{1cm}
\noindent trigger the identification analysis using \cite{Iskrev2010,Iskrev2011}, jointly with the mapping of the acceptable region.
@ -293,75 +292,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}
@ -369,33 +368,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}
@ -405,19 +404,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,
@ -449,24 +448,24 @@ without the need of any user's intervention.
\subsection{Screening analysis}
The results of the screening analysis with Morris sampling design
are stored in the subfolder \verb"\GSA\SCREEN". The data file
\verb"<DYNARE_file>_prior" stores all the information of the
\verb"<Dynare_file>_prior" stores all the information of the
analysis (Morris sample, reduced form coefficients, etc.).
Screening analysis merely concerns reduced form coefficients.
Similar synthetic bar charts as for the reduced form analysis with
MC samples are saved:
\begin{description}
\item[]\verb"<DYNARE_file>_redform_<endo name>_vs_lags_*.fig":
\item[]\verb"<Dynare_file>_redform_<endo name>_vs_lags_*.fig":
shows bar charts of the elementary effect tests for the \emph{ten
most important} parameters driving the reduced form coefficients
of the selected endogenous variables (\verb"namendo") versus
lagged endogenous variables (\verb"namlagendo");
\item[]\verb"<DYNARE_file>_redform_<endo name>_vs_shocks_*.fig":
\item[]\verb"<Dynare_file>_redform_<endo name>_vs_shocks_*.fig":
shows bar charts of the elementary effect tests for the \emph{ten
most important} parameters driving the reduced form coefficients
of the selected endogenous variables (\verb"namendo") versus
exogenous variables (\verb"namexo");
\item[]\verb"<DYNARE_file>_redform_screen.fig": shows bar chart of
\item[]\verb"<Dynare_file>_redform_screen.fig": shows bar chart of
all elementary effect tests for each parameter: this allows to
identify parameters that have a minor effect for \emph{any} of the
reduced form coefficients.

View File

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

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Copyright © 2018-2023 Dynare Team
# Copyright © 2018-2024 Dynare Team
#
# This file is part of Dynare.
#
@ -34,7 +34,7 @@ html_static_path = ['_static']
master_doc = 'index'
project = u'Dynare'
copyright = u'19962023 Dynare Team'
copyright = u'19962024 Dynare Team'
author = u'Dynare Team'
add_function_parentheses = False
@ -71,12 +71,11 @@ latex_elements = {
warningBorderColor={RGB}{255,50,50},OuterLinkColor={RGB}{34,139,34}, \
InnerLinkColor={RGB}{51,51,255},TitleColor={RGB}{51,51,255}',
'papersize': 'a4paper',
'preamble': r'\DeclareUnicodeCharacter{200B}{}', # Part of the workaround for #1707
}
latex_documents = [
(master_doc, 'dynare-manual.tex', u'Dynare Reference Manual',
u'Dynare team', 'manual'),
u'Dynare Team', 'manual'),
]
man_pages = [

View File

@ -8,17 +8,17 @@
Dynare misc commands
####################
.. matcomm:: send_endogenous_variables_to_workspace
.. matcomm:: send_endogenous_variables_to_workspace ;
Puts the simulation results for the endogenous variables stored in ``oo_.endo_simul``
into vectors with the same name as the respective variables into the base workspace.
.. matcomm:: send_exogenous_variables_to_workspace
.. matcomm:: send_exogenous_variables_to_workspace ;
Puts the simulation results for the exogenous variables stored in ``oo_.exo_simul``
into vectors with the same name as the respective variables into the base workspace.
.. matcomm:: send_irfs_to_workspace
.. matcomm:: send_irfs_to_workspace ;
Puts the IRFs stored in ``oo_.irfs`` into vectors with the same name into the base workspace.
@ -230,27 +230,97 @@ 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.
displayed instead of the name of the parameters. Requires the `json` command
line option to be set.
*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;
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.

View File

@ -11,7 +11,7 @@ Currently the development team of Dynare is composed of:
* Willi Mutschler (University of Tübingen)
* Johannes Pfeifer (University of the Bundeswehr Munich)
* Marco Ratto (European Commission, Joint Research Centre - JRC)
* Normann Rion (CY Cergy Paris Université and CEPREMAP)
* Normann Rion (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-2023, Dynare Team.
Copyright © 1996-2024, 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.

View File

@ -94,26 +94,24 @@ 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, 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
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
For convenience, you can copy and paste the following into your BibTeX file:
.. code-block:: bibtex
@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
@TechReport{Adjemianetal2024,
author = {Adjemian, St\'ephane and Juillard, Michel and
Karam\'e, Fr\'ederic and Mutschler, Willi and
Pfeifer, Johannes and Ratto, Marco and
Rion, Normann and Villemot, S\'ebastien},
title = {Dynare: Reference Manual Version 5},
year = {2022},
title = {Dynare: Reference Manual, Version 6},
year = {2024},
institution = {CEPREMAP},
type = {Dynare Working Papers},
number = {72},
number = {80},
}
If you want to give a URL, use the address of the Dynare website:

View File

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

View File

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

View File

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

View File

@ -60,7 +60,7 @@ class DynareLexer(RegexLexer):
"addSeries","addParagraph","addVspace","write","compile")
operators = (
"STEADY_STATE","EXPECTATION","var_expectation","pac_expectation")
"STEADY_STATE","EXPECTATION","var_expectation","pac_expectation","pac_target_nonstationary")
macro_dirs = (
"@#includepath", "@#include", "@#define", "@#if",
@ -83,7 +83,8 @@ 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'), prefix=r'\b', suffix=r'\s*\b'),Keyword.Reserved),
'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),
# FIXME: Commands following multiline comments are not highlighted properly.
(words(commands + report_commands,

101
examples/pacmodel.mod Normal file
View File

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

View File

@ -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 2023 are:
Upstream-Contact: Dynare Team, whose members in 2024 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 2023 are:
Source: https://www.dynare.org
Files: *
Copyright: 1996-2023 Dynare Team
Copyright: 1996-2024 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/csolve.m matlab/optimization/csminit1.m matlab/optimization/numgrad2.m
Files: matlab/optimization/bfgsi1.m matlab/optimization/csolve.m matlab/optimization/csminit1.m matlab/optimization/numgrad2.m
matlab/optimization/numgrad3.m matlab/optimization/numgrad3_.m matlab/optimization/numgrad5.m
matlab/optimization/numgrad5_.m matlab/optimization/csminwel1.m matlab/+bvar/density.m
matlab/+bvar/toolbox.m matlab/partial_information/PI_gensys.m matlab/partial_information/qzswitch.m
@ -123,6 +123,11 @@ 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
@ -172,7 +177,7 @@ Comment: Written by Jessica Cariboni and Francesca Campolongo
Files: matlab/+gsa/cumplot.m
matlab/+gsa/monte_carlo_filtering.m
matlab/+gsa/skewness.m
matlab/+gsa/log_trans_.m
matlab/+gsa/log_transform.m
matlab/+gsa/map_calibration.m
matlab/+gsa/map_identification.m
matlab/+gsa/monte_carlo_filtering_analysis.m
@ -247,7 +252,7 @@ License: BSD-2-clause
Files: examples/fs2000_data.m
Copyright: 2000-2022 Frank Schorfheide
Copyright: 2023 Dynare Team
2023 Dynare Team
License: CC-BY-SA-4.0
Files: doc/*.rst doc/*.tex doc/*.svg doc/*.pdf doc/*.bib
@ -292,28 +297,6 @@ 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+
@ -420,32 +403,6 @@ License: BSD-2-clause
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
License: BSD-3-clause
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
.
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
.
* Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
License: GFDL-NIV-1.3+
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or

View File

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

View File

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

View File

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

View File

@ -108,8 +108,9 @@ for jexo = unique_shock_entries' % loop over cell with shock names
% 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);
lgd.Position = [0.37 0.01 lgd.Position(3) lgd.Position(4)];
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');

View File

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

View File

@ -1,143 +1,169 @@
function [oo_, error_flag] = forecast(options_,M_,oo_,forecast) %,hist_period)
%function oo_ = forecast(options_,M_,oo_,forecast)
% forecast
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;
SHOCKS0 = opts.SHOCKS0;
if ~isempty(SHOCKS0)
if iscell(SHOCKS0)
for j=1:length(SHOCKS0)
sname = SHOCKS0{j}{1};
inds(j)=strmatch(sname,M_.exo_names);
SHOCKS1(j,:)=SHOCKS0{j}{2};
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(SHOCKS0)
SHOCKS1=SHOCKS0;
inds = 1:M_.exo_nbr;
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_exo_names = M_.exo_names(ishock);
effective_Sigma_e = M_.Sigma_e(ishock,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_ant = qmc_sequence(forecast*effective_exo_nbr, int64(1), 1, opts.replic)';
SHOCKS_add = qmc_sequence(forecast_horizon*effective_exo_nbr, int64(1), 1, opts.replic);
else
SHOCKS_ant = randn(forecast*effective_exo_nbr,opts.replic)';
SHOCKS_add = randn(forecast_horizon*effective_exo_nbr,opts.replic);
end
zlin0=zeros(forecast,M_.endo_nbr,opts.replic);
zpiece0=zeros(forecast,M_.endo_nbr,opts.replic);
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
if ~isempty(SHOCKS0)
for j=1:length(SHOCKS0)
SHOCKS(:,inds(j))=SHOCKS1(j,:);
end
end
error_flagx=1;
% while error_flagx,
% SHOCKS=transpose(sqrt(diag(diag(effective_Sigma_e)))*(reshape(SHOCKS_ant(iter,:),forecast,effective_exo_nbr))');
SHOCKS=transpose(U*sqrt(S)*(reshape(SHOCKS_ant(iter,:),forecast,effective_exo_nbr))');
% SHOCKS=transpose(U*sqrt(S)*randn(forecast,M_.exo_nbr)'); %realized shocks
options_.occbin.simul.endo_init = M_.endo_histval(:,1)-oo_.steady_state;
options_.occbin.simul.init_regime = opts.frcst_regimes;
options_.occbin.simul.init_binding_indicator = [];
options_.occbin.simul.exo_pos=ishock;
options_.occbin.simul.SHOCKS = SHOCKS;
options_.occbin.simul.SHOCKS = shocks_base+transpose(U*sqrt(S)*SHOCKS_add(:,:,iter));
options_.occbin.simul.waitbar=0;
[~, out] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
zlin0(:,:,iter)=out.linear;
zpiece0(:,:,iter)=out.piecewise;
ys=out.ys;
frcst_regime_history(iter,:)=out.regime_history;
[~, out] = occbin.solver(M_,options_,dr,endo_steady_state,exo_steady_state,exo_det_steady_state);
error_flag(iter)=out.error_flag;
error_flagx = error_flag(iter);
% end
simul_SHOCKS(:,:,iter) = SHOCKS;
if error_flag(iter) && debug_flag
% display('no solution')
% keyboard;
save no_solution SHOCKS zlin0 zpiece0 iter frcst_regime_history
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);
save temp zlin0 zpiece0 simul_SHOCKS error_flag
if options_.debug
save('Occbin_forecast_debug','simul_SHOCKS','z','iter','frcst_regime_history','error_flag')
end
inx=find(error_flag==0);
zlin0=zlin0(:,:,inx);
zpiece0=zpiece0(:,:,inx);
zlin = mean(zlin0,3);
zpiece = mean(zpiece0,3);
zpiecemin = min(zpiece0,[],3);
zpiecemax = max(zpiece0,[],3);
zlinmin = min(zlin0,[],3);
zlinmax = max(zlin0,[],3);
for i=1:M_.endo_nbr
for j=1:forecast
[post_mean(j,1), post_median(j,1), post_var(j,1), hpd_interval(j,:), post_deciles(j,:)] = posterior_moments(squeeze(zlin0(j,i,:)),options_.forecasts.conf_sig);
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
oo_.occbin.linear_forecast.Mean.(M_.endo_names{i})=post_mean;
oo_.occbin.linear_forecast.Median.(M_.endo_names{i})=post_median;
oo_.occbin.linear_forecast.Var.(M_.endo_names{i})=post_var;
oo_.occbin.linear_forecast.HPDinf.(M_.endo_names{i})=hpd_interval(:,1);
oo_.occbin.linear_forecast.HPDsup.(M_.endo_names{i})=hpd_interval(:,2);
oo_.occbin.linear_forecast.Deciles.(M_.endo_names{i})=post_deciles;
oo_.occbin.linear_forecast.Min.(M_.endo_names{i})=zlinmin(:,i);
oo_.occbin.linear_forecast.Max.(M_.endo_names{i})=zlinmax(:,i);
for j=1:forecast
[post_mean(j,1), post_median(j,1), post_var(j,1), hpd_interval(j,:), post_deciles(j,:)] = posterior_moments(squeeze(zpiece0(j,i,:)),options_.forecasts.conf_sig);
end
oo_.occbin.forecast.Mean.(M_.endo_names{i})=post_mean;
oo_.occbin.forecast.Median.(M_.endo_names{i})=post_median;
oo_.occbin.forecast.Var.(M_.endo_names{i})=post_var;
oo_.occbin.forecast.HPDinf.(M_.endo_names{i})=hpd_interval(:,1);
oo_.occbin.forecast.HPDsup.(M_.endo_names{i})=hpd_interval(:,2);
oo_.occbin.forecast.Deciles.(M_.endo_names{i})=post_deciles;
oo_.occbin.forecast.Min.(M_.endo_names{i})=zpiecemin(:,i);
oo_.occbin.forecast.Max.(M_.endo_names{i})=zpiecemax(:,i);
% eval([M_.endo_names{i},'_ss=zdatass(i);']);
end
else
SHOCKS = zeros(forecast,M_.exo_nbr);
if ~isempty(SHOCKS0)
for j=1:length(SHOCKS0)
SHOCKS(:,inds(j))=SHOCKS1(j,:);
end
end
options_.occbin.simul.endo_init = M_.endo_histval(:,1)-oo_.steady_state;
options_.occbin.simul.init_regime = opts.frcst_regimes;
options_.occbin.simul.init_violvecbool = [];
options_.occbin.simul.irfshock = M_.exo_names;
options_.occbin.simul.SHOCKS = SHOCKS;
[~, out] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
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
zlin=out.linear;
zpiece=out.piecewise;
frcst_regime_history=out.regime_history;
error_flag=out.error_flag;
for i=1:M_.endo_nbr
oo_.occbin.linear_forecast.Mean.(M_.endo_names{i})= zlin(:,i);
oo_.occbin.forecast.Mean.(M_.endo_names{i})= zpiece(:,i);
oo_.occbin.forecast.HPDinf.(M_.endo_names{i})= nan;
oo_.occbin.forecast.HPDsup.(M_.endo_names{i})= nan;
forecast.linear.Mean.(M_.endo_names{i})= out.linear(:,i);
forecast.piecewise.Mean.(M_.endo_names{i})= out.piecewise(:,i);
end
end
oo_.occbin.forecast.regimes=frcst_regime_history;
forecast.regimes=frcst_regime_history;

View File

@ -1,140 +1,124 @@
function [oo_] = irf(M_,oo_,options_)
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;
shocksigns = options_.occbin.irf.shocksigns; %'pos','neg'
shocksize = options_.occbin.irf.shocksize;
t0 = options_.occbin.irf.t0;
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 inital conditions + other shocks
if t0 == 0
shocks0= zeros(options_.occbin.simul.periods+1,M_.exo_nbr);
%% 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
% girf conditional to smoothed states in t0 and shocks in t0+1
shocks0= [oo_.occbin.smoother.etahat(:,t0+1)'; zeros(options_.occbin.simul.periods,M_.exo_nbr)];
options_.occbin.simul.SHOCKS=shocks0;
options_.occbin.simul.endo_init = oo_.occbin.smoother.alphahat(oo_.dr.inv_order_var,t0);
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=shocks0;
[~, out0] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
zlin0 = out0.linear;
zpiece0 = out0.piecewise;
options_.occbin.simul.SHOCKS=shocks_base;
% Select shocks of interest
jexo_all =zeros(size(shocknames,1),1);
[~, 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)
jexo_all(i) = strmatch(shocknames{i},M_.exo_names,'exact');
exo_index(i) = strmatch(shocknames{i},M_.exo_names,'exact');
end
oo_.occbin.linear_irfs = struct();
oo_.occbin.irfs = struct();
% 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)
% if isfield(oo_.posterior_mode.shocks_std,M_.exo_names{jexo})
shocksize = sqrt(diag(M_.Sigma_e(jexo_all,jexo_all))); %oo_.posterior_mode.shocks_std.(M_.exo_names{jexo});
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 counter = 1:length(jexo_all)
jexo = jexo_all(counter);
if ~options_.noprint
fprintf('Producing GIRFs for shock %s. Simulation %d out of %d. \n',M_.exo_names{jexo},counter,size(jexo_all,1));
end
if ismember('pos',shocksigns)
% (+) shock
shocks1=shocks0;
shocks1(1,jexo)=shocks0(1,jexo)+shocksize(counter);
if t0 == 0
options_.occbin.simul.SHOCKS=shocks1;
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 = [];
[~, out_pos] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
else
options_.occbin.simul.SHOCKS=shocks1;
options_.occbin.simul.endo_init = oo_.occbin.smoother.alphahat(oo_.dr.inv_order_var,t0);
[~, out_pos] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
options_.occbin.simul.endo_init = oo_.occbin.smoother.alphahat(oo_.dr.inv_order_var,t_0);
end
if out_pos.error_flag
warning('Occbin error.')
return
[~, 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
zlin_pos = out_pos.linear;
zpiece_pos = out_pos.piecewise;
% Substract inital conditions + other shocks
zlin_pos_diff = zlin_pos-zlin0;
zpiece_pos_diff = zpiece_pos-zpiece0;
end
if ismember('neg',shocksigns)
% (-) shock
shocks_1=shocks0;
shocks_1(1,jexo)=shocks0(1,jexo)-shocksize(counter);
if t0 == 0
options_.occbin.simul.SHOCKS=shocks_1;
options_.occbin.simul.endo_init = [];
[~, out_neg] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
else
options_.occbin.simul.SHOCKS=shocks_1;
options_.occbin.simul.endo_init = oo_.occbin.smoother.alphahat(oo_.dr.inv_order_var,t0);
[~, out_neg] = occbin.solver(M_,options_,oo_.dr,oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
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
if out_neg.error_flag
warning('Occbin error.')
return
end
zlin_neg = out_neg.linear;
zpiece_neg = out_neg.piecewise;
zlin_neg_diff = zlin_neg-zlin0;
zpiece_neg_diff = zpiece_neg-zpiece0;
end
% Save
if ~isfield(oo_.occbin,'linear_irfs')
oo_.occbin.linear_irfs = struct();
end
if ~isfield(oo_.occbin,'irfs')
oo_.occbin.irfs = struct();
end
for jendo=1:M_.endo_nbr
% oo_.occbin.irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '1']) = zpiece_pos (:,jendo);
% oo_.occbin.irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_1']) = zpiece_neg (:,jendo);
% oo_.occbin.linear_irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '1']) = zlin_pos (:,jendo);
% oo_.occbin.linear_irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_1']) = zlin_neg(:,jendo);
if ismember('pos',shocksigns)
oo_.occbin.irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_pos']) = zpiece_pos_diff (:,jendo);
oo_.occbin.linear_irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_pos']) = zlin_pos_diff (:,jendo);
end
if ismember('neg',shocksigns)
oo_.occbin.irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_neg']) = zpiece_neg_diff (:,jendo);
oo_.occbin.linear_irfs.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_neg']) = zlin_neg_diff (:,jendo);
end
% %
% oo_.occbin.irfs0.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '1']) = zpiece0(:,jendo);
% oo_.occbin.linear_irfs0.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '1']) = zlin0(:,jendo);
% oo_.occbin.irfs0.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_1']) = zpiece0(:,jendo);
% oo_.occbin.linear_irfs0.([M_.endo_names{jendo} '_' M_.exo_names{jexo} '_1']) = zlin0(:,jendo);
end
end
end
end

View File

@ -1,34 +1,74 @@
function plot_irfs(M_,oo_,options_,irf3,irf4)
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.
shocknames = options_.occbin.plot_irf.exo_names;
simulname = options_.occbin.plot_irf.simulname;
if isempty(simulname)
simulname_ = simulname;
else
simulname_ = [ simulname '_' ];
% 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
vars_irf = options_.occbin.plot_irf.endo_names;
endo_names_long = options_.occbin.plot_irf.endo_names_long;
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_.occbin.plot_irf.tplot;
if isempty(length_irf)
length_irf = options_.irf;
end
length_irf = options_.irf;
irflocation_lin = oo_.occbin.linear_irfs;
irflocation_piece = oo_.occbin.irfs;
steps_irf = 1;
warning('off','all')
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 i=1:size(shocknames,1)
itemp = strmatch(shocknames{i},M_.exo_names,'exact');
for var_iter=1:size(shock_names,1)
itemp = strmatch(shock_names{var_iter},M_.exo_names,'exact');
if isempty(itemp)
error(['Shock ',shocknames{i},' is not defined!'])
error(['Shock ',shock_names{var_iter},' is not defined!'])
else
iexo=[iexo, itemp];
end
@ -38,104 +78,102 @@ ncols = options_.occbin.plot_irf.ncols;
nrows = options_.occbin.plot_irf.nrows;
npan = ncols*nrows;
plot_grid = options_.occbin.plot_irf.grid;
shocksigns = options_.occbin.plot_irf.shocksigns;
threshold = options_.occbin.plot_irf.threshold;
% Add steady_state
if options_.occbin.plot_irf.add_steadystate
add_stst = options_.occbin.plot_irf.add_steadystate;
else
add_stst = 0;
end
for sss = 1:numel(shocksigns)
shocksign = shocksigns{sss};
for j=1:size(shocknames,1)
%shocknames = M_.exo_names{j};
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 i = 1:length(vars_irf)
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, .
hfig = dyn_figure(options_.nodisplay,'name',['OccbinIRFs ' shocknames{j} ' ' simulname ' ' shocksign],'PaperPositionMode', 'auto','PaperType','A4','PaperOrientation','portrait','renderermode','auto','position',[10 10 950 650]);
% 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;
isub=isub+1;
if isempty(endo_scaling_factor)
exofactor = 1;
else
exofactor = endo_scaling_factor{i};
end
subplot(nrows,ncols,isub)
irf_field = strcat(vars_irf{i,1},'_',shocknames{j},'_',shocksign);
irfvalues = irflocation_lin.(irf_field);
if add_stst
irfvalues = irfvalues + get_mean(vars_irf{i,1});
end
irfvalues(abs(irfvalues) <threshold) = 0;
plot(irfvalues(1:steps_irf:length_irf)*exofactor,'linewidth',2);
hold on
irfvalues = irflocation_piece.(irf_field);
if add_stst
irfvalues = irfvalues + get_mean(vars_irf{i,1});
end
irfvalues(abs(irfvalues) <threshold) = 0;
plot(irfvalues(1:steps_irf:length_irf)*exofactor,'r--','linewidth',2);
hold on
plot(irfvalues(1:steps_irf:length_irf)*0,'k-','linewidth',1.5);
% Optional additional IRFs
if nargin > 10
irfvalues = irf3.(irf_field) ;
irfvalues(abs(irfvalues) <threshold) = 0;
plot(irfvalues(1:steps_irf:length_irf)*exofactor,'k:','linewidth',2);
end
if nargin > 11
irfvalues = irf4.(irf_field) ;
irfvalues(abs(irfvalues) <threshold) = 0;
plot(irfvalues(1:steps_irf:length_irf)*exofactor,'g-.','linewidth',2);
end
if plot_grid
grid on
end
xlim([1 (length_irf/steps_irf)]);
% title
if isempty(endo_names_long)
title(regexprep(vars_irf{i},'_',' '))
else
title(endo_names_long{i})
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 && i==length(vars_irf))
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_',simulname_,shocknames{j},'_',shocksign,'_',int2str(ifig)],options_.nodisplay,options_.graph_format);
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
end
warning('on','all')
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fprintf(fidTeX,'%% End Of TeX file.');
fclose(fidTeX);
end

View File

@ -1,4 +1,26 @@
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;
@ -13,9 +35,15 @@ else
end
GraphDirectoryName = CheckPath('graphs',M_.dname);
fhandle = dyn_figure(options_.nodisplay,'Name',[M_.fname ': OccBin regimes']);
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)
@ -36,12 +64,23 @@ for k=1:nconstr
end
end
end
title(['regime ' int2str(k)])
xlabel('historic period')
ylabel('regime expected start')
xlim([1 nperiods])
title(['Regime ' int2str(k)])
xlabel('Historic period')
ylabel('Regime: expected start')
end
annotation('textbox',[.25,0,.15,.05],'String','Unbinding','Color','blue');
annotation('textbox',[.65,0,.15,.05],'String','Binding','Color','red');
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

View File

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

View File

@ -13,7 +13,7 @@ function M_ = parameters(pacname, M_, oo_, verbose)
% SPECIAL REQUIREMENTS
% none
% Copyright © 2018-2023 Dynare Team
% Copyright © 2018-2024 Dynare Team
%
% This file is part of Dynare.
%
@ -78,6 +78,11 @@ 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)']);
@ -90,7 +95,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/VECM model.')
error('Cannot find the trend variable in the Companion VAR model.')
else
for j=1:length(ad)
auxinfo = M_.aux_vars(get_aux_variable_id(varmodel.list_of_variables_in_companion_var{ad(j)}));
@ -105,7 +110,7 @@ if numberofcomponents
end
end
if isempty(id{i})
error('Cannot find the trend variable in the Companion VAR/VECM model.')
error('Cannot find the trend variable in the Companion VAR model.')
end
end
end
@ -115,7 +120,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 Companion VAR/VECM model.')
error('Cannot find the trend variable in the auxiliary VAR / Trend component model.')
else
for i=1:length(ad)
auxinfo = M_.aux_vars(get_aux_variable_id(varmodel.list_of_variables_in_companion_var{ad(i)}));
@ -130,7 +135,7 @@ else
end
end
if isempty(id{1})
error('Cannot find the trend variable in the Companion VAR/VECM model.')
error('Cannot find the trend variable in the auxiliary VAR / Trend component model.')
end
end
end

View File

@ -0,0 +1,42 @@
function collapse_figures_in_tabgroup
% Copyright © 2023 Eduard Benet Cerda
% Copyright © 2024 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
% Create a new figure with results
fig = uifigure(Name = 'Dynare Results');
% Add a grid layout to make sure it spans the entire width
g = uigridlayout(fig, [1,1], Padding = 0);
% Add a tabgroup
tg = uitabgroup(g);
% Find all figures with Dynare Tag
f = findobj('-regexp','tag','dynare-figure');
% Loop over all figures and reparent them to a tab. Avoid legends, they are
% automatically tied.
for j = 1 : numel(f)
t = uitab(tg);
types = arrayfun(@class, f(j).Children, 'UniformOutput', false);
idx = ismember(types, 'matlab.graphics.illustration.Legend'); % no need to reparent legends
set(f(j).Children(~idx),'Parent',t)
t.Title = f(j).Name;
delete(f(j))
end

View File

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

View File

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

View File

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

View File

@ -1,299 +0,0 @@
function dsmh(TargetFun, xparam1, mh_bounds, dataset_, dataset_info, options_, M_, estim_params_, bayestopt_, oo_)
% Dynamic Striated Metropolis-Hastings algorithm.
%
% INPUTS
% o TargetFun [char] string specifying the name of the objective
% function (posterior kernel).
% o xparam1 [double] (p*1) vector of parameters to be estimated (initial values).
% o mh_bounds [double] (p*2) matrix defining lower and upper bounds for the parameters.
% o dataset_ data structure
% o dataset_info dataset info structure
% o options_ options structure
% o M_ model structure
% o estim_params_ estimated parameters structure
% o bayestopt_ estimation options structure
% o oo_ outputs structure
%
% SPECIAL REQUIREMENTS
% None.
%
% PARALLEL CONTEXT
% The most computationally intensive part of this function may be executed
% in parallel. The code suitable to be executed in
% parallel on multi core or cluster machine (in general a 'for' cycle)
% has been removed from this function and been placed in the posterior_sampler_core.m funtion.
%
% The DYNARE parallel packages comprise a i) set of pairs of Matlab functions that can be executed in
% parallel and called name_function.m and name_function_core.m and ii) a second set of functions used
% to manage the parallel computations.
%
% This function was the first function to be parallelized. Later, other
% functions have been parallelized using the same methodology.
% Then the comments write here can be used for all the other pairs of
% parallel functions and also for management functions.
% 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_.posterior_sampler_options.dsmh;
lambda = exp(bsxfun(@minus,options_.posterior_sampler_options.dsmh.H,1:1:options_.posterior_sampler_options.dsmh.H)/(options_.posterior_sampler_options.dsmh.H-1)*log(options_.posterior_sampler_options.dsmh.lambda1));
c = 0.055 ;
MM = int64(options_.posterior_sampler_options.dsmh.N*options_.posterior_sampler_options.dsmh.G/10) ;
% Step 0: Initialization of the sampler
[param, tlogpost_iminus1, loglik, bayestopt_] = ...
smc_samplers_initialization(TargetFun, 'dsmh', opts.particles, mh_bounds, dataset_, dataset_info, options_, M_, estim_params_, bayestopt_, oo_);
ESS = zeros(options_.posterior_sampler_options.dsmh.H,1) ;
zhat = 1 ;
% The DSMH starts here
for i=2:options_.posterior_sampler_options.dsmh.H
disp('');
disp('Tempered iteration');
disp(i) ;
% Step 1: sort the densities and compute IS weigths
[tlogpost_iminus1,loglik,param] = sort_matrices(tlogpost_iminus1,loglik,param) ;
[tlogpost_i,weights,zhat,ESS,Omegachol] = compute_IS_weights_and_moments(param,tlogpost_iminus1,loglik,lambda,i,zhat,ESS) ;
% Step 2: tune c_i
c = tune_c(TargetFun,param,tlogpost_i,lambda,i,c,Omegachol,weights,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
% Step 3: Metropolis step
[param,tlogpost_iminus1,loglik] = mutation_DSMH(TargetFun,param,tlogpost_i,tlogpost_iminus1,loglik,lambda,i,c,MM,Omegachol,weights,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
end
weights = exp(loglik*(lambda(end)-lambda(end-1)));
weights = weights/sum(weights);
indx_resmpl = smc_resampling(weights,rand(1,1),options_.posterior_sampler_options.dsmh.particles);
distrib_param = param(:,indx_resmpl);
mean_xparam = mean(distrib_param,2);
npar = length(xparam1);
lb95_xparam = zeros(npar,1) ;
ub95_xparam = zeros(npar,1) ;
for i=1:npar
temp = sortrows(distrib_param(i,:)') ;
lb95_xparam(i) = temp(0.025*options_.posterior_sampler_options.dsmh.particles) ;
ub95_xparam(i) = temp(0.975*options_.posterior_sampler_options.dsmh.particles) ;
end
TeX = options_.TeX;
str = sprintf(' Param. \t Lower Bound (95%%) \t Mean \t Upper Bound (95%%)');
for l=1:npar
name = get_the_name(l,TeX,M_,estim_params_,options_.varobs);
str = sprintf('%s\n %s \t\t %5.4f \t\t %7.5f \t\t %5.4f', str, name, lb95_xparam(l), mean_xparam(l), ub95_xparam(l));
end
disp(str)
disp('')
%% Plot parameters densities
if TeX
fidTeX = fopen([M_.fname '_param_density.tex'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by DSMH.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
end
number_of_grid_points = 2^9; % 2^9 = 512 !... Must be a power of two.
bandwidth = 0; % Rule of thumb optimal bandwidth parameter.
kernel_function = 'gaussian'; % Gaussian kernel for Fast Fourier Transform approximation.
plt = 1 ;
%for plt = 1:nbplt,
if TeX
NAMES = [];
TeXNAMES = [];
end
hh_fig = dyn_figure(options_.nodisplay,'Name','Parameters Densities');
for k=1:npar %min(nstar,npar-(plt-1)*nstar)
subplot(ceil(sqrt(npar)),floor(sqrt(npar)),k)
%kk = (plt-1)*nstar+k;
[name,texname] = get_the_name(k,TeX,M_,estim_params_,options_.varobs);
optimal_bandwidth = mh_optimal_bandwidth(distrib_param(k,:)',options_.posterior_sampler_options.dsmh.particles,bandwidth,kernel_function);
[density(:,1),density(:,2)] = kernel_density_estimate(distrib_param(k,:)',number_of_grid_points,...
options_.posterior_sampler_options.dsmh.particles,optimal_bandwidth,kernel_function);
plot(density(:,1),density(:,2));
hold on
if TeX
title(texname,'interpreter','latex')
else
title(name,'interpreter','none')
end
hold off
axis tight
drawnow
end
dyn_saveas(hh_fig,[ M_.fname '_param_density' int2str(plt) ],options_.nodisplay,options_.graph_format);
if 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]{%_param_density%s}\n',min(k/floor(sqrt(npar)),1),M_.fname,int2str(plt));
fprintf(fidTeX,'\\caption{Parameter densities based on the Dynamic Striated Metropolis-Hastings algorithm.}');
fprintf(fidTeX,'\\label{Fig:ParametersDensities:%s}\n',int2str(plt));
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
end
%end
function [tlogpost_iminus1,loglik,param] = sort_matrices(tlogpost_iminus1,loglik,param)
[~,indx_ord] = sortrows(tlogpost_iminus1);
tlogpost_iminus1 = tlogpost_iminus1(indx_ord);
param = param(:,indx_ord);
loglik = loglik(indx_ord);
function [tlogpost_i,weights,zhat,ESS,Omegachol] = compute_IS_weights_and_moments(param,tlogpost_iminus1,loglik,lambda,i,zhat,ESS)
if i==1
tlogpost_i = tlogpost_iminus1 + loglik*lambda(i);
else
tlogpost_i = tlogpost_iminus1 + loglik*(lambda(i)-lambda(i-1));
end
weights = exp(tlogpost_i-tlogpost_iminus1);
zhat = (mean(weights))*zhat ;
weights = weights/sum(weights);
ESS(i) = 1/sum(weights.^2);
% estimates of mean and variance
mu = param*weights;
z = bsxfun(@minus,param,mu);
Omega = z*diag(weights)*z';
Omegachol = chol(Omega)';
function c = tune_c(TargetFun,param,tlogpost_i,lambda,i,c,Omegachol,weights,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_)
disp('tuning c_i...');
disp('Initial value =');
disp(c) ;
npar = size(param,1);
lower_prob = (.5*(options_.posterior_sampler_options.dsmh.alpha0+options_.posterior_sampler_options.dsmh.alpha1))^5;
upper_prob = (.5*(options_.posterior_sampler_options.dsmh.alpha0+options_.posterior_sampler_options.dsmh.alpha1))^(1/5);
stop=0 ;
while stop==0
acpt = 0.0;
indx_resmpl = smc_resampling(weights,rand(1,1),options_.posterior_sampler_options.dsmh.G);
param0 = param(:,indx_resmpl);
tlogpost0 = tlogpost_i(indx_resmpl);
for j=1:options_.posterior_sampler_options.dsmh.G
for l=1:options_.posterior_sampler_options.dsmh.K
validate = 0;
while validate == 0
candidate = param0(:,j) + sqrt(c)*Omegachol*randn(npar,1);
if all(candidate >= mh_bounds.lb) && all(candidate <= mh_bounds.ub)
[tlogpostx,loglikx] = tempered_likelihood(TargetFun,candidate,lambda(i),dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
if isfinite(loglikx) % if returned log-density is not Inf or Nan (penalized value)
validate = 1;
if rand(1,1)<exp(tlogpostx-tlogpost0(j)) % accept
acpt = acpt + 1/(options_.posterior_sampler_options.dsmh.G*options_.posterior_sampler_options.dsmh.K);
param0(:,j)= candidate;
tlogpost0(j) = tlogpostx;
end
end
end
end
end
end
disp('Acceptation rate =') ;
disp(acpt) ;
if options_.posterior_sampler_options.dsmh.alpha0<=acpt && acpt<=options_.posterior_sampler_options.dsmh.alpha1
disp('done!');
stop=1;
else
if acpt<lower_prob
c = c/5;
elseif lower_prob<=acpt && acpt<=upper_prob
c = c*log(.5*(options_.posterior_sampler_options.dsmh.alpha0+options_.posterior_sampler_options.dsmh.alpha1))/log(acpt);
else
c = 5*c;
end
disp('Trying with c= ') ;
disp(c)
end
end
function [out_param,out_tlogpost_iminus1,out_loglik] = mutation_DSMH(TargetFun,param,tlogpost_i,tlogpost_iminus1,loglik,lambda,i,c,MM,Omegachol,weights,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_)
indx_levels = (1:1:MM-1)*options_.posterior_sampler_options.dsmh.N*options_.posterior_sampler_options.dsmh.G/MM;
npar = size(param,1) ;
p = 1/(10*options_.posterior_sampler_options.dsmh.tau);
disp('Metropolis step...');
% build the dynamic grid of levels
levels = [0.0;tlogpost_iminus1(indx_levels)];
% initialize the outputs
out_param = param;
out_tlogpost_iminus1 = tlogpost_i;
out_loglik = loglik;
% resample and initialize the starting groups
indx_resmpl = smc_resampling(weights,rand(1,1),options_.posterior_sampler_options.dsmh.G);
param0 = param(:,indx_resmpl);
tlogpost_iminus10 = tlogpost_iminus1(indx_resmpl);
tlogpost_i0 = tlogpost_i(indx_resmpl);
loglik0 = loglik(indx_resmpl);
% Start the Metropolis
for l=1:options_.posterior_sampler_options.dsmh.N*options_.posterior_sampler_options.dsmh.tau
for j=1:options_.posterior_sampler_options.dsmh.G
u1 = rand(1,1);
u2 = rand(1,1);
if u1<p
k=1 ;
for m=1:MM-1
if levels(m)<=tlogpost_iminus10(j) && tlogpost_iminus10(j)<levels(m+1)
k = m+1;
break
end
end
indx = floor( (k-1)*options_.posterior_sampler_options.dsmh.N*options_.posterior_sampler_options.dsmh.G/MM+1 + u2*(options_.posterior_sampler_options.dsmh.N*options_.posterior_sampler_options.dsmh.G/MM-1) );
if i==1
alp = (loglik(indx)-loglik0(j))*lambda(i);
else
alp = (loglik(indx)-loglik0(j))*(lambda(i)-lambda(i-1));
end
if u2<exp(alp)
param0(:,j) = param(:,indx);
tlogpost_i0(j) = tlogpost_i(indx);
loglik0(j) = loglik(indx);
tlogpost_iminus10(j) = tlogpost_iminus1(indx);
end
else
validate= 0;
while validate==0
candidate = param0(:,j) + sqrt(c)*Omegachol*randn(npar,1);
if all(candidate(:) >= mh_bounds.lb) && all(candidate(:) <= mh_bounds.ub)
[tlogpostx,loglikx] = tempered_likelihood(TargetFun,candidate,lambda(i),dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
if isfinite(loglikx) % if returned log-density is not Inf or Nan (penalized value)
validate = 1;
if u2<exp(tlogpostx-tlogpost_i0(j)) % accept
param0(:,j) = candidate;
tlogpost_i0(j) = tlogpostx;
loglik0(j) = loglikx;
if i==1
tlogpost_iminus10(j) = tlogpostx-loglikx*lambda(i);
else
tlogpost_iminus10(j) = tlogpostx-loglikx*(lambda(i)-lambda(i-1));
end
end
end
end
end
end
end
if mod(l,options_.posterior_sampler_options.dsmh.tau)==0
rang = (l/options_.posterior_sampler_options.dsmh.tau-1)*options_.posterior_sampler_options.dsmh.G+1:l*options_.posterior_sampler_options.dsmh.G/options_.posterior_sampler_options.dsmh.tau;
out_param(:,rang) = param0;
out_tlogpost_iminus1(rang) = tlogpost_i0;
out_loglik(rang) = loglik0;
end
end

View File

@ -76,7 +76,7 @@ for j= 1:nvar
fprintf(fidTeX,' \n');
end
n_fig =n_fig+1;
eval(['hh_fig=dyn_figure(options_.nodisplay,''Name'',''Forecasts (' int2str(n_fig) ')'');']);
hh_fig=dyn_figure(options_.nodisplay,'Name',['Forecasts (' int2str(n_fig) ')']);
m = 1;
end
subplot(nr, nc, m);
@ -138,7 +138,7 @@ if isfield(oo_.forecast,'HPDinf_ME')
fprintf(fidTeX,' \n');
end
n_fig =n_fig+1;
eval(['hh_fig=dyn_figure(options_.nodisplay,''Name'',''Forecasts (' int2str(n_fig) ')'');']);
hh_fig=dyn_figure(options_.nodisplay,'Name',['Forecasts including ME (' int2str(n_fig) ')']);
m = 1;
end
subplot(nr,nc,m);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -242,8 +242,14 @@ if newdatainterface
end
else
% ... or check that nobs is smaller than the number of observations in dataset_.
if nobs>dataset_.nobs
error('makedataset: nobs (%s) cannot be greater than the last date in the dataset (%s)!', num2str(nobs), num2str(dataset_.nobs))
if FIRSTOBS>dataset_.dates(1)
if FIRSTOBS+nobs-1>dataset_.dates(end)
error('makedataset: Given first_obs=%u and %u total observations in the dataset, the current nobs of %s must not be greater than %s!', options_.first_obs, dataset_.nobs, num2str(nobs), num2str(dataset_.nobs-find(dataset_.dates==FIRSTOBS)+1))
end
else
if nobs>dataset_.nobs
error('makedataset: nobs (%s) cannot be greater than the last date in the dataset (%s)!', num2str(nobs), num2str(dataset_.nobs))
end
end
end

View File

@ -0,0 +1,25 @@
function display_parameter_values
% Copyright © 2024 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
global M_
my_title='Current parameter values:';
labels = M_.param_names;
headers = {'Parameter'; 'Value'};
lh = cellofchararraymaxlength(labels)+2;
options_.noprint=false;
dyntable(options_, my_title, headers, labels, M_.params, lh, 10, 6);

View File

@ -1,6 +1,6 @@
project('dynare',
'cpp', 'fortran', 'c',
version : '6-unstable',
version : '6.1',
# NB: update C++ standard in .clang-format whenever the following is modified
default_options : [ 'cpp_std=gnu++20', 'fortran_std=f2018',
'c_std=gnu17', 'warning_level=2' ],
@ -21,9 +21,14 @@ c_compiler = meson.get_compiler('c')
subdir('preprocessor/src')
# Compatibility symlink
# NB: the following my be improved if this wishlist item is done:
# NB: the following two symlinks my be improved if this wishlist item is done:
# https://github.com/mesonbuild/meson/issues/11519
install_symlink('dynare-preprocessor', install_dir : 'lib/dynare/preprocessor/',
pointing_to : '../../../bin/dynare-preprocessor'
+ (host_machine.system() == 'windows' ? '.exe' : ''))
# Compatibility symlink
install_symlink('dynare_m' + (host_machine.system() == 'windows' ? '.exe' : ''),
install_dir : 'lib/dynare/matlab/preprocessor64',
pointing_to : '../../../../bin/dynare-preprocessor'
@ -34,17 +39,12 @@ install_symlink('dynare_m' + (host_machine.system() == 'windows' ? '.exe' : ''),
install_subdir('matlab', install_dir : 'lib/dynare',
exclude_files : [ 'utilities/tests/.git' ,
'utilities/tests/.gitignore',
'modules/reporting/.git',
'modules/reporting/.gitignore',
'modules/reporting/.gitlab-ci.yml',
'modules/dseries/.git',
'modules/dseries/.gitignore',
'modules/dseries/src/modules/matlab-fame-io/.git',
'modules/dseries/src/modules/matlab-fame-io/.gitignore',
'modules/dseries/src/modules/matlab-fame-io/doc/.gitignore',
'modules/dseries/src/modules/matlab-fame-io/tests/FameDatabases/.gitignore',
'modules/dseries/.gitmodules',
'modules/dseries/.gitlab-ci.yml' ])
'dseries/.git',
'dseries/.gitignore',
'dseries/src/modules/matlab-fame-io/.git',
'dseries/src/modules/matlab-fame-io/.gitignore',
'dseries/.gitmodules',
'dseries/.gitlab-ci.yml' ])
sed_exe = find_program('sed')
custom_target(output : 'dynare_version.m', input : 'matlab/dynare_version.m.in',
@ -53,6 +53,9 @@ custom_target(output : 'dynare_version.m', input : 'matlab/dynare_version.m.in',
install : true,
install_dir : 'lib/dynare/matlab')
install_subdir('contrib/ms-sbvar/TZcode/MatlabFiles',
install_dir : 'lib/dynare/contrib/ms-sbvar/TZcode')
### MEX files
mex_incdir = include_directories('mex/sources')
@ -157,7 +160,20 @@ if get_option('build_for') == 'matlab'
umfpack_dep = declare_dependency(link_args : '-lmwumfpack', dependencies : blas_dep)
ut_dep = declare_dependency(link_args : '-lut')
slicot_dep = declare_dependency(dependencies : [ fortran_compiler.find_library('slicot64_pic'), blas_dep, lapack_dep ])
# Workaround for Meson bug https://github.com/mesonbuild/meson/issues/12757
# Use the C compiler as a fallback for detecting SLICOT under Linux with
# prefer_static=true (but still try the Fortran compiler to honour the -B
# option in fortran_args, as documented). Needed for building the MATLAB
# Online package.
if get_option('prefer_static') and host_machine.system() == 'linux'
slicot_dep_tmp = fortran_compiler.find_library('slicot64_pic', required : false)
if not slicot_dep_tmp.found()
slicot_dep_tmp = c_compiler.find_library('slicot64_pic')
endif
slicot_dep = declare_dependency(dependencies : [ slicot_dep_tmp, blas_dep, lapack_dep ])
else
slicot_dep = declare_dependency(dependencies : [ fortran_compiler.find_library('slicot64_pic'), blas_dep, lapack_dep ])
endif
else # Octave build
octave_exe = find_program('octave', required : not meson.is_cross_build(), disabler : true)
mkoctfile_exe = find_program('mkoctfile')
@ -291,8 +307,11 @@ if get_option('prefer_static')
# NB: constructing a dependency object with link_args : ['-Wl,-Bstatic', '-lgomp', '-Wl,-Bdynamic'] does not work,
# because it reorders the three arguments and puts -lgomp at the end
openmp_dep_tmp = cpp_compiler.find_library('gomp', static : true)
openmp_dep = declare_dependency(dependencies : [ openmp_dep, openmp_dep_tmp ])
if host_machine.system() != 'linux'
# Under Debian 12, trying to link (static) libgomp.a in a MEX fails.
openmp_dep_tmp = cpp_compiler.find_library('gomp', static : true)
openmp_dep = declare_dependency(dependencies : [ openmp_dep, openmp_dep_tmp ])
endif
endif
# For use when creating intermediate static libraries to be incorporated in MEX files
@ -346,10 +365,6 @@ shared_module('logarithmic_reduction', [ 'mex/sources/logarithmic_reduction/mexF
shared_module('disclyap_fast', [ 'mex/sources/disclyap_fast/disclyap_fast.f08' ] + mex_blas_fortran_iface,
kwargs : mex_kwargs, dependencies : [ blas_dep, lapack_dep ])
# TODO: Same remark as A_times_B_kronecker_C
shared_module('riccati_update', [ 'mex/sources/riccati_update/mexFunction.f08' ] + mex_blas_fortran_iface,
kwargs : mex_kwargs, dependencies : [ blas_dep, lapack_dep ])
qmc_sequence_src = [ 'mex/sources/sobol/qmc_sequence.cc',
'mex/sources/sobol/sobol.f08' ]
# Hack for statically linking libgfortran
@ -1811,7 +1826,6 @@ mod_and_m_tests = [
'solver-test-functions/wood.m',] },
{ 'test' : [ 'cyclereduction.m' ] },
{ 'test' : [ 'logarithmicreduction.m' ] },
{ 'test' : [ 'riccatiupdate.m' ] },
{ 'test' : [ 'kalman/likelihood/test_kalman_mex.m' ] },
{ 'test' : [ 'contribs.m' ],
'extra' : [ 'sandbox.mod',
@ -1892,7 +1906,9 @@ endforeach
git_exe = find_program('git', required : false)
etags_exe = find_program('etags', required : false)
if git_exe.found() and etags_exe.found()
fs = import('fs')
if fs.is_dir('.git') and git_exe.found() and etags_exe.found()
all_files = run_command(git_exe,
[ '--git-dir=@0@/.git'.format(meson.project_source_root()),
'ls-files', '--recurse-submodules',

View File

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

View File

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

View File

@ -1,98 +0,0 @@
! 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/>.
! Implements Ptmp = T*(P-K*Z*P)*transpose(T)+Q where
! P is the (r x r) variance-covariance matrix of the state vector
! T is the (r x r) transition matrix of the state vector
! K is the (r x n) gain matrix
! Z is the (n x r) matrix linking observable variables to state variables
! Q is the (r x r) variance-covariance matrix of innovations in the state equation
! and accounting for different properties:
! P is a (symmetric) positive semi-definite matrix
! T can be triangular
subroutine mexFunction(nlhs, plhs, nrhs, prhs) bind(c, name='mexFunction')
use matlab_mex
use blas
implicit none (type, external)
type(c_ptr), dimension(*), intent(in), target :: prhs
type(c_ptr), dimension(*), intent(out) :: plhs
integer(c_int), intent(in), value :: nlhs, nrhs
real(real64), dimension(:,:), pointer, contiguous :: P, T, K, Z, Q, Pnew
real(real64), dimension(:,:), allocatable :: tmp1, tmp2
integer :: i, n, r
character(kind=c_char, len=2) :: num2str
! 0. Checking the consistency and validity of input arguments
if (nrhs /= 5_c_int) then
call mexErrMsgTxt("Must have 5 input arguments")
end if
if (nlhs > 1_c_int) then
call mexErrMsgTxt("Too many output arguments")
end if
do i=1,5
if (.not. (c_associated(prhs(i)) .and. mxIsDouble(prhs(i)) .and. &
(.not. mxIsComplex(prhs(i))) .and. (.not. mxIsSparse(prhs(i))))) then
write (num2str,"(i2)") i
call mexErrMsgTxt("Argument " // trim(num2str) // " should be a real dense matrix")
end if
end do
r = int(mxGetM(prhs(1))) ! Number of states
n = int(mxGetN(prhs(3))) ! Number of observables
if ((r /= mxGetN(prhs(1))) & ! Number of columns of P
&.or. (r /= mxGetM(prhs(2))) & ! Number of lines of T
&.or. (r /= mxGetN(prhs(2))) & ! Number of columns of T
&.or. (r /= mxGetM(prhs(3))) & ! Number of lines of K
&.or. (n /= mxGetM(prhs(4))) & ! Number of lines of Z
&.or. (r /= mxGetN(prhs(4))) & ! Number of columns of Z
&.or. (r /= mxGetM(prhs(5))) & ! Number of lines of Q
&.or. (r /= mxGetN(prhs(5))) & ! Number of columns of Q
) then
call mexErrMsgTxt("Input dimension mismatch")
end if
! 1. Storing the relevant information in Fortran format
P(1:r,1:r) => mxGetPr(prhs(1))
T(1:r,1:r) => mxGetPr(prhs(2))
K(1:r,1:n) => mxGetPr(prhs(3))
Z(1:n,1:r) => mxGetPr(prhs(4))
Q(1:r,1:r) => mxGetPr(prhs(5))
plhs(1) = mxCreateDoubleMatrix(int(r, mwSize), int(r, mwSize), mxREAL)
Pnew(1:r, 1:r) => mxGetPr(plhs(1))
! 2. Computing the Riccati update of the P matrix
allocate(tmp1(r,r), tmp2(r,r))
! Pnew <- Q
Pnew = Q
! tmp1 <- K*Z
call matmul_add("N", "N", 1._real64, K, Z, 0._real64, tmp1)
! tmp2 <- P
tmp2 = P
! tmp2 <- tmp2 - tmp1*P
call matmul_add("N", "N", -1._real64, tmp1, P, 1._real64, tmp2)
! tmp1 <- T*tmp2
call matmul_add("N", "N", 1._real64, T, tmp2, 0._real64, tmp1)
! Pnew <- tmp1*T' + Pnew
call matmul_add("N", "T", 1._real64, tmp1, T, 1._real64, Pnew)
end subroutine mexFunction

@ -1 +1 @@
Subproject commit 5fa91a08f68d04a8baac4f32dab9db62b5a3546f
Subproject commit 20acdbc119648f8ae6438e7f3a18943b4c23e7d2

View File

@ -1,4 +1,4 @@
# Copyright 2023 Dynare Team
# Copyright 2023-2024 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 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. #
# 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. #
##############################################################################################################
# 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 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
# 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
# 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 MATLAB installed.
# Specify the base image with pre-installed MATLAB
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,6 +70,7 @@ 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 \
@ -79,11 +80,39 @@ 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 dynare dependencies.
RUN export DEBIAN_FRONTEND=noninteractive \
&& apt-get update \
&& apt-get install --no-install-recommends --yes \
build-essential \
# 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 \
gfortran \
libboost-graph-dev \
libgsl-dev \
@ -94,8 +123,6 @@ RUN export DEBIAN_FRONTEND=noninteractive \
flex \
libfl-dev \
bison \
autoconf \
automake \
texlive \
texlive-publishers \
texlive-latex-extra \
@ -109,7 +136,6 @@ RUN export DEBIAN_FRONTEND=noninteractive \
tex-gyre \
latexmk \
libjs-mathjax \
doxygen \
x13as \
liboctave-dev \
octave-control \
@ -123,10 +149,30 @@ 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; \
@ -163,20 +209,34 @@ 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
USER matlab
WORKDIR /home/matlab
RUN cd dynare \
&& autoreconf -si \
&& ./configure --with-matlab=${MATLAB_INSTALL_LOCATION} MATLAB_VERSION=${MATLAB_RELEASE} \
&& make -j$(($(nproc)+1))
# 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
# 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
@ -195,6 +255,6 @@ RUN filename="/home/matlab/Documents/MATLAB/startup.m" && \
fi && \
chown matlab:matlab "$filename"
# Set user and work directory.
# Set user and work directory
USER matlab
WORKDIR /home/matlab

View File

@ -1,5 +1,5 @@
# Dynare Docker Containers
We provide a range of pre-configured Docker containers for [Dynare](https://dynare.org), which include both Octave and MATLAB (pre-configured with Dynare already in the PATH) and all recommended toolboxes. These containers are ideal for using Dynare in CI/CD environments ([example Workflow for GitHub Actions](https://github.com/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).
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).
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,7 +7,9 @@ To minimize maintenance efforts while ensuring high levels of security, reliabil
| Tags | Dynare Version | MATLAB® Version | Octave Version | Operating System | Base Image |
|--------|----------------|-----------------|----------------|------------------|-------------------------|
| latest | 5.4 | R2023a | 5.2.0 | Ubuntu 20.04 | mathworks/matlab:R2023a |
| 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 |
| 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 |
@ -15,14 +17,21 @@ 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
```
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.
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.
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
@ -31,9 +40,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. 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).
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).
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.
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.
### Run Ubuntu desktop and interact with it via VNC
@ -45,7 +54,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).
- 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.
### Run Dynare with Octave in an interactive command prompt
@ -92,6 +101,7 @@ 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:
@ -102,14 +112,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 `matlab-license.lic`, which is located in your home folder:
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`:
```sh
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"
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"
```
### Environment variables
@ -120,7 +130,9 @@ 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=R2023a --build-arg DYNARE_RELEASE=5.4 -t dynare/dynare:latest .
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:5.4 .
docker build --build-arg MATLAB_RELEASE=R2022b --build-arg DYNARE_RELEASE=5.3 -t dynare/dynare:5.3 .
docker build --build-arg MATLAB_RELEASE=R2022a --build-arg DYNARE_RELEASE=5.2 -t dynare/dynare:5.2 .

View File

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

View File

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

View File

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

Binary file not shown.

View File

@ -83,7 +83,7 @@ method_of_moments(mom_method = irf_matching
%, mode_check_neighbourhood_size
%, mode_check_number_of_points
, mode_check_symmetric_plots = 0
, mode_compute = 1
, mode_compute = 4
, mode_file = cet_original_mode
%, nobs
%, no_posterior_kernel_density

View File

@ -192,7 +192,7 @@ method_of_moments(mom_method = irf_matching
, mh_replic=10
, plot_priors = 0
, nograph
, mode_compute = 1
, mode_compute = 5
, posterior_sampling_method = 'slice'
, posterior_sampler_options = ('rotated',1
% ,'mode_files'

View File

@ -156,14 +156,14 @@ method_of_moments(mom_method = irf_matching
method_of_moments(mom_method = irf_matching
, additional_optimizer_steps = [1]
, additional_optimizer_steps = [4]
, cova_compute=1
, dirname=cet_tarb_results
, irf_matching_file = cet_irf_matching_file
, mh_conf_sig = 0.90
, mh_replic=0
%, mode_check
, mode_compute = 4
, mode_compute = 5
, mode_file = 'cet_tarb_results/method_of_moments/cet_tarb_mh_mode'
, plot_priors = 0
, nograph

View File

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

View File

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

View File

@ -1,87 +0,0 @@
source_dir = getenv('source_root');
addpath([source_dir filesep 'matlab']);
dynare_config;
testFailed = 0;
skipline()
disp('*** TESTING: riccatiupdate.m ***');
t0 = clock;
% Set the number of experiments for time measurement
N = 5000;
% Set the dimension of the problem to be solved.
r = 50;
n = 100;
tol = 1e-15;
% Set the input arguments
% P, Q: use the fact that for any real matrix A, A'*A is positive semidefinite
P = rand(n,r);
P = P'*P;
Q = rand(n,r);
Q = Q'*Q;
K = rand(r,n);
Z = rand(n,r);
T = rand(r,r);
% Computing an upperbound for the norm the updated variance-covariance matrix
ub = norm(T,1)^2*norm(P,1)*(1+norm(K*Z,1))+norm(Q,1);
% Weighting the P and Q matrices to keep the norm of the variance-covariance matrix below 1
P = 0.5*P/ub;
Q = 0.5*Q/ub;
% 1. Update the state vairance-covariance matrix with Matlab
tElapsed1 = 0.;
tic;
for i=1:N
Ptmp_matlab = T*(P-K*Z*P)*transpose(T)+Q;
end
tElapsed1 = toc;
disp(['Elapsed time for the Matlab Riccati update is: ' num2str(tElapsed1) ' (N=' int2str(N) ').'])
% 2. Update the state varance-covariance matrix with the mex routine
tElapsed2 = 0.;
Ptmp_fortran = P;
try
tic;
for i=1:N
Ptmp_fortran = riccati_update(P, T, K, Z, Q);
end
tElapsed2 = toc;
disp(['Elapsed time for the Fortran Riccati update is: ' num2str(tElapsed2) ' (N=' int2str(N) ').'])
R = norm(Ptmp_fortran-Ptmp_matlab,1);
if (R > tol)
testFailed = testFailed+1;
dprintf('The Fortran Riccati update is wrong')
end
catch
testFailed = testFailed+1;
dprintf('Fortran Riccati update failed')
end
% Compare the Fortran and Matlab execution time
if tElapsed1<tElapsed2
skipline()
dprintf('Matlab Riccati update is %5.2f times faster than its Fortran counterpart.', tElapsed2/tElapsed1)
skipline()
else
skipline()
dprintf('Fortran Riccati update is %5.2f times faster than its Matlab counterpart.', tElapsed1/tElapsed2)
skipline()
end
% Compare results after multiple calls
N = 50;
disp(['After 1 update using the Riccati formula, the norm-1 discrepancy is ' num2str(norm(Ptmp_fortran-Ptmp_matlab,1)) '.']);
for i=2:N
Ptmp_matlab = T*(Ptmp_matlab-K*Z*Ptmp_matlab)*transpose(T)+Q;
Ptmp_fortran = riccati_update(Ptmp_fortran, T, K, Z, Q);
disp(['After ' int2str(i) ' updates using the Riccati formula, the norm-1 discrepancy is ' num2str(norm(Ptmp_fortran-Ptmp_matlab,1)) '.'])
end
t1 = clock;
fprintf('\n*** Elapsed time (in seconds): %.1f\n\n', etime(t1, t0));
quit(testFailed > 0)

View File

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

View File

@ -157,7 +157,8 @@ mingw64: tarballs/mingw-w64-x86_64-gcc-$(MINGW64_GCC_VERSION)-any.pkg.tar.zst ta
touch $@
tarballs/mingw-w64-x86_64-%-any.pkg.tar.zst:
wget $(WGET_OPTIONS) -O $@ http://repo.msys2.org/mingw/x86_64/$(notdir $@)
mkdir -p tarballs
wget $(WGET_OPTIONS) -O $@ https://www.dynare.org/windows-pkg-build/msys2/6.x/$(notdir $@)
clean-msys2:
rm -rf lib64-msys2

View File

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