Compare commits

..

7 Commits

Author SHA1 Message Date
Stéphane Adjemian (Ryûk) 1839529288
Add member to dprior class.
Name of the parameter.
2023-07-11 16:40:42 +02:00
Stéphane Adjemian (Ryûk) b5cbc397a6
One file per method. 2023-07-11 15:30:07 +02:00
Stéphane Adjemian (Ryûk) e05e9c5690
Add methods for computing moments.
- prior mean
 - prior mode
 - prior median
 - prior variance
2023-07-11 08:42:29 +02:00
Stéphane Adjemian (Ryûk) 301a45ef59
Add members to @dprior class. 2023-07-08 11:43:19 +02:00
Stéphane Adjemian (Ryûk) 5375070fa3
Make last input argument optional. 2023-07-08 11:43:19 +02:00
Stéphane Adjemian (Ryûk) 278b669a33
Add methods to dprior (density and densities).
Will be used as a replacement for priordens.
2023-07-08 11:43:19 +02:00
Stéphane Adjemian (Ryûk) 90f5fc72c9
Cosmetic changes. 2023-07-08 11:43:17 +02:00
1341 changed files with 50127 additions and 55954 deletions

View File

@ -1,27 +0,0 @@
# NB: whenever the present file is modified, the same modification should be
# applied to the copy in preprocessor.git
# For general information about our coding style, and the specific version
# of clang-format used, see:
# https://git.dynare.org/Dynare/dynare/-/wikis/CodingGuidelines#c-code
# For the list of options of clang-format, see:
# https://clang.llvm.org/docs/ClangFormatStyleOptions.html
# Effective configuration can be obtained with:
# clang-format --dump-config
Language: Cpp
Standard: c++20
ColumnLimit: 100
BasedOnStyle: GNU
AllowShortFunctionsOnASingleLine: None
AlwaysBreakTemplateDeclarations: Yes
BreakConstructorInitializers: AfterColon
BreakInheritanceList: AfterColon
Cpp11BracedListStyle: true
DeriveLineEnding: false
IndentPPDirectives: AfterHash
PackConstructorInitializers: NextLine
PPIndentWidth: 1
PointerAlignment: Left
SpaceAfterTemplateKeyword: false
SpaceBeforeParens: ControlStatements
SpaceBeforeCpp11BracedList: true

View File

@ -1,8 +0,0 @@
# NB: to use clang-tidy on the MEX source code, make sure that you have
# libomp-dev installed (the LLVM implementation of OpenMP)
# TODO: add the following check families:
# - bugprone-*
# - cppcoreguidelines-
Checks: 'performance-*,modernize-*,-modernize-use-trailing-return-type,-clang-diagnostic-unqualified-std-cast-call'

View File

@ -1,8 +1,6 @@
((c-mode . ((indent-tabs-mode . nil)
(fill-column . 100)
(c-file-style . "gnu")))
(c++-mode . ((indent-tabs-mode . nil)
(fill-column . 100)
(c-file-style . "gnu")))
(makefile-mode . ((indent-tabs-mode . t)))
(octave-mode . ((indent-tabs-mode . nil)

136
.gitignore vendored
View File

@ -3,12 +3,108 @@
# Any file that is displayed should be removed from the ignore list
# (possibly by an exclusion rule beginning with an exclamation mark)
# Generic ignore rules
*~
*.o
*.a
*.fig
\#*\#
TAGS
*.mat
# Created when building the reference manual
# Build system rules
.deps
Makefile
Makefile.in
confdefs.h
configure
config.log
config.status
aclocal.m4
autom4te.cache
config.guess
config.sub
depcomp
install-sh
/missing
/mex/build/matlab/missing
/mex/build/octave/missing
/compile
/mex/build/matlab/compile
/mex/build/octave/compile
ylwrap
ar-lib
# checksum associated with fast option
checksum
# Make Check Rules
*.trs
*.tls
# Doc rules
*.pdf
*.aux
*.log
*.out
*.toc
*.idx
*.scn
*.nav
*.snm
*.vrb
*.bbl
*.blg
*.lof
/doc/manual/build
/doc/manual/utils/version.py
/doc/manual/utils/__pycache__/*
!/doc/guide.bbl
!/doc/parallel/AvenueParadigm.pdf
!/doc/parallel/iVaNo_*.pdf
!/doc/parallel/netbook_*.pdf
!/doc/parallel/quest_*.pdf
!/doc/parallel/RWMH_quest1_*.pdf
!/doc/parallel/waitbars*.pdf
doc/internals/*.html
doc/internals/ltxpng
# Created by the Windows package build script
# MATLAB dir
/matlab/preprocessor64/
/matlab/dynare_version.m
# DLL rules
*.mex
*.mexa64
*.mexw64
*.mexmaci64
*.mexmaca64
/mex/matlab/
/mex/octave/
# Symbolic links created for building MEX files
/mex/build/matlab/*/*.c
/mex/build/matlab/*/*.cc
/mex/build/matlab/*/*.f08
/mex/build/matlab/*/*.F08
/mex/build/octave/*/*.c
/mex/build/octave/*/*.cc
/mex/build/octave/*/*.f08
/mex/build/octave/*/*.F08
# Fortran modules
/mex/build/matlab/*/*.mod
/mex/build/octave/*/*.mod
# Extra rules for trust_region MEX testfiles
/mex/sources/block_trust_region/test/*.mod
/mex/sources/block_trust_region/test/dulmage_mendelsohn_test
/mex/sources/block_trust_region/test/trust_region_test
!/mex/sources/block_trust_region/test/Makefile
# Windows
!/windows/Makefile
!/windows/deps/Makefile
/windows/deps/lib64/
/windows/deps/lib64-msys2/
/windows/deps/matlab64/
@ -19,17 +115,35 @@
/windows/exe/
/windows/7z/
/windows/zip/
/matlab/preprocessor64/
/matlab/supported_octave_version.m
# Created by the macOS package build script
/macOS/deps/arm64/sources64/
/macOS/deps/x86_64/sources64/
# MacOS stuff
.DS_Store
/macOS/pkg/
/macOS/deps/sources64/
/macOS/deps/tarballs/
/macOS/deps/arm64/lib64/
/macOS/deps/x86_64/lib64/
build-doc
/macOS/deps/lib64/
!/macOS/Makefile
!/macOS/deps/Makefile
# Emacs stuff
TAGS
scripts/dynare.elc
# MS-Sbvar
/contrib/ms-sbvar/*.prn
/contrib/ms-sbvar/*.dat
/contrib/ms-sbvar/sbvar_commandline
/contrib/ms-sbvar/sbvar_init_file
!/contrib/ms-sbvar/Makefile
/tests/ms-sbvar/*.tmp
# Reporting
*synctex.gz
tests/reporting/tmpRepDir
# Octave variables saved when Octave crashes
octave-workspace
# VERSION generated file
VERSION
matlab/supported_octave_version.m

View File

@ -1,84 +1,72 @@
variables:
GIT_SUBMODULE_STRATEGY: recursive
TERM: linux
MATLAB_VERSION: R2023b
OLD_MATLAB_VERSION: R2018b
# To ensure that "false && true" fails, see https://gitlab.com/gitlab-org/gitlab-runner/-/issues/25394#note_412609647
FF_ENABLE_BASH_EXIT_CODE_CHECK: 'true'
MATLAB_VERSION: R2023a
OLD_MATLAB_VERSION: R2014a
# The next stanza creates the version number used for the source tarball and the
# binary packages. Here are the following possible cases:
# - if VERSION was already set (when manually running a pipeline), use it
# - if we are in the official Dynare repository:
# + if on a tag: use the tag
# + if on master: use 7-unstable-$TIMESTAMP-$COMMIT
# + if on master: use 6-unstable-$TIMESTAMP-$COMMIT
# + on another branch: use $BRANCH-$TIMESTAMP-$COMMIT
# - if in a personal repository: use $USER-$TIMESTAMP-$COMMIT
before_script:
- 'if [[ -z $VERSION ]] && [[ $CI_PROJECT_NAMESPACE == Dynare ]] && [[ -n $CI_COMMIT_TAG ]]; then export VERSION=$CI_COMMIT_TAG; fi'
- 'if [[ -z $VERSION ]] && [[ $CI_PROJECT_NAMESPACE == Dynare ]] && [[ $CI_COMMIT_REF_NAME == master ]]; then export VERSION=7-unstable-$(date +%F-%H%M)-$CI_COMMIT_SHORT_SHA; fi'
- 'if [[ -z $VERSION ]] && [[ $CI_PROJECT_NAMESPACE == Dynare ]]; then export VERSION=$CI_COMMIT_REF_NAME-$(date +%F-%H%M)-$CI_COMMIT_SHORT_SHA; fi'
- 'if [[ -z $VERSION ]]; then export VERSION=$CI_PROJECT_NAMESPACE-$(date +%F-%H%M)-$CI_COMMIT_SHORT_SHA; fi'
- '[[ -z $VERSION ]] && [[ $CI_PROJECT_NAMESPACE == Dynare ]] && [[ -n $CI_COMMIT_TAG ]] && export VERSION=$CI_COMMIT_TAG'
- '[[ -z $VERSION ]] && [[ $CI_PROJECT_NAMESPACE == Dynare ]] && [[ $CI_COMMIT_REF_NAME == master ]] && export VERSION=6-unstable-$(date +%F-%H%M)-$CI_COMMIT_SHORT_SHA'
- '[[ -z $VERSION ]] && [[ $CI_PROJECT_NAMESPACE == Dynare ]] && export VERSION=$CI_COMMIT_REF_NAME-$(date +%F-%H%M)-$CI_COMMIT_SHORT_SHA'
- '[[ -z $VERSION ]] && export VERSION=$CI_PROJECT_NAMESPACE-$(date +%F-%H%M)-$CI_COMMIT_SHORT_SHA'
stages:
- build
- test
- pkg
- sign
- deploy
build_matlab:
build_binaries:
stage: build
script:
- meson setup -Dbuild_for=matlab -Dmatlab_path=/opt/MATLAB/$MATLAB_VERSION -Dbuildtype=release build-matlab
- meson compile -v -C build-matlab
- autoreconf -si
- ./configure --with-matlab=/opt/MATLAB/$MATLAB_VERSION PACKAGE_VERSION=$VERSION PACKAGE_STRING="dynare $VERSION"
- make -j $(nproc) LN_S="cp -p"
artifacts:
paths:
- build-matlab/
expire_in: 3 days
build_octave:
stage: build
script:
- meson setup -Dbuild_for=octave -Dbuildtype=release build-octave
- meson compile -v -C build-octave
artifacts:
paths:
- build-octave/
- preprocessor/dynare-preprocessor
- mex/octave/
- mex/matlab/
expire_in: 3 days
build_doc:
stage: build
script:
- meson rewrite kwargs set project / version "$VERSION"
# Use a local copy of MathJax to avoid using CDN (which are a privacy issue)
# NB: Debian 12 “Bookworm” has MathJax 2. The following needs to be updated
# when Debian moves to MathJax 3.
- meson setup -Dbuild_for=octave -Dmathjax_path=mathjax/MathJax.js?config=TeX-AMS-MML_HTMLorMML build-doc
- meson compile -v -C build-doc doc
- cp -dR /usr/share/javascript/mathjax build-doc/dynare-manual.html/_static/
- autoreconf -si
- ./configure --disable-matlab --disable-octave PACKAGE_VERSION=$VERSION PACKAGE_STRING="dynare $VERSION"
- make -j $(nproc) pdf html
artifacts:
paths:
- build-doc/
- doc/manual/build/
- doc/**/*.pdf
- preprocessor/doc/*/*.pdf
expire_in: 3 days
pkg_source:
stage: pkg
script:
- meson rewrite kwargs set project / version "$VERSION"
- git commit -a -m "Source for $VERSION"
- meson setup -Dbuild_for=octave build-src
- meson dist -C build-src --no-tests
- rm doc/manual/source/_static/mathjax && sed -i "/^mathjax_path *=/d" doc/manual/source/conf.py
- 'for f in configure.ac preprocessor/configure.ac mex/build/matlab/configure.ac mex/build/octave/configure.ac; do sed -i "s/^AC_INIT(\[\(.*\)\],\s*\[\(.*\)\])/AC_INIT([\1], [$VERSION])/" $f; done'
- autoreconf -si
- ./configure --with-matlab=/opt/MATLAB/$MATLAB_VERSION
- make dist
artifacts:
paths:
- build-src/meson-dist/dynare-*.tar.xz
- dynare-*.tar.xz
expire_in: 3 days
needs: []
pkg_windows:
stage: pkg
script:
- meson rewrite kwargs set project / version "$VERSION"
- mkdir -p windows/deps/tarballs && cp /usr/lib/dynare-runner/matlab64-* windows/deps/tarballs/
- make -C windows
- rm windows/deps/tarballs/matlab64-* # No need to cache these files
@ -102,18 +90,16 @@ pkg_windows:
expire_in: 3 days
needs: [ "build_doc" ]
pkg_macOS_x86_64:
pkg_macOS:
stage: pkg
script:
# Enforce the arm64 meson for rewrite, as a workaround to https://github.com/mesonbuild/meson/issues/12282
- env PATH="/opt/homebrew/bin:$PATH" meson rewrite kwargs set project / version "$VERSION"
- ln -s ~/tarballs macOS/deps/x86_64
- make -C macOS build-x86_64
- ln -s ~/tarballs macOS/deps/
- arch -x86_64 make -C macOS
cache:
key: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"
paths:
- macOS/deps/x86_64/sources64/
- macOS/deps/x86_64/lib64/
- macOS/deps/sources64/
- macOS/deps/lib64/
tags:
- macOS
artifacts:
@ -122,46 +108,32 @@ pkg_macOS_x86_64:
expire_in: 3 days
needs: [ "build_doc" ]
pkg_macOS_arm64:
stage: pkg
script:
# Enforce the arm64 meson for rewrite, as a workaround to https://github.com/mesonbuild/meson/issues/12282
- env PATH="/opt/homebrew/bin:$PATH" meson rewrite kwargs set project / version "$VERSION"
- ln -s ~/tarballs macOS/deps/arm64
- make -C macOS build-arm64
cache:
key: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"
paths:
- macOS/deps/arm64/sources64/
- macOS/deps/arm64/lib64/
tags:
- macOS
.test_matlab_template:
stage: test
artifacts:
paths:
- macOS/pkg/*
expire_in: 3 days
needs: [ "build_doc" ]
- tests/**/*.m.log
- tests/**/*.m.trs
- tests/**/*.jnl
- tests/run_test_matlab_output.txt
when: always
needs: [ "build_binaries" ]
test_matlab:
stage: test
extends: .test_matlab_template
script:
- meson test -C build-matlab --no-rebuild --num-processes $(($(nproc) * 3 / 4))
artifacts:
paths:
- build-matlab/meson-logs/testlog.txt
when: always
needs: [ "build_matlab" ]
- autoreconf -si
- ./configure --disable-octave --with-matlab=/opt/MATLAB/$MATLAB_VERSION
- make -j $(($(nproc) * 3 / 4)) -C tests check-matlab
test_old_matlab:
stage: test
extends: .test_matlab_template
script:
- meson setup -Dbuild_for=matlab -Dmatlab_path=/opt/MATLAB/$OLD_MATLAB_VERSION -Dbuildtype=release build-old-matlab
- meson compile -v -C build-old-matlab
- meson test -C build-old-matlab --num-processes $(($(nproc) * 3 / 4))
artifacts:
paths:
- build-old-matlab/meson-logs/testlog.txt
when: always
- autoreconf -si
- ./configure --disable-octave --with-matlab=/opt/MATLAB/$OLD_MATLAB_VERSION
- make -C mex/build/matlab clean
- make -j $(nproc) -C mex/build/matlab
- make -j $(($(nproc) * 3 / 4)) -C tests check-matlab
when: manual
test_octave:
@ -169,41 +141,22 @@ test_octave:
variables:
OPENBLAS_NUM_THREADS: 1
script:
- meson test -C build-octave --no-rebuild
- autoreconf -si
- ./configure --disable-matlab
- make -j $(nproc) -C tests check-octave
artifacts:
paths:
- build-octave/meson-logs/testlog.txt
- tests/**/*.o.log
- tests/**/*.o.trs
- tests/**/*.jnl
- tests/run_test_octave_output.txt
when: always
needs: [ "build_octave" ]
needs: [ "build_binaries" ]
when: manual
test_clang_format:
stage: test
script:
- meson setup -Dbuild_for=octave build-clang-format
- ninja -C build-clang-format clang-format-check
needs: []
# For the sign and deploy jobs, we dont use the “needs” keyword, since we
# dont want those jobs to start before the “test” and “pkg” stages have
# succeeded. Hence we stick to the “dependencies” keyword.
sign_windows:
stage: sign
rules:
- if: '$CI_PROJECT_NAMESPACE == "Dynare" && $CI_COMMIT_REF_NAME == "master"'
when: on_success
- when: never
tags:
- sign
dependencies:
- pkg_windows
script:
- f=(windows/exe/*) && mkdir -p windows/exe-signed/ && osslsigncode sign -pkcs11module /usr/lib/x86_64-linux-gnu/libykcs11.so.2 -key "pkcs11:id=%01;type=private;pin-value=$YUBIKEY_PIN" -certs ~/cepremap-code-signing-comodo-sectigo.pem -n Dynare -i https://www.dynare.org -t http://timestamp.comodoca.com -in ${f[0]} -out windows/exe-signed/${f[0]##*/}
artifacts:
paths:
- windows/exe-signed/*
expire_in: 3 days
# For the deploy jobs, we dont use the “needs” keyword, since we dont want
# those jobs to start before the “test” and “pkg” stages have succeeded. Hence
# we stick to the “dependencies” keyword.
deploy_manual_unstable:
stage: deploy
@ -212,11 +165,13 @@ deploy_manual_unstable:
when: on_success
- when: never
tags:
- deploy
- restricted
dependencies:
- build_doc
script:
- rsync --recursive --links --delete build-doc/dynare-manual.html/ /srv/www.dynare.org/manual-unstable/
- rm -rf doc/manual/build/html/_static/mathjax
- ln -s /usr/share/javascript/mathjax doc/manual/build/html/_static/mathjax
- rsync --recursive --links --delete doc/manual/build/html/ /srv/www.dynare.org/manual-unstable/
deploy_snapshot_unstable:
stage: deploy
@ -225,19 +180,17 @@ deploy_snapshot_unstable:
when: on_success
- when: never
tags:
- deploy
- restricted
dependencies:
- pkg_source
- pkg_windows
- sign_windows
- pkg_macOS_arm64
- pkg_macOS_x86_64
- pkg_macOS
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/exe/*) && osslsigncode sign -pkcs12 ~/cepremap-comodo-sectigo-code-signing.p12 -n Dynare -i https://www.dynare.org -t http://timestamp.comodoca.com -in ${f[0]} -out ${f[0]}.signed && mv ${f[0]}.signed ${f[0]}
- cp *.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/*) && 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
- f=(macOS/pkg/*) && cp ${f[0]} /srv/www.dynare.org/snapshot/macos/ && ln -sf ${f[0]##*/} /srv/www.dynare.org/snapshot/macos/dynare-latest-macos.pkg
- ~/update-snapshot-list.sh
- curl -X POST -F token="$WEBSITE_PIPELINE_TRIGGER_TOKEN" -F ref=master https://git.dynare.org/api/v4/projects/40/trigger/pipeline

11
.gitmodules vendored
View File

@ -10,10 +10,19 @@
[submodule "matlab/utilities/tests"]
path = matlab/utilities/tests
url = ../../Dynare/m-unit-tests.git
[submodule "matlab/particles"]
path = matlab/particles
url = ../../Dynare/particles.git
[submodule "matlab/modules/dseries"]
path = matlab/dseries
path = matlab/modules/dseries
url = ../../Dynare/dseries.git
branch = master
[submodule "matlab/modules/reporting"]
path = matlab/modules/reporting
url = ../../Dynare/reporting.git
[submodule "contrib/jsonlab"]
path = contrib/jsonlab
url = https://github.com/fangq/jsonlab.git
[submodule "preprocessor"]
path = preprocessor
url = ../../Dynare/preprocessor.git

View File

@ -12,8 +12,10 @@ Please note that the repositories under the purview of this page are:
* [Dynare](https://git.dynare.org/Dynare/dynare)
* [Preprocessor](https://git.dynare.org/Dynare/preprocessor)
* [Particles](https://git.dynare.org/Dynare/particles)
* [Dseries](https://git.dynare.org/Dynare/dseries)
* [Reporting](https://git.dynare.org/Dynare/reporting)
* [Testsuite](https://git.dynare.org/Dynare/testsuite)
* [M-unit-tests](https://git.dynare.org/Dynare/m-unit-tests)
## Making your Intentions Known
@ -92,9 +94,9 @@ The output from the latest run of the test suite can be found in the `test_matla
Its useful to contribute `.mod` files that test some aspect of Dynare that is not currently tested. A `.mod` file that runs into a bug is perfect. As the test suite currently takes several hours to run, we prefer you modify a current test to also create the bug youve found. If you cant do that, please add a new test that runs as quickly as possible. It will contain only those commands necessary to create the bug, nothing more. To contribute a test, after having made an issue and cloned and forked the repository as described above, do the following:
1. Modify the `mod_and_m_tests` variable in `meson.build` with a entry containing your test file name
1. If any ancillary files are needed to run your test, please include them in the `'extra'` field
1. Add and commit your test file and `meson.build` as described above
1. Modify the `MODFILES` variable in `tests/Makefile.am` with a line containing your test file name
1. If any ancillary files are needed to run your test, please include them in the `EXTRA_DIST` variable in `tests/Makefile.am`
1. Add and commit your test file and `tests/Makefile.am` as described above
1. Push and create a pull request as described above
### Unit tests

67
Makefile.am Normal file
View File

@ -0,0 +1,67 @@
SUBDIRS = preprocessor doc tests mex/sources
if ENABLE_MATLAB
SUBDIRS += mex/build/matlab
endif
if ENABLE_OCTAVE
SUBDIRS += mex/build/octave
endif
ACLOCAL_AMFLAGS = -I m4
EXTRA_DIST = \
matlab \
contrib \
NEWS.md \
license.txt \
README.md \
COPYING \
CONTRIBUTING.md \
windows \
macOS \
examples \
scripts \
.dir-locals.el
all-local:
# Create top-level preprocessor symlink needed by matlab/dynare.m (when Dynare is run
# from the locally-built copy)
$(LN_S) -f $(abs_builddir)/preprocessor/src/dynare-preprocessor$(EXEEXT) $(abs_builddir)/preprocessor/dynare-preprocessor$(EXEEXT)
# Create backward-compatibility symlink for old location of preprocessor
$(MKDIR_P) matlab/preprocessor64/
$(LN_S) -f $(abs_builddir)/preprocessor/src/dynare-preprocessor$(EXEEXT) $(abs_srcdir)/matlab/preprocessor64/dynare_m$(EXEEXT)
clean-local:
rm -f preprocessor/dynare-preprocessor$(EXEEXT)
rm -rf matlab/preprocessor64/
dist-hook:
rm -rf `find $(distdir)/matlab $(distdir)/examples -name *~`
rm -f $(distdir)/matlab/dynare_version.m
rm -rf $(distdir)/matlab/preprocessor64/
$(MKDIR_P) $(distdir)/mex/matlab $(distdir)/mex/octave
rm -rf `find $(distdir) -name '.git*'`
install-exec-local:
$(MKDIR_P) $(DESTDIR)$(pkglibdir)/preprocessor
# The following will break under Windows, but we dont use the install rule there
$(LN_S) -f $(bindir)/dynare-preprocessor$(EXEEXT) $(DESTDIR)$(pkglibdir)/preprocessor/dynare-preprocessor$(EXEEXT)
$(MKDIR_P) $(DESTDIR)$(pkglibdir)/contrib/ms-sbvar/TZcode
cp -r contrib/ms-sbvar/TZcode/MatlabFiles $(DESTDIR)$(pkglibdir)/contrib/ms-sbvar/TZcode
$(MKDIR_P) $(DESTDIR)$(pkglibdir)/contrib/jsonlab
cp -r contrib/jsonlab $(DESTDIR)$(pkglibdir)/contrib/jsonlab
cp -r examples $(DESTDIR)$(pkglibdir)
cp -r matlab $(DESTDIR)$(pkglibdir)
find $(DESTDIR)$(pkglibdir) -name LICENSE.md -delete
# Recreate backward-compatibility symlink
rm -f $(DESTDIR)$(pkglibdir)/matlab/preprocessor64/dynare_m$(EXEEXT)
$(LN_S) -f $(bindir)/dynare-preprocessor$(EXEEXT) $(DESTDIR)$(pkglibdir)/matlab/preprocessor64/dynare_m$(EXEEXT)
# We dont fail over doc install rules, since the user may deliberately not have compiled them
# (e.g. with the “nodoc” option under Debian)
$(MKDIR_P) $(DESTDIR)$(docdir)
-cp doc/*.pdf doc/gsa/gsa.pdf doc/parallel/parallel.pdf doc/dseries-and-reporting/dseriesReporting.pdf preprocessor/doc/preprocessor/preprocessor.pdf preprocessor/doc/macroprocessor/macroprocessor.pdf doc/manual/build/latex/dynare-manual.pdf $(DESTDIR)$(docdir)
-cp -r doc/manual/build/html $(DESTDIR)$(docdir)/dynare-manual.html
uninstall-local:
rm -rf $(DESTDIR)$(pkglibdir)
rm -rf $(DESTDIR)$(docdir)

461
NEWS.md
View File

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

284
README.md
View File

@ -33,6 +33,8 @@ This source can be retrieved in three forms:
- using the stable source archive of the latest Dynare version from <https://www.dynare.org/download/>
- using a source snapshot of the unstable version, also from <https://www.dynare.org/download/>
Note that if you obtain the source code via git, you will need to install more tools (see below).
The first section of this page gives general instructions, which apply to all platforms. Then some specific platforms are discussed.
**Note:** Here, when we refer to 32-bit or 64-bit, we refer to the type of
@ -56,7 +58,6 @@ a 32-bit Octave.
1. [**Fedora, CentOS or RHEL**](#fedora-centos-or-rhel)
1. [**Windows**](#windows)
1. [**macOS**](#macos)
1. [**Docker**](#docker)
## General Instructions
@ -64,27 +65,28 @@ a 32-bit Octave.
A number of tools and libraries are needed in order to recompile everything. You don't necessarily need to install everything, depending on what you want to compile.
- A POSIX compliant shell and an implementation of Make (mandatory)
- The [GNU Compiler Collection](https://gcc.gnu.org/), version 10 or later, with
gcc, g++ and gfortran
gcc, g++ and gfortran (mandatory)
- [MATLAB](https://mathworks.com) (if you want to compile the MEX for MATLAB)
- [GNU Octave](https://www.octave.org) with
- the development headers (if you want to compile the MEX for Octave)
- the development libraries corresponding to the [UMFPACK](https://people.engr.tamu.edu/davis/suitesparse.html) packaged with Octave (if you want to compile the MEX for Octave)
- the [statistics](https://octave.sourceforge.io/statistics/) package and, optionally, the [control](https://octave.sourceforge.io/control/), [io](https://octave.sourceforge.io/io/) and [optimization](https://octave.sourceforge.io/optim/) packages, either installed via your package manager or through [Octave Forge](https://octave.sourceforge.io/)
- [Meson](https://mesonbuild.com), version 0.64.0 or later
- [Pkgconf](http://pkgconf.org/), or another pkg-config implementation
- [Bash](https://www.gnu.org/software/bash/)
- the development libraries corresponding to the [UMFPACK](https://people.engr.tamu.edu/davis/suitesparse.html) packaged with Octave
- Optionally, the [Control](https://octave.sourceforge.io/control/), [IO](https://octave.sourceforge.io/io/), [Optimization](https://octave.sourceforge.io/optim/) and [Statistics](https://octave.sourceforge.io/statistics/) package either installed via your package manager or through [Octave Forge](https://octave.sourceforge.io/).
- [Boost libraries](https://www.boost.org), version 1.36 or later
- [Bison](https://www.gnu.org/software/bison/), version 3.2 or later
- [Flex](https://github.com/westes/flex), version 2.5.4 or later
- [MAT File I/O library](https://sourceforge.net/projects/matio/), version 1.5 or later (only when compiling for Octave)
- [SLICOT](http://www.slicot.org)
- [GSL library](https://www.gnu.org/software/gsl/)
- [Bison](https://www.gnu.org/software/bison/), version 3.2 or later (only if you get the source through Git)
- [Flex](https://github.com/westes/flex), version 2.5.4 or later (only if you get the source through Git)
- [Autoconf](https://www.gnu.org/software/autoconf/), version 2.62 or later (only if you get the source through Git)
- [Automake](https://www.gnu.org/software/automake/), version 1.11.2 or later (only if you get the source through Git)
- [MAT File I/O library](https://sourceforge.net/projects/matio/), version 1.5 or later (if you want to compile Markov-Switching SBVAR code)
- [SLICOT](http://www.slicot.org) (if you want to compile the Kalman steady state DLL)
- [GSL library](https://www.gnu.org/software/gsl/) (if you want to compile Markov-Switching SBVAR code)
- A decent LaTeX distribution (if you want to compile PDF documentation),
ideally with Beamer
- For building the reference manual:
- [Sphinx](https://www.sphinx-doc.org/)
- [MathJax](https://www.mathjax.org/)
- [Doxygen](https://www.doxygen.nl) (if you want to build Dynare preprocessor source documentation)
- [X-13ARIMA-SEATS Seasonal Adjustment Program](https://www.census.gov/data/software/x13as.html)
### Preparing the sources
@ -96,69 +98,99 @@ have the [Git LFS](https://git-lfs.github.com/) extension installed):
```sh
git clone --recurse-submodules https://git.dynare.org/Dynare/dynare.git
cd dynare
autoreconf -si
```
If you want a certain version (e.g. 5.x) , then add `--single-branch --branch 5.x` to the git clone command.
The last line runs Autoconf and Automake in order to prepare the build environment (this is not necessary if you got the sources from an official source archive or the source snapshot). If you want a certain version (e.g. 5.x) , then add `--single-branch --branch 5.x` to the git clone command.
### Configuring the build directory
### Configuring the build tree
If you want to compile for MATLAB, please run the following (after adapting the path to MATLAB):
Simply launch the configure script from a terminal:
```sh
meson setup -Dmatlab_path=/usr/local/MATLAB/R2023b -Dbuildtype=debugoptimized build-matlab
./configure --with-matlab=<…>
```
The build directory will thus be `build-matlab`.
where the path to MATLAB is specified.
Or for Octave:
```sh
meson setup -Dbuild_for=octave -Dbuildtype=debugoptimized build-octave
Some important options:
- `--disable-matlab`: skip the compilation of MEX files for MATLAB
- `--disable-octave`: skip the compilation of MEX files for Octave
- `--disable-doc`: skip the compilation of the documentation (PDF and HTML)
You may need to specify additional options to the configure script, see the output of the `--help` option, and also the platform specific instructions below. If the configuration goes well, the script will tell you which components are correctly configured and will be built.
Note that it is possible that some MEX files cannot be compiled, due to missing
build dependencies. If you find no way of installing the missing dependencies,
a workaround can be to give up on compiling these MEX files and rather use
slower implementations (in the MATLAB/Octave language) that are available under
the `matlab/missing/mex/` subdirectories. For example, if you fail to compile
the gensylv MEX, you can type the following at the MATLAB/Octave prompt before
running Dynare:
```matlab
addpath <DYNARE_ROOT>/matlab/missing/mex/gensylv
```
The build directory will thus be `build-octave`.
Note that if you do not chose `build-matlab` (under MATLAB) or `build-octave`
(under Octave) as the build directory, you will need to set the environment
variable `DYNARE_BUILD_DIR` to the full path of your build tree, before running
MATLAB or Octave, if you want Dynare to be able to find the preprocessor and
the MEX files.
It is possible to specify various Meson options, see the Meson documentation
for more details. Modifying options of an existing build directory can be
done using the `meson configure` command.
(where you need to replace `<DYNARE_ROOT>` with the full path to your Dynare copy).
### Building
For compiling the preprocessor and the MEX files:
Binaries are built with:
```sh
meson compile -C <builddir>
make
```
where `<builddir>` is the build directory, typically either `build-matlab` or `build-octave`.
PDF and HTML documentation can be built with:
PDF and HTML documentation are respectively built with:
```sh
meson compile -C <builddir> doc
make pdf
make html
```
### Check
Dynare comes with unit tests (in the MATLAB functions) and integration tests (under the `tests` subfolder). All the tests can be run with:
The Git source comes with unit tests (in the MATLAB functions) and integration tests (under the `tests` subfolder). All the tests can be run with:
```sh
meson test -C <builddir>
make check
```
in the `tests` subfolder. If Dynare has been compiled against MATLAB and Octave, the tests will be run with both MATLAB and Octave. Depending on the performance of your machine, this can take several hours. It is possible to run the tests only with MATLAB:
```sh
make check-matlab
```
or only with Octave:
```sh
make check-octave
```
Depending on the performance of your machine, this can take several hours.
Note that running the testsuite with Octave requires the additional packages `pstoedit`, `epstool`, `xfig`, and `gnuplot`.
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:
A summary of the results is available in `tests/run_test_matlab_output.txt` or `tests/run_test_octave_output.txt`. Often, it does not make sense to run the complete testsuite. For instance, if you modify codes only related to the perfect foresight model solver, you can decide to run only a subset of the integration tests, with:
```sh
meson test -C <builddir> --suite deterministic_simulations
make 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`:
This will run all the integration tests in `tests/deterministic_simulations` with MATLAB and Octave. Again, it is possible to do this only with MATLAB:
```sh
meson test -C <builddir> deterministic_simulations/lbj/rbc.mod
make m/deterministic_simulations
```
NB: Some individual tests cannot be run using that syntax, if they are a dependency in a chain of tests (see the `mod_and_m_tests` variable `meson.build`); in that case, you should use the name of the last `.mod` file in the chain as the test name to be passed to `meson test`.
or with Octave:
```sh
make o/deterministic_simulations
```
Finally if you want to run a single integration test, e.g. `deterministic_simulations/lbj/rbc.mod` with MATLAB:
```sh
make deterministic_simulations/lbj/rbc.m.trs
```
or with Octave:
```sh
make deterministic_simulations/lbj/rbc.o.trs
```
The result of the test (`PASSED` or `FAILED`) will be printed in the terminal, the produced log can be displayed with:
```sh
make deterministic_simulations/lbj/rbc.m.drs
```
or
```sh
make deterministic_simulations/lbj/rbc.o.drs
```
Note that only tests will be executed where the `m.trs/o.trs` does not yet exist. You can run
```sh
make clean
```
in the `tests` folder to delete files that were created by the run of the testsuite. You can also manually delete the desired `m.trs/o.trs` file(s).
## Debian or Ubuntu
@ -167,6 +199,7 @@ All the prerequisites are packaged:
- `gcc`
- `g++`
- `gfortran`
- `make`
- `octave-dev` (or `liboctave-dev` on older Debian/Ubuntu releases)
- `libboost-graph-dev`
- `libgsl-dev`
@ -175,31 +208,39 @@ All the prerequisites are packaged:
- `libsuitesparse-dev`
- `flex` and `libfl-dev`
- `bison`
- `meson`
- `pkgconf`
- `autoconf`
- `automake`
- `texlive`
- `texlive-publishers` (for Econometrica bibliographic style)
- `texlive-latex-extra` (for fullpage.sty)
- `texlive-fonts-extra` (for ccicons)
- `texlive-science` (for amstex)
- `texlive-plain-generic`
- `lmodern` (for macroprocessor PDF)
- `python3-sphinx`
- `tex-gyre`
- `latexmk`
- `libjs-mathjax`
- `doxygen`
- `x13as`
You can install them all at once with:
```sh
apt install gcc g++ gfortran octave-dev libboost-graph-dev libgsl-dev libmatio-dev libslicot-dev libslicot-pic libsuitesparse-dev flex libfl-dev bison meson pkgconf texlive texlive-publishers texlive-latex-extra texlive-fonts-extra texlive-science lmodern python3-sphinx make tex-gyre latexmk libjs-mathjax x13as
apt install gcc g++ gfortran make octave-dev libboost-graph-dev libgsl-dev libmatio-dev libslicot-dev libslicot-pic libsuitesparse-dev flex libfl-dev bison autoconf automake texlive texlive-publishers texlive-latex-extra texlive-fonts-extra texlive-science texlive-plain-generic lmodern python3-sphinx tex-gyre latexmk libjs-mathjax doxygen x13as
```
If you use MATLAB, we strongly advise to also `apt install matlab-support` and confirm to rename the GCC libraries shipped with MATLAB to avoid possible conflicts with GCC libraries shipped by your distribution.
Tested on
- Debian “Buster” 10
- Debian “Bullseye” 11
- Ubuntu 20.04
- Ubuntu 20.10
## Fedora, CentOS or RHEL
Almost all prerequisites are packaged:
- `gcc`, `gcc-c++`
- `gcc`, `gcc-c++`, `make`
- `gcc-gfortran`
- `boost-devel`
- `gsl-devel`
@ -207,23 +248,24 @@ Almost all prerequisites are packaged:
- `suitesparse-devel`
- `flex`
- `bison`
- `meson`
- `autoconf`
- `automake`
- `redhat-rpm-config`
- `octave`, `octave-devel`, `octave-statistics`, `octave-io`, `octave-optim`, `octave-control`
- `texlive-scheme-minimal`, `texlive-collection-publishers`, `texlive-collection-latexextra`, `texlive-collection-fontsextra`, `texlive-collection-latexrecommended`, `texlive-collection-science`, `texlive-collection-plaingeneric`, `texlive-lm`
- `python3-sphinx`
- `latexmk`
- `mathjax`
- `make` (for building Slicot)
- `doxygen`
You can install them all at once with:
```sh
# Minimal packages
dnf install -y gcc gcc-c++ make gcc-gfortran boost-devel gsl-devel matio-devel suitesparse-devel flex bison meson redhat-rpm-config
# Octave packages
# Minimal packages (use --disable-doc and --disable-octave flags)
dnf install -y gcc gcc-c++ make gcc-gfortran boost-devel gsl-devel matio-devel suitesparse-devel flex bison autoconf automake redhat-rpm-config
# Octave packages (use --disable-doc flag)
dnf install octave octave-devel octave-statistics octave-io octave-optim octave-control
# Documentation packages (only needed if you build documentation)
dnf install texlive-scheme-minimal texlive-collection-publishers texlive-collection-latexextra texlive-collection-fontsextra texlive-collection-latexrecommended texlive-collection-science texlive-collection-plaingeneric texlive-lm python3-sphinx latexmk mathjax
# Documentation packages
dnf install texlive-scheme-minimal texlive-collection-publishers texlive-collection-latexextra texlive-collection-fontsextra texlive-collection-latexrecommended texlive-collection-science texlive-collection-plaingeneric texlive-lm python3-sphinx latexmk mathjax doxygen
```
In Fedora these are available from the default repositories; whereas for CentOS and RHEL you need to enable the [Extra Packages for Enterprise Linux (EPEL)](https://fedoraproject.org/wiki/EPEL) repository and either the PowerTools repository for CentOS or the CodeReady Linux Builder repository for RHEL:
```sh
@ -234,7 +276,7 @@ dnf config-manager --set-enabled PowerTools
ARCH=$( /bin/arch )
subscription-manager repos --enable "codeready-builder-for-rhel-8-${ARCH}-rpms"
```
The documentation packages have slightly different names in CentOS and RHEL, but this should only impact you if you build the documentation.
The documentation packages have slightly different names in CentOS and RHEL, you can also choose to pass the `--disable-doc` flag to your configure script to skip these dependencies.
`Slicot` and `x13as` need to be compiled from source:
@ -245,19 +287,16 @@ cd /home/$USER/dynare/slicot
wget https://deb.debian.org/debian/pool/main/s/slicot/slicot_5.0+20101122.orig.tar.gz
tar xf slicot_5.0+20101122.orig.tar.gz
cd slicot-5.0+20101122
mkdir -p /home/$USER/dynare/slicot/lib
# The following two lines are only for MATLAB
make FORTRAN=gfortran OPTS="-O2 -fPIC -fdefault-integer-8" LOADER=gfortran lib
cp slicot.a /home/$USER/dynare/slicot/lib/libslicot64_pic.a
# The following two lines are only for Octave
make FORTRAN=gfortran OPTS="-O2 -fPIC" LOADER=gfortran lib
cp slicot.a /home/$USER/dynare/slicot/lib/libslicot_pic.a
mkdir -p /home/$USER/dynare/slicot/lib
cp slicot.a /home/$USER/dynare/slicot/lib/libslicot64_pic.a #for matlab
cp slicot.a /home/$USER/dynare/slicot/lib/libslicot_pic.a #for octave
# compile x13as from source and put it into /usr/bin/
mkdir -p /home/$USER/dynare/x13as
cd /home/$USER/dynare/x13as
wget https://www2.census.gov/software/x-13arima-seats/x13as/unix-linux/program-archives/x13as_asciisrc-v1-1-b60.tar.gz
tar xf x13as_asciisrc-v1-1-b60.tar.gz
wget https://www2.census.gov/software/x-13arima-seats/x13as/unix-linux/program-archives/x13as_asciisrc-v1-1-b59.tar.gz
tar xf x13as_asciisrc-v1-1-b59.tar.gz
sed -i "s|-static| |" makefile.gf # this removes '-static' in the makefile.gf
make -f makefile.gf FFLAGS="-O2 -std=legacy" PROGRAM=x13as
sudo cp x13as /usr/bin/
@ -265,16 +304,17 @@ sudo cp x13as /usr/bin/
If you use MATLAB, we strongly advise to also rename or exclude the GCC libraries shipped with MATLAB to avoid possible conflicts with GCC libraries shipped by Fedora, see e.g. [Matlab on Fedora 33](https://mutschler.eu/linux/install-guides/fedora-post-install/#matlab) or [MATLAB-ArchWiki](https://wiki.archlinux.org/index.php/MATLAB) for instructions.
Now use the following commands if using MATLAB (adapt them for Octave, see above):
Keep in mind to use the `--with-slicot` option to the configure command, e.g.:
```sh
cd /home/$USER/dynare
git clone --recurse-submodules https://git.dynare.org/dynare/dynare.git unstable
cd unstable
meson setup -Dmatlab_path=/usr/local/MATLAB/R2023b -Dfortran_args="[ '-B', '/home/$USER/dynare/slicot']" -Dbuildtype=debugoptimized build-matlab
meson compile -C build-matlab
autoreconf -si
./configure --with-slicot=/home/$USER/dynare/slicot --with-matlab=/usr/local/MATLAB/R2020b
make -j$(($(nproc)+1)) #rule of thumb: one more than CPUs as shown by e.g. lscpu
```
If your distribution ships an older version of `bison`, compile it from source and append it *temporarily* to your path before running meson:
If your distribution ships an older version of `bison`, compile it from source and append it *temporarily* to your path before calling the configure script:
```sh
bison --version # bison (GNU Bison) 3.0.4
mkdir -p /home/$USER/dynare/bison
@ -290,6 +330,12 @@ bison --version # bison (GNU Bison) 3.6.4
```
Now configure dynare as above.
Tested on
- CentOS 8
- Fedora Workstation 32
- Fedora Workstation 33
- Red Hat Enterprise Linux 8
## Windows
- Install [MSYS2](http://www.msys2.org)
@ -303,9 +349,9 @@ pacman -Syu
window to complete the upgrade.
- Install all needed dependencies:
```sh
pacman -S git bison flex make tar mingw-w64-x86_64-meson mingw-w64-x86_64-gcc mingw-w64-x86_64-gcc-fortran mingw-w64-x86_64-boost mingw-w64-x86_64-gsl mingw-w64-x86_64-matio mingw-w64-x86_64-pkgconf
pacman -S git autoconf automake-wrapper bison flex make tar texinfo mingw-w64-x86_64-gcc mingw-w64-x86_64-gcc-fortran mingw-w64-x86_64-boost mingw-w64-x86_64-gsl mingw-w64-x86_64-matio
```
- Compile and install SLICOT
- Compile and install SLICOT, needed for the `kalman_steady_state` MEX file
```sh
wget https://deb.debian.org/debian/pool/main/s/slicot/slicot_5.0+20101122.orig.tar.gz
tar xf slicot_5.0+20101122.orig.tar.gz
@ -319,10 +365,11 @@ cd ..
```sh
git clone --recurse-submodules https://git.dynare.org/Dynare/dynare.git
cd dynare
autoreconf -si
```
- Configure Dynare from the source directory:
```sh
meson setup -Dmatlab_path=<…> -Dbuildtype=debugoptimized -Dprefer_static=true -Dfortran_args="['-B','/usr/local/lib']" build-matlab
./configure --with-slicot=/usr/local --with-matlab=<…> --disable-octave --disable-doc
```
where the path of MATLAB is specified. Note that you should use
the MSYS2 notation and not put spaces in the MATLAB path, so you probably want
@ -332,11 +379,11 @@ does not have short filenames (8dot3), then you can run `mkdir -p
then pass `/usr/local/MATLAB/…` as MATLAB path to the configure script.
- Compile:
```sh
meson compile -C build-matlab
make
```
- Run the testsuite:
```sh
meson test -C build-matlab
make -C tests check-matlab
```
**Note:** The above assumes that you have a 64-bit version of MATLAB. It can be
@ -406,29 +453,29 @@ export PATH="$BREWDIR/bin:$PATH"
```
- Install required Homebrew packages:
- Install required Homebrew packages and link sphinx-doc:
```sh
arch -$ARCH $BREWDIR/bin/brew install meson bison flex boost gcc gsl libmatio veclibfort octave sphinx-doc docutils wget pkg-config git-lfs
arch -$ARCH $BREWDIR/bin/brew install automake bison flex boost gcc gsl libmatio veclibfort octave sphinx-doc docutils wget
```
If you are installing `git-lfs` for the first time, you need to run `git lfs install` once after installing it.
- Link the sphinx-doc package to be able to compile the documentation:
If you want to compile the documentation, you need to link sphinx-doc:
```sh
arch -$ARCH $BREWDIR/bin/brew link --force sphinx-doc
```
Otherwise add `--disable-doc` flag to the `configure` command below, if you want to skip this.
- Install [MacTeX](http://www.tug.org/mactex/index.html) using the universal installer, if you want to build the documentation. MacTeX runs natively on both ARM and Intel machines. On Apple Silicon, it is advised to symlink `pdflatex`, `bibtex` and `latexmk` into `/usr/local/bin`:
- Install [MacTeX](http://www.tug.org/mactex/index.html) using the universal installer. MacTeX runs natively on both ARM and Intel machines. On Apple Silicon, it is advised to symlink `pdflatex` and `bibtex` into `/usr/local/bin`:
```sh
sudo ln -s /Library/TeX/texbin/pdflatex /usr/local/bin/pdflatex
sudo ln -s /Library/TeX/texbin/bibtex /usr/local/bin/bibtex
sudo ln -s /Library/TeX/texbin/latexmk /usr/local/bin/latexmk
```
If you don't have admin privileges, then you can also symlink them into `$HOME/.local/bin` and add this folder to your PATH.
Alternatively, if you dont want to install MacTeX, you should pass the `--disable-doc` flag to the `configure` command below.
- Install MATLAB and additional toolboxes.
We recommend, but don't require, the following: Optimization, Global Optimization, Statistics and Machine Learning, Econometrics, and Control System.
For Apple Silicon: MATLAB offers a native Apple silicon version (arm64) as of version R2023b, see [the official instructions](https://de.mathworks.com/support/requirements/apple-silicon.html) how to install it.
You can also run the Intel version (x86_64) under Rosetta 2.
For Apple Silicon: MATLAB offers a native Apple silicon version of R2022b as an open beta. You can sign up and install it (including a suitable Java 8 JRE, e.g. Amazon Corretto 8) using
[the official instructions](https://de.mathworks.com/support/apple-silicon-r2022b-beta.html).
Unfortunately, this version does not support yet the Optimization, Global Optimization and Econometrics toolboxes.
If you need these, please run the Intel version (under Rosetta 2) instead.
Don't forget to run MATLAB at least once to make sure you have a valid license.
- Create a folder for Dynare and its dependencies
@ -436,7 +483,7 @@ Don't forget to run MATLAB at least once to make sure you have a valid license.
export DYNAREDIR=$HOME/dynare
```
- Compile and install SLICOT
- Compile and install SLICOT, needed for e.g. the `kalman_steady_state` MEX file.
```sh
mkdir -p $DYNAREDIR/slicot/lib
cd $DYNAREDIR/slicot
@ -448,21 +495,22 @@ cp slicot.a $DYNAREDIR/slicot/lib/libslicot_pic.a
make clean
make -j$(sysctl -n hw.ncpu) FORTRAN=$BREWDIR/bin/gfortran OPTS="-O2 -fdefault-integer-8" LOADER=gfortran lib
cp slicot.a $DYNAREDIR/slicot/lib/libslicot64_pic.a
cd $HOME/dynare
```
- Compile and install the X-13ARIMA-SEATS Seasonal Adjustment Program
```sh
mkdir -p $DYNAREDIR/x13as
cd $DYNAREDIR/x13as
curl -O https://www2.census.gov/software/x-13arima-seats/x13as/unix-linux/program-archives/x13as_asciisrc-v1-1-b60.tar.gz
tar xf x13as_asciisrc-v1-1-b60.tar.gz
curl -O https://www2.census.gov/software/x-13arima-seats/x13as/unix-linux/program-archives/x13as_asciisrc-v1-1-b59.tar.gz
tar xf x13as_asciisrc-v1-1-b59.tar.gz
sed -i '' 's/-static//g' makefile.gf
make -j$(sysctl -n hw.ncpu) -f makefile.gf FC=$BREWDIR/bin/gfortran LINKER=$BREWDIR/bin/gcc-13 FFLAGS="-O2 -std=legacy" LDFLAGS=-static-libgcc LIBS="$BREWDIR/lib/gcc/current/libgfortran.a /$BREWDIR/lib/gcc/current/libquadmath.a" PROGRAM=x13as
sudo cp $DYNAREDIR/x13as/x13as /usr/local/bin/x13as
cd $DYNAREDIR
mkdir -p $HOME/.local/bin
cp x13as $HOME/.local/bin/x13as
cd ;
x13as
```
Alternatively, if you don't have admin privileges you can install it into `$HOME/.local/bin` and add this folder to your PATH.
### Compile Dynare from source
The following commands will download the Dynare source code and compile
@ -471,48 +519,48 @@ folder where you want Dynare installed.
- Prepare the Dynare sources for the unstable version:
```sh
mkdir -p $DYNAREDIR/unstable
git clone --recurse-submodules https://git.dynare.org/Dynare/dynare.git $DYNAREDIR/unstable
cd $DYNAREDIR/unstable
arch -$ARCH autoreconf -si
```
If you want a certain version (e.g. 5.x) , then add `--single-branch --branch 5.x` to the git clone command.
You can also choose a specific version of Dynare by checking out the corresponding branch or a specific tag with git.
- Configure Dynare from the source directory:
```sh
export BUILDDIR=build-matlab
export MATLABPATH=/Applications/MATLAB_R2023b.app
arch -$ARCH meson setup --native-file macOS/homebrew-native-$ARCH.ini -Dmatlab_path=$MATLABPATH -Dbuildtype=debugoptimized -Dfortran_args="['-B','$DYNAREDIR/slicot/lib']" $BUILDDIR
arch -$ARCH ./configure --prefix=$BREWDIR CC=gcc-13 CXX=g++-13 CPPFLAGS=-I$BREWDIR/include LDFLAGS=-L$BREWDIR/lib LEX=$BREWDIR/opt/flex/bin/flex YACC=$BREWDIR/opt/bison/bin/bison --with-slicot=$DYNAREDIR/slicot --with-matlab=/Applications/MATLAB_R2022b_Beta.app
```
where you need to adapt the path to MATLAB.
Similarly, if you want to compile for Octave, replace the `-Dmatlab_path` option by `-Dbuild_for=octave`, and change the build directory to `build-octave`.
where you need to adapt the path to MATLAB. If you dont have MATLAB, simply replace `--with-matlab=<…>` by `--disable-matlab`.
Similarly, if you don't want to compile for Octave add a `--disable-octave` flag.
Check the output of the command whether Dynare is configured for building everything except the internal docs of Dynare and M2HTML.
- Compile:
```sh
arch -$ARCH meson compile -C $BUILDDIR
arch -$ARCH make -j$(sysctl -n hw.ncpu)
```
If no errors occured, you are done. Dynare is now ready to use.
- If you additionally want to compile the documentation run:
If you additionally want to compile the documentation run:
```sh
arch -$ARCH meson compile -C $BUILDDIR doc
arch -$ARCH make pdf
arch -$ARCH make html
```
- Optionally, run the testsuite:
```sh
arch -$ARCH meson test -C $BUILDDIR --num-processes=$(sysctl -n hw.perflevel0.physicalcpu)
```
where `--num-processes` specifies the number of parallel processes to use for the testsuite (here set to the number of performance cores on your mac).
### Optional: pass the full PATH to MATLAB to run system commands
If you start MATLAB from a terminal, you will get the PATH inherited from the shell.
However, when you click on the application icon in macOS, you are not running at the terminal level:
the program is run by launcher, which does not go through a shell login session.
In other words, you get the system default PATH which includes `/usr/bin:/bin:/usr/sbin:/sbin`, but not `/usr/local/bin` or `$HOME/.local/bin`.
So if you want to use system commands like `pdflatex`, `latexmk` or `x13as` you should either call them by their full path (e.g `/Library/TeX/texbin/pdflatex`)
or append the PATH by running `setenv('PATH', [getenv('PATH') ':/usr/local/bin:$HOME/.local/bin:/Library/TeX/texbin']);` in your MATLAB command line once,
e.g. by adding this to your mod file. Alternatively, you can create a `startup.m` file or change the system default PATH in the `/etc/paths` file.
So if you want to use system commands like `pdflatex` or `x13as` you should either call them by their full path (e.g `/Library/TeX/texbin/pdflatex`)
or append the PATH in MATLAB by running `setenv('PATH', [getenv('PATH') ':/usr/local/bin:$HOME/.local/bin:/Library/TeX/texbin']);`.
Alternatively, you can create a `startup.m` file or change the system default PATH in the `/etc/paths` file.
### Optional: pass the full PATH to MATLAB to run system commands
If you start MATLAB from a terminal, you will get the PATH inherited from the shell.
However, when you click on the application icon in macOS, you are not running at the terminal level:
the program is run by launcher, which does not go through a shell login session.
In other words, you get the system default PATH which includes `/usr/bin:/bin:/usr/sbin:/sbin`, but not `/usr/local/bin` or `$HOME/.local/bin`.
So if you want to use system commands like `pdflatex` or `x13as` you should either call them by their full path (e.g `/Library/TeX/texbin/pdflatex`) or append the PATH in MATLAB by running `setenv('PATH', [getenv('PATH') ':/usr/local/bin:$HOME/.local/bin:/Library/TeX/texbin']);`.
Alternatively, you can create a `startup.m` file or change the system default PATH in the `/etc/paths` file.
## Docker
We offer a variety of pre-configured Docker containers for Dynare, pre-configured with Octave and MATLAB including all recommended toolboxes.
These are readily available for your convenience on [Docker Hub](https://hub.docker.com/r/dynare/dynare).
The `scripts/docker` folder contains [information and instructions](scripts/docker/README.md) to interact, built and customize the containers.
Last tested on:
- macOS Ventura 13.3.1 (MacBook Air M1, MacBook Pro M2 MAX, M2 Virtual Machine using Parallels, Intel Virtual Machine using Quickemu)

1
VERSION.in Normal file
View File

@ -0,0 +1 @@
@PACKAGE_VERSION@

125
configure.ac Normal file
View File

@ -0,0 +1,125 @@
dnl Process this file with autoconf to produce a configure script.
dnl Copyright © 2009-2023 Dynare Team
dnl
dnl This file is part of Dynare.
dnl
dnl Dynare is free software: you can redistribute it and/or modify
dnl it under the terms of the GNU General Public License as published by
dnl the Free Software Foundation, either version 3 of the License, or
dnl (at your option) any later version.
dnl
dnl Dynare is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License
dnl along with Dynare. If not, see <https://www.gnu.org/licenses/>.
AC_PREREQ([2.62])
AC_INIT([dynare], [6-unstable])
AC_CONFIG_SRCDIR([preprocessor/src/DynareMain.cc])
AM_INIT_AUTOMAKE([1.11 -Wall -Wno-portability foreign no-dist-gzip dist-xz tar-pax])
AC_CONFIG_SUBDIRS([preprocessor])
# For setting EXEEXT, needed by top-level Makefile.am
AC_PROG_CC
AX_PROG_LN_S
AC_PROG_MKDIR_P
# Define optional components and their corresponding flags and Automake conditionals
AC_ARG_ENABLE([doc], AS_HELP_STRING([--disable-doc], [disable compilation of documentation]), [], [enable_doc=yes])
AM_CONDITIONAL([ENABLE_DOC], [test "$enable_doc" = yes])
AC_ARG_ENABLE([matlab], AS_HELP_STRING([--disable-matlab], [disable compilation of MEX files for MATLAB]), [], [enable_matlab=yes])
AM_CONDITIONAL([ENABLE_MATLAB], [test "$enable_matlab" = yes])
AC_ARG_ENABLE([octave], AS_HELP_STRING([--disable-octave], [disable compilation of MEX files for Octave]), [], [enable_octave=yes])
AM_CONDITIONAL([ENABLE_OCTAVE], [test "$enable_octave" = yes])
AC_ARG_ENABLE([org-export], AS_HELP_STRING([--enable-org-export], [enable exporting of Org files (requires Emacs, org-mode and other external programs)]))
AM_CONDITIONAL([ENABLE_ORG_EXPORT], [test -n "$enable_org_export"])
# Check utilities needed for documentation
if test "$enable_doc" = yes; then
AC_CHECK_PROG([PDFLATEX], [pdflatex], [pdflatex], [no])
test "$PDFLATEX" = no && AC_MSG_ERROR([pdflatex cannot be found. If you want to skip the compilation of the documentation, pass the --disable-doc flag.])
AC_CHECK_PROG([BIBTEX], [bibtex], [bibtex], [no])
test "$BIBTEX" = no && AC_MSG_ERROR([bibtex cannot be found. If you want to skip the compilation of the documentation, pass the --disable-doc flag.])
AC_CHECK_PROG([SPHINXBUILD], [sphinx-build], [sphinx-build], [no])
test "$SPHINXBUILD" = no && AC_MSG_ERROR([sphinx-build cannot be found. If you want to skip the compilation of the documentation, pass the --disable-doc flag.])
AX_LATEX_CLASS([beamer], [ax_latex_have_beamer], [], [AC_MSG_ERROR([beamer cannot be found. If you want to skip the compilation of the documentation, pass the --disable-doc flag.])])
fi
# Check for MATLAB
if test "$enable_matlab" = yes; then
AC_CONFIG_SUBDIRS([mex/build/matlab])
AX_MATLAB
AX_MATLAB_BATCH_OPTIONS
test "$ax_enable_matlab" != yes && AC_MSG_ERROR([MATLAB cannot be found. If you want to compile Dynare without MATLAB support, pass the --disable-matlab flag.])
fi
# Check for Octave
if test "$enable_octave" = yes; then
AC_CONFIG_SUBDIRS([mex/build/octave])
AX_OCTAVE
test "$ax_enable_octave" != yes && AC_MSG_ERROR([Octave cannot be found. If you want to compile Dynare without Octave support, pass the --disable-octave flag.])
fi
# Construct final output message
if test "$enable_doc" = yes; then
BUILD_DOC="yes"
else
BUILD_DOC="no"
fi
if test -n "$enable_org_export"; then
BUILD_INTERNAL_DOC="yes"
else
BUILD_INTERNAL_DOC="no"
fi
if test "$enable_matlab" = yes; then
TESTSUITE_MATLAB="yes"
else
TESTSUITE_MATLAB="no"
fi
if test "$enable_octave" = yes; then
TESTSUITE_OCTAVE="yes"
else
TESTSUITE_OCTAVE="no"
fi
AC_MSG_NOTICE([
Dynare is now configured for building the following components...
Documentation (with "make html pdf"):
Manual and other documents $BUILD_DOC
Dynare internal doc: $BUILD_INTERNAL_DOC
Testsuites (run with "make check"):
Dynare for MATLAB: $TESTSUITE_MATLAB
Dynare for Octave: $TESTSUITE_OCTAVE
])
AC_CONFIG_FILES([Makefile
VERSION
doc/Makefile
doc/manual/Makefile
doc/manual/utils/version.py
doc/parallel/Makefile
doc/internals/Makefile
doc/gsa/Makefile
doc/dseries-and-reporting/Makefile
tests/Makefile
matlab/dynare_version.m
mex/sources/Makefile
])
AC_OUTPUT

1
contrib/jsonlab Submodule

@ -0,0 +1 @@
Subproject commit 5a58fafdca239e61be4d7b2270307b2445bb571a

@ -1 +1 @@
Subproject commit 391689d9f1bea4bd68ef6641dc2dc4a1bd867850
Subproject commit f1d0fd61ea6d9c4f8694b373780d6c372e344f6e

@ -1 +1 @@
Subproject commit ac6d0ae1b69cda26aa9486188d54c8c010f115c4
Subproject commit 216abedb9ab4df5dd4dca07c721f7c07392801e9

34
doc/Makefile.am Normal file
View File

@ -0,0 +1,34 @@
SUBDIRS = parallel internals gsa dseries-and-reporting
if ENABLE_DOC
SUBDIRS += manual
pdf-local: guide.pdf bvar-a-la-sims.pdf dr.pdf sylvester.pdf tl.pdf
endif
EXTRA_DIST = guide.tex guide.bbl bibmad.sty bvar-a-la-sims.tex dr.tex dr.bib dynare.plots
guide.pdf: guide.tex guide.bbl bibmad.sty
$(PDFLATEX) guide
$(PDFLATEX) guide
bvar-a-la-sims.pdf: bvar-a-la-sims.tex
$(PDFLATEX) bvar-a-la-sims
$(PDFLATEX) bvar-a-la-sims
dr.pdf: dr.tex
$(PDFLATEX) dr
$(BIBTEX) dr
$(PDFLATEX) dr
$(PDFLATEX) dr
sylvester.pdf: sylvester.tex
$(PDFLATEX) sylvester
$(PDFLATEX) sylvester
tl.pdf: tl.tex
$(PDFLATEX) tl
$(PDFLATEX) tl
clean-local:
# Do not delete guide.bbl which is not autogenerated
rm -f *~ *.pdf *.log *.aux *.out *.blg dr.bbl

105
doc/bibmad.sty Normal file
View File

@ -0,0 +1,105 @@
\message{harvard bibliography,}
\def\@hiteml[#1]#2#3#4{\item[]\if@filesw%
{ \def\protect##1{\string ##1\space}\immediate%
\write\@auxout{\string\harvardcite{#4}{#2}{#1}{#3}}}\fi%
\protect\hspace*{-\labelwidth}\protect\hspace*{-\labelsep}\ignorespaces}
\def\@hitem#1#2#3{\item[]\if@filesw%
{ \def\protect##1{\string ##1\space}\immediate%
\write\@auxout{\string\harvardcite{#3}{#1}{#1}{#2}}}\fi%
\protect\hspace*{-\labelwidth}\protect\hspace*{-\labelsep}\ignorespaces}
\def\harvarditem{\@ifnextchar [{\@hiteml}{\@hitem}}
\def\harvardcite#1#2#3#4{
\global\@namedef{bhf@#1}{#2}
\global\@namedef{bha@#1}{#3}
\global\@namedef{bhy@#1}{#4}\global\@namedef{b@#1}{\csname bhf@#1\endcsname}
}
\def\citeasnoun{\@ifnextchar [{\@tempswatrue\@citex}{\@tempswafalse\@citex[]}}
\def\cite{\@ifnextchar [{\@tempswatrue\@citexasnoun}
{\@tempswafalse\@citexasnoun[]}
}
\def\citeyear{\@ifnextchar [{\@tempswatrue\@citexyear}
{\@tempswafalse\@citexyear[]}
}
\def\citename{\@ifnextchar [{\@tempswatrue\@citexname}
{\@tempswafalse\@citexname[]}
}
% \def\@enamedef#1{\expandafter\edef\csname #1\endcsname}
% Previous line should be replaced by the following to prevent
% problems with the NFSS. Solution by Bernd Raichle.
\def\@enamedef#1{\expandafter\def\csname #1\expandafter\endcsname\expandafter}
\def\@citex[#1]#2{\if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi
\def\@citea{}\@cite{\@for\@citeb:=#2\do
{\@citea\def\@citea{\@hisep\penalty\@m\ }\@ifundefined
{b@\@citeb}{{\bf ?}\@warning
{Citation `\@citeb' on page \thepage \space undefined}}%
{{\csname b@\@citeb\endcsname\@hysep\csname bhy@\@citeb\endcsname}%
\global\@enamedef{b@\@citeb}{\csname bha@\@citeb\endcsname}}%
}}{#1}}
\def\@citexasnoun[#1]#2{%
\if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi%
\@citeasnoun{{\@ifundefined%
{b@#2}%
{[{\bf ?}\@warning{Citation `#2' on page \thepage \space undefined}}%
{{\csname b@#2\endcsname\ [\csname bhy@#2\endcsname}%
\global\@namedef{b@#2}{\csname bha@#2\endcsname}}%
}}{#1}}
\def\@citexname[#1]#2{%
\if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi%
\@citename{{\@ifundefined%
{b@#2}%
{{\bf ?}\@warning{Citation `#2' on page \thepage \space undefined}}%
{{\csname bhf@#2\endcsname}}%
}}{#1}}
\def\@citexyear[#1]#2{\if@filesw\immediate\write\@auxout{\string\citation{#2}}\fi
\def\@citeayear{}\@cite{\@for\@citebyear:=#2\do
{\@citeayear\def\@citeayear{\@hisep\penalty\@m\ }\@ifundefined
{b@\@citebyear}{{\bf ?}\@warning
{Citation `\@citebyear' on page \thepage \space undefined}}%
{{\csname bhy@\@citebyear\endcsname}%
}%
}}{#1}}
\gdef\hysep@agsm{\ }\gdef\hisep@agsm{,}%
\gdef\hysep@dcu{, }\gdef\hisep@dcu{;}%
\let\@hysep\hysep@agsm \let\@hisep\hisep@agsm
\def\citationstyle#1{%
\global\@namedef{@hysep}{\csname hysep@#1\endcsname}%
\global\@namedef{@hisep}{\csname hisep@#1\endcsname}}
%DEFAULT DEFINITIONS
\def\@cite#1#2{({#1\if@tempswa , #2\fi})}
\def\@citeasnoun#1#2{{#1\if@tempswa , #2\fi]}}
\def\@citename#1#2{{#1\if@tempswa \ (#2)\fi}}
% CHANGE \end{document} - to handle double definitions
\def\enddocument{\@checkend{document}\clearpage\begingroup
\if@filesw \immediate\closeout\@mainaux
\def\global\@namedef##1##2{}\def\newlabel{\@testdef r}%
\def\bibcite{\@testdef b}%
\def\harvardcite{\@testbibh}\@tempswafalse \makeatletter\input \jobname.aux
\if@tempswa \@warning{Label(s) may have changed. Rerun to get
cross-references right}\fi\fi\endgroup\deadcycles\z@\@@end}
\def\@testbibh #1#2#3{
\def\@tempa{#2}\expandafter
\ifx \csname bhf@#1\endcsname \@tempa
\def\@tempa{#3}\expandafter
\ifx \csname bha@#1\endcsname \@tempa
\else \@tempswatrue
\fi
\else
\@tempswatrue
\fi
}
%

View File

@ -0,0 +1,14 @@
if ENABLE_DOC
pdf-local: dseriesReporting.pdf
endif
SRC = dseriesReporting.tex
EXTRA_DIST = $(SRC)
dseriesReporting.pdf: $(SRC)
$(PDFLATEX) dseriesReporting
$(PDFLATEX) dseriesReporting
clean-local:
rm -f dseriesReporting.pdf *.toc *.aux *.log *.nav *.snm *.vrb *.out *~

16
doc/gsa/Makefile.am Normal file
View File

@ -0,0 +1,16 @@
if ENABLE_DOC
pdf-local: gsa.pdf
endif
SRC = gsa.tex marco.bib
EXTRA_DIST = $(SRC)
gsa.pdf: $(SRC)
$(PDFLATEX) gsa
$(BIBTEX) gsa
$(PDFLATEX) gsa
$(PDFLATEX) gsa
clean-local:
rm -f *.pdf *.log *.aux *.toc *.lof *.blg *.bbl *.out *~

View File

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

16
doc/guide.bbl Normal file
View File

@ -0,0 +1,16 @@
\ifx\undefined\bysame
\newcommand{\bysame}{\leavevmode\hbox to\leftmargin{\hrulefill\,\,}}
\fi
\begin{thebibliography}{xx}
\harvarditem[Collard and Juillard]{Collard and Juillard}{2001}{COLL/JUIL/01a}
{ Collard, F. and M.~Juillard}, Accuracy of stochastic perturbation methods:
The case of asset pricing models, {\it Journal of Economic Dynamics and
Control}, 2001, {\it 25}, 979--999.
\harvarditem[Schmitt-Grohe and Uribe]{Schmitt-Grohe and Uribe}{2002}{SGU/02}
{ Schmitt-Grohe, S. and M.~Uribe}, {\it Solving Dynamic General Equilibrium
Models Using a Second-Order Approximation to the Policy Function}, technical
working paper, Rutgers Univsersity 2002.
\end{thebibliography}

View File

@ -0,0 +1,9 @@
EXTRA_DIST = dynare-internals.org
if ENABLE_ORG_EXPORT
html-local:
emacs --batch --visit=dynare-internals.org --funcall org-html-export-to-html
endif
clean-local:
rm -rf *.html ltxpng

View File

@ -2,6 +2,7 @@ function build_internal_documentation()
% The name of the function should be explicit...
datafiles = [];
datafiles = [ datafiles ; {'../../matlab/utilities/dataset'}, {'initialize_dataset'}];
datafiles = [ datafiles ; {'../../matlab/utilities/dataset'}, {'descriptive_statistics'}];
datafiles = [ datafiles ; {'../../matlab/utilities/dataset'}, {'compute_stdv'}];
datafiles = [ datafiles ; {'../../matlab/utilities/dataset'}, {'compute_cova'}];
@ -80,4 +81,4 @@ if rows(miscfiles)
fprintf(fid,'\n\n\n');
end
end
fclose(fid);
fclose(fid);

19
doc/manual/Makefile.am Normal file
View File

@ -0,0 +1,19 @@
EXTRA_DIST = source \
utils/dynare_dom.py \
utils/dynare_lex.py
SRC = $(wildcard source/*.rst)
html-local: build/html/index.html
build/html/index.html: $(SRC) source/conf.py
$(SPHINXBUILD) -M html source build
pdf-local: build/latex/dynare-manual.pdf
build/latex/dynare-manual.pdf: $(SRC) source/conf.py
$(SPHINXBUILD) -M latexpdf source build
clean-local:
rm -rf build
rm -rf utils/__pycache__

View File

@ -0,0 +1 @@
/usr/share/javascript/mathjax/

View File

@ -13,23 +13,20 @@ Bibliography
* Andrews, Donald W.K (1991): “Heteroskedasticity and autocorrelation consistent covariance matrix estimation”, *Econometrica*, 59(3), 817858.
* Backus, David K., Patrick J. Kehoe, and Finn E. Kydland (1992): “International Real Business Cycles,” *Journal of Political Economy*, 100(4), 745775.
* Baxter, Marianne and Robert G. King (1999): “Measuring Business Cycles: Approximate Band-pass Filters for Economic Time Series,” *Review of Economics and Statistics*, 81(4), 575593.
* 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.
* Christiano, Lawrence J., Martin Eichenbaum and Charles L. Evans (2005): “Nominal Rigidities and the Dynamic Effects of a Shock to Monetary Policy,” *Journal of Political Economy*, 113(1), 145.
* Christiano, Lawrence J., Mathias Trabandt, and Karl Walentin (2010): “DSGE Models for Monetary Policy Analysis,” In: *Handbook of Monetary Economics 3*, 285367.
* Christiano, Lawrence J., Mathias Trabandt and Karl Walentin (2011): “Introducing financial frictions and unemployment into a small open economy model,” *Journal of Economic Dynamics and Control*, 35(12), 19992041.
* Christoffel, Kai, Günter Coenen and Anders Warne (2010): “Forecasting with DSGE models,” *ECB Working Paper Series*, 1185.
* Collard, Fabrice (2001): “Stochastic simulations with Dynare: A practical guide”.
* Collard, Fabrice and Michel Juillard (2001a): “Accuracy of stochastic perturbation methods: The case of asset pricing models,” *Journal of Economic Dynamics and Control*, 25, 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 +46,6 @@ 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 (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-2024 Dynare Team
# Copyright © 2018-2022 Dynare Team
#
# This file is part of Dynare.
#
@ -31,14 +31,20 @@ templates_path = ['_templates']
html_static_path = ['_static']
mathjax_path = 'mathjax/MathJax.js?config=TeX-AMS-MML_HTMLorMML'
master_doc = 'index'
project = u'Dynare'
copyright = u'19962024 Dynare Team'
copyright = u'19962022 Dynare Team'
author = u'Dynare Team'
add_function_parentheses = False
# See ../utils/version.py, which is generated by autoconf
from version import version
from version import release
language = 'en'
exclude_patterns = []
@ -71,11 +77,12 @@ latex_elements = {
warningBorderColor={RGB}{255,50,50},OuterLinkColor={RGB}{34,139,34}, \
InnerLinkColor={RGB}{51,51,255},TitleColor={RGB}{51,51,255}',
'papersize': 'a4paper',
'preamble': r'\DeclareUnicodeCharacter{200B}{}', # Part of the workaround for #1707
}
latex_documents = [
(master_doc, 'dynare-manual.tex', u'Dynare Reference Manual',
u'Dynare Team', 'manual'),
u'Dynare team', 'manual'),
]
man_pages = [

View File

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

View File

@ -5,13 +5,13 @@ Currently the development team of Dynare is composed of:
* Stéphane Adjemian (Le Mans Université, Gains)
* Michel Juillard (Banque de France)
* Sumudu Kankanamge (Le Mans Université and CEPREMAP)
* Sumudu Kankanamge (Toulouse School of Economics and CEPREMAP)
* Frédéric Karamé (Le Mans Université, Gains and CEPREMAP)
* Junior Maih (Norges Bank)
* Willi Mutschler (University of Tübingen)
* Johannes Pfeifer (University of the Bundeswehr Munich)
* Marco Ratto (European Commission, Joint Research Centre - JRC)
* Normann Rion (CEPREMAP)
* Normann Rion (CY Cergy Paris Université and CEPREMAP)
* Sébastien Villemot (CEPREMAP)
The following people used to be members of the team:
@ -26,7 +26,7 @@ The following people used to be members of the team:
* Ferhat Mihoubi
* George Perendia
Copyright © 1996-2024, Dynare Team.
Copyright © 1996-2023, Dynare Team.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.

View File

@ -8,14 +8,14 @@ Software requirements
=====================
Packaged versions of Dynare are available for Windows (10 and 11), several
GNU/Linux distributions (Debian, Ubuntu, Linux Mint, Arch Linux), macOS (13
Ventura), and FreeBSD. Dynare should work on other systems, but some
GNU/Linux distributions (Debian, Ubuntu, Linux Mint, Arch Linux), macOS (12
“Monterey”), and FreeBSD. Dynare should work on other systems, but some
compilation steps are necessary in that case.
In order to run Dynare, you need one of the following:
* MATLAB, any version ranging from 9.5 (R2018b) to 23.2 (R2023b);
* GNU Octave, any version ranging from 7.1.0 to 8.4.0, with the ``statistics`` package
* MATLAB, any version ranging from 8.3 (R2014a) to 9.14 (R2023a);
* GNU Octave, any version ranging from 6.2.0 to 8.2.0, with the statistics package
from `Octave-Forge`_. Note however that the Dynare installer for Windows
requires a more specific version of Octave, as indicated on the download
page.
@ -26,8 +26,8 @@ extra features, but are in no way required:
* If under MATLAB: the Optimization Toolbox, the Statistics Toolbox,
the Control System Toolbox;
* If under Octave, the following `Octave-Forge`_ packages: ``optim``, ``io``,
``control``.
* If under Octave, the following `Octave-Forge`_ packages: ``optim, io,
control``.
Installation of Dynare
@ -95,23 +95,29 @@ With MATLAB
^^^^^^^^^^^
To install Dynare for use with MATLAB, execute the automated installer called
``dynare-x.y-arch.pkg`` (where *x.y* is the version number and *arch* is either arm64 for Apple Silicon or x86_64 for Intel architectures),
and follow the instructions.
This installation does not require administrative privileges.
If for some reason admin rights are requested, use *Change Install Location* and select *Install for me only*.
The default installation directory is ``/Applications/Dynare/x.y-arch``.
Installing into ``/Applications/dynare`` might fail if you have older versions of Dynare already installed in ``/Applications/Dynare``.
To fix this, modify the ownership by executing the following command in Terminal.app::
``dynare-x.y.pkg`` (where *x.y* is the version number), and follow the
instructions. The default installation directory is
``/Applications/Dynare/x.y``. After installation, this directory will contain
several sub-directories, among which are ``matlab``, ``mex``, and ``doc``.
sudo chown -R "$USER":staff /Applications/Dynare
Note that several versions of Dynare can coexist (by default in
``/Applications/Dynare``), as long as you correctly adjust your path
settings (see :ref:`words-warning`).
Alternatively, you can modify the installation path in the automated installed using *Customize* and *Location*.
After installation, the folder will contain several sub-directories, among which are ``matlab``, ``mex``, and ``doc``.
Several versions of Dynare can coexist (by default in ``/Applications/Dynare``),
as long as you correctly adjust your path settings (see :ref:`words-warning`).
By default, the installer installs a version of GCC (for use with :opt:`use_dll`)
in the installation directory, under the ``.brew`` folder. To do so, it also
installs a version of Homebrew_ in the same folder and
Xcode Command Line Tools (this is an Apple product) in a system folder.
It is recommended to install the Xcode Command Line Tools (this is an Apple product)
and GCC via Homebrew_ (see :ref:`prerequisites-macos`).
All of this requires a bit of time and hard disk space. The amount of time it
takes will depend on your computing power and internet connection. To reduce
the time the Dynare installer takes, you can install Xcode Command Line Tools
yourself (see :ref:`prerequisites-macos`). Dynare, Homebrew, and GCC use
about 600 MB of disk space while the Xcode Command Line Tools require about 400
MB.
If you do not use the :opt:`use_dll` option, you have the choice to forgo the
installation of GCC and hence Dynare will only take about 50 MB of disk space.
With Octave
^^^^^^^^^^^
@ -186,26 +192,8 @@ Dynare now ships a compilation environment that can be used with the
:opt:`use_dll` option. To install this environment correctly, the Dynare
installer ensures that the Xcode Command Line Tools (an Apple product) have
been installed on a system folder. To install the Xcode Command Line Tools
yourself, simply type ``xcode-select --install`` into the terminal
yourself, simply type ``xcode-select --install`` into the Terminal
(``/Applications/Utilities/Terminal.app``) prompt.
Additionally, to make MATLAB aware that you agree to the terms of Xcode, run the following two commands in the Terminal prompt::
CLT_VERSION=$(pkgutil --pkg-info=com.apple.pkg.CLTools_Executables | grep version | awk '{print $2}' | cut -d'.' -f1-2)
defaults write com.apple.dt.Xcode IDEXcodeVersionForAgreedToGMLicense "${CLT_VERSION}"
defaults read com.apple.dt.Xcode IDEXcodeVersionForAgreedToGMLicense
Otherwise you will see a warning that Xcode is installed, but its license has not been accepted.
You can check this e.g. by running the following command in the MATLAB command window::
mex -setup
Moreover, we recommend making use of optimized compilation flags when using :opt:`use_dll` and for this you need to install GCC via Homebrew_::
brew install gcc
If you already have installed GCC, Dynare will automatically prefer it for :opt:`use_dll`
if the binaries are either in ``/opt/homebrew/bin`` on Apple Silicon (arm64) or in ``/usr/local/bin`` on Intel (x86_64) systems.
Otherwise, it will fall back to Clang in ``/usr/bin/clang``, which works both on arm64 and x86_64 systems.
With Octave
^^^^^^^^^^^

View File

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

View File

@ -204,7 +204,7 @@ by the ``dynare`` command.
.. option:: params_derivs_order=0|1|2
When :comm:`identification`, :comm:`dynare_sensitivity` (with
identification), or :ref:`estimation <estim-comm>` are
identification), or :ref:`estimation_cmd <estim-comm>` are
present, this option is used to limit the order of the
derivatives with respect to the parameters that are calculated
by the preprocessor. 0 means no derivatives, 1 means first
@ -409,11 +409,9 @@ by the ``dynare`` command.
.. option:: fast
Dont rewrite the output files otherwise written to the disk by the preprocessor
when re-running the same model file while the lists of variables and the equations
havent changed. Note that the whole model still needs to be preprocessed. This option
is most useful with model option :opt:`use_dll`, because
the time-consuming compilation of the MEX files will be skipped. We use a 32
Only useful with model option :opt:`use_dll`. Dont recompile the
MEX files when running again the same model file and the lists
of variables and the equations havent changed. We use a 32
bit checksum, stored in ``<model filename>/checksum``. There
is a very small probability that the preprocessor misses a
change in the model. In case of doubt, re-run without the fast
@ -554,7 +552,7 @@ by the ``dynare`` command.
executing the ``dynare`` command will leave variables containing
results in the workspace available for further processing. More
details are given under the relevant computing tasks. The
``M_``, ``oo_``, and ``options_`` structures are saved in a file
``M_``,``oo_``, and ``options_`` structures are saved in a file
called ``FILENAME_results.mat`` located in the ``MODFILENAME/Output`` folder.
If they exist, ``estim_params_``,
``bayestopt_``, ``dataset_``, ``oo_recursive_`` and

View File

@ -15,16 +15,11 @@ related to the model (and hence not placed in the model file). At the
moment, it is only used when using Dynare to run parallel
computations.
On Linux and macOS, the configuration file is searched by default under
``dynare/dynare.ini`` in the configuration directories defined by the XDG
specification (typically ``$HOME/.config/dynare/dynare.ini`` for the
user-specific configuration and ``/etc/xdg/dynare/dynare.ini`` for the
system-wide configuration, the former having precedence over the latter). Under
Windows, the configuration file is searched by default in
``%APPDATA%\dynare\dynare.ini`` (typically
``c:\Users\USERNAME\AppData\Roaming\dynare\dynare.ini``). You can specify a non
standard location using the ``conffile`` option of the ``dynare`` command (see
:ref:`dyn-invoc`).
On Linux and macOS, the default location of the configuration file is
``$HOME/.dynare``, while on Windows it is ``%APPDATA%\dynare.ini``
(typically ``c:\Users\USERNAME\AppData\dynare.ini``). You
can specify a non standard location using the ``conffile`` option of
the ``dynare`` command (see :ref:`dyn-invoc`).
The parsing of the configuration file is case-sensitive and it should
take the following form, with each option/choice pair placed on a
@ -59,7 +54,7 @@ conventions such as ``USER_NAME`` have been excluded for concision):
``PATH_AND_FILE``
Indicates a valid path to a file in the underlying operating
system (e.g. ``/usr/local/MATLAB/R2023b/bin/matlab``).
system (e.g. ``/usr/local/MATLAB/R2010b/bin/matlab``).
``BOOLEAN``
@ -81,15 +76,8 @@ processing. Currently, there is only one option available.
.. option:: GlobalInitFile = PATH_AND_FILE
The location of a global initialization file that can be used to
customize some Dynare internals (typically default option values). This
is a MATLAB/Octave script.
If this option is not specified, Dynare will look for a
``global_init.m`` file in its configuration directory (typically
``$HOME/.config/dynare/global_init.m`` under Linux and macOS, and
``c:\Users\USERNAME\AppData\Roaming\dynare\global_init.m`` under
Windows).
The location of the global initialization file to be run at
the end of ``global_initialization.m``.
*Example*
@ -282,42 +270,20 @@ lines starting with a hashtag (#).
.. option:: MatlabOctavePath = PATH_AND_FILE
The path to the MATLAB or Octave executable. The default value
is ``matlab`` as MATLABs executable is typically in the %PATH% environment
is ``matlab`` as MATLAB's executable is typically in the %PATH% environment
variable. When using full paths on Windows, you may need to enclose the path
in quoted strings, e.g. ``MatlabOctavePath="C:\Program Files\MATLAB\R2023b\bin\matlab.exe"``
in quoted strings, e.g. ``MatlabOctavePath="C:\Program Files\MATLAB\R2023a\bin\matlab.exe"``
.. option:: NumberOfThreadsPerJob = INTEGER
This option controls the distribution of jobs (e.g. MCMC chains) across additional MATLAB instances that are run in parallel.
Needs to be an exact divisor of the number of cores.
The formula :opt:`CPUnbr <CPUnbr = INTEGER | [INTEGER:INTEGER]>` divided by :opt:`NumberOfThreadsPerJob <NumberOfThreadsPerJob = INTEGER>`
calculates the number of MATLAB/Octave instances that will be launched in parallel,
where each instance will then execute a certain number of jobs sequentially.
For example, if you run a MCMC estimation with 24 chains on a 12 core machine, setting ``CPUnbr = 12`` and ``NumberOfThreadsPerJob = 4``
will launch 3 MATLAB instances in parallel, each of which will compute 8 chains sequentially.
Note that this option does not dictate the number of maximum threads utilized by each MATLAB/Octave instance,
see related option :opt:`SingleCompThread <SingleCompThread = BOOLEAN>` for this.
Particularly for very large models, setting this option to 2 might distribute the workload in a
more efficient manner, depending on your hardware and task specifics.
Its advisable to experiment with different values to achieve optimal performance.
The default value is ``1``.
For Windows nodes, sets the number of threads assigned to each
remote MATLAB/Octave run. The default value is 1.
.. option:: SingleCompThread = BOOLEAN
This option allows you to enable or disable MATLABs native multithreading capability. When set to ``true``,
the additional MATLAB instances are initiated in single thread mode utilizing the ``-singleCompThread`` startup option,
thereby disabling MATLABs native multithreading. When set to ``false``, MATLABs native multithreading
is enabled, e.g. the actual number of threads utilized by each MATLAB instance is usually determined by the number of CPU cores
(you can check this by running ``maxNumCompThreads`` in MATLABs command window).
Note: While MATLAB aims to accelerate calculations by distributing them across your computers threads,
certain tasks, like MCMC estimations, may exhibit slowdowns with MATLABs multitasking especially when Dynares parallel computing is turned on
as we do not use MATLABs parallel toolbox.
So in many cases it is advisable to set this setting to ``true``.
If you want to have more control, you can manually add the MATLAB command `maxNumCompThreads(N)` at the beginning of `fParallel.m`.
The default value is ``false``. This option is ineffective under Octave.
Whether or not to disable MATLABs native multithreading. The
default value is ``false``. Option meaningless under Octave.
.. option:: OperatingSystem = OPERATING_SYSTEM
The operating system associated with a node. Only necessary

File diff suppressed because it is too large Load Diff

View File

@ -22,8 +22,6 @@ Dates
=====
.. highlight:: matlab
.. _dates in a mod file:
Dates in a mod file
-------------------
@ -2600,10 +2598,8 @@ The dseries class
.. dseriesmethod:: C = remove (A, B)
remove_ (A, B)
|br| If ``B`` is a row char array, the name of a variable, these methods
are aliases for ``pop`` and ``pop_`` methods with two arguments. They
remove variable ``B`` from ``dseries`` object ``A``. To remove more than
one variable, one can pass a cell of row char arrays for ``B``.
|br| Alias for the ``pop`` method with two arguments. Removes
variable ``B`` from ``dseries`` object ``A``.
*Example*

View File

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

View File

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

View File

@ -0,0 +1,2 @@
version = u'@PACKAGE_VERSION@'
release = u'@PACKAGE_VERSION@'

29
doc/parallel/Makefile.am Normal file
View File

@ -0,0 +1,29 @@
if ENABLE_DOC
pdf-local: parallel.pdf
endif
SRC = AvenueParadigm.pdf iVaNo_gain.pdf iVaNo_time_comp.pdf marco.bib \
netbook_complete_comp.pdf netbook_complete_openclose.pdf \
netbook_partial_comp.pdf netbook_partial_openclose.pdf parallel.tex \
quest_complete_comp.pdf quest_complete_openclose.pdf quest_partial_comp.pdf \
quest_partial_openclose.pdf RWMH_quest1_PriorsAndPosteriors1Comp.pdf \
RWMH_quest1_PriorsAndPosteriors2Comp.pdf \
RWMH_quest1_PriorsAndPosteriors3Comp.pdf \
RWMH_quest1_PriorsAndPosteriors4Comp.pdf \
RWMH_quest1_PriorsAndPosteriors5Comp.pdf \
RWMH_quest1_PriorsAndPosteriors6Comp.pdf \
RWMH_quest1_PriorsAndPosteriors7Comp.pdf waitbars1.pdf waitbars2.pdf \
waitbarsP.pdf
EXTRA_DIST = $(SRC)
parallel.pdf: $(SRC)
$(PDFLATEX) parallel
$(BIBTEX) parallel
$(PDFLATEX) parallel
$(PDFLATEX) parallel
$(PDFLATEX) parallel
clean-local:
rm -f *.log *.aux *.toc *.blg *.bbl *.out
rm -f parallel.pdf

File diff suppressed because it is too large Load Diff

View File

@ -20,7 +20,7 @@
*/
/*
* Copyright © 2021-2023 Dynare Team
* Copyright © 2021 Dynare Team
*
* This file is part of Dynare.
*
@ -147,13 +147,13 @@ end;
varobs yhat;
% Run prior function to get prior slope of the PC based on independent priors
hh_fig=figure('Name','Slope of the Phillips Curve');
hh=figure('Name','Slope of the Phillips Curve');
prior_function(function='Gali_2015_PC_slope');
PC_slope_vec=cell2mat(oo_.prior_function_results(:,1));
optimal_bandwidth = mh_optimal_bandwidth(PC_slope_vec,length(PC_slope_vec),0,'gaussian');
[density(:,1),density(:,2)] = kernel_density_estimate(PC_slope_vec,512,length(PC_slope_vec),optimal_bandwidth,'gaussian');
figure(hh_fig)
figure(hh)
subplot(3,1,1)
plot(density(:,1),density(:,2));
title('Prior')
@ -165,7 +165,7 @@ posterior_function(function='Gali_2015_PC_slope');
PC_slope_vec=cell2mat(oo_.posterior_function_results(:,1));
optimal_bandwidth = mh_optimal_bandwidth(PC_slope_vec,length(PC_slope_vec),0,'gaussian');
[density(:,1),density(:,2)] = kernel_density_estimate(PC_slope_vec,512,length(PC_slope_vec),optimal_bandwidth,'gaussian');
figure(hh_fig)
figure(hh)
subplot(3,1,2)
plot(density(:,1),density(:,2));
title('Updated Prior')
@ -178,7 +178,7 @@ posterior_function(function='Gali_2015_PC_slope');
PC_slope_vec=cell2mat(oo_.posterior_function_results(:,1));
optimal_bandwidth = mh_optimal_bandwidth(PC_slope_vec,length(PC_slope_vec),0,'gaussian');
[density(:,1),density(:,2)] = kernel_density_estimate(PC_slope_vec,512,length(PC_slope_vec),optimal_bandwidth,'gaussian');
figure(hh_fig)
figure(hh)
subplot(3,1,3)
plot(density(:,1),density(:,2));
title('Posterior')

View File

@ -1,12 +1,12 @@
function log_prior_val=Gali_2015_prior_restrictions(M_, dr, endo_steady_state, exo_steady_state, exo_det_steady_state, options_, dataset_, dataset_info);
% function prior_val=Gali_2015_prior_restrictions(M_, dr, endo_steady_state, exo_steady_state, exo_det_steady_state, options_, dataset_, dataset_info);
function log_prior_val=Gali_2015_prior_restrictions(M_, oo_, options_, dataset_, dataset_info);
% function prior_val=Gali_2015_prior_restrictions(M_, oo_, options_, dataset_, dataset_info);
% Example of a _prior_restrictions-file automatically called during
% estimation
% It imposes a prior of the slope of the New Keynesian Phillips Curve of
% 0.03. As the slope is a composite of other parameters with independent
% priors, a separate function is required to do this.
% Copyright © 2021-2023 Dynare Team
% Copyright © 2021 Dynare Team
%
% This file is part of Dynare.
%

View File

@ -26,17 +26,13 @@
* The model is written in the beginning of period stock notation. To make the model
* conform with Dynares end of period stock notation, we use the
* predetermined_variables-command.
*
* The model has been implemented in detrended form, i.e. the \mu_{i,t} are actually
* the the growth rates of the original \mu_{i,t}^{orig} in the paper, i.e.
* log(\mu_{i,t})=log(\mu_{i,t}^{orig}/\mu_{i,t-1}^{orig})
*
*
* Please note that the following copyright notice only applies to this Dynare
* implementation of the model.
*/
/*
* Copyright © 2013-2023 Dynare Team
* Copyright © 2013-2020 Dynare Team
*
* This file is part of Dynare.
*
@ -155,12 +151,12 @@ gammmaPI =1.29;
PIbar = 1.01;
rhod = 0.12;
rhophi = 0.93;
sigma_A = exp(-3.97);
sigma_d = exp(-1.51);
sigma_A = -3.97;
sigma_d = -1.51;
sigma_phi =exp(-2.36);
sigma_mu =exp(-5.43);
sigma_m =exp(-5.85);
sigma_phi =-2.36;
sigma_mu =-5.43;
sigma_m =-5.85;
Lambdamu=3.4e-3;
LambdaA = 2.8e-3;
@ -218,7 +214,7 @@ mc=(1/(1-alppha))^(1-alppha)*(1/alppha)^alppha*w^(1-alppha)*r^alppha;
1=thetap*(PI(-1)^chi/PI)^(1-epsilon)+(1-thetap)*PIstar^(1-epsilon);
[name='Taylor Rule']
R/Rbar=(R(-1)/Rbar)^gammmaR*((PI/PIbar)^gammmaPI*((yd/yd(-1)*mu_z)/exp(LambdaYd))^gammmay)^(1-gammmaR)*exp(sigma_m*epsm);
R/Rbar=(R(-1)/Rbar)^gammmaR*((PI/PIbar)^gammmaPI*((yd/yd(-1)*mu_z)/exp(LambdaYd))^gammmay)^(1-gammmaR)*exp(epsm);
[name='Resource constraint']
yd=c+x+mu_z^(-1)*mu_I^(-1)*(gammma1*(u-1)+gammma2/2*(u-1)^2)*k;
@ -239,24 +235,24 @@ PIstarw=wstar/w;
//exogenous processes
[name='Preference Shock']
log(d)=rhod*log(d(-1))+sigma_d*epsd;
log(d)=rhod*log(d(-1))+epsd;
[name='Labor disutility Shock']
log(phi)=rhophi*log(phi(-1))+sigma_phi*epsphi;
log(phi)=rhophi*log(phi(-1))+epsphi;
[name='Investment specific technology']
log(mu_I)=Lambdamu+sigma_mu*epsmu_I;
log(mu_I)=Lambdamu+epsmu_I;
[name='Neutral technology']
log(mu_A)=LambdaA+sigma_A*epsA;
log(mu_A)=LambdaA+epsA;
[name='Defininition composite technology']
mu_z=mu_A^(1/(1-alppha))*mu_I^(alppha/(1-alppha));
end;
shocks;
var epsd; stderr 1;
var epsphi; stderr 1;
var epsmu_I; stderr 1;
var epsA; stderr 1;
var epsm; stderr 1;
var epsd; stderr exp(sigma_d);
var epsphi; stderr exp(sigma_phi);
var epsmu_I; stderr exp(sigma_mu);
var epsA; stderr exp(sigma_A);
var epsm; stderr exp(sigma_m);
end;
steady;

View File

@ -0,0 +1,6 @@
Assuming that the dynare++ binary is in your PATH, you can run the example by using the following command
in a Command Prompt Window:
... > dynare++ example1.mod
Please, read the manual (doc\dynare++\dynare++-tutorial.pdf) for a description of the generated output.

View File

@ -0,0 +1,45 @@
/*
* This Dynare++ mod-file implements the RBC model with time-to-build
* described in Kamenik (2011): "DSGE Models with Dynare++. A Tutorial."
* Note that Dynare++ uses the same stock-at-the-end-of-period timing convention
* as the regular Dynare
*/
var Y, C, K, A, H, B;
varexo EPS, NU;
parameters beta, rho, alpha, delta, theta, psi, tau;
alpha = 0.36;
rho = 0.95;
tau = 0.025;
beta = 1/(1.03^0.25);
delta = 0.025;
psi = 0;
theta = 2.95;
model;
C*theta*H^(1+psi) = (1-alpha)*Y;
beta*exp(B)*C/exp(B(1))/C(1)*
(exp(B(1))*alpha*Y(1)/K(1)+1-delta) = 1;
Y = exp(A)*K^alpha*H^(1-alpha);
K = exp(B(-1))*(Y(-1)-C(-1)) + (1-delta)*K(-1);
A = rho*A(-1) + tau*B(-1) + EPS;
B = tau*A(-1) + rho*B(-1) + NU;
end;
initval;
A = 0;
B = 0;
H = ((1-alpha)/(theta*(1-(delta*alpha)/(1/beta-1+delta))))^(1/(1+psi));
Y = (alpha/(1/beta-1+delta))^(alpha/(1-alpha))*H;
K = alpha/(1/beta-1+delta)*Y;
C = Y - delta*K;
end;
vcov = [0.0002 0.00005;
0.00005 0.0001
];
order = 7;

View File

@ -1,22 +1,22 @@
/*
* This file replicates the estimation of the cash in advance model (termed M1
* in the paper) described in Frank Schorfheide (2000): "Loss function-based
* This file replicates the estimation of the cash in advance model (termed M1
* in the paper) described in Frank Schorfheide (2000): "Loss function-based
* evaluation of DSGE models", Journal of Applied Econometrics, 15(6), 645-670.
*
* The data are taken from the replication package at
* http://dx.doi.org/10.15456/jae.2022314.0708799949
* The data are in file "fsdat_simul.m", and have been artificially generated.
* They are therefore different from the original dataset used by Schorfheide.
*
* The prior distribution follows the one originally specified in Schorfheide's
* paper. Note that the elicited beta prior for rho in the paper
* paper, except for parameter rho. In the paper, the elicited beta prior for rho
* implies an asymptote and corresponding prior mode at 0. It is generally
* recommended to avoid this extreme type of prior.
*
* Because the data are already logged and we use the loglinear option to conduct
* a full log-linearization, we need to use the logdata option.
* recommended to avoid this extreme type of prior. Some optimizers, for instance
* mode_compute=12 (Mathworks' particleswarm algorithm) may find a posterior mode
* with rho equal to zero. We lowered the value of the prior standard deviation
* (changing .223 to .100) to remove the asymptote.
*
* The equations are taken from J. Nason and T. Cogley (1994): "Testing the
* implications of long-run neutrality for monetary business cycle models",
* Journal of Applied Econometrics, 9, S37-S70, NC in the following.
* Journal of Applied Econometrics, 9, S37-S70.
* Note that there is an initial minus sign missing in equation (A1), p. S63.
*
* This implementation was originally written by Michel Juillard. Please note that the
@ -25,7 +25,7 @@
*/
/*
* Copyright © 2004-2023 Dynare Team
* Copyright © 2004-2017 Dynare Team
*
* This file is part of Dynare.
*
@ -43,71 +43,33 @@
* along with Dynare. If not, see <https://www.gnu.org/licenses/>.
*/
var m ${m}$ (long_name='money growth')
P ${P}$ (long_name='Price level')
c ${c}$ (long_name='consumption')
e ${e}$ (long_name='capital stock')
W ${W}$ (long_name='Wage rate')
R ${R}$ (long_name='interest rate')
k ${k}$ (long_name='capital stock')
d ${d}$ (long_name='dividends')
n ${n}$ (long_name='labor')
l ${l}$ (long_name='loans')
gy_obs ${\Delta \ln GDP}$ (long_name='detrended capital stock')
gp_obs ${\Delta \ln P}$ (long_name='detrended capital stock')
y ${y}$ (long_name='detrended output')
dA ${\Delta A}$ (long_name='TFP growth')
;
varexo e_a ${\epsilon_A}$ (long_name='TFP shock')
e_m ${\epsilon_M}$ (long_name='Money growth shock')
;
var m P c e W R k d n l gy_obs gp_obs y dA;
varexo e_a e_m;
parameters alp ${\alpha}$ (long_name='capital share')
bet ${\beta}$ (long_name='discount factor')
gam ${\gamma}$ (long_name='long-run TFP growth')
logmst ${\log(m^*)}$ (long_name='long-run money growth')
rho ${\rho}$ (long_name='autocorrelation money growth')
phi ${\phi}$ (long_name='labor weight in consumption')
del ${\delta}$ (long_name='depreciation rate')
;
parameters alp bet gam mst rho psi del;
% roughly picked values to allow simulating the model before estimation
alp = 0.33;
bet = 0.99;
gam = 0.003;
logmst = log(1.011);
mst = 1.011;
rho = 0.7;
phi = 0.787;
psi = 0.787;
del = 0.02;
model;
[name='NC before eq. (1), TFP growth equation']
dA = exp(gam+e_a);
[name='NC eq. (2), money growth rate']
log(m) = (1-rho)*logmst + rho*log(m(-1))+e_m;
[name='NC eq. (A1), Euler equation']
log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m;
-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;
[name='NC below eq. (A1), firm borrowing constraint']
W = l/n;
[name='NC eq. (A2), intratemporal labour market condition']
-(phi/(1-phi))*(c*P/(1-n))+l/n = 0;
[name='NC below eq. (A2), credit market clearing']
-(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
[name='NC eq. (A3), credit market optimality']
1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
[name='NC eq. (18), aggregate resource constraint']
c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
[name='NC eq. (19), money market condition']
P*c = m;
[name='NC eq. (20), credit market equilibrium condition']
m-1+d = l;
[name='Definition TFP shock']
e = exp(e_a);
[name='Implied by NC eq. (18), production function']
y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
[name='Observation equation GDP growth']
gy_obs = dA*y/y(-1);
[name='Observation equation price level']
gp_obs = (P/P(-1))*m(-1)/dA;
end;
@ -119,41 +81,40 @@ end;
steady_state_model;
dA = exp(gam);
gst = 1/dA;
m = exp(logmst);
m = mst;
khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/m )^(-1);
nust = phi*m^2/( (1-alp)*(1-phi)*bet*gst^alp*khst^alp );
xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
n = xist/(nust+xist);
P = xist + nust;
k = khst*n;
l = phi*m*n/( (1-phi)*(1-n) );
c = m/P;
d = l - m + 1;
l = psi*mst*n/( (1-psi)*(1-n) );
c = mst/P;
d = l - mst + 1;
y = k^alp*n^(1-alp)*gst^alp;
R = m/bet;
R = mst/bet;
W = l/n;
ist = y-c;
q = 1 - d;
e = 1;
gp_obs = m/dA;
gy_obs = dA;
end;
steady;
check;
% Table 1 of Schorfheide (2000)
estimated_params;
alp, beta_pdf, 0.356, 0.02;
bet, beta_pdf, 0.993, 0.002;
gam, normal_pdf, 0.0085, 0.003;
logmst, normal_pdf, 0.0002, 0.007;
rho, beta_pdf, 0.129, 0.223;
phi, beta_pdf, 0.65, 0.05;
mst, normal_pdf, 1.0002, 0.007;
rho, beta_pdf, 0.129, 0.100;
psi, beta_pdf, 0.65, 0.05;
del, beta_pdf, 0.01, 0.005;
stderr e_a, inv_gamma_pdf, 0.035449, inf;
stderr e_m, inv_gamma_pdf, 0.008862, inf;
@ -161,8 +122,14 @@ end;
varobs gp_obs gy_obs;
estimation(order=1, datafile=fs2000_data, loglinear,logdata, mode_compute=4, mh_replic=20000, nodiagnostic, mh_nblocks=2, mh_jscale=0.8, mode_check);
estimation(order=1, datafile=fsdat_simul, nobs=192, loglinear, mh_replic=2000, mh_nblocks=2, mh_jscale=0.8, mode_check);
%uncomment the following lines to generate LaTeX-code of the model equations
%write_latex_original_model(write_equation_tags);
%collect_latex_files;
/*
* The following lines were used to generate the data file. If you want to
* generate another random data file, comment the "estimation" line and uncomment
* the following lines.
*/
//stoch_simul(periods=200, order=1);
//datatomfile('fsdat_simul', {'gy_obs', 'gp_obs'});

View File

@ -1,215 +0,0 @@
%This file is a direct Matlab implementation of the loaddata.g and data.prn files
%of Schorfheide, Frank (2000): Loss function-based evaluation of DSGE models
%(replication data). Version: 1. Journal of Applied Econometrics. Dataset.
%http://dx.doi.org/10.15456/jae.2022314.0708799949
% Copyright: 2000-2022 Frank Schorfheide
% Copyright: 2023 Dynare Team
% License: CC BY 4.0
% (https://creativecommons.org/licenses/by/4.0/legalcode)
% Time series, extracted 05/04/00
% columms are quarterly data from 1949:IV to 1997:IV
% 1: GDPD = GROSS DOMESTIC PRODUCT:IMPLICIT PRICE DEFLATOR (INDEX,92=100)(T7.1)
% 2: GDPQ = GROSS DOMESTIC PRODUCT
% 3: GPOP = POPULATION, NIPA basis (THOUS.,NSA)
data_q=[18.02 1474.5 150.2
17.94 1538.2 150.9
18.01 1584.5 151.4
18.42 1644.1 152
18.73 1678.6 152.7
19.46 1693.1 153.3
19.55 1724 153.9
19.56 1758.2 154.7
19.79 1760.6 155.4
19.77 1779.2 156
19.82 1778.8 156.6
20.03 1790.9 157.3
20.12 1846 158
20.1 1882.6 158.6
20.14 1897.3 159.2
20.22 1887.4 160
20.27 1858.2 160.7
20.34 1849.9 161.4
20.39 1848.5 162
20.42 1868.9 162.8
20.47 1905.6 163.6
20.56 1959.6 164.3
20.62 1994.4 164.9
20.78 2020.1 165.7
21 2030.5 166.5
21.2 2023.6 167.2
21.33 2037.7 167.9
21.62 2033.4 168.7
21.71 2066.2 169.5
22.01 2077.5 170.2
22.15 2071.9 170.9
22.27 2094 171.7
22.29 2070.8 172.5
22.56 2012.6 173.1
22.64 2024.7 173.8
22.77 2072.3 174.5
22.88 2120.6 175.3
22.92 2165 176.045
22.91 2223.3 176.727
22.94 2221.4 177.481
23.03 2230.95 178.268
23.13 2279.22 179.694
23.22 2265.48 180.335
23.32 2268.29 181.094
23.4 2238.57 181.915
23.45 2251.68 182.634
23.51 2292.02 183.337
23.56 2332.61 184.103
23.63 2381.01 184.894
23.75 2422.59 185.553
23.81 2448.01 186.203
23.87 2471.86 186.926
23.94 2476.67 187.68
24 2508.7 188.299
24.07 2538.05 188.906
24.12 2586.26 189.631
24.29 2604.62 190.362
24.35 2666.69 190.954
24.41 2697.54 191.56
24.52 2729.63 192.256
24.64 2739.75 192.938
24.77 2808.88 193.467
24.88 2846.34 193.994
25.01 2898.79 194.647
25.17 2970.48 195.279
25.32 3042.35 195.763
25.53 3055.53 196.277
25.79 3076.51 196.877
26.02 3102.36 197.481
26.14 3127.15 197.967
26.31 3129.53 198.455
26.6 3154.19 199.012
26.9 3177.98 199.572
27.21 3236.18 199.995
27.49 3292.07 200.452
27.75 3316.11 200.997
28.12 3331.22 201.538
28.39 3381.86 201.955
28.73 3390.23 202.419
29.14 3409.65 202.986
29.51 3392.6 203.584
29.94 3386.49 204.086
30.36 3391.61 204.721
30.61 3422.95 205.419
31.02 3389.36 206.13
31.5 3481.4 206.763
31.93 3500.95 207.362
32.27 3523.8 208
32.54 3533.79 208.642
33.02 3604.73 209.142
33.2 3687.9 209.637
33.49 3726.18 210.181
33.95 3790.44 210.737
34.36 3892.22 211.192
34.94 3919.01 211.663
35.61 3907.08 212.191
36.29 3947.11 212.708
37.01 3908.15 213.144
37.79 3922.57 213.602
38.96 3879.98 214.147
40.13 3854.13 214.7
41.05 3800.93 215.135
41.66 3835.21 215.652
42.41 3907.02 216.289
43.19 3952.48 216.848
43.69 4044.59 217.314
44.15 4072.19 217.776
44.77 4088.49 218.338
45.57 4126.39 218.917
46.32 4176.28 219.427
47.07 4260.08 219.956
47.66 4329.46 220.573
48.63 4328.33 221.201
49.42 4345.51 221.719
50.41 4510.73 222.281
51.27 4552.14 222.933
52.35 4603.65 223.583
53.51 4605.65 224.152
54.65 4615.64 224.737
55.82 4644.93 225.418
56.92 4656.23 226.117
58.18 4678.96 226.754
59.55 4566.62 227.389
61.01 4562.25 228.07
62.59 4651.86 228.689
64.15 4739.16 229.155
65.37 4696.82 229.674
66.65 4753.02 230.301
67.87 4693.76 230.903
68.86 4615.89 231.395
69.72 4634.88 231.906
70.66 4612.08 232.498
71.44 4618.26 233.074
72.08 4662.97 233.546
72.83 4763.57 234.028
73.48 4849 234.603
74.19 4939.23 235.153
75.02 5053.56 235.605
75.58 5132.87 236.082
76.25 5170.34 236.657
76.81 5203.68 237.232
77.63 5257.26 237.673
78.25 5283.73 238.176
78.76 5359.6 238.789
79.45 5393.57 239.387
79.81 5460.83 239.861
80.22 5466.95 240.368
80.84 5496.29 240.962
81.45 5526.77 241.539
82.09 5561.8 242.009
82.68 5618 242.52
83.33 5667.39 243.12
84.09 5750.57 243.721
84.67 5785.29 244.208
85.56 5844.05 244.716
86.66 5878.7 245.354
87.44 5952.83 245.966
88.45 6010.96 246.46
89.39 6055.61 247.017
90.13 6087.96 247.698
90.88 6093.51 248.374
92 6152.59 248.928
93.18 6171.57 249.564
94.14 6142.1 250.299
95.11 6078.96 251.031
96.27 6047.49 251.65
97 6074.66 252.295
97.7 6090.14 253.033
98.31 6105.25 253.743
99.13 6175.69 254.338
99.79 6214.22 255.032
100.17 6260.74 255.815
100.88 6327.12 256.543
101.84 6327.93 257.151
102.35 6359.9 257.785
102.83 6393.5 258.516
103.51 6476.86 259.191
104.13 6524.5 259.738
104.71 6600.31 260.351
105.39 6629.47 261.04
106.09 6688.61 261.692
106.75 6717.46 262.236
107.24 6724.2 262.847
107.75 6779.53 263.527
108.29 6825.8 264.169
108.91 6882 264.681
109.24 6983.91 265.258
109.74 7020 265.887
110.23 7093.12 266.491
111 7166.68 266.987
111.43 7236.5 267.545
111.76 7311.24 268.171
112.08 7364.63 268.815];
%Compute growth rates: from 1950:I to 1997:IV
gy_obs=1000*data_q(:,2)./data_q(:,3); %real GDP per capita
gy_obs=diff(log(gy_obs));
gp_obs = diff(log(data_q(:,1))); %GDP deflator inflation

View File

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

View File

@ -1,6 +1,6 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Dynare
Upstream-Contact: Dynare Team, whose members in 2024 are:
Upstream-Contact: Dynare Team, whose members in 2023 are:
- Stéphane Adjemian <stephane.adjemian@univ-lemans.fr>
- Michel Juillard <michel.juillard@mjui.fr>
- Frédéric Karamé <frederic.karame@univ-lemans.fr>
@ -23,7 +23,7 @@ Upstream-Contact: Dynare Team, whose members in 2024 are:
Source: https://www.dynare.org
Files: *
Copyright: 1996-2024 Dynare Team
Copyright: 1996-2023 Dynare Team
License: GPL-3+
Files: matlab/+occbin/IVF_core.m
@ -86,13 +86,13 @@ License: public-domain-aim
Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
pages 472-489
Files: matlab/optimization/bfgsi1.m matlab/optimization/csolve.m matlab/optimization/csminit1.m matlab/optimization/numgrad2.m
Files: matlab/optimization/bfgsi1.m matlab/csolve.m matlab/optimization/csminit1.m matlab/optimization/numgrad2.m
matlab/optimization/numgrad3.m matlab/optimization/numgrad3_.m matlab/optimization/numgrad5.m
matlab/optimization/numgrad5_.m matlab/optimization/csminwel1.m matlab/+bvar/density.m
matlab/+bvar/toolbox.m matlab/partial_information/PI_gensys.m matlab/partial_information/qzswitch.m
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
matlab/partial_information/qzdiv.m
Copyright: 1993-2009 Christopher Sims
2006-2023 Dynare Team
2006-2017 Dynare Team
License: GPL-3+
Files: matlab/optimization/cmaes.m
@ -113,7 +113,7 @@ Copyright: 1995 E.G.Tsionas
2015-2017 Dynare Team
License: GPL-3+
Files: matlab/estimation/endogenous_prior.m
Files: matlab/endogenous_prior.m
Copyright: 2011 Lawrence J. Christiano, Mathias Trabandt and Karl Walentin
2013-2017 Dynare Team
License: GPL-3+
@ -123,22 +123,17 @@ Copyright: 2010-2015 Alexander Meyer-Gohde
2015-2017 Dynare Team
License: GPL-3+
Files: matlab/collapse_figures_in_tabgroup.m
Copyright: 2023 Eduard Benet Cerda
2024 Dynare Team
License: GPL-3+
Files: matlab/convergence_diagnostics/raftery_lewis.m
Copyright: 2016 Benjamin Born and Johannes Pfeifer
2016-2017 Dynare Team
License: GPL-3+
Files: matlab/+pruned_SS/commutation.m matlab/+pruned_SS/duplication.m
Files: matlab/commutation.m matlab/duplication.m
Copyright: 1997 Tom Minka <minka@microsoft.com>
2019-2020 Dynare Team
License: GPL-3+
Files: matlab/+pruned_SS/allVL1.m
Files: matlab/allVL1.m
Copyright: 2007-2010 Bruno Luong <brunoluong@yahoo.com>
2020 Dynare Team
License: GPL-3+
@ -146,7 +141,7 @@ Comment: The original author gave authorization to change
the license from BSD-2-clause to GPL-3+ and redistribute
it under GPL-3+ with Dynare.
Files: matlab/+pruned_SS/uperm.m
Files: matlab/uperm.m
Copyright: 2014 Bruno Luong <brunoluong@yahoo.com>
2020 Dynare Team
License: GPL-3+
@ -154,9 +149,9 @@ Comment: The original author gave authorization to change
the license from BSD-2-clause to GPL-3+ and redistribute
it under GPL-3+ with Dynare.
Files: matlab/+pruned_SS/prodmom.m matlab/+pruned_SS/bivmom.m
Files: matlab/prodmom.m matlab/bivmom.m
Copyright: 2008-2015 Raymond Kan <kan@chass.utoronto.ca>
2019-2023 Dynare Team
2019-2020 Dynare Team
License: GPL-3+
Comment: The author gave authorization to redistribute
these functions under GPL-3+ with Dynare and would
@ -166,37 +161,57 @@ Comment: The author gave authorization to redistribute
Journal of Multivariate Analysis, 2008, vol. 99, issue 3,
pages 542-554.
Files: matlab/+gsa/Morris_Measure_Groups.m
matlab/+gsa/Sampling_Function_2.m
Files: matlab/gsa/Morris_Measure_Groups.m
matlab/gsa/Sampling_Function_2.m
Copyright: 2005 European Commission
2012-2013 Dynare Team
2012-2017 Dynare Team
License: GPL-3+
Comment: Written by Jessica Cariboni and Francesca Campolongo
Joint Research Centre, The European Commission,
Files: matlab/+gsa/cumplot.m
matlab/+gsa/monte_carlo_filtering.m
matlab/+gsa/skewness.m
matlab/+gsa/log_transform.m
matlab/+gsa/map_calibration.m
matlab/+gsa/map_identification.m
matlab/+gsa/monte_carlo_filtering_analysis.m
matlab/+gsa/boxplot.m
matlab/+gsa/prior_draw.m
matlab/+gsa/reduced_form_mapping.m
matlab/+gsa/reduced_form_screening.m
matlab/+gsa/scatter_mcf.m
matlab/+gsa/smirnov_test.m
matlab/+gsa/stability_mapping.m
matlab/+gsa/stability_mapping_univariate.m
matlab/+gsa/stability_mapping_bivariate.m
matlab/+gsa/standardize_columns.m
matlab/+gsa/tcrit.m
matlab/+gsa/teff.m
Files: matlab/gsa/cumplot.m
matlab/gsa/filt_mc_.m
matlab/gsa/gsa_plotmatrix.m
matlab/gsa/gsa_skewness.m
matlab/gsa/gsa_speed.m
matlab/gsa/log_trans_.m
matlab/gsa/map_calibration.m
matlab/gsa/map_ident_.m
matlab/gsa/mcf_analysis.m
matlab/gsa/myboxplot.m
matlab/gsa/myprctilecol.m
matlab/gsa/prior_draw_gsa.m
matlab/gsa/read_data.m
matlab/gsa/redform_map.m
matlab/gsa/redform_screen.m
matlab/gsa/scatter_mcf.m
matlab/gsa/smirnov.m
matlab/gsa/stab_map_.m
matlab/gsa/stab_map_1.m
matlab/gsa/stab_map_2.m
matlab/gsa/stand_.m
matlab/gsa/tcrit.m
matlab/gsa/teff.m
matlab/gsa/trank.m
Copyright: 2011-2018 European Commission
2011-2023 Dynare Team
2011-2018 Dynare Team
License: GPL-3+
Files: matlab/gsa/pick.m
Copyright: none
License: public-domain-jrc
This software has been developed at the Joint Research Centre of European Commission
by officers in the course of their official duties. This software is not subject to copyright
protection and is in the public domain. It is an experimental system. The Joint Research Centre
of European Commission assumes no responsibility whatsoever for its use by other parties
and makes no guarantees, expressed or implied, about its quality, reliability, or any other
characteristic. We would appreciate acknowledgement if the software is used.
Comment: This file is part of GLUEWIN.
The program has been developed by M. Ratto, European Commission, Joint Research Centre,
Institute for the Protection and Security of The Citizen, Technological and Economic Risk Management,
Applied Statistics, as a deliverable of the IMPACT project
(EC Fifth Framework Programme, SCA Project, IST-1999-11313, DG-INFSO).
Files: matlab/optimization/simpsa.m matlab/optimization/simpsaget.m matlab/optimization/simpsaset.m
Copyright: 2005 Henning Schmidt, FCC, henning@fcc.chalmers.se
2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be
@ -247,14 +262,9 @@ License: BSD-2-clause
Files: matlab/utilities/graphics/colorspace.m
Copyright: 2005-2010 Pascal Getreuer
2017-2023 Dynare Team
2017 Dynare Team
License: BSD-2-clause
Files: examples/fs2000_data.m
Copyright: 2000-2022 Frank Schorfheide
2023 Dynare Team
License: CC-BY-SA-4.0
Files: doc/*.rst doc/*.tex doc/*.svg doc/*.pdf doc/*.bib
Copyright: 1996-2022 Dynare Team
License: GFDL-NIV-1.3+
@ -272,6 +282,20 @@ Files: doc/sylvester.tex doc/tl.tex
Copyright: 2004-2011 Ondra Kamenik
License: GPL-3+
Files: m4/ax_compare_version.m4
Copyright: 2008 Tim Toolan <toolan@ele.uri.edu>
License: FSFAP
Files: m4/ax_latex_class.m4 m4/ax_latex_test.m4
Copyright: 2008 Boretti Mathieu <boretti@eig.unige.ch>
2009 Dynare Team
License: LGPL-2.1+
Files: m4/ax_matlab_arch.m4 m4/ax_matlab.m4 m4/ax_mexext.m4
Copyright: 2002-2003 Ralph Schleicher
2009-2021 Dynare Team
License: GPL-2+ with Autoconf exception
Files: scripts/dynare.el
Copyright: 2010 Yannick Kalantzis
2019-2023 Dynare Team
@ -289,6 +313,22 @@ Copyright: 2004-2009 John Burkardt
2023 Dynare Team
License: LGPL-3+
Files: macOS/brewfiles/*
Copyright: 2009-2019 Homebrew contributors
2019-2021 Dynare Team
License: BSD-2-clause
Files: preprocessor/m4/ax_boost_base.m4
Copyright: 2008-2009 Thomas Porschberg <thomas@randspringer.de>
2009 Peter Adolphs
License: FSFAP
Files: preprocessor/m4/ax_latex_class.m4
preprocessor/m4/ax_latex_test.m4
Copyright: 2008 Boretti Mathieu <boretti@eig.unige.ch>
2009 Dynare Team
License: LGPL-2.1+
Files: preprocessor/doc/macroprocessor/*
Copyright: 2008-2021 Dynare Team
License: CC-BY-SA-4.0
@ -297,6 +337,28 @@ Files: preprocessor/doc/preprocessor/*
Copyright: 2007-2019 Dynare Team
License: CC-BY-SA-4.0
Files: contrib/jsonlab/*
Copyright: 2011-2020 Qianqian Fang <q.fang at neu.edu>
2016 Bastian Bechtold
License: GPL-3+ or BSD-3-clause
Files: contrib/jsonlab/base64decode.m
contrib/jsonlab/base64encode.m
contrib/jsonlab/gzipdecode.m
contrib/jsonlab/gzipencode.m
contrib/jsonlab/zlibdecode.m
contrib/jsonlab/zlibencode.m
Copyright: 2012 Kota Yamaguchi
2011-2020 Qianqian Fang <q.fang at neu.edu>
License: GPL-3+ or BSD-2-clause
Files: contrib/jsonlab/loadjson.m
Copyright: 2011-2020 Qianqian Fang
2009 Nedialko Krouchev
2009 François Glineur
2008 Joel Feenstra
License: GPL-3+ or BSD-2-clause or BSD-3-clause
Files: contrib/ms-sbvar/utilities_dw/*
Copyright: 1996-2011 Daniel Waggoner
License: GPL-3+
@ -403,6 +465,32 @@ License: BSD-2-clause
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
License: BSD-3-clause
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
.
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
.
* Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
License: GFDL-NIV-1.3+
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
@ -411,6 +499,26 @@ License: GFDL-NIV-1.3+
.
A copy of the license can be found at <https://www.gnu.org/licenses/fdl.txt>
License: GPL-2+ with Autoconf exception
This program 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 2,
or (at your option) any later version.
.
This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
.
As a special exception to the GNU General Public License, if
you distribute this file as part of a program that contains a
configuration script generated by GNU Autoconf, you may include
it under the same distribution terms that you use for the rest
of that program.
License: GPL-3+
Dynare is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@ -425,6 +533,47 @@ License: GPL-3+
You should have received a copy of the GNU General Public License
along with Dynare. If not, see <https://www.gnu.org/licenses/>.
License: GPL-3+ with Autoconf exception
This program 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.
.
This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
.
As a special exception, the respective Autoconf Macro's copyright owner
gives unlimited permission to copy, distribute and modify the configure
scripts that are the output of Autoconf when processing the Macro. You
need not follow the terms of the GNU General Public License when using
or distributing such scripts, even though portions of the text of the
Macro appear in them. The GNU General Public License (GPL) does govern
all other use of the material that constitutes the Autoconf Macro.
.
This special exception to the GPL applies to versions of the Autoconf
Macro released by the Autoconf Archive. When you make and distribute a
modified version of the Autoconf Macro, you may extend this special
exception to the GPL to apply to your modified version as well.
License: LGPL-2.1+
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.
.
This library 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 Lesser
General Public License for more details.
.
You should have received a copy of the GNU Lesser General Public License
along with this library. If not, see <https://www.gnu.org/licenses/>.
License: LGPL-3+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@ -865,3 +1014,9 @@ License: CC-BY-SA-4.0
licenses.
.
Creative Commons may be contacted at creativecommons.org.
License: FSFAP
Copying and distribution of this file, with or without modification, are
permitted in any medium without royalty provided the copyright notice
and this notice are preserved. This file is offered as-is, without any
warranty.

177
m4/ax_compare_version.m4 Normal file
View File

@ -0,0 +1,177 @@
# ===========================================================================
# https://www.gnu.org/software/autoconf-archive/ax_compare_version.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_COMPARE_VERSION(VERSION_A, OP, VERSION_B, [ACTION-IF-TRUE], [ACTION-IF-FALSE])
#
# DESCRIPTION
#
# This macro compares two version strings. Due to the various number of
# minor-version numbers that can exist, and the fact that string
# comparisons are not compatible with numeric comparisons, this is not
# necessarily trivial to do in a autoconf script. This macro makes doing
# these comparisons easy.
#
# The six basic comparisons are available, as well as checking equality
# limited to a certain number of minor-version levels.
#
# The operator OP determines what type of comparison to do, and can be one
# of:
#
# eq - equal (test A == B)
# ne - not equal (test A != B)
# le - less than or equal (test A <= B)
# ge - greater than or equal (test A >= B)
# lt - less than (test A < B)
# gt - greater than (test A > B)
#
# Additionally, the eq and ne operator can have a number after it to limit
# the test to that number of minor versions.
#
# eq0 - equal up to the length of the shorter version
# ne0 - not equal up to the length of the shorter version
# eqN - equal up to N sub-version levels
# neN - not equal up to N sub-version levels
#
# When the condition is true, shell commands ACTION-IF-TRUE are run,
# otherwise shell commands ACTION-IF-FALSE are run. The environment
# variable 'ax_compare_version' is always set to either 'true' or 'false'
# as well.
#
# Examples:
#
# AX_COMPARE_VERSION([3.15.7],[lt],[3.15.8])
# AX_COMPARE_VERSION([3.15],[lt],[3.15.8])
#
# would both be true.
#
# AX_COMPARE_VERSION([3.15.7],[eq],[3.15.8])
# AX_COMPARE_VERSION([3.15],[gt],[3.15.8])
#
# would both be false.
#
# AX_COMPARE_VERSION([3.15.7],[eq2],[3.15.8])
#
# would be true because it is only comparing two minor versions.
#
# AX_COMPARE_VERSION([3.15.7],[eq0],[3.15])
#
# would be true because it is only comparing the lesser number of minor
# versions of the two values.
#
# Note: The characters that separate the version numbers do not matter. An
# empty string is the same as version 0. OP is evaluated by autoconf, not
# configure, so must be a string, not a variable.
#
# The author would like to acknowledge Guido Draheim whose advice about
# the m4_case and m4_ifvaln functions make this macro only include the
# portions necessary to perform the specific comparison specified by the
# OP argument in the final configure script.
#
# LICENSE
#
# Copyright (c) 2008 Tim Toolan <toolan@ele.uri.edu>
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice
# and this notice are preserved. This file is offered as-is, without any
# warranty.
#serial 13
dnl #########################################################################
AC_DEFUN([AX_COMPARE_VERSION], [
AC_REQUIRE([AC_PROG_AWK])
# Used to indicate true or false condition
ax_compare_version=false
# Convert the two version strings to be compared into a format that
# allows a simple string comparison. The end result is that a version
# string of the form 1.12.5-r617 will be converted to the form
# 0001001200050617. In other words, each number is zero padded to four
# digits, and non digits are removed.
AS_VAR_PUSHDEF([A],[ax_compare_version_A])
A=`echo "$1" | sed -e 's/\([[0-9]]*\)/Z\1Z/g' \
-e 's/Z\([[0-9]]\)Z/Z0\1Z/g' \
-e 's/Z\([[0-9]][[0-9]]\)Z/Z0\1Z/g' \
-e 's/Z\([[0-9]][[0-9]][[0-9]]\)Z/Z0\1Z/g' \
-e 's/[[^0-9]]//g'`
AS_VAR_PUSHDEF([B],[ax_compare_version_B])
B=`echo "$3" | sed -e 's/\([[0-9]]*\)/Z\1Z/g' \
-e 's/Z\([[0-9]]\)Z/Z0\1Z/g' \
-e 's/Z\([[0-9]][[0-9]]\)Z/Z0\1Z/g' \
-e 's/Z\([[0-9]][[0-9]][[0-9]]\)Z/Z0\1Z/g' \
-e 's/[[^0-9]]//g'`
dnl # In the case of le, ge, lt, and gt, the strings are sorted as necessary
dnl # then the first line is used to determine if the condition is true.
dnl # The sed right after the echo is to remove any indented white space.
m4_case(m4_tolower($2),
[lt],[
ax_compare_version=`echo "x$A
x$B" | sed 's/^ *//' | sort -r | sed "s/x${A}/false/;s/x${B}/true/;1q"`
],
[gt],[
ax_compare_version=`echo "x$A
x$B" | sed 's/^ *//' | sort | sed "s/x${A}/false/;s/x${B}/true/;1q"`
],
[le],[
ax_compare_version=`echo "x$A
x$B" | sed 's/^ *//' | sort | sed "s/x${A}/true/;s/x${B}/false/;1q"`
],
[ge],[
ax_compare_version=`echo "x$A
x$B" | sed 's/^ *//' | sort -r | sed "s/x${A}/true/;s/x${B}/false/;1q"`
],[
dnl Split the operator from the subversion count if present.
m4_bmatch(m4_substr($2,2),
[0],[
# A count of zero means use the length of the shorter version.
# Determine the number of characters in A and B.
ax_compare_version_len_A=`echo "$A" | $AWK '{print(length)}'`
ax_compare_version_len_B=`echo "$B" | $AWK '{print(length)}'`
# Set A to no more than B's length and B to no more than A's length.
A=`echo "$A" | sed "s/\(.\{$ax_compare_version_len_B\}\).*/\1/"`
B=`echo "$B" | sed "s/\(.\{$ax_compare_version_len_A\}\).*/\1/"`
],
[[0-9]+],[
# A count greater than zero means use only that many subversions
A=`echo "$A" | sed "s/\(\([[0-9]]\{4\}\)\{m4_substr($2,2)\}\).*/\1/"`
B=`echo "$B" | sed "s/\(\([[0-9]]\{4\}\)\{m4_substr($2,2)\}\).*/\1/"`
],
[.+],[
AC_WARNING(
[invalid OP numeric parameter: $2])
],[])
# Pad zeros at end of numbers to make same length.
ax_compare_version_tmp_A="$A`echo $B | sed 's/./0/g'`"
B="$B`echo $A | sed 's/./0/g'`"
A="$ax_compare_version_tmp_A"
# Check for equality or inequality as necessary.
m4_case(m4_tolower(m4_substr($2,0,2)),
[eq],[
test "x$A" = "x$B" && ax_compare_version=true
],
[ne],[
test "x$A" != "x$B" && ax_compare_version=true
],[
AC_WARNING([invalid OP parameter: $2])
])
])
AS_VAR_POPDEF([A])dnl
AS_VAR_POPDEF([B])dnl
dnl # Execute ACTION-IF-TRUE / ACTION-IF-FALSE.
if test "$ax_compare_version" = "true" ; then
m4_ifvaln([$4],[$4],[:])dnl
m4_ifvaln([$5],[else $5])dnl
fi
]) dnl AX_COMPARE_VERSION

66
m4/ax_gsl.m4 Normal file
View File

@ -0,0 +1,66 @@
dnl Detect GSL.
dnl We don't use the official M4 macro since it relies on the script gsl-config,
dnl which does not work when cross-compiling.
dnl
dnl Copyright © 2010-2021 Dynare Team
dnl
dnl This file is part of Dynare.
dnl
dnl Dynare is free software: you can redistribute it and/or modify
dnl it under the terms of the GNU General Public License as published by
dnl the Free Software Foundation, either version 3 of the License, or
dnl (at your option) any later version.
dnl
dnl Dynare is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License
dnl along with Dynare. If not, see <https://www.gnu.org/licenses/>.
AC_DEFUN([AX_GSL],
[
AC_ARG_WITH(gsl, AS_HELP_STRING([--with-gsl=DIR], [prefix to GSL installation]),
gsl_prefix="$withval", gsl_prefix="")
has_gsl=yes
if test -n "$gsl_prefix"; then
GSL_CPPFLAGS="-I$withval/include"
GSL_LDFLAGS="-L$withval/lib"
else
GSL_CPPFLAGS=""
GSL_LDFLAGS=""
fi
ac_save_CPPFLAGS="$CPPFLAGS"
ac_save_LDFLAGS="$LDFLAGS"
ac_save_LIBS="$LIBS"
LIBS=""
CPPFLAGS="$CPPFLAGS $GSL_CPPFLAGS"
LDFLAGS="$LDFLAGS $GSL_LDFLAGS"
AC_LANG_PUSH(C)
AC_CHECK_HEADER([gsl/gsl_cdf.h], [], [has_gsl=no])
AC_LANG_POP(C)
AC_CHECK_LIB([m], [cos])
AC_CHECK_LIB([gslcblas], [cblas_dgemm], [LIBS="-lgslcblas $LIBS"], [has_gsl=no])
AC_CHECK_LIB([gsl], [gsl_cdf_ugaussian_P], [LIBS="-lgsl $LIBS"], [has_gsl=no])
if test "$has_gsl" = yes; then
GSL_LIBS="$LIBS"
else
GSL_LIBS=""
fi
CPPFLAGS="$ac_save_CPPFLAGS"
LDFLAGS="$ac_save_LDFLAGS"
LIBS="$ac_save_LIBS"
AC_SUBST(GSL_CPPFLAGS)
AC_SUBST(GSL_LDFLAGS)
AC_SUBST(GSL_LIBS)
])

68
m4/ax_latex_class.m4 Normal file
View File

@ -0,0 +1,68 @@
# ===========================================================================
# http://www.nongnu.org/autoconf-archive/ax_latex_class.html
# ===========================================================================
#
# OBSOLETE MACRO
#
# Deprecated because of licensing issues. The Lesser GPL imposes licensing
# restrictions on the generated configure script unless it is augmented
# with an Autoconf Exception clause.
#
# SYNOPSIS
#
# AX_LATEX_CLASS(CLASSNAME,VARIABLETOSET[,ACTION-IF-FOUND[,ACTION-IF-NOT-FOUND]])
#
# DESCRIPTION
#
# This macros test is class CLASSNAME exists and work and set
# VARIABLETOSET to yes or no If ACTION-IF-FOUND (and ACTION-IF-NOT-FOUND)
# are set, do the correct action
#
# LICENSE
#
# Copyright © 2008 Boretti Mathieu <boretti@eig.unige.ch>
# Copyright © 2009 Dynare Team
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or (at
# your option) any later version.
#
# This library 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 Lesser
# General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library. If not, see <https://www.gnu.org/licenses/>.
AC_DEFUN([AX_LATEX_CLASS],[
AC_CACHE_CHECK([for usability of class $1],[ac_cv_latex_class_]translit($1,[-],[_]),[
AX_LATEX_TEST([\documentclass{$1}
\begin{document}
\end{document}],[ac_cv_latex_class_]translit($1,[-],[_]))
])
$2=$[ac_cv_latex_class_]translit($1,[-],[_]) ; export $2;
AC_SUBST($2)
ifelse($#,2,[],$#,3,[
if test "[$]$2" = "yes" ;
then
$3
fi
],$#,4,[
ifelse($3,[],[
if test "[$]$2" = "no" ;
then
$4
fi
],[
if test "[$]$2" = "yes" ;
then
$3
else
$4
fi
])
])
])

56
m4/ax_latex_test.m4 Normal file
View File

@ -0,0 +1,56 @@
# ===========================================================================
# http://www.nongnu.org/autoconf-archive/ax_latex_test.html
# ===========================================================================
#
# OBSOLETE MACRO
#
# Deprecated because of licensing issues. The Lesser GPL imposes licensing
# restrictions on the generated configure script unless it is augmented
# with an Autoconf Exception clause.
#
# SYNOPSIS
#
# AX_LATEX_TEST(FILEDATA,VARIABLETOSET,[NOCLEAN])
#
# DESCRIPTION
#
# This macros execute the latex application with FILEDATA as input and set
# VARIABLETOSET the yes or no depending of the result if NOCLEAN is set,
# the folder used for the test is not delete after testing.
#
# The macro assumes that the variable PDFLATEX is set.
#
# LICENSE
#
# Copyright © 2008 Boretti Mathieu <boretti@eig.unige.ch>
# Copyright © 2009 Dynare Team
#
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or (at
# your option) any later version.
#
# This library 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 Lesser
# General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library. If not, see <https://www.gnu.org/licenses/>.
AC_DEFUN([AX_LATEX_TEST],[
rm -rf conftest.dir/.acltx
AS_MKDIR_P([conftest.dir/.acltx])
cd conftest.dir/.acltx
m4_ifval([$2],[$2="no"; export $2;])
cat > conftest.tex << ACLEOF
$1
ACLEOF
cat conftest.tex | $PDFLATEX 2>&1 1>output m4_ifval([$2],[&& $2=yes])
cd ..
cd ..
sed 's/^/| /' conftest.dir/.acltx/conftest.tex >&5
echo "$as_me:$LINENO: executing cat conftest.tex | $PDFLATEX" >&5
sed 's/^/| /' conftest.dir/.acltx/output >&5
m4_ifval([$3],,[rm -rf conftest.dir/.acltx])
])

69
m4/ax_matio.m4 Normal file
View File

@ -0,0 +1,69 @@
dnl Detect the MATIO Library.
dnl
dnl Copyright © 2012-2023 Dynare Team
dnl
dnl This file is part of Dynare.
dnl
dnl Dynare is free software: you can redistribute it and/or modify
dnl it under the terms of the GNU General Public License as published by
dnl the Free Software Foundation, either version 3 of the License, or
dnl (at your option) any later version.
dnl
dnl Dynare is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License
dnl along with Dynare. If not, see <https://www.gnu.org/licenses/>.
AC_DEFUN([AX_MATIO],
[
AC_ARG_WITH(matio, AS_HELP_STRING([--with-matio=DIR], [prefix to MATIO installation]),
matio_prefix="$withval", matio_prefix="")
AC_REQUIRE([AC_CANONICAL_HOST])
has_matio=yes
if test -n "$matio_prefix"; then
CPPFLAGS_MATIO="-I$withval/include"
LDFLAGS_MATIO="-L$withval/lib"
else
CPPFLAGS_MATIO=""
LDFLAGS_MATIO=""
fi
ac_save_CPPFLAGS="$CPPFLAGS"
ac_save_LDFLAGS="$LDFLAGS"
ac_save_LIBS="$LIBS"
LIBADD_MATIO=""
CPPFLAGS="$CPPFLAGS_MATIO $CPPFLAGS"
LDFLAGS="$LDFLAGS_MATIO $LDFLAGS"
dnl Under Windows and macOS, add hdf5 and its dependencies since we are linking statically
case ${host_os} in
*mingw32*)
dnl Partly inspired by /mingw64/lib/pkgconfig/{hdf5,libcurl}.pc (in particular for the system libraries)
LIBS="-lhdf5 -lcurl -lnghttp2 -lidn2 -lssh2 -lpsl -lunistring -liconv -lbcrypt -ladvapi32 -lcrypt32 -lbcrypt -lgdi32 -lwldap32 -lzstd -lbrotlidec -lbrotlicommon -lssl -lcrypto -lws2_32 -lz -lsz"
;;
*darwin*)
LIBS="-lhdf5 -lz -lsz"
;;
*)
LIBS=""
;;
esac
AC_CHECK_HEADER([matio.h], [], [has_matio=no])
AC_CHECK_LIB([matio], [Mat_Open], [LIBADD_MATIO="-lmatio $LIBS"], [has_matio=no])
CPPFLAGS="$ac_save_CPPFLAGS"
LDFLAGS="$ac_save_LDFLAGS"
LIBS="$ac_save_LIBS"
AC_SUBST(CPPFLAGS_MATIO)
AC_SUBST(LIBADD_MATIO)
AC_SUBST(LDFLAGS_MATIO)
])

126
m4/ax_matlab.m4 Normal file
View File

@ -0,0 +1,126 @@
dnl ax_matlab.m4 --- check for MATLAB.
dnl
dnl Copyright © 2000-2003 Ralph Schleicher
dnl Copyright © 2009-2021 Dynare Team
dnl
dnl This program is free software; you can redistribute it and/or
dnl modify it under the terms of the GNU General Public License as
dnl published by the Free Software Foundation; either version 2,
dnl or (at your option) any later version.
dnl
dnl This program is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License along
dnl with this program. If not, see <https://www.gnu.org/licenses/>.
dnl
dnl As a special exception to the GNU General Public License, if
dnl you distribute this file as part of a program that contains a
dnl configuration script generated by GNU Autoconf, you may include
dnl it under the same distribution terms that you use for the rest
dnl of that program.
dnl
dnl Code:
# AX_MATLAB
# ---------
# Check for MATLAB.
AC_DEFUN([AX_MATLAB],
[dnl
AC_PREREQ([2.50])
ax_enable_matlab=
AC_ARG_WITH([matlab], AS_HELP_STRING([--with-matlab=ARG], [check for MATLAB [[yes]]]),
[case $withval in
yes | no)
# Explicitly enable or disable MATLAB but determine
# MATLAB prefix automatically.
ax_enable_matlab=$withval
;;
*)
# Enable MATLAB and use ARG as the MATLAB prefix.
# ARG must be an existing directory.
ax_enable_matlab=yes
MATLAB=$(cd "${withval-/}" > /dev/null 2>&1 && pwd)
if test -z "$MATLAB" ; then
AC_MSG_ERROR([invalid value '$withval' for --with-matlab])
fi
;;
esac])
AC_CACHE_CHECK([for MATLAB prefix], [ax_cv_matlab],
[if test "${MATLAB+set}" = set ; then
ax_cv_matlab=$(cd "${MATLAB-/}" > /dev/null 2>&1 && pwd)
else
ax_cv_matlab=
IFS=${IFS= } ; ax_ifs=$IFS ; IFS=:
for ax_dir in ${PATH-/opt/bin:/usr/local/bin:/usr/bin:/bin} ; do
if test -z "$ax_dir" ; then
ax_dir=.
fi
if test -x "$ax_dir/matlab" ; then
ax_dir=$(echo "$ax_dir" | sed 's,/bin$,,')
# Directory sanity check.
ax_cv_matlab=$(cd "${ax_dir-/}" > /dev/null 2>&1 && pwd)
if test -n "$ax_cv_matlab" ; then
break
fi
fi
done
IFS=$ax_ifs
fi
if test -z "$ax_cv_matlab" ; then
ax_cv_matlab="not found"
fi])
if test "$ax_cv_matlab" = "not found" ; then
unset MATLAB
else
# Strip trailing dashes.
MATLAB=$(echo "$ax_cv_matlab" | sed 's,/*$,,')
fi
AC_MSG_CHECKING([whether to enable MATLAB support])
if test "$ax_enable_matlab" != no; then
if test "${MATLAB+set}" = set && test -d "$MATLAB/extern/include" ; then
ax_enable_matlab=yes
elif test -z "$ax_enable_matlab"; then
ax_enable_matlab=no
else
# Fail if MATLAB was explicitly enabled.
AC_MSG_RESULT([failure])
AC_MSG_ERROR([check your MATLAB setup])
fi
fi
AC_MSG_RESULT([$ax_enable_matlab])
if test "$ax_enable_matlab" = yes; then
AC_DEFINE([HAVE_MATLAB], [1], [Define if you have MATLAB.])
fi
AC_SUBST([MATLAB])
])
# AX_REQUIRE_MATLAB
# -----------------
# Like AX_MATLAB but fail if MATLAB support is disabled.
AC_DEFUN([AX_REQUIRE_MATLAB],
[dnl
AC_PREREQ([2.50])
AC_REQUIRE([AX_MATLAB])
if test "$ax_enable_matlab" = no; then
AC_MSG_ERROR([can not enable MATLAB support])
fi
])
# AX_MATLAB_CONDITIONAL
# ---------------------
# Define MATLAB conditional for GNU Automake.
AC_DEFUN([AX_MATLAB_CONDITIONAL],
[dnl
AC_PREREQ([2.50])
AC_REQUIRE([AX_MATLAB])
AM_CONDITIONAL([MATLAB], [test "$ax_enable_matlab" = yes])
])
dnl ax_matlab.m4 ends here
dnl Local variables:
dnl tab-width: 8
dnl End:

76
m4/ax_matlab_arch.m4 Normal file
View File

@ -0,0 +1,76 @@
dnl matlabarch.m4 --- check for MATLAB machine architecture.
dnl
dnl Copyright © 2002, 2003 Ralph Schleicher
dnl Copyright © 2009-2023 Dynare Team
dnl
dnl This program is free software; you can redistribute it and/or
dnl modify it under the terms of the GNU General Public License as
dnl published by the Free Software Foundation; either version 2,
dnl or (at your option) any later version.
dnl
dnl This program is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License along
dnl with this program. If not, see <https://www.gnu.org/licenses/>.
dnl
dnl As a special exception to the GNU General Public License, if
dnl you distribute this file as part of a program that contains a
dnl configuration script generated by GNU Autoconf, you may include
dnl it under the same distribution terms that you use for the rest
dnl of that program.
dnl
dnl Code:
# AX_MATLAB_ARCH
# --------------
# Check for MATLAB machine architecture.
AC_DEFUN([AX_MATLAB_ARCH],
[dnl
AC_PREREQ([2.50])
AC_REQUIRE([AX_MEXEXT])
AC_CACHE_CHECK([for MATLAB machine architecture], [ax_cv_matlab_arch],
[if test "${MATLAB_ARCH+set}" = set ; then
ax_cv_matlab_arch="$MATLAB_ARCH"
else
case $MEXEXT in
*dll | *mexw32)
ax_cv_matlab_arch=win32
;;
*mexw64)
ax_cv_matlab_arch=win64
;;
*mexglx)
ax_cv_matlab_arch=glnx86
;;
*mexa64)
ax_cv_matlab_arch=glnxa64
;;
*mexs64)
ax_cv_matlab_arch=sol64
;;
*mexmaci)
ax_cv_matlab_arch=maci
;;
*mexmaci64)
ax_cv_matlab_arch=maci64
;;
*mexmaca64)
ax_cv_matlab_arch=maca64
;;
*)
ax_cv_matlab_arch=unknown
;;
esac
fi])
MATLAB_ARCH="$ax_cv_matlab_arch"
AC_SUBST([MATLAB_ARCH])
])
dnl matlabarch.m4 ends here
dnl Local variables:
dnl tab-width: 8
dnl End:

View File

@ -0,0 +1,41 @@
dnl Copyright © 2019 Dynare Team
dnl
dnl This file is part of Dynare.
dnl
dnl Dynare is free software: you can redistribute it and/or modify
dnl it under the terms of the GNU General Public License as published by
dnl the Free Software Foundation, either version 3 of the License, or
dnl (at your option) any later version.
dnl
dnl Dynare is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License
dnl along with Dynare. If not, see <https://www.gnu.org/licenses/>.
AC_DEFUN([AX_MATLAB_BATCH_OPTIONS],
[dnl
AC_REQUIRE([AX_MATLAB])
AC_REQUIRE([AX_MATLAB_ARCH])
AC_REQUIRE([AX_MATLAB_VERSION])
AX_COMPARE_VERSION([$MATLAB_VERSION], [ge], [9.6],
[
if test "${MATLAB_ARCH}" = win32 -o "${MATLAB_ARCH}" = win64; then
MATLAB_BATCH_OPTIONS='-noFigureWindows -batch'
else
MATLAB_BATCH_OPTIONS='-nodisplay -batch'
fi
],
[
if test "${MATLAB_ARCH}" = win32 -o "${MATLAB_ARCH}" = win64; then
MATLAB_BATCH_OPTIONS='-nosplash -automation -wait -sd "$(CURDIR)" -r'
else
MATLAB_BATCH_OPTIONS='-nosplash -nodisplay -r'
fi
])
AC_SUBST([MATLAB_BATCH_OPTIONS])
])

176
m4/ax_matlab_version.m4 Normal file
View File

@ -0,0 +1,176 @@
dnl Copyright © 2009-2023 Dynare Team
dnl
dnl This file is part of Dynare.
dnl
dnl Dynare is free software: you can redistribute it and/or modify
dnl it under the terms of the GNU General Public License as published by
dnl the Free Software Foundation, either version 3 of the License, or
dnl (at your option) any later version.
dnl
dnl Dynare is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License
dnl along with Dynare. If not, see <https://www.gnu.org/licenses/>.
AC_DEFUN([AX_MATLAB_VERSION],
[dnl
AC_REQUIRE([AX_MATLAB])
AC_MSG_CHECKING([for MATLAB version])
if test -n "$MATLAB"; then
dnl Try to autodetect MATLAB version
if test -f "${MATLAB}/VersionInfo.xml"; then
dnl The VersionInfo.xml file is present on all versions since R2017a, on all platforms.
dnl Extract the version number as x.y, since it is our preferred form, and is
dnl more robust to future versions.
dnl NB: brackets in regular expressions are enclosed in other brackets, because this is m4
MATLAB_VERSION=$(sed -En '/<version>/s/.*>([[0-9]]+\.[[0-9]]+).*/\1/p' "${MATLAB}/VersionInfo.xml")
elif test -f "${MATLAB}/bin/util/mex/version.txt"; then
dnl The bin/util/mex/version.txt file is present on Windows and macOS, at least
dnl since R2009b. It contains the release number (Rnnnnx).
MATLAB_VERSION=$(cat "${MATLAB}/bin/util/mex/version.txt")
elif test -f "${MATLAB}/bin/mex" || test -f "${MATLAB}/bin/mexsh"; then
dnl Works on Linux and macOS until R2018a included. Returns the release number (Rnnnnx).
dnl Older MATLABs have the version in bin/mex, more recent in bin/mexsh
dnl NB: brackets in regular expressions are enclosed in other brackets, because this is m4
MATLAB_VERSION=$(sed -En "/^.*full_ver=/s/^.*full_ver='(R[[^']]+)'.*/\1/p" "${MATLAB}"/bin/mex*)
fi
fi
if test -n "$MATLAB_VERSION"; then
dnl Convert a release number (Rnnnnx) into a version number (x.y)
case $MATLAB_VERSION in
*2023a | *2023A)
MATLAB_VERSION="9.14"
;;
*2022b | *2022B)
MATLAB_VERSION="9.13"
;;
*2022a | *2022A)
MATLAB_VERSION="9.12"
;;
*2021b | *2021B)
MATLAB_VERSION="9.11"
;;
*2021a | *2021A)
MATLAB_VERSION="9.10"
;;
*2020b | *2020B)
MATLAB_VERSION="9.9"
;;
*2020a | *2020A)
MATLAB_VERSION="9.8"
;;
*2019b | *2019B)
MATLAB_VERSION="9.7"
;;
*2019a | *2019A)
MATLAB_VERSION="9.6"
;;
*2018b | *2018B)
MATLAB_VERSION="9.5"
;;
*2018a | *2018A)
MATLAB_VERSION="9.4"
;;
*2017b | *2017B)
MATLAB_VERSION="9.3"
;;
*2017a | *2017A)
MATLAB_VERSION="9.2"
;;
*2016b | *2016B)
MATLAB_VERSION="9.1"
;;
*2016a | *2016A)
MATLAB_VERSION="9.0"
;;
*2015b | *2015B)
MATLAB_VERSION="8.6"
;;
*2015a | *2015A)
MATLAB_VERSION="8.5"
;;
*2014b | *2014B)
MATLAB_VERSION="8.4"
;;
*2014a | *2014A)
MATLAB_VERSION="8.3"
;;
*2013b | *2013B)
MATLAB_VERSION="8.2"
;;
*2013a | *2013A)
MATLAB_VERSION="8.1"
;;
*2012b | *2012B)
MATLAB_VERSION="8.0"
;;
*2012a | *2012A)
MATLAB_VERSION="7.14"
;;
*2011b | *2011B)
MATLAB_VERSION="7.13"
;;
*2011a | *2011A)
MATLAB_VERSION="7.12"
;;
*2010b | *2010B)
MATLAB_VERSION="7.11"
;;
*2010a | *2010A)
MATLAB_VERSION="7.10"
;;
*2009b | *2009B)
MATLAB_VERSION="7.9"
;;
*2009a | *2009A)
MATLAB_VERSION="7.8"
;;
*2008b | *2008B)
MATLAB_VERSION="7.7"
;;
*2008a | *2008A)
MATLAB_VERSION="7.6"
;;
*2007b | *2007B)
MATLAB_VERSION="7.5"
;;
*2007a | *2007A)
MATLAB_VERSION="7.4"
;;
*2006b | *2006B)
MATLAB_VERSION="7.3"
;;
*2006a | *2006A)
MATLAB_VERSION="7.2"
;;
*14SP3 | *14sp3)
MATLAB_VERSION="7.1"
;;
*14SP2 | *14sp2)
MATLAB_VERSION="7.0.4"
;;
*14SP1 | *14sp1)
MATLAB_VERSION="7.0.1"
;;
R14 | r14)
MATLAB_VERSION="7.0.0"
;;
esac
dnl Check that we have an x.y version number
if ! echo "${MATLAB_VERSION}" | grep -qE '^[[0-9.]]+$'; then
AC_MSG_ERROR([unknown MATLAB version ${MATLAB_VERSION}])
fi
AC_MSG_RESULT([${MATLAB_VERSION}])
ax_matlab_version_ok="yes"
else
AC_MSG_RESULT([unknown])
ax_matlab_version_ok="no"
fi
AC_SUBST([MATLAB_VERSION])
])

75
m4/ax_mexext.m4 Normal file
View File

@ -0,0 +1,75 @@
dnl ax_mexext.m4 --- check for MEX-file suffix.
dnl
dnl Copyright © 2000-2003 Ralph Schleicher
dnl Copyright © 2009-2019 Dynare Team
dnl
dnl This program is free software; you can redistribute it and/or
dnl modify it under the terms of the GNU General Public License as
dnl published by the Free Software Foundation; either version 2,
dnl or (at your option) any later version.
dnl
dnl This program is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License along
dnl with this program. If not, see <https://www.gnu.org/licenses/>.
dnl
dnl As a special exception to the GNU General Public License, if
dnl you distribute this file as part of a program that contains a
dnl configuration script generated by GNU Autoconf, you may include
dnl it under the same distribution terms that you use for the rest
dnl of that program.
dnl
dnl Code:
# AX_MEXEXT
# ---------
# Check for MEX-file suffix.
AC_DEFUN([AX_MEXEXT],
[dnl
AC_PREREQ([2.50])
AC_REQUIRE([AX_MATLAB])
AC_REQUIRE([AC_CANONICAL_BUILD])
AC_CACHE_CHECK([for MEX-file suffix], [ax_cv_mexext],
[if test "${MEXEXT+set}" = set ; then
ax_cv_mexext="$MEXEXT"
else
case $build_os in
*cygwin*|*mingw*)
ax_cv_mexext=$("$MATLAB"/bin/mexext.bat | sed 's/\r//')
;;
*)
ax_cv_mexext=$("$MATLAB"/bin/mexext)
;;
esac
fi])
MEXEXT="$ax_cv_mexext"
AC_SUBST([MEXEXT])
])
# AX_DOT_MEXEXT
# -------------
# Check for MEX-file suffix with leading dot.
AC_DEFUN([AX_DOT_MEXEXT],
[dnl
AC_REQUIRE([AX_MEXEXT])
case $MEXEXT in
.*)
;;
*)
if test -n "$MEXEXT" ; then
MEXEXT=.$MEXEXT
AC_MSG_RESULT([setting MEX-file suffix to $MEXEXT])
AC_SUBST([MEXEXT])
fi
;;
esac
])
dnl ax_mexext.m4 ends here
dnl Local variables:
dnl tab-width: 8
dnl End:

139
m4/ax_mexopts.m4 Normal file
View File

@ -0,0 +1,139 @@
dnl Copyright © 2009-2023 Dynare Team
dnl
dnl This file is part of Dynare.
dnl
dnl Dynare is free software: you can redistribute it and/or modify
dnl it under the terms of the GNU General Public License as published by
dnl the Free Software Foundation, either version 3 of the License, or
dnl (at your option) any later version.
dnl
dnl Dynare is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License
dnl along with Dynare. If not, see <https://www.gnu.org/licenses/>.
AC_DEFUN([AX_MEXOPTS],
[dnl
AC_REQUIRE([AX_MEXEXT])
AC_REQUIRE([AX_MATLAB_ARCH])
AC_REQUIRE([AX_MATLAB_VERSION])
AC_REQUIRE([AC_PROG_SED])
AX_COMPARE_VERSION([$MATLAB_VERSION], [lt], [8.3], [AC_MSG_ERROR([Your MATLAB is too old, please upgrade to 8.3 (R2014a) at least.])])
AC_MSG_CHECKING([for options to compile MEX for MATLAB])
MATLAB_CPPFLAGS="-I$MATLAB/extern/include"
case ${MATLAB_ARCH} in
glnxa64)
MATLAB_DEFS="-D_GNU_SOURCE -DNDEBUG"
MATLAB_CFLAGS="-fexceptions -fPIC -pthread"
MATLAB_CXXFLAGS="-fPIC -pthread"
MATLAB_FCFLAGS="-fPIC -fexceptions"
MATLAB_LDFLAGS_NOMAP="-shared -Wl,--no-undefined -Wl,-rpath-link,$MATLAB/bin/glnxa64 -L$MATLAB/bin/glnxa64"
MATLAB_LDFLAGS="$MATLAB_LDFLAGS_NOMAP -Wl,--version-script,$MATLAB/extern/lib/glnxa64/mexFunction.map"
MATLAB_LIBS="-lmx -lmex -lmat -lm -lmwlapack -lmwblas"
FORTRAN_LIBS_FOR_CXXLINK="-lgfortran -lquadmath"
ax_mexopts_ok="yes"
;;
win64)
MATLAB_CFLAGS="-fexceptions"
MATLAB_CXXFLAGS=""
MATLAB_FCFLAGS="-fexceptions -fno-underscoring"
MATLAB_DEFS="-DNDEBUG"
# The hack for libquadmath is needed because -static-libgfortran
# unfortunately does not imply the static linking of the former.
# The last part about winpthread is a hack to avoid dynamically linking
# against libwinpthread DLL (which is pulled in by libstdc++, even without
# using threads, since we are using the POSIX threads version of MinGW)
MATLAB_LDFLAGS_NOMAP="-static-libgcc -static-libstdc++ -static-libgfortran -Wl,-Bstatic,--whole-archive -lquadmath -Wl,-Bdynamic,--no-whole-archive -shared -L$MATLAB/bin/win64 -Wl,-Bstatic,--whole-archive -lwinpthread -Wl,-Bdynamic,--no-whole-archive"
MATLAB_LDFLAGS="$MATLAB_LDFLAGS_NOMAP \$(abs_top_srcdir)/mex.def"
# Hack for libssp, which is pulled in by -fstack-protector
# (curiously only on some MEX files), see windows/build.sh.
# Note that the link against libssp should not happen with compilers
# from MSYS2, see:
# https://www.msys2.org/news/#2022-10-10-libssp-is-no-longer-required
# But it happens with Debians cross compilers (as of Debian “bookworm” 12).
# Also note that the -lssp must come by the end of the link command
# (otherwise it will have to be enclosed within --whole-archive).
MATLAB_LIBS="-lmex -lmx -lmat -lmwlapack -lmwblas -Wl,-Bstatic -lssp -Wl,-Bdynamic"
# Hack for static linking of libgomp, needed for OpenMP.
# Should come by the end of the link command
# (otherwise it will have to be enclosed within --whole-archive).
OPENMP_LIBS="-Wl,-Bstatic -lgomp -Wl,-Bdynamic"
FORTRAN_LIBS_FOR_CXXLINK="-Wl,-Bstatic -lgfortran -Wl,-Bdynamic" # libquadmath is already in MATLAB_LDFLAGS_NOMAP
ax_mexopts_ok="yes"
;;
mac[[ai]]64)
MATLAB_DEFS="-DNDEBUG"
MATLAB_CFLAGS="-fno-common -fexceptions"
MATLAB_CXXFLAGS="-fno-common -fexceptions"
MATLAB_FCFLAGS="-fexceptions -fbackslash"
MATLAB_LDFLAGS_NOMAP="-Wl,-twolevel_namespace -undefined error -bundle"
MATLAB_LDFLAGS="$MATLAB_LDFLAGS_NOMAP -Wl,-exported_symbols_list,\$(abs_top_srcdir)/mexFunction-MacOSX.map"
# This -L flag is put here, hence later on the linker command line, so as
# to avoid linking against the HDF5 shipped by MATLAB (which would
# otherwise override the HDF5 from Homebrew)
MATLAB_LIBS="-L$MATLAB/bin/${MATLAB_ARCH} -lmx -lmex -lmat -lmwlapack -lmwblas"
FORTRAN_LIBS_FOR_CXXLINK="-lgfortran -lquadmath"
ax_mexopts_ok="yes"
;;
*)
ax_mexopts_ok="no"
;;
esac
# Converts the MATLAB version number into comparable integers with only major and minor version numbers
# For example, 7.4.2 will become 0704
ax_matlab_ver=$(echo "$MATLAB_VERSION" | $SED -e 's/\([[0-9]]*\)\.\([[0-9]]*\).*/Z\1ZZ\2Z/' \
-e 's/Z\([[0-9]]\)Z/Z0\1Z/g' \
-e 's/[[^0-9]]//g')
MATLAB_DEFS="$MATLAB_DEFS -DMATLAB_VERSION=0x${ax_matlab_ver}"
if test "$ax_mexopts_ok" = "yes"; then
AC_MSG_RESULT([ok])
else
AC_MSG_RESULT([unknown])
fi
# Allow user to override default Matlab compilation flags
# Github ticket #1121
if test -n "$MATLAB_MEX_CPPFLAGS"; then
MATLAB_CPPFLAGS="$MATLAB_CPPFLAGS $MATLAB_MEX_CPPFLAGS"
fi
if test -n "$MATLAB_MEX_DEFS"; then
MATLAB_DEFS="$MATLAB_DEFS $MATLAB_MEX_DEFS"
fi
if test -n "$MATLAB_MEX_CFLAGS"; then
MATLAB_CFLAGS="$MATLAB_CFLAGS $MATLAB_MEX_CFLAGS"
fi
if test -n "$MATLAB_MEX_CXXFLAGS"; then
MATLAB_CXXFLAGS="$MATLAB_CXXFLAGS $MATLAB_MEX_CXXFLAGS"
fi
if test -n "$MATLAB_MEX_LDFLAGS"; then
MATLAB_LDFLAGS="$MATLAB_LDFLAGS $MATLAB_MEX_LDFLAGS"
fi
if test -n "$MATLAB_MEX_LIBS"; then
MATLAB_LIBS="$MATLAB_LIBS $MATLAB_MEX_LIBS"
fi
AC_SUBST([MATLAB_CPPFLAGS])
AC_SUBST([MATLAB_DEFS])
AC_SUBST([MATLAB_CFLAGS])
AC_SUBST([MATLAB_CXXFLAGS])
AC_SUBST([MATLAB_FCFLAGS])
AC_SUBST([MATLAB_LDFLAGS])
AC_SUBST([MATLAB_LIBS])
AC_SUBST([OPENMP_LIBS])
AC_SUBST([FORTRAN_LIBS_FOR_CXXLINK])
])

56
m4/ax_octave.m4 Normal file
View File

@ -0,0 +1,56 @@
dnl ax_octave.m4 --- check for Octave
dnl
dnl Copyright © 2020-2021 Dynare Team
dnl
dnl This program is free software; you can redistribute it and/or
dnl modify it under the terms of the GNU General Public License as
dnl published by the Free Software Foundation; either version 2,
dnl or (at your option) any later version.
dnl
dnl This program is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License along
dnl with this program. If not, see <https://www.gnu.org/licenses/>.
dnl
dnl As a special exception to the GNU General Public License, if
dnl you distribute this file as part of a program that contains a
dnl configuration script generated by GNU Autoconf, you may include
dnl it under the same distribution terms that you use for the rest
dnl of that program.
# AX_OCTAVE
# ---------
# Checks for Octave.
# Search in the argument given to --with-octave if any.
# Otherwise, search in PATH.
# Sets OCTAVE and MKOCTFILE variables and calls AC_SUBST on them.
# Sets ax_enable_octave=yes if successful, ax_enable_octave=no otherwise
AC_DEFUN([AX_OCTAVE],
[dnl
AC_ARG_WITH([octave], AS_HELP_STRING([--with-octave=PATH], [Path to search for Octave installation]),
[
if test -n "$withval"; then
if test -x "$withval/bin/octave" && test -x "$withval/bin/mkoctfile"; then
OCTAVE="$withval/bin/octave"
MKOCTFILE="$withval/bin/mkoctfile"
else
AC_MSG_ERROR([invalid value '$withval' for --with-octave])
fi
fi
])
AC_CHECK_PROG([OCTAVE], [octave], [octave])
AC_CHECK_PROG([MKOCTFILE], [mkoctfile], [mkoctfile])
if test -n "$OCTAVE" && test -n "$MKOCTFILE"; then
ax_enable_octave=yes
else
ax_enable_octave=no
fi
AC_SUBST([OCTAVE])
AC_SUBST([MKOCTFILE])
])

27
m4/ax_prog_ln_s.m4 Normal file
View File

@ -0,0 +1,27 @@
dnl Copyright © 2009-2010 Dynare Team
dnl
dnl This file is part of Dynare.
dnl
dnl Dynare is free software: you can redistribute it and/or modify
dnl it under the terms of the GNU General Public License as published by
dnl the Free Software Foundation, either version 3 of the License, or
dnl (at your option) any later version.
dnl
dnl Dynare is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License
dnl along with Dynare. If not, see <https://www.gnu.org/licenses/>.
AC_DEFUN([AX_PROG_LN_S],
[
AC_REQUIRE([AC_CANONICAL_HOST])
AC_REQUIRE([AC_PROG_LN_S])
case ${host_os} in
*cygwin*|*mingw32*)
LN_S="cp -p" # Symbolic links are not understood by MATLAB under Windows
;;
esac
])

68
m4/ax_slicot.m4 Normal file
View File

@ -0,0 +1,68 @@
dnl Detect the SLICOT Library.
dnl Called with an argument of either 'matlab' or 'octave', depending
dnl on the configure script from which we're calling it
dnl
dnl AX_SLICOT([matlab])
dnl AX_SLICOT([octave])
dnl
dnl Copyright © 2012-2021 Dynare Team
dnl
dnl This file is part of Dynare.
dnl
dnl Dynare is free software: you can redistribute it and/or modify
dnl it under the terms of the GNU General Public License as published by
dnl the Free Software Foundation, either version 3 of the License, or
dnl (at your option) any later version.
dnl
dnl Dynare is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
dnl GNU General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License
dnl along with Dynare. If not, see <https://www.gnu.org/licenses/>.
AC_DEFUN([AX_SLICOT],
[
if test "$1" != matlab && test "$1" != octave; then
AC_MSG_ERROR([Argument to autoconf slicot macro must be either 'matlab' or 'octave'])
fi
AC_ARG_WITH(slicot, AS_HELP_STRING([--with-slicot=DIR], [prefix to SLICOT installation]),
slicot_prefix="$withval", slicot_prefix="")
has_slicot=yes
if test -n "$slicot_prefix"; then
LDFLAGS_SLICOT="-L$withval/lib"
else
LDFLAGS_SLICOT=""
fi
my_save_LDFLAGS=$LDFLAGS
# At this point we should add MATLAB_FCFLAGS to FCFLAGS for Windows (which has -fno-underscoring),
# but that does not work. The actual underscore test seems to happen at the very beginning of the
# macro. Hence the modification of FCFLAGS was moved higher (in mex/build/matlab/configure.ac).
AC_FC_FUNC(sb02od)
if test "$1" = matlab; then
LDFLAGS="$LDFLAGS $MATLAB_LDFLAGS_NOMAP $LDFLAGS_SLICOT"
# Add MATLAB_CFLAGS to get the -fPIC on Linux/x86_64 (otherwise linking fails)
my_save_CFLAGS=$CFLAGS
CFLAGS="$CFLAGS $MATLAB_CFLAGS"
AC_CHECK_LIB([slicot64_pic], [$sb02od], [LIBADD_SLICOT="-lslicot64_pic"], [has_slicot=no], [$MATLAB_LIBS])
CFLAGS=$my_save_CFLAGS
else
LDFLAGS="$LDFLAGS $LDFLAGS_SLICOT"
# Fallback on libslicot_pic if dynamic libslicot not found
AC_CHECK_LIB([slicot], [$sb02od], [LIBADD_SLICOT="-lslicot"],
[
AC_CHECK_LIB([slicot_pic], [$sb02od], [LIBADD_SLICOT="-lslicot_pic"], [has_slicot=no], [$($MKOCTFILE -p BLAS_LIBS) $($MKOCTFILE -p LAPACK_LIBS)])
],
[$($MKOCTFILE -p BLAS_LIBS) $($MKOCTFILE -p LAPACK_LIBS)])
fi
LDFLAGS=$my_save_LDFLAGS
AC_SUBST(LDFLAGS_SLICOT)
AC_SUBST(LIBADD_SLICOT)
])

View File

@ -15,28 +15,22 @@
# You should have received a copy of the GNU General Public License
# along with Dynare. If not, see <https://www.gnu.org/licenses/>.
ARCHS = arm64 x86_64
BUILDS = $(addprefix build-, $(ARCHS))
DEPS = $(addprefix deps-, $(ARCHS))
CLEAN_DEPS = $(addprefix clean-deps-, $(ARCHS))
CLEAN_ALL = $(addprefix clean-all-, $(ARCHS))
.PHONY: all deps clean-deps clean clean-all build
.PHONY: all $(BUILDS) $(DEPS) clean-pkg $(CLEAN_DEPS) $(CLEAN_ALL) clean-all
NTHREADS=$(shell sysctl -n hw.ncpu)
all: $(BUILDS)
all: build
$(BUILDS): build-%: deps-%
./build.sh $*
deps:
make -C deps -j$(NTHREADS)
$(DEPS): deps-%:
make -C deps DEPS_ARCH=$*
clean-deps:
make -C deps clean-all
$(CLEAN_DEPS): clean-deps-%:
make -C deps clean-all DEPS_ARCH=$*
clean-pkg:
clean:
rm -rf pkg
$(CLEAN_ALL): clean-all-%: clean-deps-% clean-pkg
clean-all: clean-deps clean
clean-all: $(CLEAN_ALL)
build: deps
./build.sh

279
macOS/brewfiles/gcc.rb Normal file
View File

@ -0,0 +1,279 @@
class Gcc < Formula
desc "GNU compiler collection"
homepage "https://gcc.gnu.org/"
license "GPL-3.0-or-later" => { with: "GCC-exception-3.1" }
head "https://gcc.gnu.org/git/gcc.git", branch: "master"
stable do
url "https://ftp.gnu.org/gnu/gcc/gcc-13.1.0/gcc-13.1.0.tar.xz"
mirror "https://ftpmirror.gnu.org/gcc/gcc-13.1.0/gcc-13.1.0.tar.xz"
sha256 "61d684f0aa5e76ac6585ad8898a2427aade8979ed5e7f85492286c4dfc13ee86"
# Branch from the Darwin maintainer of GCC, with a few generic fixes and
# Apple Silicon support, located at https://github.com/iains/gcc-13-branch
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/5c206c47/gcc/gcc-13.1.0.diff"
sha256 "cb4e8a89387f748a744da0273025d0dc2e3c76780cc390b18ada704676afea11"
end
end
livecheck do
url :stable
regex(%r{href=["']?gcc[._-]v?(\d+(?:\.\d+)+)(?:/?["' >]|\.t)}i)
end
bottle do
sha256 cellar: :any, arm64_ventura: "d2b21a257c73e9b8f9c6bc03e6330ea8ba9fb3e7cdb9eb945d7ff7d96ba9708c"
sha256 cellar: :any, arm64_monterey: "5405f3b1ecdabb68e161308f35d72af907af21694a0e2b67f10edb25b2dd8f90"
sha256 cellar: :any, arm64_big_sur: "cc92fced3516bc72b69e31b0495fe416f206b540be02f1c817db96afbcc38f28"
sha256 cellar: :any, ventura: "3abd8c2c88a8e74b5df5c44f9c151ff7e760cf705307ecf3c95762492e777f1e"
sha256 cellar: :any, monterey: "f9cbc7eb14781df9228518a2d02590941206947e7dc419c0b232d523f39b1475"
sha256 cellar: :any, big_sur: "2eb458ed309ea4fa9451ab547fa3d797bd523ba4f50f01d5c997212109b74e5e"
sha256 cellar: :any_skip_relocation, x86_64_linux: "cca77a5d6625d3bb711ce40551751974d4cb5c74306329fc2fc8cdcade2ef564"
end
# The bottles are built on systems with the CLT installed, and do not work
# out of the box on Xcode-only systems due to an incorrect sysroot.
pour_bottle? only_if: :clt_installed
depends_on "gmp"
depends_on "isl"
depends_on "libmpc"
depends_on "mpfr"
depends_on "zstd"
uses_from_macos "zlib"
on_linux do
depends_on "binutils"
end
# GCC bootstraps itself, so it is OK to have an incompatible C++ stdlib
cxxstdlib_check :skip
def version_suffix
if build.head?
"HEAD"
else
version.major.to_s
end
end
def install
# GCC will suffer build errors if forced to use a particular linker.
ENV.delete "LD"
# We avoiding building:
# - Ada and D, which require a pre-existing GCC to bootstrap
# - Go, currently not supported on macOS
# - BRIG
languages = %w[c c++ objc obj-c++ fortran]
pkgversion = "Homebrew GCC #{pkg_version} #{build.used_options*" "}".strip
# Use `lib/gcc/current` to provide a path that doesn't change with GCC's version.
args = %W[
--prefix=#{opt_prefix}
--libdir=#{opt_lib}/gcc/current
--disable-nls
--enable-checking=release
--with-gcc-major-version-only
--enable-languages=#{languages.join(",")}
--program-suffix=-#{version_suffix}
--with-gmp=#{Formula["gmp"].opt_prefix}
--with-mpfr=#{Formula["mpfr"].opt_prefix}
--with-mpc=#{Formula["libmpc"].opt_prefix}
--with-isl=#{Formula["isl"].opt_prefix}
--with-zstd=#{Formula["zstd"].opt_prefix}
--with-pkgversion=#{pkgversion}
--with-bugurl=#{tap.issues_url}
--with-system-zlib
]
if OS.mac?
cpu = Hardware::CPU.arm? ? "aarch64" : "x86_64"
args << "--build=#{cpu}-apple-darwin#{OS.kernel_version.major}"
# System headers may not be in /usr/include
sdk = MacOS.sdk_path_if_needed
args << "--with-sysroot=#{sdk}" if sdk
else
# Fix cc1: error while loading shared libraries: libisl.so.15
args << "--with-boot-ldflags=-static-libstdc++ -static-libgcc #{ENV.ldflags}"
# Fix Linux error: gnu/stubs-32.h: No such file or directory.
args << "--disable-multilib"
# Enable to PIE by default to match what the host GCC uses
args << "--enable-default-pie"
# Change the default directory name for 64-bit libraries to `lib`
# https://stackoverflow.com/a/54038769
inreplace "gcc/config/i386/t-linux64", "m64=../lib64", "m64="
end
mkdir "build" do
system "../configure", *args
system "make"
# Do not strip the binaries on macOS, it makes them unsuitable
# for loading plugins
install_target = OS.mac? ? "install" : "install-strip"
# To make sure GCC does not record cellar paths, we configure it with
# opt_prefix as the prefix. Then we use DESTDIR to install into a
# temporary location, then move into the cellar path.
system "make", install_target, "DESTDIR=#{Pathname.pwd}/../instdir"
mv Dir[Pathname.pwd/"../instdir/#{opt_prefix}/*"], prefix
end
bin.install_symlink bin/"gfortran-#{version_suffix}" => "gfortran"
# Provide a `lib/gcc/xy` directory to align with the versioned GCC formulae.
# We need to create `lib/gcc/xy` as a directory and not a symlink to avoid `brew link` conflicts.
(lib/"gcc"/version_suffix).install_symlink (lib/"gcc/current").children
# Only the newest brewed gcc should install gfortan libs as we can only have one.
lib.install_symlink lib.glob("gcc/current/libgfortran.*") if OS.linux?
# Handle conflicts between GCC formulae and avoid interfering
# with system compilers.
# Rename man7.
man7.glob("*.7") { |file| add_suffix file, version_suffix }
# Even when we disable building info pages some are still installed.
info.rmtree
# Work around GCC install bug
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105664
rm_rf bin.glob("*-gcc-tmp")
end
def add_suffix(file, suffix)
dir = File.dirname(file)
ext = File.extname(file)
base = File.basename(file, ext)
File.rename file, "#{dir}/#{base}-#{suffix}#{ext}"
end
def post_install
if OS.linux?
gcc = bin/"gcc-#{version_suffix}"
libgcc = Pathname.new(Utils.safe_popen_read(gcc, "-print-libgcc-file-name")).parent
raise "command failed: #{gcc} -print-libgcc-file-name" if $CHILD_STATUS.exitstatus.nonzero?
glibc = Formula["glibc"]
glibc_installed = glibc.any_version_installed?
# Symlink system crt1.o and friends where gcc can find it.
crtdir = if glibc_installed
glibc.opt_lib
else
Pathname.new(Utils.safe_popen_read("/usr/bin/cc", "-print-file-name=crti.o")).parent
end
ln_sf Dir[crtdir/"*crt?.o"], libgcc
# Create the GCC specs file
# See https://gcc.gnu.org/onlinedocs/gcc/Spec-Files.html
# Locate the specs file
specs = libgcc/"specs"
ohai "Creating the GCC specs file: #{specs}"
specs_orig = Pathname.new("#{specs}.orig")
rm_f [specs_orig, specs]
system_header_dirs = ["#{HOMEBREW_PREFIX}/include"]
if glibc_installed
# https://github.com/Linuxbrew/brew/issues/724
system_header_dirs << glibc.opt_include
else
# Locate the native system header dirs if user uses system glibc
target = Utils.safe_popen_read(gcc, "-print-multiarch").chomp
raise "command failed: #{gcc} -print-multiarch" if $CHILD_STATUS.exitstatus.nonzero?
system_header_dirs += ["/usr/include/#{target}", "/usr/include"]
end
# Save a backup of the default specs file
specs_string = Utils.safe_popen_read(gcc, "-dumpspecs")
raise "command failed: #{gcc} -dumpspecs" if $CHILD_STATUS.exitstatus.nonzero?
specs_orig.write specs_string
# Set the library search path
# For include path:
# * `-isysroot #{HOMEBREW_PREFIX}/nonexistent` prevents gcc searching built-in
# system header files.
# * `-idirafter <dir>` instructs gcc to search system header
# files after gcc internal header files.
# For libraries:
# * `-nostdlib -L#{libgcc} -L#{glibc.opt_lib}` instructs gcc to use
# brewed glibc if applied.
# * `-L#{libdir}` instructs gcc to find the corresponding gcc
# libraries. It is essential if there are multiple brewed gcc
# with different versions installed.
# Noted that it should only be passed for the `gcc@*` formulae.
# * `-L#{HOMEBREW_PREFIX}/lib` instructs gcc to find the rest
# brew libraries.
# Note: *link will silently add #{libdir} first to the RPATH
libdir = HOMEBREW_PREFIX/"lib/gcc/current"
specs.write specs_string + <<~EOS
*cpp_unique_options:
+ -isysroot #{HOMEBREW_PREFIX}/nonexistent #{system_header_dirs.map { |p| "-idirafter #{p}" }.join(" ")}
*link_libgcc:
#{glibc_installed ? "-nostdlib -L#{libgcc} -L#{glibc.opt_lib}" : "+"} -L#{libdir} -L#{HOMEBREW_PREFIX}/lib
*link:
+ --dynamic-linker #{HOMEBREW_PREFIX}/lib/ld.so -rpath #{libdir}
*homebrew_rpath:
-rpath #{HOMEBREW_PREFIX}/lib
EOS
inreplace(specs, " %o ", "\\0%(homebrew_rpath) ")
end
end
test do
(testpath/"hello-c.c").write <<~EOS
#include <stdio.h>
int main()
{
puts("Hello, world!");
return 0;
}
EOS
system "#{bin}/gcc-#{version_suffix}", "-o", "hello-c", "hello-c.c"
assert_equal "Hello, world!\n", shell_output("./hello-c")
(testpath/"hello-cc.cc").write <<~EOS
#include <iostream>
struct exception { };
int main()
{
std::cout << "Hello, world!" << std::endl;
try { throw exception{}; }
catch (exception) { }
catch (...) { }
return 0;
}
EOS
system "#{bin}/g++-#{version_suffix}", "-o", "hello-cc", "hello-cc.cc"
assert_equal "Hello, world!\n", shell_output("./hello-cc")
(testpath/"test.f90").write <<~EOS
integer,parameter::m=10000
real::a(m), b(m)
real::fact=0.5
do concurrent (i=1:m)
a(i) = a(i) + fact*b(i)
end do
write(*,"(A)") "Done"
end
EOS
system "#{bin}/gfortran", "-o", "test", "test.f90"
assert_equal "Done\n", shell_output("./test")
end
end

102
macOS/brewfiles/gmp.rb Normal file
View File

@ -0,0 +1,102 @@
class Gmp < Formula
desc "GNU multiple precision arithmetic library"
homepage "https://gmplib.org/"
license any_of: ["LGPL-3.0-or-later", "GPL-2.0-or-later"]
revision 1
stable do
url "https://gmplib.org/download/gmp/gmp-6.2.1.tar.xz"
mirror "https://ftp.gnu.org/gnu/gmp/gmp-6.2.1.tar.xz"
sha256 "fd4829912cddd12f84181c3451cc752be224643e87fac497b69edddadc49b4f2"
# Fix -flat_namespace being used on Big Sur and later.
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/03cf8088210822aa2c1ab544ed58ea04c897d9c4/libtool/configure-big_sur.diff"
sha256 "35acd6aebc19843f1a2b3a63e880baceb0f5278ab1ace661e57a502d9d78c93c"
end
end
livecheck do
url "https://gmplib.org/download/gmp/"
regex(/href=.*?gmp[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
sha256 cellar: :any, arm64_ventura: "2436cd120e5678d67c24020a50cbbf7c0220e7ecaac63981335872b9d666bcad"
sha256 cellar: :any, arm64_monterey: "a43a2ae4c44d90626b835a968a32327c8b8bbf754ec1d2590f8ac656c71dace9"
sha256 cellar: :any, arm64_big_sur: "491220f1ff2c662b96295d931a80702523eeaee681d7305fb02b561e527dcbb8"
sha256 cellar: :any, ventura: "4c6488dfd53b8287702827a4e6d50569926417f2cd08613d37720de54b6afe0c"
sha256 cellar: :any, monterey: "dddc6d8c871c92f6e5fb1249c28768aa2b4b47c38836a69cf787a639cf5eee73"
sha256 cellar: :any, big_sur: "e566452815d2ff5dc66da160bd1cd3d9cf02a17a07284cf0bac46496133383ae"
sha256 cellar: :any, catalina: "5ee7a460668864c28e541db15420e1480c3d31c5f216797a453a5310106fbc97"
sha256 cellar: :any, mojave: "b9d7d36c8d263be0e02e17d435350546f9f7008eb21b6e86bf42f719efcba85e"
sha256 cellar: :any_skip_relocation, x86_64_linux: "786ae29f0c0b06ea86e42bd9c6ac2c49bd5757da037dead7053e8bd612c4cf8c"
end
head do
url "https://gmplib.org/repo/gmp/", using: :hg
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
uses_from_macos "m4" => :build
# Prevent crash on macOS 12 betas with release gmp 6.2.1, can be removed after the next gmp release.
patch do
url "https://gmplib.org/repo/gmp/raw-rev/5f32dbc41afc"
sha256 "a44ef57903b240df6fde6c9d2fe40063f785995c43b6bfc7a237c571f53613e0"
end
def install
system "./.bootstrap" if build.head?
args = std_configure_args
args << "--enable-cxx"
# Enable --with-pic to avoid linking issues with the static library
args << "--with-pic"
cpu = Hardware::CPU.arm? ? "aarch64" : Hardware.oldest_cpu
if OS.mac?
args << "--build=#{cpu}-apple-darwin#{OS.kernel_version.major}"
else
args << "--build=#{cpu}-linux-gnu"
args << "ABI=32" if Hardware::CPU.is_32_bit?
end
system "./configure", *args
system "make"
system "make", "check"
system "make", "install"
# Prevent brew from trying to install metafiles that
# are actually symlinks to files in autotools kegs
buildpath.children.select(&:symlink?).map(&:unlink) if build.head?
end
test do
(testpath/"test.c").write <<~EOS
#include <gmp.h>
#include <stdlib.h>
int main() {
mpz_t i, j, k;
mpz_init_set_str (i, "1a", 16);
mpz_init (j);
mpz_init (k);
mpz_sqrtrem (j, k, i);
if (mpz_get_si (j) != 5 || mpz_get_si (k) != 1) abort();
return 0;
}
EOS
system ENV.cc, "test.c", "-L#{lib}", "-lgmp", "-o", "test"
system "./test"
# Test the static library to catch potential linking issues
system ENV.cc, "test.c", "#{lib}/libgmp.a", "-o", "test"
system "./test"
end
end

65
macOS/brewfiles/isl.rb Normal file
View File

@ -0,0 +1,65 @@
class Isl < Formula
# NOTE: Always use tarball instead of git tag for stable version.
#
# Currently isl detects its version using source code directory name
# and update isl_version() function accordingly. All other names will
# result in isl_version() function returning "UNKNOWN" and hence break
# package detection.
desc "Integer Set Library for the polyhedral model"
homepage "https://libisl.sourceforge.io/"
url "https://libisl.sourceforge.io/isl-0.26.tar.xz"
sha256 "a0b5cb06d24f9fa9e77b55fabbe9a3c94a336190345c2555f9915bb38e976504"
license "MIT"
livecheck do
url :homepage
regex(/href=.*?isl[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
sha256 cellar: :any, arm64_ventura: "1814fe867c61b34cd5c763cf2ebda99d7883db78348c8b663f98cc95a1348d16"
sha256 cellar: :any, arm64_monterey: "0a3e83c458420e4b469ad7464d16d6c9cd26a888059358eb5f1f9d3cff54bbd7"
sha256 cellar: :any, arm64_big_sur: "a68a647249ad644cd8d1e1057bac65e5b4e1e08f9adaf15a07121853b0ed40cc"
sha256 cellar: :any, ventura: "0301489db7b26967657be0f6c89f11ea7e1e5fb50631686f86c597b01c00dc85"
sha256 cellar: :any, monterey: "0dcc555fd2517c6c93bca8999c741029bbdd821bfeb397505ec1f98deb79c551"
sha256 cellar: :any, big_sur: "91965ce2f54c7d1b16747ed05de989a3a122f5dbee67546bbf9bf065873b13c5"
sha256 cellar: :any_skip_relocation, x86_64_linux: "db14ba1e4ea23ab41e06930dcf25ae9023c5e395c88602da2a9b6a98d54c92d3"
end
head do
url "https://repo.or.cz/isl.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "gmp"
def install
system "./autogen.sh" if build.head?
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--with-gmp=system",
"--with-gmp-prefix=#{Formula["gmp"].opt_prefix}"
system "make"
system "make", "install"
(share/"gdb/auto-load").install Dir["#{lib}/*-gdb.py"]
end
test do
(testpath/"test.c").write <<~EOS
#include <isl/ctx.h>
int main()
{
isl_ctx* ctx = isl_ctx_alloc();
isl_ctx_free(ctx);
return 0;
}
EOS
system ENV.cc, "test.c", "-L#{lib}", "-lisl", "-o", "test"
system "./test"
end
end

60
macOS/brewfiles/libmpc.rb Normal file
View File

@ -0,0 +1,60 @@
class Libmpc < Formula
desc "C library for the arithmetic of high precision complex numbers"
homepage "http://www.multiprecision.org/mpc/"
url "https://ftp.gnu.org/gnu/mpc/mpc-1.3.1.tar.gz"
mirror "https://ftpmirror.gnu.org/mpc/mpc-1.3.1.tar.gz"
sha256 "ab642492f5cf882b74aa0cb730cd410a81edcdbec895183ce930e706c1c759b8"
license "LGPL-3.0-or-later"
bottle do
sha256 cellar: :any, arm64_ventura: "da4ff781bc469c82af17f98f0bdbf20932e222d0520ab784cd1b322b789ad7a5"
sha256 cellar: :any, arm64_monterey: "dd3994160b3625b1f14e34abf632b90bf49e71db1cc85c12e9ab529d4cae2a87"
sha256 cellar: :any, arm64_big_sur: "43bbe994c7bbb40f7172ef7a750bc6d2687275a76a25f67fc2d53ef00728d912"
sha256 cellar: :any, ventura: "aa4ddb0e50ace93746e6af2e6185493698b501e9359cf73ce41cfbb70369db09"
sha256 cellar: :any, monterey: "c32f2c3fe7ab06e308e6fa74874e1d4d92ff6eb3598da6e0f8e6fa7a333350f5"
sha256 cellar: :any, big_sur: "47b50c3df6a35ea3c876397eac4a7dc157b5f4109247671a16599a9a41b9c035"
sha256 cellar: :any_skip_relocation, x86_64_linux: "f6542ae5bcf643ca0c980c7000cde1585922e76be080b3cc3422dac0d4a50904"
end
head do
url "https://gitlab.inria.fr/mpc/mpc.git", branch: "master"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "gmp"
depends_on "mpfr"
def install
system "autoreconf", "--force", "--install", "--verbose" if build.head?
system "./configure", *std_configure_args,
"--with-gmp=#{Formula["gmp"].opt_prefix}",
"--with-mpfr=#{Formula["mpfr"].opt_prefix}"
system "make"
system "make", "check"
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <mpc.h>
#include <assert.h>
#include <math.h>
int main() {
mpc_t x;
mpc_init2 (x, 256);
mpc_set_d_d (x, 1., INFINITY, MPC_RNDNN);
mpc_tanh (x, x, MPC_RNDNN);
assert (mpfr_nan_p (mpc_realref (x)) && mpfr_nan_p (mpc_imagref (x)));
mpc_clear (x);
return 0;
}
EOS
system ENV.cc, "test.c", "-L#{lib}", "-L#{Formula["mpfr"].opt_lib}",
"-L#{Formula["gmp"].opt_lib}", "-lmpc", "-lmpfr",
"-lgmp", "-o", "test"
system "./test"
end
end

101
macOS/brewfiles/mpfr.rb Normal file
View File

@ -0,0 +1,101 @@
class Mpfr < Formula
desc "C library for multiple-precision floating-point computations"
homepage "https://www.mpfr.org/"
license "LGPL-3.0-or-later"
stable do
url "https://ftp.gnu.org/gnu/mpfr/mpfr-4.2.0.tar.xz"
mirror "https://ftpmirror.gnu.org/mpfr/mpfr-4.2.0.tar.xz"
sha256 "06a378df13501248c1b2db5aa977a2c8126ae849a9d9b7be2546fb4a9c26d993"
version "4.2.0-p9"
# Upstream patches, list at https://www.mpfr.org/mpfr-current/#fixed
%w[
01 2e465c31689e780a93b24bf2959917443fb882da85b7f1ef23ae53d3de614aa4
02 e1ef3d4dab999f4e0ad5ee046c3a2823d3a9395fb8092c3dcb85d3fe29994b52
03 a906f9ed8e4a7230980322a0154702664164690614e5ff55ae7049c3fae55584
04 ece14ee57596dc2e4f67d2e857c5c6b23d76b20183a50a8b6759b640df001b78
05 c4144564097a1be89c9cc2e7ee255c9fe59eb1b94a17c9d4a08169223e705ac1
06 70456748a8072265ba103d93ba94e9f93ae64565e6a5742194c56030086540fa
07 472386aa5f8c51fbdf60154c19268ce2212be03e1c2f9004c1673b6c270508f6
08 6ecd3bd2edf178f4ede4be612964d1b2d0a0bb10ad6f8c51d1a8011fff87d5ea
09 3e9aed5bcea95d34d0bd179a61cd7acb712c89c9a745535f18f0ef619833ba3b
].each_slice(2) do |p, checksum|
patch do
url "https://www.mpfr.org/mpfr-4.2.0/patch#{p}"
sha256 checksum
end
end
end
livecheck do
url "https://www.mpfr.org/mpfr-current/"
regex(/href=.*?mpfr[._-]v?(\d+(?:\.\d+)+)\.t/i)
strategy :page_match do |page, regex|
version = page.scan(regex).map { |match| Version.new(match[0]) }.max&.to_s
next if version.blank?
patch = page.scan(%r{href=["']?/?patch(\d+)["' >]}i)
.map { |match| Version.new(match[0]) }
.max
&.to_s
next version if patch.blank?
"#{version}-p#{patch.to_i}"
end
end
bottle do
sha256 cellar: :any, arm64_ventura: "176114984411aeb1187a50fd9ffc39d7dfe0bf5dc29ab13b0ecc95307d619ff9"
sha256 cellar: :any, arm64_monterey: "77a979ab547618549fc85a12212abd57b085b1712c53299847966d76a4e261f9"
sha256 cellar: :any, arm64_big_sur: "f5776604dbb68288c8dfe371e46398a671b6c34329ad473ada5d4e1fa7562086"
sha256 cellar: :any, ventura: "781d9c4887b8b18ccb96653ce59bb9aa5ee49dd1fb6c7d804750f58ce8726a2f"
sha256 cellar: :any, monterey: "a8eb9e75c01527d80843daba945a7581942362e689e3f3b7c6c891daa2655e9e"
sha256 cellar: :any, big_sur: "22360e6d89681f3d3d326a5654ab0cfb22d5ac42241c40e9f8f91eb06bb1b77c"
sha256 cellar: :any_skip_relocation, x86_64_linux: "d0cafd93a5957220615ae6478033031b750ba5eb6a830cf86d4cbde5bffec8d5"
end
head do
url "https://gitlab.inria.fr/mpfr/mpfr.git", branch: "master"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "gmp"
def install
system "./autogen.sh" if build.head?
system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}",
"--disable-silent-rules"
system "make"
system "make", "check"
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
#include <mpfr.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
int main() {
mpfr_t x, y;
mpfr_inits2 (256, x, y, NULL);
mpfr_set_ui (x, 2, MPFR_RNDN);
mpfr_rootn_ui (y, x, 2, MPFR_RNDN);
mpfr_pow_si (x, y, 4, MPFR_RNDN);
mpfr_add_si (y, x, -4, MPFR_RNDN);
mpfr_abs (y, y, MPFR_RNDN);
if (fabs(mpfr_get_d (y, MPFR_RNDN)) > 1.e-30) abort();
if (strcmp("#{version}", mpfr_get_version())) abort();
return 0;
}
EOS
system ENV.cc, "test.c", "-L#{lib}", "-L#{Formula["gmp"].opt_lib}",
"-lgmp", "-lmpfr", "-o", "test"
system "./test"
end
end

61
macOS/brewfiles/zstd.rb Normal file
View File

@ -0,0 +1,61 @@
class Zstd < Formula
desc "Zstandard is a real-time compression algorithm"
homepage "https://facebook.github.io/zstd/"
url "https://github.com/facebook/zstd/archive/v1.5.5.tar.gz"
mirror "http://fresh-center.net/linux/misc/zstd-1.5.5.tar.gz"
mirror "http://fresh-center.net/linux/misc/legacy/zstd-1.5.5.tar.gz"
sha256 "98e9c3d949d1b924e28e01eccb7deed865eefebf25c2f21c702e5cd5b63b85e1"
license "BSD-3-Clause"
head "https://github.com/facebook/zstd.git", branch: "dev"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 cellar: :any, arm64_ventura: "b709835f4cd5d339b97103f0dfa343489a02d2073f8e80ba7b04d682f1d29bd4"
sha256 cellar: :any, arm64_monterey: "e3cb579108afe4794143b33f24b6020648ca166f0104eb3d13cee56da62c949f"
sha256 cellar: :any, arm64_big_sur: "faf929cf92dad72eca2b16fb5aedb695f5d291aac18b496061b8b14003b2e224"
sha256 cellar: :any, ventura: "e4eb8cc0473c699ec424bfecc67fcfd30631f7fe5eacf26c727bfed73dcf7c12"
sha256 cellar: :any, monterey: "9c1cfe9158a48f6bd3eeb92608ed2799a048d1d27e70e7acef82d5eb4a7a1cea"
sha256 cellar: :any, big_sur: "73d78b5fef5ba31d3c37b8201310fe042f30c6000a97b8ba0d91208e1e1de231"
sha256 cellar: :any_skip_relocation, x86_64_linux: "68c8655224f058316c16462507b6cdd061bd546e161bf8419c68ca526d3a9a48"
end
depends_on "cmake" => :build
depends_on "lz4"
depends_on "xz"
uses_from_macos "zlib"
def install
# Legacy support is the default after
# https://github.com/facebook/zstd/commit/db104f6e839cbef94df4df8268b5fecb58471274
# Set it to `ON` to be explicit about the configuration.
system "cmake", "-S", "build/cmake", "-B", "builddir",
"-DZSTD_PROGRAMS_LINK_SHARED=ON", # link `zstd` to `libzstd`
"-DZSTD_BUILD_CONTRIB=ON",
"-DCMAKE_INSTALL_RPATH=#{rpath}",
"-DZSTD_LEGACY_SUPPORT=ON",
"-DZSTD_ZLIB_SUPPORT=ON",
"-DZSTD_LZMA_SUPPORT=ON",
"-DZSTD_LZ4_SUPPORT=ON",
"-DCMAKE_CXX_STANDARD=11",
*std_cmake_args
system "cmake", "--build", "builddir"
system "cmake", "--install", "builddir"
end
test do
[bin/"zstd", bin/"pzstd", "xz", "lz4", "gzip"].each do |prog|
data = "Hello, #{prog}"
assert_equal data, pipe_output("#{bin}/zstd -d", pipe_output(prog, data))
if prog.to_s.end_with?("zstd")
# `pzstd` can only decompress zstd-compressed data.
assert_equal data, pipe_output("#{bin}/pzstd -d", pipe_output(prog, data))
else
assert_equal data, pipe_output("#{prog} -d", pipe_output("#{bin}/zstd --format=#{prog}", data))
end
end
end
end

View File

@ -1,6 +1,6 @@
#!/usr/bin/env bash
# Copyright © 2019-2024 Dynare Team
# Copyright © 2019-2023 Dynare Team
#
# This file is part of Dynare.
#
@ -18,81 +18,39 @@
# along with Dynare. If not, see <https://www.gnu.org/licenses/>.
set -ex
#exec > >(tee build-logfile.log) 2>&1 # uncomment for debugging
ROOTDIR=$(pwd)/..
##
## Set settings based on architecture
##
path_remove () { export "$1"="$(echo -n "${!1}" | awk -v RS=: -v ORS=: '$1 != "'"$2"'"' | sed 's/:$//')"; }
path_prepend () { path_remove "$1" "$2"; export "$1"="$2:${!1}"; }
PKG_ARCH=${1:-x86_64} # default to x86_64
if [[ "$PKG_ARCH" == arm64 ]]; then
BREWDIR=/opt/homebrew
# Make sure /opt/homebrew/bin is set first in PATH (as it might come last)
path_prepend PATH /opt/homebrew/bin
MATLAB_ARCH=maca64
else
BREWDIR=/usr/local
# Remove /opt/homebrew/bin from PATH, so it does not intervene with the x86_64 compilations
path_remove PATH /opt/homebrew/bin
MATLAB_ARCH=maci64
fi
MATLAB_PATH=/Applications/"$PKG_ARCH"/MATLAB_R2023b.app
# Append texbin to PATH to access latexmk and friends
path_prepend PATH /Library/TeX/texbin
# Set the GCC version
GCC_VERSION=13
# Set the compilers
CC=gcc-$GCC_VERSION
CXX=g++-$GCC_VERSION
# Set the number of threads
NTHREADS=$(sysctl -n hw.ncpu)
# Set dependency directory
LIB64="$ROOTDIR"/macOS/deps/"$PKG_ARCH"/lib64
LIB64="$ROOTDIR"/macOS/deps/lib64
## Hack for statically linking libquadmath, similar to the one used in
## deps/Makefile for several libraries (there is no -static-libquadmath flag,
## see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=46539).
##
## NB: The hack done for Windows does not work for two reasons:
## - the macOS linker is different from GNU ld and does not have the equivalent of -Bstatic/-Bdynamic
## - libgfortran.spec does not include --as-needed on macOS, hence it will link the library anyways
## Also, it does not seem possible to override libgfortran.spec with the --specs option.
GCC_VERSION=$(sed -En "/^c[[:space:]]*=/s/c[[:space:]]*=[[:space:]]*'.*gcc-([0-9]+)'/\1/p" "$ROOTDIR"/macOS/homebrew-native-"$PKG_ARCH".ini)
QUADMATH_DIR=$(mktemp -d)
ln -s "$BREWDIR"/opt/gcc/lib/gcc/"$GCC_VERSION"/libquadmath.a "$QUADMATH_DIR"
##
## Compile Dynare
## Find Dynare Version
##
cd "$ROOTDIR"
# NB: the addition of -Wl,-ld_classic is a workaround for https://github.com/mesonbuild/meson/issues/12282 (see also the native file)
common_meson_opts=(-Dbuild_for=matlab -Dbuildtype=release -Dprefer_static=true -Dfortran_args="[ '-B', '$LIB64/Slicot/' ]" \
-Dc_link_args="[ '-Wl,-ld_classic', '-L$QUADMATH_DIR' ]" -Dcpp_link_args="[ '-Wl,-ld_classic', '-L$QUADMATH_DIR' ]" -Dfortran_link_args="[ '-Wl,-ld_classic', '-L$QUADMATH_DIR' ]" \
--native-file macOS/homebrew-native-$PKG_ARCH.ini)
# Build for MATLAB ⩾ R2018b (x86_64) and MATLAB ⩾ R2023b (arm64)
arch -"$PKG_ARCH" meson setup "${common_meson_opts[@]}" -Dmatlab_path="$MATLAB_PATH" build-matlab --wipe
arch -"$PKG_ARCH" meson compile -v -C build-matlab
# If not in CI, build the docs
if [[ -z $CI ]]; then
arch -"$PKG_ARCH" meson compile -v -C build-matlab doc
ln -s build-matlab build-doc
fi
##
## Create package
##
# Determine Dynare version if not passed by an environment variable as in the CI
if [[ -z $VERSION ]]; then
cd build-matlab
VERSION=$(meson introspect --projectinfo | sed -En 's/^.*"version": "([^"]*)".*$/\1/p')
cd ..
fi
# Other useful variables
DATE=$(date +%Y-%m-%d-%H%M)
DATELONG=$(date '+%d %B %Y')
if [[ -d ../.git/ ]]; then
SHA=$(git rev-parse HEAD)
SHASHORT=$(git rev-parse --short HEAD)
fi
if [[ -z $VERSION ]]; then
VERSION=$(grep '^AC_INIT(' ../configure.ac | sed 's/AC_INIT(\[dynare\], \[\(.*\)\])/\1/')
if [[ -d ../.git/ ]]; then
VERSION="$VERSION"-"$SHASHORT"
fi
fi
# Install location must not be too long for gcc.
# Otherwise, the headers of the compiled libraries cannot be modified
@ -105,82 +63,146 @@ else
# Get the first component, truncate it to 5 characters, and add the date
LOCATION=$(echo "$VERSION" | cut -f1 -d"-" | cut -c 1-5)-"$DATE"
fi
# Add architecture to LOCATION and VERSION
VERSION="$VERSION"-"$PKG_ARCH"
LOCATION="$LOCATION"-"$PKG_ARCH"
## Hack for statically linking libquadmath, similar to the one used in
## deps/Makefile for several libraries (there is no -static-libquadmath flag,
## see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=46539).
##
## NB: The hack done for Windows (see m4/ax_mexopts.m4) does not work for two reasons:
## - the macOS linker is different from GNU ld and does not have the equivalent of -Bstatic/-Bdynamic
## - libgfortran.spec does not include --as-needed on macOS, hence it will link the library anyways
## Also, it does not seem possible to override libgfortran.spec with the --specs option.
QUADMATH_DIR=$(mktemp -d)
ln -s /usr/local/opt/gcc/lib/gcc/$GCC_VERSION/libquadmath.a $QUADMATH_DIR
##
## Compile Dynare doc, preprocessor, mex for MATLAB < 2018a
##
## NB: In Homebrew, -static-libgfortran is implied by -static-libgcc (see “gfortran -dumpspecs”)
## NB2: We use the hack for libquadmath in LDFLAGS
cd "$ROOTDIR"
[[ -f configure ]] || autoreconf -si
./configure \
PACKAGE_VERSION="$VERSION" \
PACKAGE_STRING="dynare $VERSION" \
CC=$CC \
CXX=$CXX \
CPPFLAGS=-I/usr/local/include \
LDFLAGS="-static-libgcc -L$QUADMATH_DIR" \
LEX=/usr/local/opt/flex/bin/flex \
YACC=/usr/local/opt/bison/bin/bison \
--with-gsl="$LIB64"/gsl \
--with-matio="$LIB64"/matio \
--with-slicot="$LIB64"/Slicot/with-underscore \
--disable-octave \
--with-matlab=/Applications/MATLAB_R2016b.app
if [[ -z $CI ]]; then
# If not in Gitlab CI, clean the source and build the doc
make clean
make -j"$NTHREADS" pdf html
fi
make -j"$NTHREADS"
##
## Create package
##
NAME=dynare-"$VERSION"
PKGFILES="$ROOTDIR"/macOS/pkg/"$NAME"
mkdir -p \
"$PKGFILES"/preprocessor \
"$PKGFILES"/mex/matlab/maci64-8.3-9.3 \
"$PKGFILES"/mex/matlab/maci64-9.4-9.14 \
"$PKGFILES"/doc \
"$PKGFILES"/scripts \
"$PKGFILES"/contrib/ms-sbvar/TZcode
if [[ "$PKG_ARCH" == x86_64 ]]; then
mkdir -p "$PKGFILES"/mex/matlab/"$MATLAB_ARCH"-9.5-23.2
else
mkdir -p "$PKGFILES"/mex/matlab/"$MATLAB_ARCH"-23.2
fi
if [[ $VERSION == *-unstable* ]]; then
echo "$SHA" > "$PKGFILES"/sha.txt
fi
cp -p "$ROOTDIR"/NEWS.md "$PKGFILES"
cp -p "$ROOTDIR"/COPYING "$PKGFILES"
cp -p "$ROOTDIR"/VERSION "$PKGFILES"
cp -p "$ROOTDIR"/license.txt "$PKGFILES"
cp -pr "$ROOTDIR"/matlab "$PKGFILES"
cp -p "$ROOTDIR"/build-matlab/dynare_version.m "$PKGFILES"/matlab
cp -pr "$ROOTDIR"/examples "$PKGFILES"
cp -p "$ROOTDIR"/build-matlab/preprocessor/src/dynare-preprocessor "$PKGFILES"/preprocessor
cp -p "$ROOTDIR"/preprocessor/src/dynare-preprocessor "$PKGFILES"/preprocessor
# Create backward-compatibility symlink
mkdir -p "$PKGFILES"/matlab/preprocessor64
# Recreate backward-compatibility symlink
rm -f "$ROOTDIR"/matlab/preprocessor64/dynare_m
ln -sf ../../preprocessor/dynare-preprocessor "$PKGFILES"/matlab/preprocessor64/dynare_m
if [[ "$PKG_ARCH" == x86_64 ]]; then
cp -L "$ROOTDIR"/build-matlab/*.mex"$MATLAB_ARCH" "$PKGFILES"/mex/matlab/"$MATLAB_ARCH"-9.5-23.2
else
cp -L "$ROOTDIR"/build-matlab/*.mex"$MATLAB_ARCH" "$PKGFILES"/mex/matlab/"$MATLAB_ARCH"-23.2
fi
cp -L "$ROOTDIR"/mex/matlab/* "$PKGFILES"/mex/matlab/maci64-8.3-9.3
cp -p "$ROOTDIR"/scripts/dynare.el "$PKGFILES"/scripts
cp -pr "$ROOTDIR"/contrib/ms-sbvar/TZcode/MatlabFiles "$PKGFILES"/contrib/ms-sbvar/TZcode
cp -pr "$ROOTDIR"/contrib/jsonlab "$PKGFILES"/contrib
cp "$ROOTDIR"/build-doc/*.pdf "$PKGFILES"/doc
cp "$ROOTDIR"/build-doc/preprocessor/doc/*.pdf "$PKGFILES"/doc
cp -r "$ROOTDIR"/build-doc/dynare-manual.html "$PKGFILES"/doc
cp "$ROOTDIR"/doc/*.pdf "$PKGFILES"/doc
cp "$ROOTDIR"/doc/gsa/gsa.pdf "$PKGFILES"/doc
cp "$ROOTDIR"/doc/parallel/parallel.pdf "$PKGFILES"/doc
cp "$ROOTDIR"/doc/dseries-and-reporting/dseriesReporting.pdf "$PKGFILES"/doc
cp "$ROOTDIR"/preprocessor/doc/preprocessor/preprocessor.pdf "$PKGFILES"/doc
cp "$ROOTDIR"/preprocessor/doc/macroprocessor/macroprocessor.pdf "$PKGFILES"/doc
cp "$ROOTDIR"/doc/manual/build/latex/dynare-manual.pdf "$PKGFILES"/doc
cp -r "$ROOTDIR"/doc/manual/build/html "$PKGFILES"/doc/dynare-manual.html
mkdir -p "$PKGFILES"/matlab/dseries/externals/x13/macOS/64
cp -p "$ROOTDIR"/macOS/deps/"$PKG_ARCH"/lib64/x13as/x13as "$PKGFILES"/matlab/dseries/externals/x13/macOS/64
mkdir -p "$PKGFILES"/matlab/modules/dseries/externals/x13/macOS/64
cp -p "$ROOTDIR"/macOS/deps/lib64/x13as/x13as "$PKGFILES"/matlab/modules/dseries/externals/x13/macOS/64
##
## Create mex for MATLAB ≥ 2018a
##
cd "$ROOTDIR"/mex/build/matlab
make clean
./configure \
PACKAGE_VERSION="$VERSION" \
PACKAGE_STRING="dynare $VERSION" \
CC=$CC \
CXX=$CXX \
CPPFLAGS=-I/usr/local/include \
LDFLAGS="-static-libgcc -L$QUADMATH_DIR" \
--with-gsl="$LIB64"/gsl \
--with-matio="$LIB64"/matio \
--with-slicot="$LIB64"/Slicot/with-underscore \
--with-matlab=/Applications/MATLAB_R2022b.app
make -j"$NTHREADS"
cp -L "$ROOTDIR"/mex/matlab/* "$PKGFILES"/mex/matlab/maci64-9.4-9.14
##
## Make package
##
cd "$ROOTDIR"/macOS/pkg
# Dynare option
arch -"$PKG_ARCH" pkgbuild --root "$PKGFILES" --identifier org.dynare."$VERSION" --version "$VERSION" --install-location /Applications/Dynare/"$LOCATION" "$NAME".pkg
pkgbuild --root "$PKGFILES" --identifier org.dynare --version "$VERSION" --install-location /Applications/Dynare/"$LOCATION" "$NAME".pkg
# Create distribution.xml by replacing variables in distribution_template.xml
sed -e "s/VERSION_NO_SPACE/$VERSION/g" \
-e "s/LOCATION/$LOCATION/g" \
"$ROOTDIR"/macOS/distribution_template.xml > distribution.xml
# GCC option
# Create dummy payload for GCC package; otherwise the size is displayed as 0 bytes in the installer
dd if=/dev/zero of="$ROOTDIR"/macOS/brewfiles/dummy bs=1m count=800
pkgbuild --root "$ROOTDIR"/macOS/brewfiles --identifier org.dynare.gcc --version "$VERSION" --scripts "$ROOTDIR"/macOS/scripts --install-location /Applications/Dynare/"$LOCATION" "$NAME"-gcc.pkg
# Create welcome.html by replacing variables in welcome_template.html
sed -e "s/VERSION_NO_SPACE/$VERSION/g" \
-e "s/DATE/$DATELONG/g" \
"$ROOTDIR"/macOS/welcome_template.html > "$ROOTDIR"/macOS/welcome.html
# Create conclusion.html by replacing variables in conclusion_template.html
sed -e "s/GCC_VERSION/$GCC_VERSION/g" \
"$ROOTDIR"/macOS/conclusion_template.html > "$ROOTDIR"/macOS/conclusion.html
# Replace variables in displayed files
sed "s/VERSION_READ/$VERSION/g" "$ROOTDIR"/macOS/distribution_template.xml > distribution_tmp.xml
sed "s/VERSION_NO_SPACE/$VERSION/g" distribution_tmp.xml > distribution.xml
sed "s/GCC_BINARY/$CC/g" "$ROOTDIR"/macOS/welcome_template.html > "$ROOTDIR"/macOS/welcome.html
sed "s/VERSION_NO_SPACE/$VERSION/g" "$ROOTDIR"/macOS/welcome.html > "$ROOTDIR"/macOS/welcome_tmp.html
sed "s/DATE/$DATELONG/g" "$ROOTDIR"/macOS/welcome_tmp.html > "$ROOTDIR"/macOS/welcome.html
# Create installer
arch -"$PKG_ARCH" productbuild --distribution distribution.xml --resources "$ROOTDIR"/macOS --package-path ./"$NAME".pkg "$NAME"-productbuild.pkg
productbuild --distribution distribution.xml --resources "$ROOTDIR"/macOS --package-path ./"$NAME".pkg "$NAME"-new.pkg
# Cleanup
rm -f ./distribution.xml
# cleanup
rm -f ./*.xml
rm -rf "$PKGFILES"
rm -f "$NAME"-gcc.pkg
rm -f "$ROOTDIR"/macOS/brewfiles/dummy
rm -f "$ROOTDIR"/macOS/welcome.html
rm -f "$ROOTDIR"/macOS/conclusion.html
rm -f "$ROOTDIR"/macOS/welcome_tmp.html
# Final pkg
mv "$NAME"-productbuild.pkg "$NAME".pkg
mv "$NAME"-new.pkg "$NAME".pkg

View File

@ -1,45 +0,0 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Recommendations</title>
<style>
.center-text {
text-align: center;
}
.bold-text {
font-weight: bold;
}
code {
font-family: "Courier New", Courier, monospace;
}
</style>
</head>
<body>
<header class="center-text">
<h1>Recommendations</h1>
</header>
<main>
<p class="bold-text">Xcode Command Line Tools</p>
<p>Dynare highly benefits from installing Xcode Command Line Tools (an Apple product). To install the Xcode Command Line Tools type the following into Terminal.app:</p>
<code>
xcode-select --install
</code>
<p class="bold-text">Compilation Environment for use_dll option</p>
<p>Dynare ships a compilation environment that can be used with the use_dll option. To install this environment correctly, the Xcode Command Line Tools are sufficient. Check this by running the following command in the MATLAB command window:</p>
<code>
mex -setup
</code>
<p>If you get a warning in MATLAB, that Xcode is installed, but its license has not been accepted, please refer to the <a href="https://www.dynare.org/manual/installation-and-configuration.html#prerequisites-on-macos" target="_blank" rel="noopener noreferrer">manual</a> for a workaround.</p>
<p>Moreover, we recommend making use of optimized compilation flags and for this you need to install GCC via Homebrew.
Follow <a href="https://brew.sh" target="_blank" rel="noopener noreferrer">https://brew.sh</a> to install Homebrew and then type the following into Terminal.app:</p>
<code>
brew install gcc@GCC_VERSION
</code>
<p>If you already have installed GCC, Dynare will automatically prefer it for use_dll if the binaries are either in /opt/homebrew/bin/gcc-GCC_VERSION (arm64) or in /usr/local/bin/gcc-GCC_VERSION (x86_64). Otherwise, it will fall back to Clang in /usr/bin/clang (for both arm64 and x86_64).</p>
</main>
</body>
</html>

View File

@ -1,4 +1,4 @@
# Copyright © 2019-2024 Dynare Team
# Copyright © 2019-2023 Dynare Team
#
# This file is part of Dynare.
#
@ -17,19 +17,11 @@
include versions.mk
# settings for different architectures
DEPS_ARCH ?= x86_64 # use x86_64 by default
BREWDIR := $(if $(filter arm64,$(DEPS_ARCH)),/opt/homebrew,/usr/local)
GCC_VERSION = $(shell sed -En "/^c[[:space:]]*=/s/c[[:space:]]*=[[:space:]]*'.*gcc-([0-9]+)'/\1/p" ../homebrew-native-$(DEPS_ARCH).ini)
GCC_VERSION = 13
ROOT_PATH = $(realpath .)
WGET_OPTIONS := --no-verbose --no-use-server-timestamps --retry-connrefused --retry-on-host-error
NTHREADS=$(shell sysctl -n hw.perflevel0.physicalcpu)
.PHONY: all build build-slicot build-x13as \
clean-lib clean-libslicot clean-x13as-bin \
clean-src clean-slicot-src clean-x13as-src \
@ -38,7 +30,7 @@ NTHREADS=$(shell sysctl -n hw.perflevel0.physicalcpu)
all: build
build: build-slicot build-x13as
build: build-slicot build-x13as ln-matio ln-gsl
clean-lib: clean-libslicot clean-x13as-bin
@ -48,35 +40,91 @@ clean-tar: clean-slicot-tar clean-x13as-tar
clean-all: clean-lib clean-src clean-tar
#
# slicot
# Matio & GSL
# (done to link only to static Matio and GSL libraries)
# Matio
lib64/matio/lib/libmatio.a: /usr/local/lib/libmatio.a
mkdir -p $(dir $@) && ln -sf $< $@
lib64/matio/lib/libhdf5.a: /usr/local/lib/libhdf5.a
mkdir -p $(dir $@) && ln -sf $< $@
lib64/matio/lib/libsz.a: /usr/local/lib/libsz.a
mkdir -p $(dir $@) && ln -sf $< $@
lib64/matio/include/matio.h: /usr/local/include/matio.h
mkdir -p $(dir $@) && cd $(dir $@).. && rm -rf include && ln -sf $(dir $<) .
ln-matio: lib64/matio/lib/libmatio.a \
lib64/matio/lib/libhdf5.a \
lib64/matio/lib/libsz.a \
lib64/matio/include/matio.h
clean-matio:
rm -rf lib64/matio
# GSL
lib64/gsl/lib/libgsl.a: /usr/local/lib/libgsl.a
mkdir -p $(dir $@) && ln -sf $< $@
lib64/gsl/lib/libgslcblas.a: /usr/local/lib/libgslcblas.a
mkdir -p $(dir $@) && ln -sf $< $@
lib64/gsl/include/gsl/gsl_blas.h: /usr/local/include/gsl/gsl_blas.h
mkdir -p $(dir $@) && cd $(dir $@).. && rm -rf gsl && ln -sf $(dir $<) .
ln-gsl: lib64/gsl/lib/libgsl.a \
lib64/gsl/lib/libgslcblas.a \
lib64/gsl/include/gsl/gsl_blas.h
clean-gsl:
rm -rf lib64/gsl
#
# Slicot
#
tarballs/slicot-$(SLICOT_VERSION).tar.gz:
mkdir -p tarballs
wget $(WGET_OPTIONS) -O $@ https://deb.debian.org/debian/pool/main/s/slicot/slicot_$(SLICOT_VERSION).orig.tar.xz
wget $(WGET_OPTIONS) -O $@ https://deb.debian.org/debian/pool/main/s/slicot/slicot_$(SLICOT_VERSION).orig.tar.gz
$(DEPS_ARCH)/sources64/slicot-$(SLICOT_VERSION): tarballs/slicot-$(SLICOT_VERSION).tar.gz
rm -rf $(DEPS_ARCH)/sources64/slicot-*
sources64/slicot-$(SLICOT_VERSION)-with-32bit-integer-and-underscore: tarballs/slicot-$(SLICOT_VERSION).tar.gz
rm -rf sources64/slicot-*-with-32bit-integer-and-underscore
mkdir -p $@
tar xf $< --directory $@ --strip-components=1
touch $@
$(DEPS_ARCH)/lib64/slicot/libslicot64_pic.a: $(DEPS_ARCH)/sources64/slicot-$(SLICOT_VERSION)
make -C $< -f makefile_Unix FORTRAN=$(BREWDIR)/bin/gfortran LOADER=$(BREWDIR)/bin/gfortran SLICOTLIB=../libslicot64_pic.a OPTS="-O3 -fdefault-integer-8" lib -j$(NTHREADS)
sources64/slicot-$(SLICOT_VERSION)-with-64bit-integer-and-underscore: tarballs/slicot-$(SLICOT_VERSION).tar.gz
rm -rf sources64/slicot-*-with-64bit-integer-and-underscore
mkdir -p $@
tar xf $< --directory $@ --strip-components=1
touch $@
lib64/Slicot/with-underscore/lib/libslicot_pic.a: sources64/slicot-$(SLICOT_VERSION)-with-32bit-integer-and-underscore
make -C $< FORTRAN=gfortran LOADER=gfortran SLICOTLIB=../libslicot_pic.a OPTS="-O2 -g" lib
strip -S $</libslicot_pic.a
mkdir -p $(dir $@)
cp $</libslicot_pic.a $@
lib64/Slicot/with-underscore/lib/libslicot64_pic.a: sources64/slicot-$(SLICOT_VERSION)-with-64bit-integer-and-underscore
make -C $< FORTRAN=gfortran LOADER=gfortran SLICOTLIB=../libslicot64_pic.a OPTS="-O2 -g -fdefault-integer-8" lib
strip -S $</libslicot64_pic.a
mkdir -p $(dir $@)
cp $</libslicot64_pic.a $@
build-slicot: $(DEPS_ARCH)/lib64/slicot/libslicot64_pic.a
build-slicot: lib64/Slicot/with-underscore/lib/libslicot_pic.a \
lib64/Slicot/with-underscore/lib/libslicot64_pic.a
clean-slicot-tar:
rm -f tarballs/slicot-$(SLICOT_VERSION).tar.gz
clean-slicot-src:
rm -rf $(DEPS_ARCH)/sources64/slicot-$(SLICOT_VERSION)
rm -rf sources64/slicot-$(SLICOT_VERSION)-with-64bit-integer-and-underscore
clean-libslicot:
rm -rf $(DEPS_ARCH)/lib64/slicot
rm -rf lib64/Slicot
clean-slicot-all: clean-slicot-src clean-slicot-tar clean-libslicot
@ -89,12 +137,12 @@ tarballs/x13as_asciisrc-v$(X13AS_VERSION).tar.gz:
mkdir -p tarballs
wget $(WGET_OPTIONS) -O $@ https://www2.census.gov/software/x-13arima-seats/x13as/unix-linux/program-archives/x13as_asciisrc-v$(X13AS_VERSION).tar.gz
$(DEPS_ARCH)/sources64/x13as-$(X13AS_VERSION): tarballs/x13as_asciisrc-v$(X13AS_VERSION).tar.gz
rm -rf $(DEPS_ARCH)/sources64/x13as-*
sources64/x13as-$(X13AS_VERSION): tarballs/x13as_asciisrc-v$(X13AS_VERSION).tar.gz
rm -rf sources64/x13as-*
mkdir -p $@
tar xf $< --directory $@
$(DEPS_ARCH)/lib64/x13as/x13as: $(DEPS_ARCH)/sources64/x13as-$(X13AS_VERSION)
lib64/x13as/x13as: sources64/x13as-$(X13AS_VERSION)
# Statically link x13as (see #1865).
# Using -static is not possible, it does not work under Darwin.
# Implement an ugly workaround in the absence of -static-libquadmath flag.
@ -105,21 +153,20 @@ $(DEPS_ARCH)/lib64/x13as/x13as: $(DEPS_ARCH)/sources64/x13as-$(X13AS_VERSION)
# gfortran as the linker with -static-libgfortran and
# -static-libquadmath flags, and drop the GCC_VERSION variable.
cd $< && sed -i '' 's/-static//g' makefile.gf
make -C $< -f makefile.gf FC=$(BREWDIR)/bin/gfortran LINKER=$(BREWDIR)/bin/gcc-$(GCC_VERSION) FFLAGS="-O3 -std=legacy" LDFLAGS=-static-libgcc LIBS="$(BREWDIR)/lib/gcc/$(GCC_VERSION)/libgfortran.a $(BREWDIR)/lib/gcc/$(GCC_VERSION)/libquadmath.a" PROGRAM=x13as -j$(NTHREADS)
make -C $< -f makefile.gf FC=gfortran LINKER=gcc-$(GCC_VERSION) FFLAGS="-O2 -std=legacy" LDFLAGS=-static-libgcc LIBS="/usr/local/lib/gcc/current/libgfortran.a /usr/local/lib/gcc/current/libquadmath.a" PROGRAM=x13as
strip $</x13as
mkdir -p $(dir $@)
cp $</x13as $@
build-x13as: $(DEPS_ARCH)/lib64/x13as/x13as
build-x13as: lib64/x13as/x13as
clean-x13as-tar:
rm -f tarballs/x13as_asciisrc-v$(X13AS_VERSION).tar.gz
rm -f tarballs/x13assrc_V$(X13AS_VERSION).tar.gz
clean-x13as-src:
rm -rf $(DEPS_ARCH)/sources64/x13as-$(X13AS_VERSION)
rm -rf sources64/x13as-$(X13AS_VERSION)
clean-x13as-bin:
rm -rf $(DEPS_ARCH)/lib64/x13as
rm -rf lib64/x13as
clean-x13as-all: clean-x13as-tar clean-x13as-src clean-x13as-bin

View File

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

View File

@ -1,19 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<installer-gui-script minSpecVersion="1">
<title>Dynare VERSION_NO_SPACE</title>
<title>Dynare VERSION_READ</title>
<background file="background.png" scaling="tofit" mime-type="image/png" alignment="topleft" />
<background-darkAqua file="background.png" scaling="tofit" mime-type="image/png" alignment="topleft" />
<welcome file="welcome.html" mime-type="text/html" />
<conclusion file="conclusion.html" mime-type="text/html" />
<license file="gpl-3.0-standalone.html" mime-type="text/html" />
<domains enable_anywhere="false" enable_currentUserHome="true" enable_localSystem="false"/> <!-- on enable_currentUserHome="true" does not require admin rights! enable_localSystem="true" or enable_anywhere="true" requires admin rights by default, even though this can be changed in the installer though under Change Installation. -->
<pkg-ref id="default" />
<options customize="allow" require-scripts="false" hostArchitectures="x86_64,arm64" />
<pkg-ref id="org.dynare" />
<options customize="allow" require-scripts="false" hostArchitectures="x86_64" />
<choices-outline>
<line choice="default" />
<line choice="org.dynare" />
<line choice="org.dynare.gcc" />
</choices-outline>
<choice id="default" title="Dynare" description="Dynare Required Files" start_enabled="false" enabled="false" customLocation="/Applications/Dynare/LOCATION">
<pkg-ref id="org.dynare.VERSION_NO_SPACE" />
</choice>
<pkg-ref id="org.dynare.VERSION_NO_SPACE" version="VERSION_NO_SPACE">dynare-VERSION_NO_SPACE.pkg</pkg-ref>
</installer-gui-script>
<choice id="org.dynare" title="Dynare" description="Dynare Required Files" start_enabled="false" enabled="false">
<pkg-ref id="org.dynare" />
</choice>
<choice id="org.dynare.gcc" title="GCC for `use_dll`" description="This is necessary for the use of Dynare with the `use_dll` option. NB: This takes a few minutes and requires an active internet connection.">
<pkg-ref id="org.dynare.gcc" />
</choice>
<pkg-ref id="org.dynare" version="VERSION_NO_SPACE">dynare-VERSION_NO_SPACE.pkg</pkg-ref>
<pkg-ref id="org.dynare.gcc" version="VERSION_NO_SPACE">dynare-VERSION_NO_SPACE-gcc.pkg</pkg-ref>
</installer-gui-script>

View File

@ -1,15 +0,0 @@
# Meson native file for compiling under Homebrew for arm64 architecture
[binaries]
cpp = '/opt/homebrew/bin/g++-13'
c = '/opt/homebrew/bin/gcc-13'
flex = '/opt/homebrew/opt/flex/bin/flex'
bison = '/opt/homebrew/opt/bison/bin/bison'
[built-in options]
cpp_args = [ '-I/opt/homebrew/include', '-B', '/opt/homebrew/lib' ]
# XCode 15 (on Ventura and Sonoma) has a linker issue, see https://github.com/mesonbuild/meson/issues/12282, workaround is to use ld_classic
cpp_link_args = [ '-Wl,-ld_classic' ]
c_link_args = [ '-Wl,-ld_classic' ]
fortran_link_args = [ '-Wl,-ld_classic' ]
#fortran_args = [ '-B', '/Users/sebastien/slicot' ]

View File

@ -1,15 +0,0 @@
# Meson native file for compiling under Homebrew for x86_64 architecture
[binaries]
cpp = '/usr/local/bin/g++-13'
c = '/usr/local/bin/gcc-13'
flex = '/usr/local/opt/flex/bin/flex'
bison = '/usr/local/opt/bison/bin/bison'
[built-in options]
cpp_args = [ '-I/usr/local/include', '-B', '/usr/local/lib' ]
# XCode 15 (on Ventura and Sonoma) has a linker issue, see https://github.com/mesonbuild/meson/issues/12282, workaround is to use ld_classic
cpp_link_args = [ '-Wl,-ld_classic' ]
c_link_args = [ '-Wl,-ld_classic' ]
fortran_link_args = [ '-Wl,-ld_classic' ]
#fortran_args = [ '-B', '/Users/sebastien/slicot' ]

96
macOS/scripts/postinstall Executable file
View File

@ -0,0 +1,96 @@
#!/usr/bin/env bash
# Copyright © 2019-2021 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/>.
set -ex
set -o errexit
readonly LOG_FILE="$2"/install.log
sudo touch "$LOG_FILE"
exec 1>"$LOG_FILE"
exec 2>&1
# Remove dummy payload
rm -f "$2"/dummy
# Test for Internet connection
if ! curl -s -m 4 https://github.com >/dev/null; then
osascript -e 'display alert "Dynare Installation Error" message "Not able to connect to github.com. Either you are not connected to the internet or github.com is blocked where you are.\n\nAccess to GitHub is necessary to make Dynare work with the `use_dll` option on macOS.\n\nIf you cannot establish this connection or do not want to use the `use_dll` option of Dynare, please run the installer again and choose \"Customize\" from the \"Installation Type\" screen and uncheck the `GCC` option." as critical'
echo "No internet connection to github.com"
exit 1
fi
# Install Command Line Tools
# Checking that “xcode-select -print-path” returns a valid path is not enough, because
# the contents of that directory might have been removed (this is the official way of
# uninstalling CLT, see https://developer.apple.com/library/archive/technotes/tn2339/_index.html#//apple_ref/doc/uid/DTS40014588-CH1-HOW_CAN_I_UNINSTALL_THE_COMMAND_LINE_TOOLS_)
# Hence we also check that the directory contains the git binary.
if ! xcpath=$(/usr/bin/xcode-select -print-path) || [[ ! -x "$xcpath"/usr/bin/git ]]; then
touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
SUC=$(softwareupdate -l |
grep "\*.*Command Line" |
grep -m1 "" |
awk -F"*" '{print $2}' |
sed -e 's/^ *//' |
tr -d '\n')
# On macOS 10.15 softwareupdate output is preceded by "Label: "
[[ $SUC == Label:* ]] && SUC=${SUC#"Label: "}
softwareupdate -i "$SUC" --verbose
rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
softwareupdate -l
fi
# If CLT installation didn't work, exit
if ! xcpath=$(/usr/bin/xcode-select -print-path) || [[ ! -x "$xcpath"/usr/bin/git ]]; then
osascript -e 'display alert "Dynare Installation Error" message "Not able to find Command Line Tools.\n\nCommand Line Tools is necessary to make Dynare work with the `use_dll` option on macOS.\n\nIf you cannot establish this connection or do not want to use the `use_dll` option of Dynare, please run the installer again and choose \"Customize\" from the \"Installation Type\" screen and uncheck the `GCC` option." as critical'
echo "Command Line Tools not installed"
exit 1
fi
# Ensure git is in the path
if ! which git >/dev/null; then
osascript -e 'display alert "Dynare Installation Error" message "Not able to find Git even though the Command Line Tools have already been installed. This is likely a problem with your PATH environment variable.\n\nGit is necessary to make Dynare work with the `use_dll` option on macOS.\n\nIf you cannot establish this connection or do not want to use the `use_dll` option of Dynare, please run the installer again and choose \"Customize\" from the \"Installation Type\" screen and uncheck the `GCC` option." as critical'
echo $PATH
echo "Git not found in PATH"
exit 1
fi
# Install Homebrew
BREWDIR="$2"/.brew
[ -d "$BREWDIR" ] || mkdir -p "$BREWDIR"
BREW_URL="https://github.com/Homebrew/brew"
BREW_BRANCH="master"
curl -\# -L "$BREW_URL"/tarball/"$BREW_BRANCH" | tar xz -m --strip 1 -C "$BREWDIR"
# Change ownership of Dynare directory
chown -R "$USER":staff "$2"
sudo -u "$USER" "$BREWDIR"/bin/brew tap homebrew/core
HOMEBREW_CACHE="$HOME"/Library/Caches/Homebrew-Dynare
HOMEBREW_NO_AUTO_UPDATE=1
[[ -z "${HOMEBREW_NO_ANALYTICS}" ]] && HOMEBREW_NO_ANALYTICS=1
# Move modified formulas to Homebrew Formula directory
mv "$2"/*.rb "$BREWDIR"/Library/Taps/homebrew/homebrew-core/Formula
# Install GCC & deps
sudo -u "$USER" "$BREWDIR"/bin/brew install gcc -v --force-bottle
exit 0

View File

@ -1,37 +1,15 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dynare Installer</title>
<style>
.center-text {
text-align: center;
}
.bold-text {
font-weight: bold;
}
code {
font-family: "Courier New", Courier, monospace;
}
</style>
</head>
<body>
<header class="center-text">
<h1>Welcome to Dynare</h1>
<p>Version VERSION_NO_SPACE</p>
<p>DATE</p>
</header>
<h3 style="text-align: center;">Welcome to Dynare</h3>
<p style="text-align: center;">Version VERSION_NO_SPACE</p>
<p style="text-align: center;">DATE</p>
<main>
<p>Thank you for choosing Dynare!</p>
<p>This installation does not require administrative privileges. If for some reason admin rights are requested, use 'Change Install Location' and select 'Install for me only'.</p>
<p>By default Dynare will be installed into /Applications/Dynare. To modify the installation path, click <strong>Customize</strong> after accepting the license. Then, under <strong>Location</strong>, select your desired folder.</p>
<p>Installing into /Applications/Dynare might fail if you have older versions of Dynare installed in /Applications/Dynare. To fix this, modify the ownership by executing the following command in Terminal.app:</p>
<code>
sudo chown -R "$USER":staff /Applications/Dynare
</code>
</main>
<p><b>Just a few things to note</b>. This installation can be customized as you can choose not to install the GNU Compiler Collection (GCC). Installing GCC is necessary if you want to use the <tt>use_dll</tt> option in Dynare, but otherwise unnecessary.</p>
<p>To install GCC we run a script that first installs the XCode Command Line Tools (an Apple product). The script then installs Homebrew, a package manager for macOS and, finally, GCC itself. Both Homebrew and GCC will be installed in your Dynare installation folder. So, when you delete this folder, they too will be deleted.</p>
<p>Installing GCC will require an active internet connection with the ability to connect to the Apple servers and GitHub. The installation will take anywhere from a few minutes to a half an hour during the <i>Running package scripts</i> phase of Installation. The time it takes depends on your internet speed, the speed of your computer, and whether or not you already have XCode Command Line Tools installed. The progress bar will not advance during this phase. Please be patient.</p>
<p> You can choose not to install GCC by choosing <i>Customize</i> from the <i>Installation Type</i> screen and deselecting <i>GCC compiler</i>. If you already have <tt>GCC_BINARY</tt> installed under <tt>/usr/local</tt>, you can forgo the installation of GCC here as Dynare will find your system compiler when you use <tt>use_dll</tt>.</p>
</body>
</html>
</html>

View File

@ -1,5 +1,5 @@
function write(M_)
% write(M_)
function write(DynareModel)
% Writes the nonlinear problem to be solved for computing the growth
% rates and levels along the Balanced Growth Path. Note that for
% the variables growing along the BGP, the identified levels are
@ -7,7 +7,7 @@ function write(M_)
% sharing the same trend(s) are relevant.
%
% INPUTS
% - M_ [struct] Dynare generated stucture describing the model (M_).
% - DynareModel [struct] Dynare generated stucture describing the model (M_).
%
% OUTPUTS
% None
@ -15,7 +15,7 @@ function write(M_)
% REMARKS
% - The trends are assumed to be multiplicative.
% Copyright © 2019-2023 Dynare Team
% Copyright © 2019 Dynare Team
%
% This file is part of Dynare.
%
@ -32,18 +32,18 @@ function write(M_)
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if M_.maximum_lag && ~M_.maximum_lead
i0 = transpose(M_.lead_lag_incidence(1,:)); % Indices of the lagged variables.
i1 = transpose(M_.lead_lag_incidence(2,:)); % Indices of the current variables.
if DynareModel.maximum_lag && ~DynareModel.maximum_lead
i0 = transpose(DynareModel.lead_lag_incidence(1,:)); % Indices of the lagged variables.
i1 = transpose(DynareModel.lead_lag_incidence(2,:)); % Indices of the current variables.
i2 = []; % Indices of the leaded variables.
elseif M_.maximum_lag && M_.maximum_lead
i0 = transpose(M_.lead_lag_incidence(1,:)); % Indices of the lagged variables.
i1 = transpose(M_.lead_lag_incidence(2,:)); % Indices of the current variables.
i2 = transpose(M_.lead_lag_incidence(3,:)); % Indices of the leaded variables.
elseif ~M_.maximum_lag && M_.maximum_lead
elseif DynareModel.maximum_lag && DynareModel.maximum_lead
i0 = transpose(DynareModel.lead_lag_incidence(1,:)); % Indices of the lagged variables.
i1 = transpose(DynareModel.lead_lag_incidence(2,:)); % Indices of the current variables.
i2 = transpose(DynareModel.lead_lag_incidence(3,:)); % Indices of the leaded variables.
elseif ~DynareModel.maximum_lag && DynareModel.maximum_lead
i0 = []; % Indices of the lagged variables.
i1 = transpose(M_.lead_lag_incidence(1,:)); % Indices of the current variables.
i2 = transpose(M_.lead_lag_incidence(2,:)); % Indices of the leaded variables.
i1 = transpose(DynareModel.lead_lag_incidence(1,:)); % Indices of the current variables.
i2 = transpose(DynareModel.lead_lag_incidence(2,:)); % Indices of the leaded variables.
else
error('The model is static. The BGP is trivial.')
end
@ -71,7 +71,7 @@ else
end
% Create function in mod namespace.
fid = fopen(sprintf('+%s/bgpfun.m', M_.fname), 'w');
fid = fopen(sprintf('+%s/bgpfun.m', DynareModel.fname), 'w');
% Write header.
fprintf(fid, 'function [F, JAC] = bgpfun(z)\n\n');
@ -80,8 +80,8 @@ fprintf(fid, '%% This file has been generated by dynare (%s).\n\n', datestr(now)
% The function admits a unique vector as input argument. The first
% half of the elements are for the levels of the endogenous
% variables, the second half for the growth factors.
fprintf(fid, 'y = z(1:%u);\n\n', M_.endo_nbr);
fprintf(fid, 'g = z(%u:%u);\n', M_.endo_nbr+1, 2*M_.endo_nbr);
fprintf(fid, 'y = z(1:%u);\n\n', DynareModel.endo_nbr);
fprintf(fid, 'g = z(%u:%u);\n', DynareModel.endo_nbr+1, 2*DynareModel.endo_nbr);
% Define the point where the dynamic model is to be evaluated.
fprintf(fid, 'Y = zeros(%u, 1);\n', 2*(n0+n1+n2));
@ -118,39 +118,39 @@ end
fprintf(fid, '\n');
% Define the vector of parameters.
fprintf(fid, 'p = zeros(%u, 1);\n', M_.param_nbr);
for i = 1:M_.param_nbr
fprintf(fid, 'p(%u) = %16.12f;\n', i, M_.params(i));
fprintf(fid, 'p = zeros(%u, 1);\n', DynareModel.param_nbr);
for i = 1:DynareModel.param_nbr
fprintf(fid, 'p(%u) = %16.12f;\n', i, DynareModel.params(i));
end
fprintf(fid, '\n');
% Initialize the vector holding the residuals over the two periods.
fprintf(fid, 'F = NaN(%u, 1);\n', 2*M_.endo_nbr);
fprintf(fid, 'F = NaN(%u, 1);\n', 2*DynareModel.endo_nbr);
% Set vector of exogenous variables to 0.
fprintf(fid, 'x = zeros(1, %u);\n\n', M_.exo_nbr);
fprintf(fid, 'x = zeros(1, %u);\n\n', DynareModel.exo_nbr);
% Evaluate the residuals and jacobian of the dynamic model in periods t and t+1.
fprintf(fid, 'if nargout>1\n');
fprintf(fid, ' J = zeros(%u, %u);\n', 2*M_.endo_nbr, n0+n1+n2+M_.endo_nbr);
fprintf(fid, ' [F(1:%u), tmp] = %s.dynamic(Y(1:%u), x, p, y, 1);\n', M_.endo_nbr, M_.fname, n0+n1+n2);
fprintf(fid, ' J(1:%u,1:%u) = tmp(:,1:%u);\n', M_.endo_nbr, n0+n1+n2, n0+n1+n2);
fprintf(fid, ' [F(%u:%u), tmp] = %s.dynamic(Y(1+%u:%u), x, p, y, 1);\n', M_.endo_nbr+1, 2*M_.endo_nbr, M_.fname, n0+n1+n2, 2*(n0+n1+n2));
fprintf(fid, ' J(%u:%u,1:%u) = tmp(:,1:%u);\n', M_.endo_nbr+1, 2*M_.endo_nbr, n0+n1+n2, n0+n1+n2);
fprintf(fid, ' J = zeros(%u, %u);\n', 2*DynareModel.endo_nbr, n0+n1+n2+DynareModel.endo_nbr);
fprintf(fid, ' [F(1:%u), tmp] = %s.dynamic(Y(1:%u), x, p, y, 1);\n', DynareModel.endo_nbr, DynareModel.fname, n0+n1+n2);
fprintf(fid, ' J(1:%u,1:%u) = tmp(:,1:%u);\n', DynareModel.endo_nbr, n0+n1+n2, n0+n1+n2);
fprintf(fid, ' [F(%u:%u), tmp] = %s.dynamic(Y(1+%u:%u), x, p, y, 1);\n', DynareModel.endo_nbr+1, 2*DynareModel.endo_nbr, DynareModel.fname, n0+n1+n2, 2*(n0+n1+n2));
fprintf(fid, ' J(%u:%u,1:%u) = tmp(:,1:%u);\n', DynareModel.endo_nbr+1, 2*DynareModel.endo_nbr, n0+n1+n2, n0+n1+n2);
fprintf(fid, 'else\n');
fprintf(fid, ' F(1:%u) = %s.dynamic(Y(1:%u), x, p, y, 1);\n', M_.endo_nbr, M_.fname, n0+n1+n2);
fprintf(fid, ' F(%u:%u) = %s.dynamic(Y(1+%u:%u), x, p, y, 1);\n', M_.endo_nbr+1, 2*M_.endo_nbr, M_.fname, n0+n1+n2, 2*(n0+n1+n2));
fprintf(fid, ' F(1:%u) = %s.dynamic(Y(1:%u), x, p, y, 1);\n', DynareModel.endo_nbr, DynareModel.fname, n0+n1+n2);
fprintf(fid, ' F(%u:%u) = %s.dynamic(Y(1+%u:%u), x, p, y, 1);\n', DynareModel.endo_nbr+1, 2*DynareModel.endo_nbr, DynareModel.fname, n0+n1+n2, 2*(n0+n1+n2));
fprintf(fid, 'end\n\n');
% Compute the jacobian if required.
fprintf(fid, 'if nargout>1\n');
fprintf(fid, ' JAC = zeros(%u,%u);\n', 2*M_.endo_nbr, 2*M_.endo_nbr);
fprintf(fid, ' JAC = zeros(%u,%u);\n', 2*DynareModel.endo_nbr, 2*DynareModel.endo_nbr);
% Compute the derivatives of the first block of equations (period t)
% with respect to the endogenous variables.
if purely_backward_model || purely_forward_model
for i=1:M_.eq_nbr
for j=1:M_.endo_nbr
for i=1:DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
if I1(j)
if I0(j)
fprintf(fid, ' JAC(%u,%u) = J(%u,%u)+J(%u,%u)*g(%u);\n', i, j, i, I0(j), i, I1(j), j);
@ -165,8 +165,8 @@ if purely_backward_model || purely_forward_model
end
end
else
for i=1:M_.eq_nbr
for j=1:M_.endo_nbr
for i=1:DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
if I2(j)
if I1(j)
if I0(j)
@ -201,8 +201,8 @@ end
% Compute the derivatives of the second block of equations (period t+1)
% with respect to the endogenous variables.
if purely_backward_model || purely_forward_model
for i=M_.eq_nbr+1:2*M_.eq_nbr
for j=1:M_.endo_nbr
for i=DynareModel.eq_nbr+1:2*DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
if I1(j)
if I0(j)
fprintf(fid, ' JAC(%u,%u) = J(%u,%u)*g(%u)+J(%u,%u)*g(%u)*g(%u);\n', i, j, i, I0(j), j, i, I1(j), j, j);
@ -217,8 +217,8 @@ if purely_backward_model || purely_forward_model
end
end
else
for i=M_.eq_nbr+1:2*M_.eq_nbr
for j=1:M_.endo_nbr
for i=DynareModel.eq_nbr+1:2*DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
if I2(j)
if I1(j)
if I0(j)
@ -253,16 +253,16 @@ end
% Compute the derivatives of the first block of equations (period t)
% with respect to the growth factors.
if purely_backward_model || purely_forward_model
for i=1:M_.eq_nbr
for j=1:M_.endo_nbr
for i=1:DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
if I1(j)
fprintf(fid, ' J(%u,%u) = J(%u,%u)*y(%u);\n', i, n0+n1+n2+j, i, I1(j), j);
end
end
end
else
for i=1:M_.eq_nbr
for j=1:M_.endo_nbr
for i=1:DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
if I2(j)
if I1(j)
fprintf(fid, ' J(%u,%u) = J(%u,%u)*y(%u)+J(%u,%u)*2*g(%u)*y(%u);\n', i, n0+n1+n2+j, i, I1(j), j, i, I2(j), j, j);
@ -281,8 +281,8 @@ end
% Compute the derivatives of the second block of equations (period t+1)
% with respect to the endogenous variables.
if purely_backward_model || purely_forward_model
for i=M_.eq_nbr+1:2*M_.eq_nbr
for j=1:M_.endo_nbr
for i=DynareModel.eq_nbr+1:2*DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
if I0(j)
fprintf(fid, ' J(%u,%u) = J(%u,%u)+J(%u,%u)*y(%u);\n', i, n0+n1+n2+j, i, n0+n1+n2+j, i, I0(j), j);
end
@ -292,8 +292,8 @@ if purely_backward_model || purely_forward_model
end
end
else
for i=M_.eq_nbr+1:2*M_.eq_nbr
for j=1:M_.endo_nbr
for i=DynareModel.eq_nbr+1:2*DynareModel.eq_nbr
for j=1:DynareModel.endo_nbr
if I2(j)
if I1(j)
if I0(j)
@ -325,7 +325,7 @@ else
end
end
fprintf(fid, ' JAC(:,%u:%u) = J(:,%u:%u);\n', M_.endo_nbr+1, 2*M_.endo_nbr, n0+n1+n2+1, n0+n1+n2+M_.endo_nbr);
fprintf(fid, ' JAC(:,%u:%u) = J(:,%u:%u);\n', DynareModel.endo_nbr+1, 2*DynareModel.endo_nbr, n0+n1+n2+1, n0+n1+n2+DynareModel.endo_nbr);
fprintf(fid,'end\n');
fclose(fid);

View File

@ -28,7 +28,7 @@ function nls(eqname, params, data, range, optimizer, varargin)
% equation must have NaN values in the object.
% [4] It is assumed that the residual is additive.
% Copyright © 2021-2023 Dynare Team
% Copyright © 2021-2022 Dynare Team
%
% This file is part of Dynare.
%
@ -179,6 +179,12 @@ write_residuals_routine(lhs, rhs, eqname, ipnames_, M_);
% Create a routine for evaluating the sum of squared residuals of the nonlinear model
write_ssr_routine(lhs, rhs, eqname, ipnames_, M_);
% Workaround for Octave bug https://savannah.gnu.org/bugs/?46282
% Octave will randomly fail to read the ssr_* file generated in the +folder
if isoctave && octave_ver_less_than('7')
path(path)
end
% Create a function handle returning the sum of square residuals for a given vector of parameters.
ssrfun = @(p) feval([M_.fname '.ssr_' eqname], p, DATA, M_, oo_);
@ -292,23 +298,23 @@ end
%
if is_gauss_newton
[params1, SSR] = gauss_newton(resfun, params0);
[params1, SSR, exitflag] = gauss_newton(resfun, params0);
elseif is_lsqnonlin
if ismember('levenberg-marquardt', varargin)
% Levenberg Marquardt does not handle boundary constraints.
[params1, SSR] = lsqnonlin(resfun, params0, [], [], optimset(varargin{:}));
[params1, SSR, ~, exitflag] = lsqnonlin(resfun, params0, [], [], optimset(varargin{:}));
else
[params1, SSR] = lsqnonlin(resfun, params0, bounds(:,1), bounds(:,2), optimset(varargin{:}));
[params1, SSR, ~, exitflag] = lsqnonlin(resfun, params0, bounds(:,1), bounds(:,2), optimset(varargin{:}));
end
else
% Estimate the parameters by minimizing the sum of squared residuals.
[params1, SSR] = dynare_minimize_objective(ssrfun, params0, ...
minalgo, ...
options_, ...
bounds, ...
parameter_names, ...
[], ...
[]);
[params1, SSR, exitflag] = dynare_minimize_objective(ssrfun, params0, ...
minalgo, ...
options_, ...
bounds, ...
parameter_names, ...
[], ...
[]);
end
% Revert local modifications to the options.

View File

@ -1,305 +0,0 @@
function map_identification(OutputDirectoryName,opt_gsa,M_,oo_,options_,estim_params_,bayestopt_)
% map_identification(OutputDirectoryName,opt_gsa,M_,oo_,options_,estim_params_,bayestopt_)
% Inputs
% - OutputDirectoryName [string] name of the output directory
% - opt_gsa [structure] GSA options structure
% - M_ [structure] Matlab's structure describing the model
% - oo_ [structure] Matlab's structure describing the results
% - options_ [structure] Matlab's structure describing the current options
% - estim_params_ [structure] characterizing parameters to be estimated
% - bayestopt_ [structure] describing the priors
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
% marco.ratto@ec.europa.eu
% Copyright © 2012-2016 European Commission
% Copyright © 2012-2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
fname_ = M_.fname;
dr=oo_.dr;
nliv = opt_gsa.morris_nliv;
itrans = opt_gsa.trans_ident;
np = size(estim_params_.param_vals,1);
pnames = M_.param_names(estim_params_.param_vals(:,1));
if opt_gsa.pprior
filetoload=[OutputDirectoryName '/' fname_ '_prior'];
else
filetoload=[OutputDirectoryName '/' fname_ '_mc'];
end
load(filetoload,'lpmat','lpmat0','istable','T','yys')
if ~isempty(lpmat0)
lpmatx=lpmat0(istable,:);
else
lpmatx=[];
end
Nsam = size(lpmat,1);
nshock = size(lpmat0,2);
npT = np+nshock;
fname_ = M_.fname;
if opt_gsa.load_ident_files==0
mss = yys(bayestopt_.mfys,:);
mss = gsa.teff(mss(:,istable),Nsam,istable);
yys = gsa.teff(yys(dr.order_var,istable),Nsam,istable);
if exist('T','var')
[vdec, cc, ac] = gsa.monte_carlo_moments(T, lpmatx, dr, M_, options_, estim_params_);
else
return
end
if opt_gsa.morris==2
pdraws = identification.run(M_,oo_,options_,bayestopt_,estim_params_,options_.options_ident,[lpmatx lpmat(istable,:)]);
if ~isempty(pdraws) && max(max(abs(pdraws-[lpmatx lpmat(istable,:)])))==0
disp(['Sample check OK. Largest difference: ', num2str(max(max(abs(pdraws-[lpmatx lpmat(istable,:)]))))]),
clear pdraws;
end
clear GAM gas
end
if opt_gsa.morris~=1 && M_.exo_nbr>1
ifig=0;
for j=1:M_.exo_nbr
if mod(j,6)==1
hh_fig=dyn_figure(options_.nodisplay,'name','Variance decomposition shocks');
ifig=ifig+1;
iplo=0;
end
iplo=iplo+1;
subplot(2,3,iplo)
gsa.boxplot(squeeze(vdec(:,j,:))',[],'.',[],10)
set(gca,'xticklabel',' ','fontsize',10,'xtick',1:size(options_.varobs,1))
set(gca,'xlim',[0.5 size(options_.varobs,1)+0.5])
set(gca,'ylim',[-2 102])
for ip=1:size(options_.varobs,1)
if options_.TeX
text(ip,-4,deblank(opt_gsa.varobs_tex(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','latex')
else
text(ip,-4,deblank(options_.varobs(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
end
xlabel(' ')
ylabel(' ')
title(M_.exo_names{j},'interpreter','none')
if mod(j,6)==0 || j==M_.exo_nbr
dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],options_.nodisplay,options_.graph_format);
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],ifig,'Variance decomposition shocks','vdec_exo',options_.figures.textwidth*min(iplo/3,1))
end
end
end
for j=1:size(cc,1)
cc(j,j,:)=gsa.standardize_columns(squeeze(log(cc(j,j,:))))./2;
end
[vdec, ~, ir_vdec, ic_vdec] = gsa.teff(vdec,Nsam,istable);
[cc, ~, ir_cc, ic_cc] = gsa.teff(cc,Nsam,istable);
[ac, ~, ir_ac, ic_ac] = gsa.teff(ac,Nsam,istable);
nc1= size(T,2);
endo_nbr = M_.endo_nbr;
nstatic = M_.nstatic;
nspred = M_.nspred;
iv = (1:endo_nbr)';
ic = [ nstatic+(1:nspred) endo_nbr+(1:size(dr.ghx,2)-nspred) ]';
dr.ghx = T(:, 1:(nc1-M_.exo_nbr),1);
dr.ghu = T(:, (nc1-M_.exo_nbr+1):end, 1);
[Aa,Bb] = kalman_transition_matrix(dr,iv,ic);
A = zeros(size(Aa,1),size(Aa,2)+size(Aa,1),length(istable));
if ~isempty(lpmatx)
M_=gsa.set_shocks_param(M_,estim_params_,lpmatx(1,:));
end
A(:,:,1)=[Aa, triu(Bb*M_.Sigma_e*Bb')];
for j=2:length(istable)
dr.ghx = T(:, 1:(nc1-M_.exo_nbr),j);
dr.ghu = T(:, (nc1-M_.exo_nbr+1):end, j);
[Aa,Bb] = kalman_transition_matrix(dr, iv, ic);
if ~isempty(lpmatx)
M_=gsa.set_shocks_param(M_,estim_params_,lpmatx(j,:));
end
A(:,:,j)=[Aa, triu(Bb*M_.Sigma_e*Bb')];
end
clear T
clear lpmatx
[yt, j0]=gsa.teff(A,Nsam,istable);
yt = [yys yt];
if opt_gsa.morris==2
clear TAU A
else
clear A
end
save([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss')
else %load identification files
load([OutputDirectoryName,'/',fname_,'_main_eff.mat'],'ac','cc','vdec','yt','mss')
end
if opt_gsa.morris==1
if ~isempty(vdec)
if opt_gsa.load_ident_files==0
SAMorris=NaN(npT,3,size(vdec,2));
for i=1:size(vdec,2)
[~, SAMorris(:,:,i)] = gsa.Morris_Measure_Groups(npT, [lpmat0 lpmat], vdec(:,i),nliv);
end
SAvdec = squeeze(SAMorris(:,1,:))';
save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAvdec','vdec','ir_vdec','ic_vdec')
else
load([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAvdec')
end
hh_fig = dyn_figure(options_.nodisplay,'name','Screening identification: variance decomposition');
gsa.boxplot(SAvdec,[],'.',[],10)
set(gca,'xticklabel',' ','fontsize',10,'xtick',1:npT)
set(gca,'xlim',[0.5 npT+0.5])
ydum = get(gca,'ylim');
set(gca,'ylim',[0 ydum(2)])
set(gca,'position',[0.13 0.2 0.775 0.7])
for ip=1:npT
if options_.TeX
[~, param_name_tex_temp]= get_the_name(ip,options_.TeX,M_,estim_params_,options_.varobs);
text(ip,-2,param_name_tex_temp,'rotation',90,'HorizontalAlignment','right','interpreter','latex')
else
text(ip,-2,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
end
xlabel(' ')
title('Elementary effects variance decomposition')
dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_morris_vdec'],options_.nodisplay,options_.graph_format);
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_vdec'],1,'Screening identification: variance decomposition','morris_vdec',1)
else
save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'vdec')
end
if opt_gsa.load_ident_files==0
ccac = [mss cc ac];
SAMorris=NaN(npT,3,size(ccac,2));
for i=1:size(ccac,2)
[~, SAMorris(:,:,i)] = gsa.Morris_Measure_Groups(npT, [lpmat0 lpmat], [ccac(:,i)],nliv);
end
SAcc = squeeze(SAMorris(:,1,:))';
SAcc = SAcc./(max(SAcc,[],2)*ones(1,npT));
save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAcc','cc','ir_cc','ic_cc','-append')
save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'ac','ir_ac','ic_ac','-append')
else
load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAcc','cc','ir_cc','ic_cc')
load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'ac','ir_ac','ic_ac')
end
hh_fig=dyn_figure(options_.nodisplay,'name','Screening identification: theoretical moments');
gsa.boxplot(SAcc,[],'.',[],10)
set(gca,'xticklabel',' ','fontsize',10,'xtick',1:npT)
set(gca,'xlim',[0.5 npT+0.5])
set(gca,'ylim',[0 1])
set(gca,'position',[0.13 0.2 0.775 0.7])
for ip=1:npT
if options_.TeX
[~, param_name_tex_temp]= get_the_name(ip,options_.TeX,M_,estim_params_,options_.varobs);
text(ip,-0.02,param_name_tex_temp,'rotation',90,'HorizontalAlignment','right','interpreter','latex')
else
text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
end
xlabel(' ')
title('Elementary effects in the moments')
dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_morris_moments'],options_.nodisplay,options_.graph_format);
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_moments'],1,'Screening identification: theoretical moments','morris_moments',1)
if opt_gsa.load_ident_files==0
SAMorris=NaN(npT,3,j0);
for j=1:j0
[~, SAMorris(:,:,j)] = gsa.Morris_Measure_Groups(npT, [lpmat0 lpmat], yt(:,j),nliv);
end
SAM = squeeze(SAMorris(1:end,1,:));
SAnorm=NaN(npT,j0);
irex=NaN(j0);
for j=1:j0
SAnorm(:,j)=SAM(:,j)./max(SAM(:,j));
irex(j)=length(find(SAnorm(:,j)>0.01));
end
SAMmu = squeeze(SAMorris(1:end,2,:));
SAmunorm=NaN(npT,j0);
for j=1:j0
SAmunorm(:,j)=SAMmu(:,j)./max(SAM(:,j)); % normalised w.r.t. mu*
end
SAMsig = squeeze(SAMorris(1:end,3,:));
SAsignorm=NaN(npT,j0);
for j=1:j0
SAsignorm(:,j)=SAMsig(:,j)./max(SAMsig(:,j));
end
save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'SAnorm','SAmunorm','SAsignorm','-append')
else
load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAnorm')
end
hh_fig=dyn_figure(options_.nodisplay,'name','Screening identification: model');
gsa.boxplot(SAnorm',[],'.',[],10)
set(gca,'xticklabel',' ','fontsize',10,'xtick',1:npT)
set(gca,'xlim',[0.5 npT+0.5])
set(gca,'ylim',[0 1])
set(gca,'position',[0.13 0.2 0.775 0.7])
xlabel(' ')
for ip=1:npT
if options_.TeX
[~, param_name_tex_temp]= get_the_name(ip,options_.TeX,M_,estim_params_,options_.varobs);
text(ip,-0.02,param_name_tex_temp,'rotation',90,'HorizontalAlignment','right','interpreter','latex')
else
text(ip,-0.02,bayestopt_.name{ip},'rotation',90,'HorizontalAlignment','right','interpreter','none')
end
end
xlabel(' ')
title('Elementary effects in the model')
dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_morris_par'],options_.nodisplay,options_.graph_format);
create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_par'],1,'Screening identification: model','morris_par',1)
elseif opt_gsa.morris==3
return
elseif opt_gsa.morris==2 % ISKREV stuff
return
else
error('gsa/map_identification: unsupported option morris=%u',opt_gsa.morris)
end
function []=create_TeX_loader(options_,figpath,ifig_number,caption,label_name,scale_factor)
if nargin<6
scale_factor=1;
end
if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([figpath '.tex'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by map_ident_.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n\n']);
fprintf(fidTeX,'\\begin{figure}[H]\n');
fprintf(fidTeX,'\\centering \n');
fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s}\n',scale_factor,strrep(figpath,'\','/'));
fprintf(fidTeX,'\\caption{%s.}',caption);
fprintf(fidTeX,'\\label{Fig:%s:%u}\n',label_name,ifig_number);
fprintf(fidTeX,'\\end{figure}\n\n');
fprintf(fidTeX,'%% End Of TeX file. \n');
fclose(fidTeX);
end
function yr = trank(y)
% yr is the rank transformation of y
yr=NaN(size(y));
[nr, nc] = size(y);
for j=1:nc
[~, is]=sort(y(:,j));
yr(is,j)=[1:nr]'./nr;
end

View File

@ -1,115 +0,0 @@
function indmcf = monte_carlo_filtering_analysis(lpmat, ibeha, inobeha, options_mcf, M_, options_, bayestopt_, estim_params_)
% indmcf = monte_carlo_filtering_analysis(lpmat, ibeha, inobeha, options_mcf, M_, options_, bayestopt_, estim_params_)
% Inputs:
% - lpmat [double] Monte Carlo matrix
% - ibeha [integer] index of behavioural runs
% - inobeha [integer] index of non-behavioural runs
% - options_gsa_ [structure] GSA options_
% - M_ [structure] describing the model
% - options_ [structure] describing the options
% - bayestopt_ [structure] describing the priors
% - estim_params_ [structure] characterizing parameters to be estimated
%
% Outputs:
% - indmcf [double] results of matrix
% Written by Marco Ratto
% Joint Research Centre, The European Commission,
% marco.ratto@ec.europa.eu
%
% Copyright © 2014 European Commission
% Copyright © 2016-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/>.
pvalue_ks = options_mcf.pvalue_ks;
pvalue_corr = options_mcf.pvalue_corr;
alpha2 = options_mcf.alpha2;
param_names = options_mcf.param_names;
if options_.TeX
if ~isfield(options_mcf,'param_names_tex')
param_names_tex = options_mcf.param_names;
else
param_names_tex = options_mcf.param_names_tex;
end
else
param_names_tex = strrep(options_mcf.param_names,'_','\_');
end
amcf_name = options_mcf.amcf_name;
amcf_title = options_mcf.amcf_title;
beha_title = options_mcf.beha_title;
nobeha_title = options_mcf.nobeha_title;
if options_.TeX
beha_title_latex = options_mcf.beha_title_latex;
nobeha_title_latex = options_mcf.nobeha_title_latex;
end
title = options_mcf.title;
fname_ = options_mcf.fname_;
xparam1=[];
if isfield(options_mcf,'xparam1')
xparam1=options_mcf.xparam1;
end
OutputDirectoryName = options_mcf.OutputDirectoryName;
[proba, dproba] = gsa.stability_mapping_univariate(lpmat, ibeha, inobeha, [],fname_, options_, bayestopt_.name, estim_params_,0);
indmcf=find(proba<pvalue_ks);
[~,jtmp] = sort(proba(indmcf),1,'ascend');
indmcf = indmcf(jtmp);
if ~isempty(indmcf)
skipline()
headers = {'Parameter','d-stat','p-value'};
labels = param_names(indmcf);
data_mat=[dproba(indmcf) proba(indmcf)];
options_temp.noprint=0;
dyntable(options_temp,['Smirnov statistics in driving ', title],headers,labels,data_mat,size(labels,2)+2,16,3);
if options_.TeX
labels_TeX=param_names_tex(indmcf);
M_temp.dname=OutputDirectoryName ;
M_temp.fname=fname_;
dyn_latex_table(M_temp,options_temp,['Smirnov statistics in driving ', strrep(title,'_','\\_')],amcf_name,headers,labels_TeX,data_mat,size(labels,2)+2,16,6);
end
end
if length(ibeha)>10 && length(inobeha)>10
if options_.TeX
indcorr1 = gsa.stability_mapping_bivariate(lpmat(ibeha,:),alpha2, pvalue_corr, M_, options_, bayestopt_, estim_params_, beha_title, beha_title_latex);
indcorr2 = gsa.stability_mapping_bivariate(lpmat(inobeha,:),alpha2, pvalue_corr, M_, options_, bayestopt_, estim_params_, nobeha_title, nobeha_title_latex);
else
indcorr1 = gsa.stability_mapping_bivariate(lpmat(ibeha,:),alpha2, pvalue_corr, M_, options_, bayestopt_, estim_params_, beha_title);
indcorr2 = gsa.stability_mapping_bivariate(lpmat(inobeha,:),alpha2, pvalue_corr, M_, options_, bayestopt_, estim_params_, nobeha_title);
end
indcorr = union(indcorr1(:), indcorr2(:));
indcorr = indcorr(~ismember(indcorr(:),indmcf));
indmcf = [indmcf(:); indcorr(:)];
end
if ~isempty(indmcf) && ~options_.nograph
skipline()
xx=[];
if ~ isempty(xparam1)
xx=xparam1(indmcf);
end
if options_.TeX
gsa.scatter_mcf(lpmat(ibeha,indmcf),lpmat(inobeha,indmcf), param_names_tex(indmcf), ...
'.', [fname_,'_',amcf_name], OutputDirectoryName, amcf_title,xx, options_, ...
beha_title, nobeha_title, beha_title_latex, nobeha_title_latex)
else
gsa.scatter_mcf(lpmat(ibeha,indmcf),lpmat(inobeha,indmcf), param_names_tex(indmcf), ...
'.', [fname_,'_',amcf_name], OutputDirectoryName, amcf_title,xx, options_, ...
beha_title, nobeha_title)
end
end

View File

@ -1,60 +0,0 @@
function [vdec, cc, ac] = monte_carlo_moments(mm, ss, dr, M_, options_, estim_params_)
% [vdec, cc, ac] = monte_carlo_moments(mm, ss, dr, M_, options_,estim_params_)
% Conduct Monte Carlo simulation of second moments for GSA
% Inputs:
% - dr [structure] decision rules
% - M_ [structure] model structure
% - options_ [structure] Matlab's structure describing the current options
% - estim_params_ [structure] characterizing parameters to be estimated
%
% Outputs:
% - vdec [double] variance decomposition matrix
% - cc [double] vector of unique elements of cross correlation matrix
% - ac [cell] autocorrelation matrix
% Copyright © 2012-2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
[~, nc1, nsam] = size(mm);
nobs=length(options_.varobs);
disp('monte_carlo_moments: Computing theoretical moments ...')
h = dyn_waitbar(0,'Theoretical moments ...');
vdec = zeros(nobs,M_.exo_nbr,nsam);
cc = zeros(nobs,nobs,nsam);
ac = zeros(nobs,nobs*options_.ar,nsam);
for j=1:nsam
dr.ghx = mm(:, 1:(nc1-M_.exo_nbr),j);
dr.ghu = mm(:, (nc1-M_.exo_nbr+1):end, j);
if ~isempty(ss)
M_=gsa.set_shocks_param(M_,estim_params_,ss(j,:));
end
[vdec(:,:,j), corr, autocorr] = gsa.th_moments(dr,options_,M_);
cc(:,:,j)=triu(corr);
dum=NaN(nobs,nobs*options_.ar);
for i=1:options_.ar
dum(:,(i-1)*nobs+1:i*nobs)=autocorr{i};
end
ac(:,:,j)=dum;
if mod(j,3)==0
dyn_waitbar(j/nsam,h)
end
end
dyn_waitbar_close(h)
skipline()
disp('... done !')

View File

@ -13,7 +13,7 @@ function run(json)
% SPECIAL REQUIREMENTS
% none
% Copyright © 2019-2023 Dynare Team
% Copyright © 2019-2022 Dynare Team
%
% This file is part of Dynare.
%
@ -30,7 +30,7 @@ function run(json)
% 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_ options_ oo_
global M_ options_ oo_ ys0_ ex0_
%% Check Inputs
if nargin ~= 1 || ~ischar(json)
@ -64,12 +64,12 @@ end
%% ENDVAL instructions
% initialize exogenous shocks to zero and compute final ss unless there is a permanent shock
oo_.initial_steady_state = [];
oo_.initial_exo_steady_state = [];
ys0_ = [];
ex0_ = [];
M_.det_shocks = [];
if ~isempty(jm.anticipated_permanent_shocks) || ~isempty(jm.endval_endo)
oo_.initial_steady_state= oo_.steady_state;
oo_.initial_exo_steady_state = oo_.exo_steady_state;
ys0_= oo_.steady_state;
ex0_ = oo_.exo_steady_state;
for i = 1:length(jm.endval_endo)
oo_.steady_state(jm.endval_endo(i).id) = jm.endval_endo(i).value;
end
@ -84,7 +84,7 @@ if ~isempty(jm.anticipated_permanent_shocks) || ~isempty(jm.endval_endo)
struct(...
'exo_det', false, ...
'exo_id', s.exo_id, ...
'type', 'level', ...
'multiplicative', false, ...
'periods', 1:s.start_date, ...
'value', 0)];
end
@ -99,7 +99,7 @@ if ~isempty(jm.anticipated_transitory_shocks)
M_.det_shocks; ...
struct('exo_det', false, ...
'exo_id', s.exo_id, ...
'type', 'level', ...
'multiplicative', false, ...
'periods', s.start_date:s.end_date, ...
'value', s.value)];
end
@ -142,26 +142,26 @@ mapkeys = unique(cell2mat([keys(unanticipated_p_shocks) keys(unanticipated_t_sho
%% Simulation
options_.periods = jm.periods;
oo_=perfect_foresight_setup(M_, options_, oo_);
perfect_foresight_setup;
% no surprise shocks present
if isempty(mapkeys)
oo_=perfect_foresight_solver(M_, options_, oo_);
perfect_foresight_solver;
return
end
% surprise shocks present
% in case there are unanticipated shocks...
if isempty(oo_.initial_steady_state)
if isempty(ys0_)
yy = oo_.steady_state;
else
yy = oo_.initial_steady_state;
yy = ys0_;
end
if mapkeys(1) ~= 1
% if first unanticipated shock is not in period 1
% simulate until first unanticipated shock and save
oo_=perfect_foresight_solver(M_, options_, oo_);
perfect_foresight_solver;
yy = [yy oo_.endo_simul(:, 2:mapkeys(1)+1)];
end
@ -203,7 +203,7 @@ for i = 1:length(mapkeys)
last_period = this_period;
assert(rows(oo_.exo_simul) == oo_exo_simul_rows, 'error encountered setting oo_.exo_simul');
oo_.endo_simul(:, 1) = yy(:, end);
oo_=perfect_foresight_solver(M_, options_, oo_);
perfect_foresight_solver;
if next_period > 0
yy = [yy oo_.endo_simul(:, 2:next_period-this_period+1)];
else

View File

@ -1,73 +0,0 @@
function J_test = Jtest(xparam, objective_function, Q, model_moments, m_data, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
% J_test = Jtest(xparam, objective_function, Q, model_moments, m_data, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
% -------------------------------------------------------------------------
% Computes the J-test statistic and p-value given a GMM/SMM estimation
% -------------------------------------------------------------------------
% INPUTS
% xparam: [vector] estimated parameter vector
% objective_function: [function handle] objective function
% Q: [scalar] value of moments distance criterion
% model_moments: [vector] model moments
% m_data: [matrix] selected empirical moments at each point in time
% data_moments: [vector] empirical moments
% weighting_info: [struct] information on weighting matrix
% options_mom_: [struct] options
% M_: [struct] model information
% estim_params_: [struct] estimated parameters
% bayestopt_: [struct] info on prior distributions
% BoundsInfo: [struct] info bounds on parameters
% dr: [struct] reduced form model
% endo_steady_state: [vector] steady state of endogenous variables (initval)
% exo_steady_state: [vector] steady state of exogenous variables (initval)
% exo_det_steady_state: [vector] steady state of deterministic exogenous variables (initval)
% -------------------------------------------------------------------------
% OUTPUT
% J_test: [struct] results of J test
% -------------------------------------------------------------------------
% This function is called by
% o mom.run
% -------------------------------------------------------------------------
% This function calls
% o mom.objective_function
% o mom.optimal_weighting_matrix
% -------------------------------------------------------------------------
% Copyright © 2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if options_mom_.mom.mom_nbr > length(xparam)
% Get optimal weighting matrix for J test, if necessary
if ~weighting_info.Woptflag
W_opt = mom.optimal_weighting_matrix(m_data, model_moments, options_mom_.mom.bartlett_kernel_lag);
weighting_info.Sw = chol(W_opt);
fval = feval(objective_function, xparam, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
else
fval = Q;
end
% Compute J statistic
if strcmp(options_mom_.mom.mom_method,'SMM')
variance_correction_factor = options_mom_.mom.variance_correction_factor;
elseif strcmp(options_mom_.mom.mom_method,'GMM')
variance_correction_factor = 1;
end
J_test.j_stat = options_mom_.nobs*variance_correction_factor*fval/options_mom_.mom.weighting_matrix_scaling_factor;
J_test.degrees_freedom = length(model_moments)-length(xparam);
J_test.p_val = 1-chi2cdf(J_test.j_stat, J_test.degrees_freedom);
fprintf('\nValue of J-test statistic: %f\n',J_test.j_stat);
fprintf('p-value of J-test statistic: %f\n',J_test.p_val);
end

View File

@ -1,57 +0,0 @@
function [irf_matching_file_name, irf_matching_file_path] = check_irf_matching_file(irf_matching_file)
% [irf_matching_file_name, irf_matching_file_path] = check_irf_matching_file(irf_matching_file)
% -------------------------------------------------------------------------
% Check if the provided irf_matching_file is a valid MATLAB function with
% .m extension and return name, path and extension of the file.
% -------------------------------------------------------------------------
% INPUTS
% - irf_matching_file: [string] user provided name (with possible path and extension)
% of the MATLAB function that transforms model IRFs
% -------------------------------------------------------------------------
% OUTPUTS
% - irf_matching_file_name: [string] name of the MATLAB function (without extension)
% - irf_matching_file_path: [string] path to irf_matching_file_name
% -------------------------------------------------------------------------
% This function is called by
% - mom.run
% -------------------------------------------------------------------------
% Copyright © 2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if isempty(irf_matching_file)
% no irf_matching_file provided, so no transformations will be done
irf_matching_file_name = '';
irf_matching_file_path = '';
else
[irf_matching_file_path, irf_matching_file_name, irf_matching_file_ext] = fileparts(irf_matching_file);
% make sure file is a MATLAB function with .m extension
if ~strcmp(irf_matching_file_ext,'.m')
if strcmp(irf_matching_file_ext,'')
irf_matching_file_ext = '.m';
else
error('method_of_moments: ''irf_matching_file'' needs to point towards a MATLAB function with extension ''.m''!');
end
end
if isempty(irf_matching_file_path)
irf_matching_file_path = '.';
end
if exist([irf_matching_file_path filesep irf_matching_file_name irf_matching_file_ext],'file') ~= 2
error('method_of_moments: Could not find a ''irf_matching_file'' called ''%s''!',[irf_matching_file_path filesep irf_matching_file_name irf_matching_file_ext]);
end
end

185
matlab/+mom/check_plot.m Normal file
View File

@ -0,0 +1,185 @@
function check_plot(fun,xparam,SE_vec,options_,M_,estim_params_,Bounds,bayestopt_,varargin)
%function check_plot(fun,xparam,SE_vec,options_,M_,estim_params_,Bounds,bayestopt_,varargin)
% Checks the estimated local minimum of the moment's distance objective
% Copyright © 2020-2021 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/>.
TeX = options_.TeX;
if ~isempty(SE_vec)
[ s_min, k ] = min(SE_vec);
end
fval = feval(fun,xparam,varargin{:});
if ~isempty(SE_vec)
skipline()
disp('LOCAL MINIMUM CHECK')
skipline()
fprintf('Fval obtained by the minimization routine: %f', fval);
skipline()
if s_min<eps
fprintf('Most negative variance %f for parameter %d (%s = %f)', s_min, k , bayestopt_.name{k}, xparam(k))
end
end
[nbplt,nr,nc,lr,lc,nstar] = pltorg(length(xparam));
if ~exist([M_.dname filesep 'graphs'],'dir')
mkdir(M_.dname,'graphs');
end
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fidTeX = fopen([M_.dname, '/graphs/', M_.fname '_MoMCheckPlots.tex'],'w');
fprintf(fidTeX,'%% TeX eps-loader file generated by mom.check_plot.m (Dynare).\n');
fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
fprintf(fidTeX,' \n');
end
ll = options_.mode_check.neighbourhood_size;
if isinf(ll)
options_.mode_check.symmetric_plots = false;
end
mcheck = struct('cross',struct(),'emin',struct());
for plt = 1:nbplt
if TeX
NAMES = [];
TeXNAMES = [];
end
hh = dyn_figure(options_.nodisplay,'Name','Minimum check plots');
for k=1:min(nstar,length(xparam)-(plt-1)*nstar)
subplot(nr,nc,k)
kk = (plt-1)*nstar+k;
[name,texname] = get_the_name(kk,TeX,M_,estim_params_,options_);
xx = xparam;
if xparam(kk)~=0 || ~isinf(Bounds.lb(kk)) || ~isinf(Bounds.lb(kk))
l1 = max(Bounds.lb(kk),(1-sign(xparam(kk))*ll)*xparam(kk)); m1 = 0; %lower bound
l2 = min(Bounds.ub(kk),(1+sign(xparam(kk))*ll)*xparam(kk)); %upper bound
else
%size info for 0 parameter is missing, use prior standard
%deviation
upper_bound=Bounds.lb(kk);
if isinf(upper_bound)
upper_bound=-1e-6*options_.huge_number;
end
lower_bound=Bounds.ub(kk);
if isinf(lower_bound)
lower_bound=-1e-6*options_.huge_number;
end
l1 = max(lower_bound,-bayestopt_.p2(kk)); m1 = 0; %lower bound
l2 = min(upper_bound,bayestopt_.p2(kk)); %upper bound
end
binding_lower_bound=0;
binding_upper_bound=0;
if isequal(xparam(kk),Bounds.lb(kk))
binding_lower_bound=1;
bound_value=Bounds.lb(kk);
elseif isequal(xparam(kk),Bounds.ub(kk))
binding_upper_bound=1;
bound_value=Bounds.ub(kk);
end
if options_.mode_check.symmetric_plots && ~binding_lower_bound && ~binding_upper_bound
if l2<(1+ll)*xparam(kk) %test whether upper bound is too small due to prior binding
l1 = xparam(kk) - (l2-xparam(kk)); %adjust lower bound to become closer
m1 = 1;
end
if ~m1 && (l1>(1-ll)*xparam(kk)) && (xparam(kk)+(xparam(kk)-l1)<Bounds.ub(kk)) % if lower bound was truncated and using difference from lower bound does not violate upper bound
l2 = xparam(kk) + (xparam(kk)-l1); %set upper bound to same distance as lower bound
end
end
z1 = l1:((xparam(kk)-l1)/(options_.mode_check.number_of_points/2)):xparam(kk);
z2 = xparam(kk):((l2-xparam(kk))/(options_.mode_check.number_of_points/2)):l2;
z = union(z1,z2);
if options_.mom.penalized_estimator
y = zeros(length(z),2);
dy=(xx-bayestopt_.p1)'/diag(bayestopt_.p2.^2)*(xx-bayestopt_.p1);
else
y = zeros(length(z),1);
end
for i=1:length(z)
xx(kk) = z(i);
[fval, info, exit_flag] = feval(fun,xx,varargin{:});
if exit_flag
y(i,1) = fval;
else
y(i,1) = NaN;
if options_.debug
fprintf('mom.check_plot:: could not solve model for parameter %s at value %4.3f, error code: %u\n',name,z(i),info(1))
end
end
if options_.mom.penalized_estimator
prior=(xx-bayestopt_.p1)'/diag(bayestopt_.p2.^2)*(xx-bayestopt_.p1);
y(i,2) = (y(i,1)+prior-dy);
end
end
mcheck.cross = setfield(mcheck.cross, name, [transpose(z), y]);
mcheck.emin = setfield(mcheck.emin, name, xparam(kk));
fighandle=plot(z,y);
hold on
yl=get(gca,'ylim');
plot( [xparam(kk) xparam(kk)], yl, 'c', 'LineWidth', 1)
NaN_index = find(isnan(y(:,1)));
zNaN = z(NaN_index);
yNaN = yl(1)*ones(size(NaN_index));
plot(zNaN,yNaN,'o','MarkerEdgeColor','r','MarkerFaceColor','r','MarkerSize',6);
if TeX
title(texname,'interpreter','latex')
else
title(name,'interpreter','none')
end
axis tight
if binding_lower_bound || binding_upper_bound
xl=get(gca,'xlim');
plot( [bound_value bound_value], yl, 'r--', 'LineWidth', 1)
xlim([xl(1)-0.5*binding_lower_bound*(xl(2)-xl(1)) xl(2)+0.5*binding_upper_bound*(xl(2)-xl(1))])
end
hold off
drawnow
end
if options_.mom.penalized_estimator
if isoctave
axes('outerposition',[0.3 0.93 0.42 0.07],'box','on'),
else
axes('position',[0.3 0.01 0.42 0.05],'box','on'),
end
line_color=get(fighandle,'color');
plot([0.48 0.68],[0.5 0.5],'color',line_color{2})
hold on, plot([0.04 0.24],[0.5 0.5],'color',line_color{1})
set(gca,'xlim',[0 1],'ylim',[0 1],'xtick',[],'ytick',[])
text(0.25,0.5,'log-post')
text(0.69,0.5,'log-lik kernel')
end
dyn_saveas(hh,[M_.dname, '/graphs/', M_.fname '_MoMCheckPlots' 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]{%s_MoMCheckPlots%s}\n',options_.figures.textwidth*min(k/nc,1),[M_.dname, '/graphs/',M_.fname],int2str(plt));
fprintf(fidTeX,'\\caption{Method of Moments check plots.}');
fprintf(fidTeX,'\\label{Fig:MoMCheckPlots:%s}\n',int2str(plt));
fprintf(fidTeX,'\\end{figure}\n');
fprintf(fidTeX,' \n');
end
end
if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
fclose(fidTeX);
end
save([M_.dname filesep 'graphs' filesep M_.fname '_MoMCheckPlots_data.mat'],'mcheck');

View File

@ -1,25 +1,22 @@
function [data_moments, m_data] = get_data_moments(data, obs_var, inv_order_var, matched_moments_, options_mom_)
% [data_moments, m_data] = get_data_moments(data, obs_var, inv_order_var, matched_moments_, options_mom_)
% -------------------------------------------------------------------------
% Computes the user-selected empirical moments from data
% -------------------------------------------------------------------------
function [dataMoments, m_data] = data_moments(data, oo_, matched_moments_, options_mom_)
% [dataMoments, m_data] = data_moments(data, oo_, matched_moments_, options_mom_)
% This function computes the user-selected empirical moments from data
% =========================================================================
% INPUTS
% o data [T x varobs_nbr] data set
% o obs_var: [integer] index of observables
% o inv_order_var: [integer] inverse decision rule order
% o oo_: [structure] storage for results
% o matched_moments_: [structure] information about selected moments to match in estimation
% o options_mom_: [structure] information about all settings (specified by the user, preprocessor, and taken from global options_)
% -------------------------------------------------------------------------
% OUTPUTS
% o data_moments [numMom x 1] mean of selected empirical moments
% o dataMoments [numMom x 1] mean of selected empirical moments
% o m_data [T x numMom] selected empirical moments at each point in time
% -------------------------------------------------------------------------
% This function is called by
% o mom.run
% o mom.objective_function
% -------------------------------------------------------------------------
% Copyright © 2020-2023 Dynare Team
% o mom.run.m
% o mom.objective_function.m
% =========================================================================
% Copyright © 2020-2021 Dynare Team
%
% This file is part of Dynare.
%
@ -35,20 +32,24 @@ function [data_moments, m_data] = get_data_moments(data, obs_var, inv_order_var,
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
% -------------------------------------------------------------------------
% Author(s):
% o Willi Mutschler (willi@mutschler.eu)
% o Johannes Pfeifer (jpfeifer@uni-koeln.de)
% =========================================================================
% Initialization
T = size(data,1); % Number of observations (T)
data_moments = NaN(options_mom_.mom.mom_nbr,1);
dataMoments = NaN(options_mom_.mom.mom_nbr,1);
m_data = NaN(T,options_mom_.mom.mom_nbr);
% Product moment for each time period, i.e. each row t contains y_t1(l1)^p1*y_t2(l2)^p2*...
% note that here we already are able to treat leads and lags and any power product moments
for jm = 1:options_mom_.mom.mom_nbr
vars = inv_order_var(matched_moments_{jm,1})';
vars = oo_.dr.inv_order_var(matched_moments_{jm,1})';
leadlags = matched_moments_{jm,2}; % lags are negative numbers and leads are positive numbers
powers = matched_moments_{jm,3};
for jv = 1:length(vars)
jvar = (obs_var == vars(jv));
jvar = (oo_.dr.obs_var == vars(jv));
y = NaN(T,1); %Take care of T_eff instead of T for lags and NaN via mean with 'omitnan' option below
y( (1-min(leadlags(jv),0)) : (T-max(leadlags(jv),0)), 1) = data( (1+max(leadlags(jv),0)) : (T+min(leadlags(jv),0)), jvar).^powers(jv);
if jv==1
@ -58,11 +59,14 @@ for jm = 1:options_mom_.mom.mom_nbr
end
end
% We replace NaN (due to leads and lags and missing values) with the corresponding mean
if isoctave && octave_ver_less_than('8')
data_moments(jm,1) = nanmean(m_data_tmp);
if isoctave || matlab_ver_less_than('8.5')
dataMoments(jm,1) = nanmean(m_data_tmp);
else
data_moments(jm,1) = mean(m_data_tmp,'omitnan');
dataMoments(jm,1) = mean(m_data_tmp,'omitnan');
end
m_data_tmp(isnan(m_data_tmp)) = data_moments(jm,1);
m_data_tmp(isnan(m_data_tmp)) = dataMoments(jm,1);
m_data(:,jm) = m_data_tmp;
end
end %function end

View File

@ -1,475 +0,0 @@
function options_mom_ = default_option_mom_values(options_mom_, options_, dname, do_bayesian_estimation)
% options_mom_ = default_option_mom_values(options_mom_, options_, dname, do_bayesian_estimation)
% -------------------------------------------------------------------------
% Returns structure containing the options for method_of_moments command.
% Note 1: options_mom_ is local and contains default and user-specified
% values for all settings needed for the method of moments estimation.
% Some options, though, are set by the preprocessor into options_ and we
% copy these over. The idea is to be independent of options_ and have full
% control of the estimation instead of possibly having to deal with options
% chosen somewhere else in the mod file.
% Note 2: we call a "mode" the minimum of the objective function, i.e.
% the parameter vector that minimizes the distance between the moments/IRFs
% computed from the model and the moments/IRFs computed from the data.
% -------------------------------------------------------------------------
% INPUTS
% o options_mom_: [structure] all user-specified settings (from the method_of_moments command)
% o options_: [structure] global options
% o dname: [string] default name of directory to store results
% o do_bayesian_estimation [boolean] indicator whether we do Bayesian estimation
% -------------------------------------------------------------------------
% OUTPUTS
% o options_mom_: [structure] all user-specified and updated settings required for method_of_moments estimation
% -------------------------------------------------------------------------
% This function is called by
% o mom.run
% -------------------------------------------------------------------------
% This function calls
% o set_default_option
% o user_has_matlab_license
% o user_has_octave_forge_package
% -------------------------------------------------------------------------
% Copyright © 2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
mom_method = options_mom_.mom.mom_method; % this is a required option
% -------------------------------------------------------------------------
% LIMITATIONS
% -------------------------------------------------------------------------
if options_.logged_steady_state || options_.loglinear
error('method_of_moments: The loglinear option is not supported. Please append the required logged variables as auxiliary equations.');
else
options_mom_.logged_steady_state = 0;
options_mom_.loglinear = false;
end
if isfield(options_mom_,'hessian') && options_mom_.hessian.use_penalized_objective
warning('method_of_moments: The ''use_penalized_objective_for_hessian'' option is not supported yet and will be skipped.');
end
options_mom_.hessian.use_penalized_objective = false; % penalized objective not yet supported
if isfield(options_,'trend_coeffs')
error('method_of_moments: %s does not allow for trend in data',mom_method);
end
if ~isempty(options_.endogenous_prior_restrictions.irf) && ~isempty(options_.endogenous_prior_restrictions.moment)
warning('method_of_moments: Endogenous prior restrictions are not supported yet and will be skipped.');
end
options_mom_.endogenous_prior_restrictions.irf = {};
options_mom_.endogenous_prior_restrictions.moment = {};
if isfield(options_mom_,'bayesian_irf') && options_mom_.bayesian_irf % do we need this at all??
warning('method_of_moments: The ''bayesian_irf'' option is not supported yet and will be skipped.');
end
options_mom_.bayesian_irf = false;
if strcmp(mom_method,'IRF_MATCHING')
if isfield(options_mom_.mom,'penalized_estimator') && options_mom_.mom.penalized_estimator
warning('method_of_moments: The ''penalized_estimator'' option is not supported yet for IRF_MATCHING and will be ignored.');
end
options_mom_.mom.penalized_estimator = false;
end
% -------------------------------------------------------------------------
% OPTIONS POSSIBLY SET BY THE USER
% -------------------------------------------------------------------------
% common settings
options_mom_ = set_default_option(options_mom_,'dirname',dname); % specify directory in which to store estimation output
options_mom_ = set_default_option(options_mom_,'graph_format','eps'); % specify the file format(s) for graphs saved to disk
options_mom_ = set_default_option(options_mom_,'nodisplay',false); % do not display the graphs, but still save them to disk
options_mom_ = set_default_option(options_mom_,'nograph',false); % do not create graphs (which implies that they are not saved to the disk nor displayed)
options_mom_ = set_default_option(options_mom_,'noprint',false); % do not print output to console
options_mom_ = set_default_option(options_mom_,'TeX',false); % print TeX tables and graphics
options_mom_.mom = set_default_option(options_mom_.mom,'verbose',false); % display and store intermediate estimation results
if do_bayesian_estimation
options_mom_ = set_default_option(options_mom_,'plot_priors',true); % control plotting of priors
options_mom_ = set_default_option(options_mom_,'prior_trunc',1e-10); % probability of extreme values of the prior density that is ignored when computing bounds for the parameters
end
% specific method_of_moments settings
if strcmp(mom_method,'GMM') || strcmp(mom_method,'SMM')
options_mom_.mom = set_default_option(options_mom_.mom,'bartlett_kernel_lag',20); % bandwith in optimal weighting matrix
options_mom_.mom = set_default_option(options_mom_.mom,'penalized_estimator',false); % include deviation from prior mean as additional moment restriction and use prior precision as weights
options_mom_.mom = set_default_option(options_mom_.mom,'se_tolx',1e-5); % step size for numerical computation of standard errors
options_mom_.mom = set_default_option(options_mom_.mom,'weighting_matrix_scaling_factor',1); % scaling of weighting matrix in objective function
options_mom_.mom = set_default_option(options_mom_.mom,'weighting_matrix',{'DIAGONAL'; 'OPTIMAL'}); % weighting matrix in moments distance objective function at each iteration of estimation;
% possible values are 'OPTIMAL', 'IDENTITY_MATRIX' ,'DIAGONAL' or a filename. Size of cell determines stages in iterated estimation.
end
if strcmp(mom_method,'SMM')
options_mom_.mom = set_default_option(options_mom_.mom,'burnin',500); % number of periods dropped at beginning of simulation
options_mom_.mom = set_default_option(options_mom_.mom,'bounded_shock_support',false); % trim shocks in simulation to +- 2 stdev
options_mom_.mom = set_default_option(options_mom_.mom,'seed',24051986); % seed used in simulations
options_mom_.mom = set_default_option(options_mom_.mom,'simulation_multiple',7); % multiple of the data length used for simulation
end
if strcmp(mom_method,'GMM')
options_mom_.mom = set_default_option(options_mom_.mom,'analytic_standard_errors',false); % compute standard errors numerically (0) or analytically (1). Analytical derivatives are only available for GMM.
end
if strcmp(mom_method,'IRF_MATCHING')
if ~isfield(options_mom_.mom,'irf_matching_file')
options_mom_.mom.irf_matching_file = []; % irf_matching file enables to transform model IRFs before matching them to data IRFs
end
options_mom_.mom.irf_matching_file = set_default_option(options_mom_.mom.irf_matching_file,'name','');
options_mom_.mom = set_default_option(options_mom_.mom,'simulation_method','STOCH_SIMUL'); % simulation method used to compute IRFs
options_mom_ = set_default_option(options_mom_,'add_tiny_number_to_cholesky',1e-14); % add tiny number to Cholesky factor to avoid numerical problems when computing IRFs
options_mom_ = set_default_option(options_mom_,'drop',100); % truncation / burnin for order>1 irf simulations
options_mom_ = set_default_option(options_mom_,'relative_irf',false); % requests the computation of normalized IRFs
end
% data related options
if strcmp(mom_method,'GMM') || strcmp(mom_method,'SMM')
options_mom_ = set_default_option(options_mom_,'first_obs',1); % number of first observation
options_mom_ = set_default_option(options_mom_,'logdata',false); % if data is already in logs
options_mom_ = set_default_option(options_mom_,'nobs',NaN); % number of observations
options_mom_ = set_default_option(options_mom_,'prefilter',false); % demean each data series by its empirical mean and use centered moments
options_mom_ = set_default_option(options_mom_,'xls_sheet',1); % name of sheet with data in Excel, Octave does not support the empty string, rather use first sheet
options_mom_ = set_default_option(options_mom_,'xls_range',''); % range of data in Excel sheet
end
% optimization related
if strcmp(mom_method,'GMM') || strcmp(mom_method,'SMM')
if (isoctave && user_has_octave_forge_package('optim')) || (~isoctave && user_has_matlab_license('optimization_toolbox'))
options_mom_ = set_default_option(options_mom_,'mode_compute',13); % specifies lsqnonlin as default optimizer for minimization
else
options_mom_ = set_default_option(options_mom_,'mode_compute',5); % specifies newrat as fallback default option for minimization
end
elseif strcmp(mom_method,'IRF_MATCHING')
options_mom_ = set_default_option(options_mom_,'mode_compute',5); % specifies newrat as fallback default option for minimization
end
options_mom_ = set_default_option(options_mom_,'additional_optimizer_steps',[]); % vector of additional mode-finders run after mode_compute
options_mom_ = set_default_option(options_mom_,'optim_opt',[]); % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
options_mom_ = set_default_option(options_mom_,'silent_optimizer',false); % run minimization of moments distance silently without displaying results or saving files in between
options_mom_ = set_default_option(options_mom_,'huge_number',1e7); % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
options_mom_.mom = set_default_option(options_mom_.mom,'analytic_jacobian',false); % use analytic Jacobian in optimization, only available for GMM and gradient-based optimizers
options_mom_.optimizer_vec = [options_mom_.mode_compute;num2cell(options_mom_.additional_optimizer_steps)];
options_mom_.mom.analytic_jacobian_optimizers = [1, 3, 4, 13, 101]; % these are currently supported optimizers that are able to use the analytic_jacobian option
options_mom_.analytic_derivation = 0; % force to 0 as we check this seperately in dynare_minimize_objective.m
options_mom_ = set_default_option(options_mom_,'mode_file',''); % name of the file containing initial values for the mode
options_mom_ = set_default_option(options_mom_,'cova_compute',true); % 1: computed covariance via Hessian after the computation of the mode, 0: turn off computation of covariance matrix
% perturbation related
options_mom_ = set_default_option(options_mom_,'order',1); % order of Taylor approximation in perturbation
if strcmp(mom_method,'IRF_MATCHING') % number of simulated series used to compute IRFs
if options_mom_.order == 1
options_mom_ = set_default_option(options_mom_,'replic',1);
else
options_mom_ = set_default_option(options_mom_,'replic',50);
end
end
options_mom_ = set_default_option(options_mom_,'pruning',false); % use pruned state space system at order>1
options_mom_ = set_default_option(options_mom_,'aim_solver',false); % use AIM algorithm to compute perturbation approximation instead of mjdgges
options_mom_ = set_default_option(options_mom_,'k_order_solver',false); % use k_order_perturbation instead of mjdgges
options_mom_ = set_default_option(options_mom_,'dr_cycle_reduction',false); % use cycle reduction algorithm to solve the polynomial equation for retrieving the coefficients associated to the endogenous variables in the decision rule
options_mom_ = set_default_option(options_mom_,'dr_cycle_reduction_tol',1e-7); % convergence criterion used in the cycle reduction algorithm
options_mom_ = set_default_option(options_mom_,'dr_logarithmic_reduction',false); % use logarithmic reduction algorithm to solve the polynomial equation for retrieving the coefficients associated to the endogenous variables in the decision rule
options_mom_ = set_default_option(options_mom_,'dr_logarithmic_reduction_maxiter',100); % maximum number of iterations used in the logarithmic reduction algorithm
options_mom_ = set_default_option(options_mom_,'dr_logarithmic_reduction_tol',1e-12); % convergence criterion used in the cycle reduction algorithm
options_mom_ = set_default_option(options_mom_,'qz_criterium',1-1e-6); % value used to split stable from unstable eigenvalues in reordering the Generalized Schur decomposition used for solving first order problems
% if there are no unit roots one can use 1.0 (or slightly below) which we set as default; if they are possible, you may have have multiple unit roots and the accuracy decreases when computing the eigenvalues in lyapunov_symm
% Note that unit roots are only possible at first-order, at higher order we set it to 1 in pruned_state_space_system and focus only on stationary observables.
options_mom_ = set_default_option(options_mom_,'qz_zero_threshold',1e-6); % value used to test if a generalized eigenvalue is 0/0 in the generalized Schur decomposition
options_mom_ = set_default_option(options_mom_,'schur_vec_tol',1e-11); % tolerance level used to find nonstationary variables in Schur decomposition of the transition matrix.
% numerical algorithms
options_mom_ = set_default_option(options_mom_,'lyapunov_db',false); % doubling algorithm (disclyap_fast) to solve Lyapunov equation to compute variance-covariance matrix of state variables
options_mom_ = set_default_option(options_mom_,'lyapunov_fp',false); % fixed-point algorithm to solve Lyapunov equation to compute variance-covariance matrix of state variables
options_mom_ = set_default_option(options_mom_,'lyapunov_srs',false); % square-root-solver (dlyapchol) algorithm to solve Lyapunov equation to compute variance-covariance matrix of state variables
options_mom_ = set_default_option(options_mom_,'lyapunov_complex_threshold',1e-15); % complex block threshold for the upper triangular matrix in symmetric Lyapunov equation solver
options_mom_ = set_default_option(options_mom_,'lyapunov_fixed_point_tol',1e-10); % convergence criterion used in the fixed point Lyapunov solver
options_mom_ = set_default_option(options_mom_,'lyapunov_doubling_tol',1e-16); % convergence criterion used in the doubling algorithm
% Bayesian MCMC related
if do_bayesian_estimation
options_mom_ = set_default_option(options_mom_,'mh_replic',0); % number of draws in Metropolis-Hastings and slice samplers
options_mom_ = set_default_option(options_mom_,'mh_posterior_mode_estimation',false); % skip optimizer-based mode-finding and instead compute the mode based on a run of a MCMC
options_mom_ = set_default_option(options_mom_,'load_mh_file',false); % add to previous Metropolis-Hastings or slice simulations instead of starting from scratch
options_mom_ = set_default_option(options_mom_,'load_results_after_load_mh',false); % load the previously computed convergence diagnostics, marginal data density, and posterior statistics from an existing mom_results file instead of recomputing them
if options_mom_.mh_replic > 0 || options_mom_.load_mh_file
options_mom_ = set_default_option(options_mom_,'sub_draws',[]);
options_mom_ = set_default_option(options_mom_,'posterior_max_subsample_draws',1200);
options_mom_ = set_default_option(options_mom_,'mh_nblck',2); % number of parallel chains for Metropolis-Hastings or slice algorithm
options_mom_ = set_default_option(options_mom_,'mh_drop',0.5); % fraction of initially generated parameter vectors to be dropped as a burn-in before using posterior simulations
options_mom_ = set_default_option(options_mom_,'mh_conf_sig',0.9); % confidence/HPD interval used for the computation of prior and posterior statistics
options_mom_ = set_default_option(options_mom_,'mh_recover',false); % attempts to recover a Metropolis-Hastings simulation that crashed prematurely
options_mom_ = set_default_option(options_mom_,'MCMC_jumping_covariance','hessian'); % which covariance to use for the proposal density of the MCMC sampler
if ~isfield(options_mom_,'mh_initialize_from_previous_mcmc')
options_mom_.mh_initialize_from_previous_mcmc.status = false; % pick initial values for new MCMC from a previous one
end
options_mom_.mh_initialize_from_previous_mcmc = set_default_option(options_mom_.mh_initialize_from_previous_mcmc,'directory',''); % pick initial values for new MCMC from a previous one: directory
options_mom_.mh_initialize_from_previous_mcmc = set_default_option(options_mom_.mh_initialize_from_previous_mcmc,'record',''); % pick initial values for new MCMC from a previous one: record file name
options_mom_.mh_initialize_from_previous_mcmc = set_default_option(options_mom_.mh_initialize_from_previous_mcmc,'prior',''); % pick initial values for new MCMC from a previous one: prior file name
if ~isfield(options_mom_,'posterior_sampler_options')
options_mom_.posterior_sampler_options = [];
end
options_mom_.posterior_sampler_options = set_default_option(options_mom_.posterior_sampler_options,'posterior_sampling_method','random_walk_metropolis_hastings'); % selects the sampler used to sample from the posterior distribution during Bayesian estimation
options_mom_.posterior_sampler_options = set_default_option(options_mom_.posterior_sampler_options,'sampling_opt',[]); % used to set options for the posterior sampling methods
switch options_mom_.posterior_sampler_options.posterior_sampling_method
case 'random_walk_metropolis_hastings'
if ~isfield(options_mom_.posterior_sampler_options,'rwmh')
options_mom_.posterior_sampler_options.rwmh = [];
end
options_mom_.posterior_sampler_options.rwmh = set_default_option(options_mom_.posterior_sampler_options.rwmh,'proposal_distribution','rand_multivariate_normal');
options_mom_.posterior_sampler_options.rwmh = set_default_option(options_mom_.posterior_sampler_options.rwmh,'student_degrees_of_freedom',3);
options_mom_.posterior_sampler_options.rwmh = set_default_option(options_mom_.posterior_sampler_options.rwmh,'use_mh_covariance_matrix',false);
options_mom_.posterior_sampler_options.rwmh = set_default_option(options_mom_.posterior_sampler_options.rwmh,'save_tmp_file',false);
case 'tailored_random_block_metropolis_hastings'
if ~isfield(options_mom_.posterior_sampler_options,'tarb')
options_mom_.posterior_sampler_options.tarb = [];
end
options_mom_.posterior_sampler_options.tarb = set_default_option(options_mom_.posterior_sampler_options.tarb,'proposal_distribution','rand_multivariate_normal');
options_mom_.posterior_sampler_options.tarb = set_default_option(options_mom_.posterior_sampler_options.tarb,'student_degrees_of_freedom',3);
options_mom_.posterior_sampler_options.tarb = set_default_option(options_mom_.posterior_sampler_options.tarb,'mode_compute',4);
options_mom_.posterior_sampler_options.tarb = set_default_option(options_mom_.posterior_sampler_options.tarb,'new_block_probability',0.25);
options_mom_.posterior_sampler_options.tarb = set_default_option(options_mom_.posterior_sampler_options.tarb,'optim_opt','');
options_mom_.posterior_sampler_options.tarb = set_default_option(options_mom_.posterior_sampler_options.tarb,'save_tmp_file',true);
case 'slice'
if ~isfield(options_mom_.posterior_sampler_options,'slice')
options_mom_.posterior_sampler_options.slice = [];
end
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'proposal_distribution','');
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'rotated',0);
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'slice_initialize_with_mode',false); % must be used with rotated
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'use_mh_covariance_matrix',false); % must be used with rotated
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'WR',[]);
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'mode_files',[]);
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'mode',[]);
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'initial_step_size',0.8);
options_mom_.posterior_sampler_options.slice = set_default_option(options_mom_.posterior_sampler_options.slice,'save_tmp_file',true);
case 'independent_metropolis_hastings'
if ~isfield(options_mom_.posterior_sampler_options,'imh')
options_mom_.posterior_sampler_options.imh = [];
end
options_mom_.posterior_sampler_options.imh = set_default_option(options_mom_.posterior_sampler_options.imh,'proposal_distribution','rand_multivariate_normal');
options_mom_.posterior_sampler_options.imh = set_default_option(options_mom_.posterior_sampler_options.imh,'use_mh_covariance_matrix',false);
options_mom_.posterior_sampler_options.imh = set_default_option(options_mom_.posterior_sampler_options.imh,'save_tmp_file',false);
end
if ~strcmp(options_mom_.posterior_sampler_options.posterior_sampling_method,'slice')
options_mom_ = set_default_option(options_mom_,'mh_init_scale_factor',2);
options_mom_ = set_default_option(options_mom_,'mh_jscale',[]);
end
% mh_tune_jscale options
if strcmp(options_mom_.posterior_sampler_options.posterior_sampling_method,'random_walk_metropolis_hastings')
if ~isfield(options_mom_,'mh_tune_jscale')
options_mom_.mh_tune_jscale = [];
end
options_mom_.mh_tune_jscale = set_default_option(options_mom_.mh_tune_jscale,'status',false);
options_mom_.mh_tune_jscale = set_default_option(options_mom_.mh_tune_jscale,'target',0.33);
options_mom_.mh_tune_jscale = set_default_option(options_mom_.mh_tune_jscale,'guess',[]);
options_mom_.mh_tune_jscale.maxiter = options_.mh_tune_jscale.maxiter;
options_mom_.mh_tune_jscale.rho = options_.mh_tune_jscale.rho;
options_mom_.mh_tune_jscale.stepsize = options_.mh_tune_jscale.stepsize;
options_mom_.mh_tune_jscale.c1 = options_.mh_tune_jscale.c1;
options_mom_.mh_tune_jscale.c2 = options_.mh_tune_jscale.c2;
options_mom_.mh_tune_jscale.c3 = options_.mh_tune_jscale.c3;
end
% convergence diagnostics
options_mom_ = set_default_option(options_mom_,'nodiagnostic',false);
if ~isfield(options_mom_,'convergence')
options_mom_.convergence = [];
end
if ~isfield(options_mom_.convergence,'geweke')
options_mom_.convergence.geweke = [];
end
if ~isfield(options_mom_.convergence,'rafterylewis')
options_mom_.convergence.rafterylewis = [];
end
if ~isfield(options_mom_.convergence,'brooksgelman')
options_mom_.convergence.brooksgelman = [];
end
options_mom_.convergence.geweke = set_default_option(options_mom_.convergence.geweke,'taper_steps', [4 8 15]);
options_mom_.convergence.geweke = set_default_option(options_mom_.convergence.geweke,'geweke_interval', [0.2 0.5]);
options_mom_.convergence.rafterylewis = set_default_option(options_mom_.convergence.rafterylewis,'indicator', false);
options_mom_.convergence.rafterylewis = set_default_option(options_mom_.convergence.rafterylewis,'qrs', [0.025 0.005 0.95]);
options_mom_.convergence.brooksgelman = set_default_option(options_mom_.convergence.brooksgelman,'plotrows',3);
end
end
% mode check plot options
options_mom_.mode_check.nolik = false; % we don't do likelihood (also this initializes mode_check substructure)
options_mom_.mode_check = set_default_option(options_mom_.mode_check,'status',false); % plot the target function for values around the computed mode for each estimated parameter in turn. This is helpful to diagnose problems with the optimizer.
options_mom_.mode_check = set_default_option(options_mom_.mode_check,'neighbourhood_size',.5); % width of the window around the computed mode to be displayed on the diagnostic plots. This width is expressed in percentage deviation. The Inf value is allowed, and will trigger a plot over the entire domain
options_mom_.mode_check = set_default_option(options_mom_.mode_check,'symmetric_plots',true); % ensure that the check plots are symmetric around the mode. A value of 0 allows to have asymmetric plots, which can be useful if the mode is close to a domain boundary, or in conjunction with neighbourhood_size = Inf when the domain is not the entire real line
options_mom_.mode_check = set_default_option(options_mom_.mode_check,'number_of_points',20); % number of points around the mode where the target function is evaluated (for each parameter)
% -------------------------------------------------------------------------
% OPTIONS THAT NEED TO BE CARRIED OVER (E.G. SET BY THE PREPROCESSOR)
% -------------------------------------------------------------------------
% related to VAROBS block
options_mom_.varobs = options_.varobs; % observable variables in order they are declared in varobs
options_mom_.varobs_id = options_.varobs_id; % index for observable variables in M_.endo_names
options_mom_.obs_nbr = length(options_mom_.varobs); % number of observed variables
% related to call of dynare
options_mom_.console_mode = options_.console_mode;
if options_mom_.console_mode
options_mom_.nodisplay = true;
end
options_mom_.parallel = options_.parallel;
options_mom_.parallel_info = options_.parallel_info;
options_mom_.debug = options_.debug; % debug option is needed by some functions, e.g. check_plot
% related to estimated_params and estimated_params_init blocks
options_mom_.use_calibration_initialization = options_.use_calibration_initialization;
% related to model block
options_mom_.linear = options_.linear;
options_mom_.use_dll = options_.use_dll;
options_mom_.block = options_.block;
options_mom_.bytecode = options_.bytecode;
% related to steady-state computations
options_mom_.homotopy_force_continue = options_.homotopy_force_continue;
options_mom_.homotopy_mode = options_.homotopy_mode;
options_mom_.homotopy_steps = options_.homotopy_steps;
options_mom_.markowitz = options_.markowitz;
options_mom_.solve_algo = options_.solve_algo;
options_mom_.solve_tolf = options_.solve_tolf;
options_mom_.solve_tolx = options_.solve_tolx;
options_mom_.steady = options_.steady;
options_mom_.steadystate = options_.steadystate;
options_mom_.steadystate_flag = options_.steadystate_flag;
options_mom_.threads = options_.threads; % needed by resol
options_mom_.debug = options_.debug; % debug option needed by some functions, e.g. check_plot
% random numbers
options_mom_.DynareRandomStreams.seed = options_.DynareRandomStreams.seed;
options_mom_.DynareRandomStreams.algo = options_.DynareRandomStreams.algo;
% dataset_ related
options_mom_.dataset = options_.dataset;
options_mom_.initial_period = options_.initial_period;
% optimization related
if any(cellfun(@(x) isnumeric(x) && any(x == 2), options_mom_.optimizer_vec)) % simulated annealing (mode_compute=2)
options_mom_.saopt = options_.saopt;
end
if any(cellfun(@(x) isnumeric(x) && any(x == 4), options_mom_.optimizer_vec)) % csminwel (mode_compute=4)
options_mom_.csminwel = options_.csminwel;
end
if any(cellfun(@(x) isnumeric(x) && any(x == 5), options_mom_.optimizer_vec)) % newrat (mode_compute=5)
options_mom_.newrat = options_.newrat;
end
if any(cellfun(@(x) isnumeric(x) && any(x == 6), options_mom_.optimizer_vec)) % gmhmaxlik (mode_compute=6)
options_mom_.gmhmaxlik = options_.gmhmaxlik;
options_mom_.mh_jscale = options_.mh_jscale;
end
if any(cellfun(@(x) isnumeric(x) && any(x == 8), options_mom_.optimizer_vec)) % simplex variation on Nelder Mead algorithm (mode_compute=8)
options_mom_.simplex = options_.simplex;
end
if any(cellfun(@(x) isnumeric(x) && any(x == 9), options_mom_.optimizer_vec)) % cmaes (mode_compute=9)
options_mom_.cmaes = options_.cmaes;
end
if any(cellfun(@(x) isnumeric(x) && any(x == 10), options_mom_.optimizer_vec)) % simpsa (mode_compute=10)
options_mom_.simpsa = options_.simpsa;
end
if any(cellfun(@(x) isnumeric(x) && any(x == 12), options_mom_.optimizer_vec)) % particleswarm (mode_compute=12)
options_mom_.particleswarm = options_.particleswarm;
end
if any(cellfun(@(x) isnumeric(x) && any(x == 101), options_mom_.optimizer_vec)) % solveopt (mode_compute=101)
options_mom_.solveopt = options_.solveopt;
end
if any(cellfun(@(x) isnumeric(x) && (any(x == 4) || any(x == 5)), options_mom_.optimizer_vec)) % used by csminwel and newrat
options_mom_.gradient_method = options_.gradient_method;
options_mom_.gradient_epsilon = options_.gradient_epsilon;
end
options_mom_.gstep = options_.gstep; % needed by hessian.m
options_mom_.trust_region_initial_step_bound_factor = options_.trust_region_initial_step_bound_factor; % used in dynare_solve for trust_region
% miscellaneous
options_mom_.threads = options_.threads;
options_mom_.MaxNumberOfBytes = options_.MaxNumberOfBytes;
options_mom_.marginal_data_density = options_.marginal_data_density;
% -------------------------------------------------------------------------
% DEFAULT VALUES
% -------------------------------------------------------------------------
options_mom_.mom.compute_derivs = false; % flag to compute derivs in objective function (might change for GMM with either analytic_standard_errors or analytic_jacobian (dependent on optimizer))
options_mom_.mom.vector_output = false; % specifies whether the objective function returns a vector
options_mom_.analytic_derivation_mode = 0; % needed by get_perturbation_params_derivs.m, ie use efficient sylvester equation method to compute analytical derivatives as in Ratto & Iskrev (2012)
options_mom_.initialize_estimated_parameters_with_the_prior_mode = 0; % needed by set_prior.m
options_mom_.figures = options_.figures; % needed by plot_priors.m
options_mom_.ramsey_policy = false; % needed by evaluate_steady_state
options_mom_.risky_steadystate = false; % needed by resol
options_mom_.jacobian_flag = true; % needed by dynare_solve
options_mom_.use_mh_covariance_matrix = false; % needed by posterior_sampler, get's overwritten by same option in options_mom_.posterior_sampler_options
% -------------------------------------------------------------------------
% CHECKS ON SETTINGS
% -------------------------------------------------------------------------
if strcmp(mom_method,'GMM') || strcmp(mom_method,'SMM')
if numel(options_mom_.nobs) > 1
error('method_of_moments: Recursive estimation is not supported. Please set an integer as ''nobs''!');
end
if numel(options_mom_.first_obs) > 1
error('method_of_moments: Recursive estimation is not supported. Please set an integer as ''first_obs''!');
end
end
if options_mom_.order < 1
error('method_of_moments: The order of the Taylor approximation cannot be 0!')
end
if options_mom_.order > 2
fprintf('Dynare will use ''k_order_solver'' as the order>2\n');
options_mom_.k_order_solver = true;
end
if strcmp(mom_method,'SMM')
if options_mom_.mom.simulation_multiple < 1
fprintf('The simulation horizon is shorter than the data. Dynare resets the simulation_multiple to 7.\n')
options_mom_.mom.simulation_multiple = 7;
end
end
if strcmp(mom_method,'GMM')
% require pruning with GMM at higher order
if options_mom_.order > 1 && ~options_mom_.pruning
fprintf('GMM at higher order only works with pruning, so we set pruning option to 1.\n');
options_mom_.pruning = true;
end
if options_mom_.order > 3
error('method_of_moments: Perturbation orders higher than 3 are not implemented for GMM estimation, try using SMM!');
end
end
if strcmp(mom_method,'IRF_MATCHING') && do_bayesian_estimation
if isfield(options_mom_,'mh_tune_jscale') && options_mom_.mh_tune_jscale.status && (options_mom_.mh_tune_jscale.maxiter<options_mom_.mh_tune_jscale.stepsize)
warning('method_of_moments: You specified mh_tune_jscale, but the maximum number of iterations is smaller than the step size. No update will take place.')
end
if options_mom_.load_results_after_load_mh
if ~exist([options_mom_.dirname filesep 'method_of_moments' filesep M_.fname '_mom_results.mat'],'file')
fprintf('\nYou specified the ''load_results_after_load_mh'' option, but no ''%s_mom_results.mat'' file\n',M_.fname);
fprintf('was found in the folder %s%smethod_of_moments.\n',options_mom_.dirname,filesep);
fprintf('Results will be recomputed and option ''load_results_after_load_mh'' is reset to false.\n');
options_mom_.load_results_after_load_mh = false;
end
end
if options_mom_.mh_replic>0 && options_mom_.mh_nblck<1
error('method_of_moments: Bayesian MCMC estimation cannot be conducted with ''mh_nblocks''=0!')
end
end
if options_mom_.mom.analytic_jacobian && ~strcmp(mom_method,'GMM')
options_mom_.mom.analytic_jacobian = false;
fprintf('\n''analytic_jacobian'' option will be dismissed as it only works with GMM.\n');
end
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
if any(cellfun(@(x) isnumeric(x) && any(x == 13), options_mom_.optimizer_vec))
error('method_of_moments: lsqnonlin (mode_compute=13) is not yet supported for IRF matching!');
end
end

View File

@ -1,96 +0,0 @@
function display_comparison_moments_irfs(M_, options_mom_, data_moments, model_moments)
% display_comparison_moments_irfs(M_, options_mom_, data_moments, model_moments)
% -------------------------------------------------------------------------
% Displays and saves to disk the comparison of the data moments/IRFs and the model moments/IRFs
% -------------------------------------------------------------------------
% INPUTS
% M_: [structure] model information
% options_mom_: [structure] method of moments options
% data_moments: [vector] data moments
% model_moments: [vector] model moments
% -------------------------------------------------------------------------
% OUTPUT
% No output, just displays and saves to disk the comparison of the data moments and the model moments
% -------------------------------------------------------------------------
% This function is called by
% o mom.run
% -------------------------------------------------------------------------
% This function calls
% o dyn_latex_table
% o dyntable
% o cellofchararraymaxlength
% -------------------------------------------------------------------------
% Copyright © 2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
titl = upper('Comparison of matched data IRFs and model IRFs');
headers = {'IRF','Data','Model'};
idx = 1;
for jj = 1:size(M_.matched_irfs,1)
irf_varname = M_.matched_irfs{jj,1};
irf_shockname = M_.matched_irfs{jj,2};
% note that periods can span over multiple rows
IRF_PERIODS = [];
for kk = 1:size(M_.matched_irfs{jj,3},1)
irf_periods = M_.matched_irfs{jj,3}{kk,1};
IRF_PERIODS = [IRF_PERIODS; irf_periods(:)];
end
for hh = 1:length(IRF_PERIODS)
labels{idx,1} = sprintf('%s %s (%u)',irf_varname,irf_shockname,IRF_PERIODS(hh));
labels_TeX{idx,1} = sprintf('%s %s (%u)',M_.endo_names_tex{ismember(M_.endo_names,irf_varname)},M_.exo_names_tex{ismember(M_.exo_names,irf_shockname)},IRF_PERIODS(hh));
idx = idx+1;
end
end
else
titl = ['Comparison of matched data moments and model moments (',options_mom_.mom.mom_method,')'];
headers = {'Moment','Data','Model'};
for jm = 1:size(M_.matched_moments,1)
lables_tmp = 'E[';
lables_tmp_tex = 'E \left[ ';
for jvar = 1:length(M_.matched_moments{jm,1})
lables_tmp = [lables_tmp M_.endo_names{M_.matched_moments{jm,1}(jvar)}];
lables_tmp_tex = [lables_tmp_tex, '{', M_.endo_names_tex{M_.matched_moments{jm,1}(jvar)}, '}'];
if M_.matched_moments{jm,2}(jvar) ~= 0
lables_tmp = [lables_tmp, '(', num2str(M_.matched_moments{jm,2}(jvar)), ')'];
lables_tmp_tex = [lables_tmp_tex, '_{t', num2str(M_.matched_moments{jm,2}(jvar)), '}'];
else
lables_tmp_tex = [lables_tmp_tex, '_{t}'];
end
if M_.matched_moments{jm,3}(jvar) > 1
lables_tmp = [lables_tmp, '^', num2str(M_.matched_moments{jm,3}(jvar))];
lables_tmp_tex = [lables_tmp_tex, '^{', num2str(M_.matched_moments{jm,3}(jvar)) '}'];
end
if jvar == length(M_.matched_moments{jm,1})
lables_tmp = [lables_tmp, ']'];
lables_tmp_tex = [lables_tmp_tex, ' \right]'];
else
lables_tmp = [lables_tmp, '*'];
lables_tmp_tex = [lables_tmp_tex, ' \times '];
end
end
labels{jm,1} = lables_tmp;
labels_TeX{jm,1} = lables_tmp_tex;
end
end
data_mat = [data_moments model_moments];
dyntable(options_mom_, titl, headers, labels, data_mat, cellofchararraymaxlength(labels)+2, 10, 7);
if options_mom_.TeX
dyn_latex_table(M_, options_mom_, titl, ['comparison_moments_', options_mom_.mom.mom_method], headers, labels_TeX, data_mat, cellofchararraymaxlength(labels)+2, 10, 7);
end

View File

@ -1,130 +0,0 @@
function graph_comparison_irfs(matched_irfs,irf_model_varobs,varobs_id,irf_horizon,relative_irf,endo_names,endo_names_tex,exo_names,exo_names_tex,dname,fname,graph_format,TeX,nodisplay,figures_textwidth)
% graph_comparison_irfs(matched_irfs,irf_model_varobs,varobs_id,irf_horizon,relative_irf,endo_names,endo_names_tex,exo_names,exo_names_tex,dname,fname,graph_format,TeX,nodisplay,figures_textwidth)
% -------------------------------------------------------------------------
% Plots and saves to disk the comparison of the selected data IRFs and corresponding model IRfs
% -------------------------------------------------------------------------
% INPUTS
% matched_irfs: [matrix] information on matched data IRFs
% irf_model_varobs: [matrix] model IRFs for observable variables
% varobs_id: [vector] index for observable variables in endo_names
% irf_horizon: [scalar] maximum horizon of IRFs
% relative_irf: [boolean] if true, plots normalized IRFs
% endo_names: [cell] names of endogenous variables
% endo_names_tex: [cell] names of endogenous variables in latex
% exo_names: [cell] names of exogenous variables
% exo_names_tex: [cell] names of exogenous variables in latex
% dname: [string] name of the directory where to save the graphs
% fname: [string] name of the mod file
% graph_format: [cell] format of the graphs
% TeX: [boolean] if true, uses latex for plots
% nodisplay: [boolean] if true, does not display the graphs
% figures_textwidth: [scalar] textwidth used in plots
% -------------------------------------------------------------------------
% OUTPUT
% No output, just displays and saves to disk the graphs
% -------------------------------------------------------------------------
% This function is called by
% o mom.run
% -------------------------------------------------------------------------
% This function calls
% o dyn_figure
% o dyn_saveas
% o remove_fractional_xticks
% o CheckPath
% o pltorg
% -------------------------------------------------------------------------
% Copyright © 2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
graph_directory_name = CheckPath('graphs',dname);
latex_directory_name = CheckPath('latex',dname);
if TeX && any(strcmp('eps',cellstr(graph_format)))
fid_TeX = fopen([latex_directory_name '/' fname '_irf_matching_plot.tex'],'w');
fprintf(fid_TeX,'%% TeX eps-loader file generated by mom.run.m (Dynare).\n');
fprintf(fid_TeX,['%% ' datestr(now,0) '\n']);
fprintf(fid_TeX,' \n');
end
unique_shock_entries = unique(matched_irfs(:, 2));
colDarkGrey = [0.3, 0.3, 0.3]; % dark grey
for jexo = unique_shock_entries' % loop over cell with shock names
unique_variables = unique(matched_irfs(ismember(matched_irfs(:, 2),jexo), 1));
[nbplt,nr,nc,lr,lc,nstar] = pltorg(length(unique_variables));
fig = 0;
for jvar = 1:length(unique_variables)
% get data points, note that periods and values can span over multiple rows
jj = ismember(matched_irfs(:,1), unique_variables(jvar)) & ismember(matched_irfs(:,2), jexo);
IRF_PERIODS = []; IRF_VALUES = [];
for kk = 1:size(matched_irfs{jj,3},1)
irf_periods = matched_irfs{jj,3}{kk,1};
irf_values = matched_irfs{jj,3}{kk,2};
if length(irf_values)==1
irf_values = repmat(irf_values,length(irf_periods),1);
end
IRF_PERIODS = [IRF_PERIODS; irf_periods(:)];
IRF_VALUES = [IRF_VALUES; irf_values(:)];
end
if jvar==1 || ~( (fig-1)*nstar<jvar && jvar<=fig*nstar )
fig = fig+1;
fig_irf = dyn_figure(nodisplay,'Name',['IRF matching shock to ' jexo{:} ' figure ' int2str(fig)]);
end
plt = jvar-(fig-1)*nstar;
if nbplt>1 && fig==nbplt
subplot(lr,lc,plt);
else
subplot(nr,nc,plt);
end
plt_data = plot(IRF_PERIODS,IRF_VALUES,'h', 'MarkerEdgeColor',colDarkGrey,'MarkerFaceColor',colDarkGrey,'MarkerSize',8);
hold on
plt_model = plot(1:irf_horizon, irf_model_varobs(:,varobs_id==find(ismember(endo_names,unique_variables(jvar))) , ismember(exo_names,jexo)),'-k','linewidth',2);
hold on
plot([1 irf_horizon],[0 0],'-r','linewidth',1);
hold off
xlim([1 irf_horizon]);
remove_fractional_xticks
if TeX
title(['$' endo_names_tex{ismember(endo_names,unique_variables(jvar))} '$'],'Interpreter','latex');
else
title(unique_variables{jvar},'Interpreter','none');
end
set(gca,'FontSize',12);
if (plt==nstar) || jvar==length(unique_variables)
% Adding a legend at the bottom
axes('Position',[0, 0, 1, 1],'Visible','off');
lgd = legend([plt_data,plt_model],{'Data', 'Model'}, 'Location', 'southeast','NumColumns',2,'FontSize',14);
if ~isoctave
lgd.Position = [0.37 0.01 lgd.Position(3) lgd.Position(4)];
end
dyn_saveas(fig_irf,[graph_directory_name filesep fname '_matched_irf_' jexo{:} int2str(fig)],nodisplay,graph_format);
if TeX && any(strcmp('eps',cellstr(graph_format)))
fprintf(fid_TeX,'\\begin{figure}[H]\n');
fprintf(fid_TeX,'\\centering \n');
fprintf(fid_TeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_matched_irf_%s%s}\n',figures_textwidth*min(plt/nc,1),[graph_directory_name '/' fname],jexo{:},int2str(fig));
if relative_irf
fprintf(fid_TeX,'\\caption{Relative impulse response functions (orthogonalized shock to $%s$).}', jexo{:});
else
fprintf(fid_TeX,'\\caption{Impulse response functions (orthogonalized shock to $%s$).}', jexo{:});
end
fprintf(fid_TeX,'\\label{Fig:MatchedIRF:%s:%s}\n', jexo{:},int2str(fig));
fprintf(fid_TeX,'\\end{figure}\n');
fprintf(fid_TeX,' \n');
end
end
end
end

View File

@ -1,151 +0,0 @@
function [data_irfs, weight_mat, irf_index, max_irf_horizon] = matched_irfs_blocks(matched_irfs, matched_irfs_weight, varobs_id, obs_nbr, exo_nbr, endo_names, exo_names)
% [data_irfs, weight_mat, irf_index, max_irf_horizon] = matched_irfs_blocks(matched_irfs, matched_irfs_weight, varobs_id, obs_nbr, exo_nbr, endo_names, exo_names)
% -------------------------------------------------------------------------
% Checks and transforms matched_irfs and matched_irfs_weight blocks
% for further use in the estimation.
% -------------------------------------------------------------------------
% INPUTS
% matched_irfs: [cell array] original matched_irfs block
% matched_irfs_weight: [cell array] original matched_irfs_weight block
% varobs_id: [vector] index for observable variables in endo_names
% obs_nbr: [scalar] number of observable variables
% exo_nbr: [scalar] number of exogenous variables
% endo_names: [cell array] names of endogenous variables
% exo_names: [cell array] names of exogenous variables
% -------------------------------------------------------------------------
% OUTPUT
% data_irfs: [matrix] IRFs for VAROBS as declared in matched_irfs block
% weight_mat: [matrix] weighting matrix for IRFs as declared in matched_irfs_weight block
% irf_index: [vector] index for selecting specific IRFs from full IRF matrix of observables
% max_irf_horizon: [scalar] maximum IRF horizon as declared in matched_irfs block
% -------------------------------------------------------------------------
% This function is called by
% o mom.run
% -------------------------------------------------------------------------
% Copyright © 2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
% note matched_irfs block:
% - each row in the cell contains a unique combination of var and varexo,
% however the third column in each row is a nested cell with information
% on periods, values and weights
% - periods, values and weights can span several rows with different lengths of entries
% - in some cases we need to duplicate values and/or weights
% - at the end we want to have everything vectorized and the same length
% get maximum IRF horizons
max_irf_horizon = [];
for jj = 1:size(matched_irfs,1)
max_irf_horizon = [max_irf_horizon; cell2mat(cellfun(@(c) c(:), matched_irfs{jj,3}(:,1), 'UniformOutput', false))];
end
max_irf_horizon = max(max_irf_horizon);
% create full matrix where 1st dimension are IRF periods, 2nd dimension are variables as declared in VAROBS, 3rd dimension are shocks
% idea: overwrite NaN values if they are declared in matched_irfs block; at the end the remaining NaN values will be removed
data_irfs = NaN(max_irf_horizon,obs_nbr,exo_nbr);
% create full empirical weighting matrix, identity matrix by default, i.e. all IRFs are equally important
% idea: first specify full matrix and then reduce it using only entries that are declared in matched_irfs block
weight_mat = speye(max_irf_horizon*obs_nbr*exo_nbr);
for jj = 1:size(matched_irfs,1)
id_var = find(ismember(endo_names,matched_irfs{jj,1}));
id_varobs = find(varobs_id==id_var,1);
id_shock = find(ismember(exo_names,matched_irfs{jj,2}));
if isempty(id_varobs)
skipline;
error('method_of_moments: You specified an IRF matching involving variable %s, but it is not declared as a varobs!',endo_names{id_var})
end
IRF_PERIODS = []; IRF_VALUES = []; IRF_WEIGHTS = [];
for kk = 1:size(matched_irfs{jj,3},1)
irf_periods = matched_irfs{jj,3}{kk,1};
if length(unique(irf_periods)) < length(irf_periods) % row-specific check for unique periods
error('method_of_moments: You specified an IRF matching involving variable %s and shock %s, but there were duplicate ''periods'' in the specification!',endo_names{id_var},exo_names{id_shock});
end
irf_values = matched_irfs{jj,3}{kk,2};
if length(irf_values)==1
irf_values = repmat(irf_values,length(irf_periods),1);
end
if length(irf_periods) ~= length(irf_values) % row-specific check for enough values
error('method_of_moments: You specified an IRF matching involving variable %s and shock %s, but the length of ''periods'' does not match the length of ''values''!',endo_names{id_var},exo_names{id_shock});
end
irf_weights = matched_irfs{jj,3}{kk,3};
if length(irf_weights)==1
irf_weights = repmat(irf_weights,length(irf_periods),1);
end
if length(irf_periods) ~= length(irf_weights) % row-specific check for enough weights
error('method_of_moments: You specified an IRF matching involving variable %s and shock %s, but the length of ''periods'' does not match the length of ''weights''!',endo_names{id_var},exo_names{id_shock});
end
IRF_PERIODS = [IRF_PERIODS; irf_periods(:)];
IRF_VALUES = [IRF_VALUES; irf_values(:)];
IRF_WEIGHTS = [IRF_WEIGHTS; irf_weights(:)];
end
if length(unique(irf_periods)) < length(irf_periods) % overall check for unique periods
error('method_of_moments: You specified an IRF matching involving variable %s and shock %s, but there were duplicate ''periods'' in the specification!',endo_names{id_var},exo_names{id_shock});
end
for hh = 1:length(IRF_PERIODS)
data_irfs(IRF_PERIODS(hh),id_varobs,id_shock) = IRF_VALUES(hh);
if IRF_WEIGHTS(hh) ~= 1
idweight_mat = sub2ind(size(data_irfs),IRF_PERIODS(hh),id_varobs,id_shock);
weight_mat(idweight_mat,idweight_mat) = IRF_WEIGHTS(hh);
end
end
end
% fine-tune weighting matrix using matched_irfs_weights
for jj = 1:size(matched_irfs_weight,1)
id_var1 = find(ismember(endo_names,matched_irfs_weight{jj,1}));
id_var2 = find(ismember(endo_names,matched_irfs_weight{jj,4}));
id_varobs1 = find(varobs_id==id_var1,1);
id_varobs2 = find(varobs_id==id_var2,1);
if isempty(id_varobs1)
skipline;
error('method_of_moments: You specified a weight for an IRF matching involving variable %s, but it is not a varobs!',endo_names{id_var1})
end
if isempty(id_varobs2)
skipline;
error('method_of_moments: You specified a weight for an IRF matching involving variable %s, but it is not a varobs!',endo_names{id_var2})
end
id_shock1 = find(ismember(exo_names,matched_irfs_weight{jj,3}));
id_shock2 = find(ismember(exo_names,matched_irfs_weight{jj,6}));
irf_periods1 = matched_irfs_weight{jj,2};
irf_periods2 = matched_irfs_weight{jj,5};
if length(irf_periods1) ~= length(irf_periods2)
error('method_of_moments: You specified a ''matched_irfs_weights'' entry for an IRF matching involving %s/%s and %s/%s,\n but the horizons do not have the same length!',endo_names{id_var1},exo_names{id_shock1},endo_names{id_var2},exo_names{id_shock2});
end
if max([irf_periods1(:);irf_periods2(:)]) > max_irf_horizon
error('method_of_moments: You specified a ''matched_irfs_weights'' entry for an IRF matching involving %s/%s and %s/%s,\n but the horizon is larger than the maximum one declared in the ''matched_irfs'' block!',endo_names{id_var1},exo_names{id_shock1},endo_names{id_var2},exo_names{id_shock2});
end
weight_mat_values = matched_irfs_weight{jj,7};
if length(weight_mat_values)==1 && length(irf_periods1)>1
weight_mat_values = repmat(weight_mat_values,length(irf_periods1),1);
end
if length(weight_mat_values) ~= length(irf_periods1)
error('method_of_moments: You specified a ''matched_irfs_weights'' entry for an IRF matching involving %s/%s and %s/%s,\n but the horizons do not match the length of ''weights''!',endo_names{id_var1},exo_names{id_shock1},endo_names{id_var2},exo_names{id_shock2});
end
for hh = 1:length(irf_periods1)
idweight_mat1 = sub2ind(size(data_irfs),irf_periods1(hh),id_varobs1,id_shock1);
idweight_mat2 = sub2ind(size(data_irfs),irf_periods2(hh),id_varobs2,id_shock2);
weight_mat(idweight_mat1,idweight_mat2) = weight_mat_values(hh);
weight_mat(idweight_mat2,idweight_mat1) = weight_mat_values(hh); % symmetry
end
end
% remove non-specified IRFs
irf_index = find(~isnan(data_irfs));
data_irfs = data_irfs(irf_index);
weight_mat = weight_mat(irf_index,irf_index);

View File

@ -1,81 +0,0 @@
function matched_moments = matched_moments_block(matched_moments, mom_method)
% matched_moments = matched_moments_block(matched_moments, mom_method)
% -------------------------------------------------------------------------
% Checks and transforms matched_moments block for further use in the estimation
% -------------------------------------------------------------------------
% INPUTS
% matched_moments: [cell array] original matched_moments block
% mom_method: [string] method of moments method (GMM or SMM)
% -------------------------------------------------------------------------
% OUTPUT
% matched_moments: [cell array] transformed matched_moments block
% -------------------------------------------------------------------------
% This function is called by
% o mom.run
% -------------------------------------------------------------------------
% Copyright © 2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
matched_moments_orig = matched_moments;
% higher-order product moments not supported yet for GMM
if strcmp(mom_method, 'GMM') && any(cellfun(@sum,matched_moments(:,3))> 2)
error('method_of_moments: GMM does not yet support product moments higher than 2. Change your ''matched_moments'' block!');
end
% check for duplicate moment conditions
for jm = 1:size(matched_moments,1)
% expand powers to vector of ones
if any(matched_moments{jm,3}>1)
tmp1=[]; tmp2=[]; tmp3=[];
for jjm=1:length(matched_moments{jm,3})
tmp1 = [tmp1 repmat(matched_moments{jm,1}(jjm),[1 matched_moments{jm,3}(jjm)]) ];
tmp2 = [tmp2 repmat(matched_moments{jm,2}(jjm),[1 matched_moments{jm,3}(jjm)]) ];
tmp3 = [tmp3 repmat(1,[1 matched_moments{jm,3}(jjm)]) ];
end
matched_moments{jm,1} = tmp1;
matched_moments{jm,2} = tmp2;
matched_moments{jm,3} = tmp3;
end
% shift time structure to focus only on lags
matched_moments{jm,2} = matched_moments{jm,2} - max(matched_moments{jm,2});
% sort such that t=0 variable comes first
[matched_moments{jm,2},idx_sort] = sort(matched_moments{jm,2},'descend');
matched_moments{jm,1} = matched_moments{jm,1}(idx_sort);
matched_moments{jm,3} = matched_moments{jm,3}(idx_sort);
end
% find duplicate rows in cell array by making groups according to powers as we can then use cell2mat for the unique function
powers = cellfun(@sum,matched_moments(:,3))';
unique_mom_idx = [];
for jpow = unique(powers)
idx1 = find(powers==jpow);
[~,idx2] = unique(cell2mat(matched_moments(idx1,:)),'rows');
unique_mom_idx = [unique_mom_idx idx1(idx2)];
end
% remove duplicate elements
duplicate_moms = setdiff(1:size(matched_moments_orig,1),unique_mom_idx);
if ~isempty(duplicate_moms)
fprintf('Duplicate declared moments found and removed in ''matched_moments'' block in rows:\n %s.\n',num2str(duplicate_moms));
fprintf('Dynare will continue with remaining moment conditions\n');
end
if strcmp(mom_method, 'SMM')
% for SMM: keep the original structure, but get rid of duplicate moments
matched_moments = matched_moments_orig(sort(unique_mom_idx),:);
elseif strcmp(mom_method, 'GMM')
% for GMM we use the transformed matched_moments structure
matched_moments = matched_moments(sort(unique_mom_idx),:);
end

View File

@ -1,141 +0,0 @@
function [xparam1, weighting_info, mom_verbose] = mode_compute_gmm_smm(xparam0, objective_function, m_data, data_moments, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
% [xparam1, weighting_info, mom_verbose] = mode_compute_gmm_smm(xparam0, objective_function, m_data, data_moments, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
% -------------------------------------------------------------------------
% Iterated method of moments for GMM and SMM, computes the minimum of the
% objective function (distance between data moments and model moments)
% for a sequence of optimizers and GMM/SMM iterations with different
% weighting matrices.
% -------------------------------------------------------------------------
% INPUTS
% xparam0: [vector] vector of initialized parameters
% objective_function: [func handle] name of the objective function
% m_data: [matrix] selected data moments at each point in time
% data_moments: [vector] vector of data moments
% options_mom_: [structure] options
% M_: [structure] model information
% estim_params_: [structure] information on estimated parameters
% bayestopt_: [structure] information on priors
% BoundsInfo: [structure] bounds for optimization
% dr: [structure] reduced form model
% endo_steady_state: [vector] steady state for endogenous variables (initval)
% exo_steady_state: [vector] steady state for exogenous variables (initval)
% exo_det_steady_state: [vector] steady state for exogenous deterministic variables (initval)
% -------------------------------------------------------------------------
% OUTPUT
% xparam1: [vector] mode of objective function
% weighting_info: [structure] information on weighting matrix
% mom_verbose: [structure] information on intermediate estimation results
% -------------------------------------------------------------------------
% This function is called by
% o mom.run
% -------------------------------------------------------------------------
% This function calls
% o mom.optimal_weighting_matrix
% o mom.display_estimation_results_table
% o dynare_minimize_objective
% o mom.objective_function
% o prior_dist_names
% -------------------------------------------------------------------------
% Copyright © 2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
mom_verbose = [];
if size(options_mom_.mom.weighting_matrix,1)>1 && ~(any(strcmpi('diagonal',options_mom_.mom.weighting_matrix)) || any(strcmpi('optimal',options_mom_.mom.weighting_matrix)))
fprintf('\nYou did not specify the use of an optimal or diagonal weighting matrix. There is no point in running an iterated method of moments.\n');
end
for stage_iter = 1:size(options_mom_.mom.weighting_matrix,1)
fprintf('Estimation stage %u\n',stage_iter);
weighting_info.Woptflag = false;
switch lower(options_mom_.mom.weighting_matrix{stage_iter})
case 'identity_matrix'
fprintf(' - identity weighting matrix\n');
weighting_matrix = eye(options_mom_.mom.mom_nbr);
case 'diagonal'
fprintf(' - diagonal of optimal weighting matrix (Bartlett kernel with %d lags)\n', options_mom_.mom.bartlett_kernel_lag);
if stage_iter == 1
fprintf(' and using data-moments as initial estimate of model-moments\n');
weighting_matrix = diag(diag( mom.optimal_weighting_matrix(m_data, data_moments, options_mom_.mom.bartlett_kernel_lag) ));
else
fprintf(' and using previous stage estimate of model-moments\n');
weighting_matrix = diag(diag( mom.optimal_weighting_matrix(m_data, model_moments, options_mom_.mom.bartlett_kernel_lag) ));
end
case 'optimal'
fprintf(' - optimal weighting matrix (Bartlett kernel with %d lags)\n', options_mom_.mom.bartlett_kernel_lag);
if stage_iter == 1
fprintf(' and using data-moments as initial estimate of model-moments\n');
weighting_matrix = mom.optimal_weighting_matrix(m_data, data_moments, options_mom_.mom.bartlett_kernel_lag);
else
fprintf(' and using previous stage estimate of model-moments\n');
weighting_matrix = mom.optimal_weighting_matrix(m_data, model_moments, options_mom_.mom.bartlett_kernel_lag);
weighting_info.Woptflag = true;
end
otherwise % user specified matrix in file
fprintf(' - user-specified weighting matrix\n');
try
load(options_mom_.mom.weighting_matrix{stage_iter},'weighting_matrix')
catch
error(['method_of_moments: No matrix named ''weighting_matrix'' could be found in ',options_mom_.mom.weighting_matrix{stage_iter},'.mat !']);
end
[nrow, ncol] = size(weighting_matrix);
if ~isequal(nrow,ncol) || ~isequal(nrow,length(data_moments)) %check if square and right size
error(['method_of_moments: ''weighting_matrix'' must be square and have ',num2str(length(data_moments)),' rows and columns!']);
end
end
try % check for positive definiteness of weighting_matrix
weighting_info.Sw = chol(weighting_matrix);
catch
error('method_of_moments: Specified ''weighting_matrix'' is not positive definite. Check whether your model implies stochastic singularity!');
end
for optim_iter = 1:length(options_mom_.optimizer_vec)
options_mom_.current_optimizer = options_mom_.optimizer_vec{optim_iter};
if options_mom_.optimizer_vec{optim_iter} == 0
xparam1 = xparam0; % no minimization, evaluate objective at current values
fval = feval(objective_function, xparam1, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
else
if options_mom_.optimizer_vec{optim_iter} == 13
options_mom_.mom.vector_output = true;
else
options_mom_.mom.vector_output = false;
end
if strcmp(options_mom_.mom.mom_method,'GMM') && options_mom_.mom.analytic_jacobian && ismember(options_mom_.optimizer_vec{optim_iter},options_mom_.mom.analytic_jacobian_optimizers) %do this only for gradient-based optimizers
options_mom_.mom.compute_derivs = true;
else
options_mom_.mom.compute_derivs = false;
end
[xparam1, fval] = dynare_minimize_objective(objective_function, xparam0, options_mom_.optimizer_vec{optim_iter}, options_mom_, [BoundsInfo.lb BoundsInfo.ub], bayestopt_.name, bayestopt_, [],...
data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
if options_mom_.mom.vector_output
fval = fval'*fval;
end
end
fprintf('\nStage %d Iteration %d: Value of minimized moment distance objective function: %12.10f.\n',stage_iter,optim_iter,fval);
if options_mom_.mom.verbose
fprintf('\n''verbose'' option: ');
std_via_invhessian_xparam1_iter = NaN(size(xparam1));
tbl_title_iter = sprintf('FREQUENTIST %s (STAGE %d ITERATION %d) VERBOSE',options_mom_.mom.mom_method,stage_iter,optim_iter);
field_name_iter = sprintf('%s_stage_%d_iter_%d',lower(options_mom_.mom.mom_method),stage_iter,optim_iter);
mom_verbose.(field_name_iter) = display_estimation_results_table(xparam1,std_via_invhessian_xparam1_iter,M_,options_mom_,estim_params_,bayestopt_,[],prior_dist_names,tbl_title_iter,field_name_iter);
end
xparam0 = xparam1;
end
options_mom_.vector_output = false;
[~, ~, ~, ~, ~, ~, model_moments] = feval(objective_function, xparam1, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state); % get model_moments for iterated GMM/SMM to compute optimal weighting matrix
end

View File

@ -1,122 +0,0 @@
function [xparam1, hessian_xparam1, fval, mom_verbose] = mode_compute_irf_matching(xparam0, hessian_xparam0, objective_function, doBayesianEstimation, weighting_info, data_moments, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
% [xparam1, hessian_xparam1, fval, mom_verbose] = mode_compute_irf_matching(xparam0, hessian_xparam0, objective_function, doBayesianEstimation, weighting_info, data_moments, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
% -------------------------------------------------------------------------
% Computes the minimum of the objective function (distance between data IRFs
% and model IRFs) for a sequence of optimizers.
% Note that we call a "mode" the minimum of the objective function, i.e.
% the parameter vector that minimizes the distance between the IRFs
% computed from the model and the IRFs computed from the data.
% -------------------------------------------------------------------------
% INPUTS
% xparam0: [vector] initialized parameters
% hessian_xparam0: [matrix] initialized hessian at xparam0
% objective_function: [func handle] name of the objective function
% doBayesianEstimation: [logical] true if Bayesian estimation
% weighting_info: [structure] information on weighting matrix
% data_moments: [vector] data moments
% options_mom_: [structure] options
% M_: [structure] model information
% estim_params_: [structure] information on estimated parameters
% bayestopt_: [structure] information on priors
% BoundsInfo: [structure] bounds for optimization
% dr: [structure] information reduced-form model
% endo_steady_state: [vector] steady state of endogenous variables (initval)
% exo_steady_state: [vector] steady state of exogenous variables (initval)
% exo_det_steady_state: [vector] steady state of deterministic exogenous variables (initval)
% -------------------------------------------------------------------------
% OUTPUT
% xparam1: [vector] mode of objective function
% hessian_xparam1: [matrix] hessian at xparam1
% fval: [double] function value at mode
% mom_verbose: [structure] information on intermediate estimation results
% Also saves the computed mode and hessian to a file.
% -------------------------------------------------------------------------
% This function is called by
% o mom.run
% -------------------------------------------------------------------------
% This function calls
% o display_estimation_results_table
% o dynare_minimize_objective
% o hessian
% o mom.objective_function
% -------------------------------------------------------------------------
% Copyright © 2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
mom_verbose = [];
for optim_iter = 1:length(options_mom_.optimizer_vec)
options_mom_.current_optimizer = options_mom_.optimizer_vec{optim_iter};
if options_mom_.optimizer_vec{optim_iter}==0
% no minimization, evaluate objective at current values
xparam1 = xparam0;
hessian_xparam1 = hessian_xparam0;
fval = feval(objective_function, xparam1, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
else
[xparam1, fval, exitflag, hessian_xparam1, options_mom_, Scale, new_rat_hess_info] = dynare_minimize_objective(objective_function, xparam0, options_mom_.optimizer_vec{optim_iter}, options_mom_, [BoundsInfo.lb BoundsInfo.ub], bayestopt_.name, bayestopt_, hessian_xparam0,...
data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
end
fprintf('\nMode Compute Iteration %d: Value of minimized moment distance objective function: %12.10f.\n',optim_iter,fval);
if options_mom_.mom.verbose
fprintf('\n''verbose'' option: ');
if options_mom_.cova_compute
if options_mom_.optimizer_vec{optim_iter}==0
hessian_xparam1_iter = hessian_xparam1;
else
fprintf('computing Hessian');
hessian_xparam1_iter = hessian(objective_function, xparam1, options_mom_.gstep,...
data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
hessian_xparam1_iter = reshape(hessian_xparam1_iter, length(xparam1), length(xparam1));
end
hsd_iter = sqrt(diag(hessian_xparam1_iter));
invhessian_xparam1_iter = inv(hessian_xparam1_iter./(hsd_iter*hsd_iter'))./(hsd_iter*hsd_iter');
std_via_invhessian_xparam1_iter = sqrt(diag(invhessian_xparam1_iter));
else
std_via_invhessian_xparam1_iter = NaN(size(xparam1));
end
fprintf(' and displaying intermediate results.');
if doBayesianEstimation
tbl_title_iter = sprintf('BAYESIAN %s (OPTIM ITERATION %d) VERBOSE',strrep(options_mom_.mom.mom_method,'_',' '),optim_iter);
field_name_iter = sprintf('posterior_iter_%d',optim_iter);
else
tbl_title_iter = sprintf('FREQUENTIST %s (OPTIM ITERATION %d) VERBOSE',strrep(options_mom_.mom.mom_method,'_',' '),optim_iter);
field_name_iter = sprintf('iter_%d',optim_iter);
end
mom_verbose.(field_name_iter) = display_estimation_results_table(xparam1,std_via_invhessian_xparam1_iter,M_,options_mom_,estim_params_,bayestopt_,[],prior_dist_names,tbl_title_iter,field_name_iter);
end
xparam0 = xparam1;
hessian_xparam0 = hessian_xparam1;
end
if options_mom_.cova_compute
if options_mom_.mom.verbose
hessian_xparam1 = hessian_xparam1_iter;
else
fprintf('\nComputing Hessian at the mode.\n');
hessian_xparam1 = hessian(objective_function, xparam1, options_mom_.gstep,...
data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
hessian_xparam1 = reshape(hessian_xparam1, length(xparam1), length(xparam1));
end
end
parameter_names = bayestopt_.name;
if options_mom_.cova_compute || options_mom_.mode_compute==5 || options_mom_.mode_compute==6
hh = hessian_xparam1;
save([M_.dname filesep 'method_of_moments' filesep M_.fname '_mode.mat'],'xparam1','hh','parameter_names','fval');
else
save([M_.dname filesep 'method_of_moments' filesep M_.fname '_mode.mat'],'xparam1','parameter_names','fval');
end

View File

@ -1,53 +1,42 @@
function [fval, info, exit_flag, df, junk_hessian, Q, model_moments, model_moments_params_derivs, irf_model_varobs] = objective_function(xparam, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
% [fval, info, exit_flag, df, junk_hessian, Q, model_moments, model_moments_params_derivs, irf_model_varobs] = objective_function(xparam, data_moments, weighting_info, options_mom_, M_, estim_params_, bayestopt_, BoundsInfo, dr, endo_steady_state, exo_steady_state, exo_det_steady_state)
function [fval, info, exit_flag, df, junk1, oo_, M_, options_mom_] = objective_function(xparam1, Bounds, oo_, estim_params_, M_, options_mom_)
% [fval, info, exit_flag, df, junk1, oo_, M_, options_mom_] = objective_function(xparam1, Bounds, oo_, estim_params_, M_, options_mom_)
% -------------------------------------------------------------------------
% This function evaluates the objective function for method of moments estimation,
% i.e. distance between model and data moments/IRFs, possibly augmented with priors.
% -------------------------------------------------------------------------
% INPUTS (same ones as in dsge_likelihood.m and dsge_var_likelihood.m)
% - xparam: [vector] current value of estimated parameters as returned by set_prior()
% - data_moments: [vector] data with moments/IRFs to match (corresponds to dataset_ in likelihood-based estimation)
% - weighting_info: [structure] storing information on weighting matrices (corresponds to dataset_info in likelihood-based estimation)
% - options_mom_: [structure] information about all settings (specified by the user, preprocessor, and taken from global options_)
% - M_ [structure] model information
% - estim_params_: [structure] information from estimated_params block
% - bayestopt_: [structure] information on the prior distributions
% - BoundsInfo: [structure] parameter bounds
% - dr: [structure] reduced form model
% - endo_steady_state: [vector] steady state value for endogenous variables (initval)
% - exo_steady_state: [vector] steady state value for exogenous variables (initval)
% - exo_det_steady_state: [vector] steady state value for exogenous deterministic variables (initval)
% This function evaluates the objective function for GMM/SMM estimation
% =========================================================================
% INPUTS
% o xparam1: current value of estimated parameters as returned by set_prior()
% o Bounds: structure containing parameter bounds
% o oo_: structure for results
% o estim_params_: structure describing the estimated_parameters
% o M_ structure describing the model
% o options_mom_: structure information about all settings (specified by the user, preprocessor, and taken from global options_)
% -------------------------------------------------------------------------
% OUTPUTS
% - fval: [double] value of the quadratic form of the moment difference (except for lsqnonlin, where this is done implicitly)
% - info: [vector] information on error codes and penalties
% - exit_flag: [double] flag for exit status (0 if error, 1 if no error)
% - df: [matrix] analytical jacobian of the moment difference (wrt paramters), currently for GMM only
% - junk_hessian: [matrix] empty matrix required for optimizer interface (Hessian would typically go here)
% - Q: [double] value of the quadratic form of the moment difference
% - model_moments: [vector] model moments
% - model_moments_params_derivs: [matrix] analytical jacobian of the model moments wrt estimated parameters (currently for GMM only)
% - irf_model_varobs: [matrix] model IRFs for observable variables (used for plotting matched IRfs in mom.run)
% o fval: value of the quadratic form of the moment difference (except for lsqnonlin, where this is done implicitly)
% o info: vector storing error code and penalty
% o exit_flag: 0 if error, 1 if no error
% o df: analytical parameter Jacobian of the quadratic form of the moment difference (for GMM only)
% o junk1: empty matrix required for optimizer interface (Hessian would go here)
% o oo_: structure containing the results with the following updated fields:
% - mom.model_moments [numMom x 1] vector with model moments
% - mom.Q value of the quadratic form of the moment difference
% - mom.model_moments_params_derivs
% [numMom x numParams] Jacobian matrix of derivatives of model_moments with respect to estimated parameters
% (only for GMM with analytical derivatives)
% o M_: Matlab's structure describing the model
% o options_mom_: structure information about all settings (specified by the user, preprocessor, and taken from global options_)
% -------------------------------------------------------------------------
% This function is called by
% o mom.run
% o dynare_minimize_objective
% o mom.run.m
% o dynare_minimize_objective.m
% -------------------------------------------------------------------------
% This function calls
% o check_bounds_and_definiteness_estimation
% o get_lower_cholesky_covariance
% o get_perturbation_params_derivs
% o getIrfShocksIndx
% o irf
% o mom.get_data_moments
% o priordens
% o pruned_state_space_system
% o resol
% o set_all_parameters
% o simult_
% -------------------------------------------------------------------------
% Copyright © 2020-2023 Dynare Team
% o check_bounds_and_definiteness_estimation
% o pruned_state_space_system
% o resol
% o set_all_parameters
% =========================================================================
% Copyright © 2020-2021 Dynare Team
%
% This file is part of Dynare.
%
@ -63,311 +52,250 @@ function [fval, info, exit_flag, df, junk_hessian, Q, model_moments, model_momen
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
% -------------------------------------------------------------------------
% Author(s):
% o Willi Mutschler (willi@mutschler.eu)
% o Johannes Pfeifer (jpfeifer@uni-koeln.de)
% =========================================================================
%------------------------------------------------------------------------------
% Initialization of the returned variables and others...
% 0. Initialization of the returned variables and others...
%------------------------------------------------------------------------------
irf_model_varobs = [];
model_moments_params_derivs = [];
model_moments = [];
Q = [];
junk_hessian = [];
df = []; % required to be empty by e.g. newrat
if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_jacobian
if options_mom_.mom.vector_output == 1
if options_mom_.mom.penalized_estimator
df = NaN(options_mom_.mom.mom_nbr+length(xparam),length(xparam));
else
df = NaN(options_mom_.mom.mom_nbr,length(xparam));
end
if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_jacobian
if options_mom_.vector_output == 1
if options_mom_.mom.penalized_estimator
df = nan(size(oo_.mom.data_moments,1)+length(xparam1),length(xparam1));
else
df = NaN(length(xparam),1);
df = nan(size(oo_.mom.data_moments,1),length(xparam1));
end
else
df = nan(1,length(xparam1));
end
else
df=[]; %required to be empty by e.g. newrat
end
junk1 = [];
junk2 = [];
%--------------------------------------------------------------------------
% Get the structural parameters and define penalties
% 1. Get the structural parameters & define penalties
%--------------------------------------------------------------------------
% Ensure that xparam1 is a column vector; particleswarm.m requires this.
xparam = xparam(:);
M_ = set_all_parameters(xparam, estim_params_, M_);
[fval,info,exit_flag] = check_bounds_and_definiteness_estimation(xparam, M_, estim_params_, BoundsInfo);
xparam1 = xparam1(:);
M_ = set_all_parameters(xparam1, estim_params_, M_);
[fval,info,exit_flag]=check_bounds_and_definiteness_estimation(xparam1, M_, estim_params_, Bounds);
if info(1)
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
fval = ones(options_mom_.mom.mom_nbr,1)*options_mom_.huge_number;
if options_mom_.vector_output == 1 % lsqnonlin requires vector output
fval = ones(size(oo_.mom.data_moments,1),1)*options_mom_.huge_number;
end
return
end
%--------------------------------------------------------------------------
% 2. call resol to compute steady state and model solution
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
% Call resol to compute steady state and model solution
%--------------------------------------------------------------------------
% Compute linear approximation around the deterministic steady state
[dr, info, M_.params] = resol(0, M_, options_mom_, dr, endo_steady_state, exo_steady_state, exo_det_steady_state);
[dr, info, M_, oo_] = resol(0, M_, options_mom_, oo_);
% Return, with endogenous penalty when possible, if resol issues an error code
if info(1)
if info(1) == 3 || info(1) == 4 || info(1) == 5 || info(1)==6 ||info(1) == 19 ||...
info(1) == 20 || info(1) == 21 || info(1) == 23 || info(1) == 26 || ...
info(1) == 81 || info(1) == 84 || info(1) == 85 || info(1) == 86
% meaningful second entry of output that can be used
%meaningful second entry of output that can be used
fval = Inf;
info(4) = info(2);
exit_flag = 0;
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
fval = ones(options_mom_.mom.mom_nbr,1)*options_mom_.huge_number;
if options_mom_.vector_output == 1 % lsqnonlin requires vector output
fval = ones(size(oo_.mom.data_moments,1),1)*options_mom_.huge_number;
end
return
else
fval = Inf;
info(4) = 0.1;
exit_flag = 0;
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
fval = ones(options_mom_.mom.mom_nbr,1)*options_mom_.huge_number;
if options_mom_.vector_output == 1 % lsqnonlin requires vector output
fval = ones(size(oo_.mom.data_moments,1),1)*options_mom_.huge_number;
end
return
end
end
%--------------------------------------------------------------------------
% GMM: Set up pruned state-space system and compute model moments
%--------------------------------------------------------------------------
if strcmp(options_mom_.mom.mom_method,'GMM')
%--------------------------------------------------------------------------
% 3. Set up pruned state-space system and compute model moments
%--------------------------------------------------------------------------
if options_mom_.mom.compute_derivs && ( options_mom_.mom.analytic_standard_errors || options_mom_.mom.analytic_jacobian )
indpmodel = []; % initialize index for model parameters
indpmodel = []; %initialize index for model parameters
if ~isempty(estim_params_.param_vals)
indpmodel = estim_params_.param_vals(:,1); % values correspond to parameters declaration order, row number corresponds to order in estimated_params
indpmodel = estim_params_.param_vals(:,1); %values correspond to parameters declaration order, row number corresponds to order in estimated_params
end
indpstderr=[]; % initialize index for stderr parameters
indpstderr=[]; %initialize index for stderr parameters
if ~isempty(estim_params_.var_exo)
indpstderr = estim_params_.var_exo(:,1); % values correspond to varexo declaration order, row number corresponds to order in estimated_params
indpstderr = estim_params_.var_exo(:,1); %values correspond to varexo declaration order, row number corresponds to order in estimated_params
end
indpcorr=[]; % initialize matrix for corr paramters
indpcorr=[]; %initialize matrix for corr paramters
if ~isempty(estim_params_.corrx)
indpcorr = estim_params_.corrx(:,1:2); % values correspond to varexo declaration order, row number corresponds to order in estimated_params
indpcorr = estim_params_.corrx(:,1:2); %values correspond to varexo declaration order, row number corresponds to order in estimated_params
end
if estim_params_.nvn || estim_params_.ncn % nvn is number of stderr parameters and ncn is number of corr parameters of measurement innovations as declared in estimated_params
error('Analytic computation of standard errrors does not (yet) support measurement errors.\nInstead, define them explicitly as varexo and provide measurement equations in the model definition.\nAlternatively, use numerical standard errors.');
if estim_params_.nvn || estim_params_.ncn %nvn is number of stderr parameters and ncn is number of corr parameters of measurement innovations as declared in estimated_params
error('Analytic computation of standard errrors does not (yet) support measurement errors.\nInstead, define them explicitly as varexo and provide measurement equations in the model definition.\nAlternatively, use numerical standard errors.')
end
modparam_nbr = estim_params_.np; % number of model parameters as declared in estimated_params
stderrparam_nbr = estim_params_.nvx; % number of stderr parameters
corrparam_nbr = estim_params_.ncx; % number of corr parameters
totparam_nbr = stderrparam_nbr+corrparam_nbr+modparam_nbr;
dr.derivs = identification.get_perturbation_params_derivs(M_, options_mom_, estim_params_, dr, endo_steady_state, exo_steady_state, exo_det_steady_state, indpmodel, indpstderr, indpcorr, 0); %analytic derivatives of perturbation matrices
model_moments_params_derivs = NaN(options_mom_.mom.mom_nbr,totparam_nbr);
pruned_state_space = pruned_SS.pruned_state_space_system(M_, options_mom_, dr, options_mom_.mom.obs_var, options_mom_.ar, 0, 1);
dr.derivs = get_perturbation_params_derivs(M_, options_mom_, estim_params_, oo_, indpmodel, indpstderr, indpcorr, 0); %analytic derivatives of perturbation matrices
oo_.mom.model_moments_params_derivs = NaN(options_mom_.mom.mom_nbr,totparam_nbr);
pruned_state_space = pruned_state_space_system(M_, options_mom_, dr, oo_.dr.obs_var, options_mom_.ar, 0, 1);
else
pruned_state_space = pruned_SS.pruned_state_space_system(M_, options_mom_, dr, options_mom_.mom.obs_var, options_mom_.ar, 0, 0);
pruned_state_space = pruned_state_space_system(M_, options_mom_, dr, oo_.dr.obs_var, options_mom_.ar, 0, 0);
end
model_moments = NaN(options_mom_.mom.mom_nbr,1);
oo_.mom.model_moments = NaN(options_mom_.mom.mom_nbr,1);
for jm = 1:size(M_.matched_moments,1)
% First moments
if ~options_mom_.prefilter && (sum(M_.matched_moments{jm,3}) == 1)
idx1 = (options_mom_.mom.obs_var == find(dr.order_var==M_.matched_moments{jm,1}) );
model_moments(jm,1) = pruned_state_space.E_y(idx1);
idx1 = (oo_.dr.obs_var == find(oo_.dr.order_var==M_.matched_moments{jm,1}) );
oo_.mom.model_moments(jm,1) = pruned_state_space.E_y(idx1);
if options_mom_.mom.compute_derivs && ( options_mom_.mom.analytic_standard_errors || options_mom_.mom.analytic_jacobian )
model_moments_params_derivs(jm,:) = pruned_state_space.dE_y(idx1,:);
oo_.mom.model_moments_params_derivs(jm,:) = pruned_state_space.dE_y(idx1,:);
end
end
% second moments
% Second moments
if (sum(M_.matched_moments{jm,3}) == 2)
idx1 = (options_mom_.mom.obs_var == find(dr.order_var==M_.matched_moments{jm,1}(1)) );
idx2 = (options_mom_.mom.obs_var == find(dr.order_var==M_.matched_moments{jm,1}(2)) );
idx1 = (oo_.dr.obs_var == find(oo_.dr.order_var==M_.matched_moments{jm,1}(1)) );
idx2 = (oo_.dr.obs_var == find(oo_.dr.order_var==M_.matched_moments{jm,1}(2)) );
if nnz(M_.matched_moments{jm,2}) == 0
% covariance
% Covariance
if options_mom_.prefilter
model_moments(jm,1) = pruned_state_space.Var_y(idx1,idx2);
oo_.mom.model_moments(jm,1) = pruned_state_space.Var_y(idx1,idx2);
if options_mom_.mom.compute_derivs && ( options_mom_.mom.analytic_standard_errors || options_mom_.mom.analytic_jacobian )
model_moments_params_derivs(jm,:) = pruned_state_space.dVar_y(idx1,idx2,:);
oo_.mom.model_moments_params_derivs(jm,:) = pruned_state_space.dVar_y(idx1,idx2,:);
end
else
model_moments(jm,1) = pruned_state_space.Var_y(idx1,idx2) + pruned_state_space.E_y(idx1)*pruned_state_space.E_y(idx2)';
oo_.mom.model_moments(jm,1) = pruned_state_space.Var_y(idx1,idx2) + pruned_state_space.E_y(idx1)*pruned_state_space.E_y(idx2)';
if options_mom_.mom.compute_derivs && ( options_mom_.mom.analytic_standard_errors || options_mom_.mom.analytic_jacobian )
for jp=1:totparam_nbr
model_moments_params_derivs(jm,jp) = pruned_state_space.dVar_y(idx1,idx2,jp) + pruned_state_space.dE_y(idx1,jp)*pruned_state_space.E_y(idx2)' + pruned_state_space.E_y(idx1)*pruned_state_space.dE_y(idx2,jp)';
oo_.mom.model_moments_params_derivs(jm,jp) = pruned_state_space.dVar_y(idx1,idx2,jp) + pruned_state_space.dE_y(idx1,jp)*pruned_state_space.E_y(idx2)' + pruned_state_space.E_y(idx1)*pruned_state_space.dE_y(idx2,jp)';
end
end
end
else
% autocovariance
lag = -M_.matched_moments{jm,2}(2); %note that leads/lags in M_.matched_moments are transformed such that first entry is always 0 and the second is a lag
% Autocovariance
lag = -M_.matched_moments{jm,2}(2); %note that leads/lags in matched_moments are transformed such that first entry is always 0 and the second is a lag
if options_mom_.prefilter
model_moments(jm,1) = pruned_state_space.Var_yi(idx1,idx2,lag);
oo_.mom.model_moments(jm,1) = pruned_state_space.Var_yi(idx1,idx2,lag);
if options_mom_.mom.compute_derivs && ( options_mom_.mom.analytic_standard_errors || options_mom_.mom.analytic_jacobian )
model_moments_params_derivs(jm,:) = pruned_state_space.dVar_yi(idx1,idx2,lag,:);
oo_.mom.model_moments_params_derivs(jm,:) = pruned_state_space.dVar_yi(idx1,idx2,lag,:);
end
else
model_moments(jm,1) = pruned_state_space.Var_yi(idx1,idx2,lag) + pruned_state_space.E_y(idx1)*pruned_state_space.E_y(idx2)';
oo_.mom.model_moments(jm,1) = pruned_state_space.Var_yi(idx1,idx2,lag) + pruned_state_space.E_y(idx1)*pruned_state_space.E_y(idx2)';
if options_mom_.mom.compute_derivs && ( options_mom_.mom.analytic_standard_errors || options_mom_.mom.analytic_jacobian )
for jp=1:totparam_nbr
model_moments_params_derivs(jm,jp) = vec( pruned_state_space.dVar_yi(idx1,idx2,lag,jp) + pruned_state_space.dE_y(idx1,jp)*pruned_state_space.E_y(idx2)' + pruned_state_space.E_y(idx1)*pruned_state_space.dE_y(idx2,jp)');
oo_.mom.model_moments_params_derivs(jm,jp) = vec( pruned_state_space.dVar_yi(idx1,idx2,lag,jp) + pruned_state_space.dE_y(idx1,jp)*pruned_state_space.E_y(idx2)' + pruned_state_space.E_y(idx1)*pruned_state_space.dE_y(idx2,jp)');
end
end
end
end
end
end
end
%------------------------------------------------------------------------------
% SMM: Compute Moments of the model solution for Gaussian innovations
%------------------------------------------------------------------------------
if strcmp(options_mom_.mom.mom_method,'SMM')
elseif strcmp(options_mom_.mom.mom_method,'SMM')
%------------------------------------------------------------------------------
% 3. Compute Moments of the model solution for normal innovations
%------------------------------------------------------------------------------
% create shock series with correct covariance matrix from iid standard normal shocks
i_exo_var = setdiff(1:M_.exo_nbr, find(diag(M_.Sigma_e) == 0 )); % find singular entries in covariance
i_exo_var = setdiff(1:M_.exo_nbr, find(diag(M_.Sigma_e) == 0 )); %find singular entries in covariance
chol_S = chol(M_.Sigma_e(i_exo_var,i_exo_var));
scaled_shock_series = zeros(size(options_mom_.mom.shock_series)); % initialize
scaled_shock_series(:,i_exo_var) = options_mom_.mom.shock_series(:,i_exo_var)*chol_S; % set non-zero entries
scaled_shock_series = zeros(size(options_mom_.mom.shock_series)); %initialize
scaled_shock_series(:,i_exo_var) = options_mom_.mom.shock_series(:,i_exo_var)*chol_S; %set non-zero entries
% simulate series
y_sim = simult_(M_, options_mom_, dr.ys, dr, scaled_shock_series, options_mom_.order);
% provide meaningful penalty if data is NaN or Inf
% provide meaningful penalty if data is nan or inf
if any(any(isnan(y_sim))) || any(any(isinf(y_sim)))
if options_mom_.vector_output == 1 % lsqnonlin requires vector output
fval = Inf(size(oo_.mom.Sw,1),1);
else
fval = Inf;
end
info(1)=180;
info(4) = 0.1;
exit_flag = 0;
fval = Inf;
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
fval = ones(options_mom_.mom.mom_nbr,1)*options_mom_.huge_number;
if options_mom_.vector_output == 1 % lsqnonlin requires vector output
fval = ones(size(oo_.mom.data_moments,1),1)*options_mom_.huge_number;
end
return
end
% remove burn-in and focus on observables (note that y_sim is in declaration order)
y_sim = y_sim(dr.order_var(options_mom_.mom.obs_var) , end-options_mom_.mom.long+1:end)';
% Remove burn-in and focus on observables (note that y_sim is in declaration order)
y_sim = y_sim(oo_.dr.order_var(oo_.dr.obs_var) , end-options_mom_.mom.long+1:end)';
if ~all(diag(M_.H)==0)
i_ME = setdiff(1:size(M_.H,1),find(diag(M_.H) == 0)); % find ME with 0 variance
chol_S = chol(M_.H(i_ME,i_ME)); % decompose rest
shock_mat=zeros(size(options_mom_.mom.ME_shock_series)); % initialize
i_ME = setdiff([1:size(M_.H,1)],find(diag(M_.H) == 0)); % find ME with 0 variance
chol_S = chol(M_.H(i_ME,i_ME)); %decompose rest
shock_mat=zeros(size(options_mom_.mom.ME_shock_series)); %initialize
shock_mat(:,i_ME)=options_mom_.mom.ME_shock_series(:,i_ME)*chol_S;
y_sim = y_sim+shock_mat;
end
% remove mean if centered moments
% Remove mean if centered moments
if options_mom_.prefilter
y_sim = bsxfun(@minus, y_sim, mean(y_sim,1));
end
model_moments = mom.get_data_moments(y_sim, options_mom_.mom.obs_var, dr.inv_order_var, M_.matched_moments, options_mom_);
oo_.mom.model_moments = mom.data_moments(y_sim, oo_, M_.matched_moments, options_mom_);
end
%------------------------------------------------------------------------------
% IRF_MATCHING using STOCH_SIMUL: Compute IRFs given model solution and Cholesky
% decomposition on shock covariance matrix; this resembles the core codes in
% stoch_simul
%------------------------------------------------------------------------------
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING') && strcmp(options_mom_.mom.simulation_method,'STOCH_SIMUL')
cs = get_lower_cholesky_covariance(M_.Sigma_e,options_mom_.add_tiny_number_to_cholesky);
irf_shocks_indx = getIrfShocksIndx(M_, options_mom_);
model_irf = NaN(options_mom_.irf,M_.endo_nbr,M_.exo_nbr);
for i = irf_shocks_indx
if options_mom_.order>1 && options_mom_.relative_irf % normalize shock to 0.01 before IRF generation for GIRFs; multiply with 100 later
y_irf = irf(M_, options_mom_, dr, cs(:,i)./cs(i,i)/100, options_mom_.irf, options_mom_.drop, options_mom_.replic, options_mom_.order);
else % for linear model, rescaling is done later
y_irf = irf(M_, options_mom_, dr, cs(:,i), options_mom_.irf, options_mom_.drop, options_mom_.replic, options_mom_.order);
end
if any(any(isnan(y_irf))) && ~options_mom_.pruning && ~(options_mom_.order==1)
info(1) = 181;
info(4) = 0.1;
fval = Inf;
exit_flag = 0;
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
fval = ones(options_mom_.mom.mom_nbr,1)*options_mom_.huge_number;
end
message = get_error_message(info,options_mom_);
fprintf('\n%s\n info = %d for shock %s.\n', message, info(1), M_.exo_names{i});
return
end
if options_mom_.relative_irf
if options_mom_.order==1 % multiply with 100 for backward compatibility
y_irf = 100*y_irf/cs(i,i);
end
end
model_irf(:,:,i) = transpose(y_irf);
%--------------------------------------------------------------------------
% 4. Compute quadratic target function
%--------------------------------------------------------------------------
moments_difference = oo_.mom.data_moments - oo_.mom.model_moments;
residuals = sqrt(options_mom_.mom.weighting_matrix_scaling_factor)*oo_.mom.Sw*moments_difference;
oo_.mom.Q = residuals'*residuals;
if options_mom_.vector_output == 1 % lsqnonlin requires vector output
fval = residuals;
if options_mom_.mom.penalized_estimator
fval=[fval;(xparam1-oo_.prior.mean)./sqrt(diag(oo_.prior.variance))];
end
% do transformations on model IRFs if irf_matching_file is provided
if ~isempty(options_mom_.mom.irf_matching_file.name)
[model_irf, check] = feval(str2func(options_mom_.mom.irf_matching_file.name), model_irf, M_, options_mom_, dr.ys);
if check
fval = Inf;
info(1) = 180;
info(4) = 0.1;
exit_flag = 0;
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
fval = ones(options_mom_.mom.mom_nbr,1)*options_mom_.huge_number;
end
return
end
else
fval = oo_.mom.Q;
if options_mom_.mom.penalized_estimator
fval=fval+(xparam1-oo_.prior.mean)'/oo_.prior.variance*(xparam1-oo_.prior.mean);
end
irf_model_varobs = model_irf(:,options_mom_.varobs_id,:); % focus only on observables (this will be used later for plotting)
model_moments = irf_model_varobs(options_mom_.mom.irfIndex); % focus only on selected IRF periods
end
%--------------------------------------------------------------------------
% Compute quadratic target function
%--------------------------------------------------------------------------
moments_difference = data_moments - model_moments;
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
Q = transpose(moments_difference)*weighting_info.W*moments_difference;
% log-likelihood
lnlik = options_mom_.mom.mom_nbr/2*log(1/2/pi) - 1/2*weighting_info.Winv_logdet - 1/2*Q;
if isinf(lnlik)
fval = Inf; info(1) = 50; info(4) = 0.1; exit_flag = 0;
return
if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_jacobian
if options_mom_.mom.penalized_estimator
dxparam1 = eye(length(xparam1));
end
if isnan(lnlik)
fval = Inf; info(1) = 45; info(4) = 0.1; exit_flag = 0;
return
end
if imag(lnlik)~=0
fval = Inf; info(1) = 46; info(4) = 0.1; exit_flag = 0;
return
end
% add log prior if necessary
lnprior = priordens(xparam,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
fval = - (lnlik + lnprior);
elseif strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
residuals = sqrt(options_mom_.mom.weighting_matrix_scaling_factor)*weighting_info.Sw*moments_difference;
Q = residuals'*residuals;
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
fval = residuals;
if options_mom_.mom.penalized_estimator
fval=[fval;(xparam-bayestopt_.p1)./bayestopt_.p2];
end
else
fval = Q;
if options_mom_.mom.penalized_estimator
fval=fval+(xparam-bayestopt_.p1)'/(diag(bayestopt_.p2.^2))*(xparam-bayestopt_.p1);
end
end
if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_jacobian
if options_mom_.mom.penalized_estimator
dxparam = eye(length(xparam));
end
for jp=1:length(xparam)
dmoments_difference = - model_moments_params_derivs(:,jp);
dresiduals = sqrt(options_mom_.mom.weighting_matrix_scaling_factor)*weighting_info.Sw*dmoments_difference;
if options_mom_.mom.vector_output == 1 % lsqnonlin requires vector output
if options_mom_.mom.penalized_estimator
df(:,jp)=[dresiduals;dxparam(:,jp)./bayestopt_.p2];
else
df(:,jp) = dresiduals;
end
for jp=1:length(xparam1)
dmoments_difference = - oo_.mom.model_moments_params_derivs(:,jp);
dresiduals = sqrt(options_mom_.mom.weighting_matrix_scaling_factor)*oo_.mom.Sw*dmoments_difference;
if options_mom_.vector_output == 1 % lsqnonlin requires vector output
if options_mom_.mom.penalized_estimator
df(:,jp)=[dresiduals;dxparam1(:,jp)./sqrt(diag(oo_.prior.variance))];
else
df(jp,1) = dresiduals'*residuals + residuals'*dresiduals;
if options_mom_.mom.penalized_estimator
df(jp,1)=df(jp,1)+(dxparam(:,jp))'/(diag(bayestopt_.p2.^2))*(xparam-bayestopt_.p1)+(xparam-bayestopt_.p1)'/(diag(bayestopt_.p2.^2))*(dxparam(:,jp));
end
df(:,jp) = dresiduals;
end
else
df(:,jp) = dresiduals'*residuals + residuals'*dresiduals;
if options_mom_.mom.penalized_estimator
df(:,jp)=df(:,jp)+(dxparam1(:,jp))'/oo_.prior.variance*(xparam1-oo_.prior.mean)+(xparam1-oo_.prior.mean)'/oo_.prior.variance*(dxparam1(:,jp));
end
end
end
end
end % main function end
end%main function end

View File

@ -2,10 +2,9 @@ function W_opt = optimal_weighting_matrix(m_data, moments, q_lag)
% W_opt = optimal_weighting_matrix(m_data, moments, q_lag)
% -------------------------------------------------------------------------
% This function computes the optimal weigthing matrix by a Bartlett kernel with maximum lag q_lag
% Adapted from replication codes of Andreasen, Fernández-Villaverde, Rubio-Ramírez (2018):
% "The Pruned State-Space System for Non-Linear DSGE Models: Theory and Empirical Applications",
% Review of Economic Studies, 85(1):1-49.
% -------------------------------------------------------------------------
% Adapted from replication codes of
% o Andreasen, Fernández-Villaverde, Rubio-Ramírez (2018): "The Pruned State-Space System for Non-Linear DSGE Models: Theory and Empirical Applications", Review of Economic Studies, 85(1):1-49.
% =========================================================================
% INPUTS
% o m_data [T x numMom] selected data moments at each point in time
% o moments [numMom x 1] selected estimated moments (either data_moments or estimated model_moments)
@ -18,10 +17,9 @@ function W_opt = optimal_weighting_matrix(m_data, moments, q_lag)
% o mom.run.m
% -------------------------------------------------------------------------
% This function calls:
% o corr_matrix (embedded)
% -------------------------------------------------------------------------
% Copyright © 2020-2023 Dynare Team
% o CorrMatrix (embedded)
% =========================================================================
% Copyright © 2020-2021 Dynare Team
%
% This file is part of Dynare.
%
@ -37,42 +35,46 @@ function W_opt = optimal_weighting_matrix(m_data, moments, q_lag)
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
% -------------------------------------------------------------------------
% Author(s):
% o Willi Mutschler (willi@mutschler.eu)
% o Johannes Pfeifer (jpfeifer@uni-koeln.de)
% =========================================================================
% initialize
[T,num_Mom] = size(m_data); % note that in m_data NaN values (due to leads or lags in matched_moments and missing data) were replaced by the mean
% Initialize
[T,num_Mom] = size(m_data); %note that in m_data NaN values (due to leads or lags in matched_moments and missing data) were replaced by the mean
% center around moments (could be either data_moments or model_moments)
h_func = m_data - repmat(moments',T,1);
h_Func = m_data - repmat(moments',T,1);
% the required correlation matrices
gamma_array = zeros(num_Mom,num_Mom,q_lag);
gamma0 = corr_matrix(h_func,T,num_Mom,0);
% The required correlation matrices
GAMA_array = zeros(num_Mom,num_Mom,q_lag);
GAMA0 = Corr_Matrix(h_Func,T,num_Mom,0);
if q_lag > 0
for ii=1:q_lag
gamma_array(:,:,ii) = corr_matrix(h_func,T,num_Mom,ii);
GAMA_array(:,:,ii) = Corr_Matrix(h_Func,T,num_Mom,ii);
end
end
% the estimate of S
S = gamma0;
% The estimate of S
S = GAMA0;
if q_lag > 0
for ii=1:q_lag
S = S + (1-ii/(q_lag+1))*(gamma_array(:,:,ii) + gamma_array(:,:,ii)');
S = S + (1-ii/(q_lag+1))*(GAMA_array(:,:,ii) + GAMA_array(:,:,ii)');
end
end
% the estimate of W
% The estimate of W
W_opt = S\eye(size(S,1));
W_opt = (W_opt+W_opt')/2; % ensure symmetry
end % main function end
W_opt=(W_opt+W_opt')/2; %assure symmetry
end
% The correlation matrix
function gamma_corr = corr_matrix(h_func,T,num_Mom,v)
gamma_corr = zeros(num_Mom,num_Mom);
function GAMA_corr = Corr_Matrix(h_Func,T,num_Mom,v)
GAMA_corr = zeros(num_Mom,num_Mom);
for t = 1+v:T
gamma_corr = gamma_corr + h_func(t-v,:)'*h_func(t,:);
GAMA_corr = GAMA_corr + h_Func(t-v,:)'*h_Func(t,:);
end
gamma_corr = gamma_corr/T;
end % corr_matrix end
GAMA_corr = GAMA_corr/T;
end

View File

@ -1,137 +0,0 @@
function print_info_on_estimation_settings(options_mom_, number_of_estimated_parameters, do_bayesian_estimation)
% print_info_on_estimation_settings(options_mom_, number_of_estimated_parameters, do_bayesian_estimation)
% -------------------------------------------------------------------------
% Print information on the method of moments estimation settings to the console
% -------------------------------------------------------------------------
% INPUTS
% options_mom_ [struct] options for the method of moments estimation
% number_of_estimated_parameters [integer] number of estimated parameters
% do_bayesian_estimation [boolean] true if the estimation is Bayesian
% -------------------------------------------------------------------------
% OUTPUT
% No output, just displays the chosen settings
% -------------------------------------------------------------------------
% This function is called by
% o mom.run
% -------------------------------------------------------------------------
% This function calls
% o skipline
% -------------------------------------------------------------------------
% Copyright © 2023 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare. If not, see <https://www.gnu.org/licenses/>.
fprintf('\n---------------------------------------------------\n')
if strcmp(options_mom_.mom.mom_method,'SMM')
fprintf('Simulated method of moments with');
elseif strcmp(options_mom_.mom.mom_method,'GMM')
fprintf('General method of moments with');
end
if strcmp(options_mom_.mom.mom_method,'SMM') || strcmp(options_mom_.mom.mom_method,'GMM')
if options_mom_.prefilter
fprintf('\n - centered moments (prefilter=1)');
else
fprintf('\n - uncentered moments (prefilter=0)');
end
if options_mom_.mom.penalized_estimator
fprintf('\n - penalized estimation using deviation from prior mean and weighted with prior precision');
end
end
if strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
if do_bayesian_estimation
fprintf('Bayesian Impulse Response Function Matching with');
else
fprintf('Frequentist Impulse Response Function Matching with');
end
if ~isempty(options_mom_.mom.irf_matching_file.name)
fprintf('\n - irf_matching_file: %s',[options_mom_.mom.irf_matching_file.path filesep options_mom_.mom.irf_matching_file.name '.m']);
end
end
for i = 1:length(options_mom_.optimizer_vec)
if i == 1
str = '- optimizer (mode_compute';
else
str = ' (additional_optimizer_steps';
end
switch options_mom_.optimizer_vec{i}
case 0
fprintf('\n %s=0): no minimization',str);
case 1
fprintf('\n %s=1): fmincon',str);
case 2
fprintf('\n %s=2): continuous simulated annealing',str);
case 3
fprintf('\n %s=3): fminunc',str);
case 4
fprintf('\n %s=4): csminwel',str);
case 5
fprintf('\n %s=5): newrat',str);
case 6
fprintf('\n %s=6): gmhmaxlik',str);
case 7
fprintf('\n %s=7): fminsearch',str);
case 8
fprintf('\n %s=8): Dynare Nelder-Mead simplex',str);
case 9
fprintf('\n %s=9): CMA-ES',str);
case 10
fprintf('\n %s=10): simpsa',str);
case 11
skipline;
error('method_of_moments: online_auxiliary_filter (mode_compute=11) is only supported with likelihood-based estimation techniques!');
case 12
fprintf('\n %s=12): particleswarm',str);
case 101
fprintf('\n %s=101): SolveOpt',str);
case 102
fprintf('\n %s=102): simulannealbnd',str);
case 13
fprintf('\n %s=13): lsqnonlin',str);
otherwise
if ischar(options_mom_.optimizer_vec{i})
fprintf('\n %s=%s): user-defined',str,options_mom_.optimizer_vec{i});
else
skipline;
error('method_of_moments: Unknown optimizer!');
end
end
if options_mom_.silent_optimizer
fprintf(' (silent)');
end
if strcmp(options_mom_.mom.mom_method,'GMM') && options_mom_.mom.analytic_jacobian && ismember(options_mom_.optimizer_vec{i},options_mom_.mom.analytic_jacobian_optimizers)
fprintf(' (using analytical Jacobian)');
end
end
if options_mom_.order > 0
fprintf('\n - stochastic simulations with perturbation order: %d', options_mom_.order)
end
if options_mom_.order > 1 && options_mom_.pruning
fprintf(' (with pruning)')
end
if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_method,'SMM')
if strcmp(options_mom_.mom.mom_method,'GMM') && options_mom_.mom.analytic_standard_errors
fprintf('\n - standard errors: analytic derivatives');
else
fprintf('\n - standard errors: numerical derivatives');
end
fprintf('\n - number of matched moments: %d', options_mom_.mom.mom_nbr);
elseif strcmp(options_mom_.mom.mom_method,'IRF_MATCHING')
fprintf('\n - number of matched IRFs: %d', options_mom_.mom.mom_nbr);
end
fprintf('\n - number of parameters: %d', number_of_estimated_parameters);
fprintf('\n\n');

File diff suppressed because it is too large Load Diff

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