diff --git a/configure.ac b/configure.ac index afed6de63..8d18442d2 100755 --- a/configure.ac +++ b/configure.ac @@ -1,6 +1,6 @@ dnl Process this file with autoconf to produce a configure script. -dnl Copyright (C) 2009-2016 Dynare Team +dnl Copyright (C) 2009-2017 Dynare Team dnl dnl This file is part of Dynare. dnl @@ -86,10 +86,6 @@ CPPFLAGS="$CPPFLAGS_SAVED" # Don't use deprecated hash structures AC_DEFINE([BOOST_NO_HASH], [], [Don't use deprecated STL hash structures]) -# Check for dlopen(), needed by tests for estimation DLL -AC_CHECK_LIB([dl], [dlopen], [LIBADD_DLOPEN="-ldl"], []) -AC_SUBST([LIBADD_DLOPEN]) - # Check for libmatio, needed by Dynare++ AX_MATIO AM_CONDITIONAL([HAVE_MATIO], [test "x$has_matio" = "xyes"]) @@ -175,7 +171,6 @@ AC_CONFIG_FILES([Makefile doc/Makefile doc/preprocessor/Makefile doc/macroprocessor/Makefile - doc/userguide/Makefile doc/parallel/Makefile doc/internals/Makefile doc/gsa/Makefile @@ -200,10 +195,6 @@ AC_CONFIG_FILES([Makefile dynare++/kord/Makefile dynare++/src/Makefile mex/sources/Makefile - mex/sources/estimation/Makefile - mex/sources/estimation/tests/Makefile - mex/sources/estimation/libmat/Makefile - mex/sources/estimation/libmat/tests/Makefile ]) AC_ARG_ENABLE([matlab], AS_HELP_STRING([--disable-matlab], [disable compilation of MEX files for MATLAB]), [], [enable_matlab=yes]) @@ -247,12 +238,6 @@ else BUILD_DYNAREPLUSPLUS_SRCDOC="no (missing one of: cweave, pdftex, eplain)" fi -if test "x$PDFLATEX" != "x" -a "x$BIBTEX" != "x"; then - BUILD_DYNARE_USERGUIDE="yes" -else - BUILD_DYNARE_USERGUIDE="no (missing one of: pdflatex, bibtex)" -fi - if test "x$PDFLATEX" != "x" -a "x$ax_latex_have_beamer" = "xyes"; then BUILD_BEAMER_DOC="yes" else @@ -313,7 +298,6 @@ Binaries (with "make"): PDF documentation (with "make pdf"): Dynare reference manual: $BUILD_DYNARE_PDF_MANUAL - Dynare user guide: $BUILD_DYNARE_USERGUIDE Dynare++ developer documentation: $BUILD_DYNAREPLUSPLUS_SRCDOC Beamer presentations: $BUILD_BEAMER_DOC Various other documents: $BUILD_OTHER_PDF_DOC diff --git a/doc/Makefile.am b/doc/Makefile.am index 99bd82d70..96bd93598 100644 --- a/doc/Makefile.am +++ b/doc/Makefile.am @@ -1,4 +1,4 @@ -SUBDIRS = preprocessor macroprocessor userguide parallel internals gsa dseries-and-reporting +SUBDIRS = preprocessor macroprocessor parallel internals gsa dseries-and-reporting info_TEXINFOS = dynare.texi diff --git a/doc/userguide/DynareBib.bib b/doc/userguide/DynareBib.bib deleted file mode 100644 index 4931fd007..000000000 --- a/doc/userguide/DynareBib.bib +++ /dev/null @@ -1,225 +0,0 @@ -%% This BibTeX bibliography file was created using BibDesk. -%% http://bibdesk.sourceforge.net/ - - -%% Created for Tommaso Mancini Griffoli at 2007-04-11 12:27:04 +0200 - - -%% Saved with string encoding Western (ASCII) - - - -@book{Zellner1971, - Address = {New York}, - Author = {Zellner, Arnold}, - Date-Added = {2007-04-09 15:21:11 +0200}, - Date-Modified = {2007-04-09 15:25:37 +0200}, - Publisher = {John Wiley \& Sons, Inc.}, - Title = {An Introduction to Bayesian Inference in Econometrics}, - Year = {1971}} - -@article{ClaridaGaliGertler1999, - Author = {Richard Clarida and Jordi Gali and Mark Gertler}, - Date-Added = {2007-04-07 12:26:52 +0200}, - Date-Modified = {2007-04-07 12:30:46 +0200}, - Journal = {Journal of Economic Literature}, - Pages = {1661-1707}, - Title = {The Science of Monetary Policy: A New Keynesian Perspective}, - Volume = {XXXVII}, - Year = {1999}} - -@article{Geweke1999, - Author = {John Geweke}, - Date-Added = {2007-02-27 11:20:59 +0100}, - Date-Modified = {2007-02-27 11:22:10 +0100}, - Journal = {Econometric Review}, - Number = {1}, - Pages = {1-126}, - Title = {Using Simulation Methods for Bayesian Econometric Models: In- ference, Development and Communication}, - Volume = {18}, - Year = {1999}} - -@book{DurbinKoopman2001, - Address = {Oxford, U.K.}, - Author = {J. Durbin and S.J. Koopman}, - Date-Added = {2007-02-25 22:51:56 +0100}, - Date-Modified = {2007-02-25 22:55:08 +0100}, - Publisher = {Oxford University Press}, - Title = {Time Series Analysis by State Space Methods}, - Year = {2001}} - -@article{CogleyNason1994, - Author = {Nason, James M and Cogley, Timothy}, - Date-Added = {2007-02-25 16:17:26 +0100}, - Date-Modified = {2007-02-25 16:17:53 +0100}, - Journal = {Journal of Applied Econometrics}, - Month = {Suppl. De}, - Number = {S}, - Pages = {S37-70}, - Title = {Testing the Implications of Long-Run Neutrality for Monetary Business Cycle Models}, - Volume = {9}, - Year = 1994} - -@book{Hamilton1994, - Address = {Princeton, NJ}, - Author = {James D. Hamilton}, - Date-Added = {2007-02-25 11:16:40 +0100}, - Date-Modified = {2007-02-25 11:18:17 +0100}, - Publisher = {Princeton University Press}, - Title = {Time Series Analysis}, - Year = {1994}} - -@techreport{LubikSchorfheide2005, - Author = {Thomas Lubik and Frank Schorfheide}, - Date-Added = {2007-02-25 10:19:43 +0100}, - Date-Modified = {2007-02-25 10:20:03 +0100}, - Institution = {The Johns Hopkins University,Department of Economics}, - Month = May, - Number = {521}, - Title = {A Bayesian Look at New Open Economy Macroeconomics}, - Type = {Economics Working Paper Archive}, - Year = 2005} - -@article{VillaverdeRubioRamirez2004, - Author = {Fernandez-Villaverde, Jesus and Rubio-Ramirez, Juan Francisco}, - Date-Added = {2007-02-24 22:19:57 +0100}, - Date-Modified = {2007-02-24 22:42:27 +0100}, - Journal = {Journal of Econometrics}, - Month = {November}, - Number = {1}, - Pages = {153-187}, - Title = {Comparing dynamic equilibrium models to data: a Bayesian approach}, - Volume = {123}, - Year = 2004} - -@article{RabanalRubioRamirez2005, - Author = {Rabanal, Pau and Rubio-Ramirez, Juan F.}, - Date-Added = {2007-02-24 22:19:17 +0100}, - Date-Modified = {2007-02-24 22:19:34 +0100}, - Journal = {Journal of Monetary Economics}, - Month = {September}, - Number = {6}, - Pages = {1151-1166}, - Title = {Comparing New Keynesian models of the business cycle: A Bayesian approach}, - Volume = {52}, - Year = 2005} - -@article{AnSchorfheide2006, - Author = {An, Sungbae and Schorfheide, Frank}, - Date-Added = {2007-02-24 22:16:05 +0100}, - Date-Modified = {2007-02-24 22:17:40 +0100}, - Journal = {Econometric Review}, - Title = {Bayesian Analysis of DSGE Models}, - Volume = {Forthcoming}, - Year = {2006}} - -@techreport{LubikSchorfheide2003, - Author = {Thomas Lubik and Frank Schorfheide}, - Date-Added = {2007-02-24 22:15:28 +0100}, - Date-Modified = {2007-02-24 22:15:43 +0100}, - Institution = {The Johns Hopkins University,Department of Economics}, - Month = Nov, - Number = {505}, - Title = {Do Central Banks Respond to Exchange Rate Movements? A Structural Investigation}, - Type = {Economics Working Paper Archive}, - Year = 2003} - -@article{Schorfheide2000, - Author = {Frank Schorfheide}, - Date-Added = {2007-02-24 22:00:46 +0100}, - Date-Modified = {2007-02-24 22:01:00 +0100}, - Journal = {Journal of Applied Econometrics}, - Number = {6}, - Pages = {645-670}, - Title = {Loss function-based evaluation of DSGE models}, - Volume = {15}, - Year = 2000} - -@article{Ireland2004, - Author = {Ireland, Peter N.}, - Date-Added = {2007-02-24 21:58:47 +0100}, - Date-Modified = {2007-02-24 21:59:01 +0100}, - Journal = {Journal of Economic Dynamics and Control}, - Month = {March}, - Number = {6}, - Pages = {1205-1226}, - Title = {A method for taking models to the data}, - Volume = {28}, - Year = 2004} - -@article{SmetsWouters2003, - Author = {Frank Smets and Raf Wouters}, - Date-Added = {2007-02-24 21:57:12 +0100}, - Date-Modified = {2007-02-24 21:57:32 +0100}, - Journal = {Journal of the European Economic Association}, - Month = {09}, - Number = {5}, - Pages = {1123-1175}, - Title = {An Estimated Dynamic Stochastic General Equilibrium Model of the Euro Area}, - Volume = {1}, - Year = 2003} - -@article{CollardJuillard2001b, - Author = {Collard, Fabrice and Juillard, Michel}, - Date-Added = {2007-02-18 19:21:56 +0100}, - Date-Modified = {2007-02-18 19:22:12 +0100}, - Journal = {Journal of Economic Dynamics and Control}, - Month = {June}, - Number = {6-7}, - Pages = {979-999}, - Title = {Accuracy of stochastic perturbation methods: The case of asset pricing models}, - Volume = {25}, - Year = 2001} - -@article{CollardJuillard2001a, - Author = {Collard, Fabrice and Juillard, Michel}, - Date-Added = {2007-02-18 19:21:03 +0100}, - Date-Modified = {2007-02-18 19:21:33 +0100}, - Journal = {Computational Economics}, - Month = {June}, - Number = {2-3}, - Pages = {125-39}, - Title = {A Higher-Order Taylor Expansion Approach to Simulation of Stochastic Forward-Looking Models with an Application to a Nonlinear Phillips Curve Model}, - Volume = {17}, - Year = 2001} - -@techreport{Juillard1996, - Author = {Juillard, Michel}, - Date-Added = {2007-02-18 18:37:46 +0100}, - Date-Modified = {2007-02-18 18:38:46 +0100}, - Institution = {CEPREMAP}, - Number = {9602}, - Title = {Dynare : a program for the resolution and simulation of dynamic models with forward variables through the use of a relaxation algorithm}, - Type = {CEPREMAP working papers}, - Year = {1996}} - -@unpublished{CollardJuillard2003, - Author = {Fabrice Collard and Michel Juillard}, - Date-Added = {2007-02-17 13:03:34 +0100}, - Date-Modified = {2007-02-18 19:45:10 +0100}, - Note = {CEPREMAP mimeo}, - Title = {Stochastic simulations with DYNARE. A practical guide.}, - Year = {2003}} - -@article{SchmittGrohe2004, - Author = {Schmitt-Grohe, Stephanie and Uribe, Martin}, - Date-Added = {2007-02-17 11:51:08 +0100}, - Date-Modified = {2007-02-17 12:20:24 +0100}, - Journal = {Journal of Economic Dynamics and Control}, - Month = {January}, - Number = {4}, - Pages = {755-775}, - Title = {Solving dynamic general equilibrium models using a second-order approximation to the policy function}, - Volume = {28}, - Year = 2004} - -@techreport{CollardJuillard1999, - Author = {Michel Juillard and Fabrice Collard}, - Date-Added = {2007-02-17 11:48:00 +0100}, - Date-Modified = {2007-02-17 13:07:56 +0100}, - Institution = {Society for Computational Economics}, - Month = Mar, - Number = {144}, - Title = {Stochastic Simulations of a Non-Linear Phillips Curve Model}, - Type = {Computing in Economics and Finance 1999}, - Year = 1999} diff --git a/doc/userguide/Graphics/DynareFigures.key/Contents/PkgInfo b/doc/userguide/Graphics/DynareFigures.key/Contents/PkgInfo deleted file mode 100644 index b0bc8e076..000000000 --- a/doc/userguide/Graphics/DynareFigures.key/Contents/PkgInfo +++ /dev/null @@ -1 +0,0 @@ -???????? \ No newline at end of file diff --git a/doc/userguide/Graphics/DynareFigures.key/QuickLook/Thumbnail.jpg b/doc/userguide/Graphics/DynareFigures.key/QuickLook/Thumbnail.jpg deleted file mode 100644 index 155249097..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/QuickLook/Thumbnail.jpg and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/droppedImage-1.pdf b/doc/userguide/Graphics/DynareFigures.key/droppedImage-1.pdf deleted file mode 100644 index b9576ee90..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/droppedImage-1.pdf and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/droppedImage-2.pdf b/doc/userguide/Graphics/DynareFigures.key/droppedImage-2.pdf deleted file mode 100644 index c1d7cb5e4..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/droppedImage-2.pdf and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/droppedImage.pdf b/doc/userguide/Graphics/DynareFigures.key/droppedImage.pdf deleted file mode 100644 index 1abfea8aa..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/droppedImage.pdf and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/index.apxl.gz b/doc/userguide/Graphics/DynareFigures.key/index.apxl.gz deleted file mode 100644 index ea9db953c..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/index.apxl.gz and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-0.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-0.tiff deleted file mode 100644 index fd92f2251..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-0.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-11.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-11.tiff deleted file mode 100644 index 52f7c29d3..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-11.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-12.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-12.tiff deleted file mode 100644 index fb026ccca..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-12.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-13.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-13.tiff deleted file mode 100644 index db3be7c08..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-13.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-14.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-14.tiff deleted file mode 100644 index 1db1a422d..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-14.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-15.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-15.tiff deleted file mode 100644 index 3731cda96..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-15.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-16.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-16.tiff deleted file mode 100644 index 5cad5a2fb..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-16.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-17.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-17.tiff deleted file mode 100644 index d243309c7..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-17.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-18.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-18.tiff deleted file mode 100644 index 6af4f8053..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-18.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-19.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-19.tiff deleted file mode 100644 index a505ebefd..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-19.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-20.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-20.tiff deleted file mode 100644 index af6704981..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-20.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-21.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-21.tiff deleted file mode 100644 index 335ca9dee..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-21.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-3.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-3.tiff deleted file mode 100644 index 77892995d..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-3.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-4.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-4.tiff deleted file mode 100644 index aa1427fad..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/mt0-4.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/st0.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/st0.tiff deleted file mode 100644 index e0556eb54..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/st0.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/st1.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/st1.tiff deleted file mode 100644 index 14d79ac74..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/st1.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/st2.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/st2.tiff deleted file mode 100644 index 32a5ea768..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/st2.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/st3.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/st3.tiff deleted file mode 100644 index 181201f41..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/st3.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/st4.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/st4.tiff deleted file mode 100644 index 8835507a6..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/st4.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareFigures.key/thumbs/st5.tiff b/doc/userguide/Graphics/DynareFigures.key/thumbs/st5.tiff deleted file mode 100644 index 95b1722e5..000000000 Binary files a/doc/userguide/Graphics/DynareFigures.key/thumbs/st5.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/Contents/PkgInfo b/doc/userguide/Graphics/DynareTitle.key/Contents/PkgInfo deleted file mode 100644 index b0bc8e076..000000000 --- a/doc/userguide/Graphics/DynareTitle.key/Contents/PkgInfo +++ /dev/null @@ -1 +0,0 @@ -???????? \ No newline at end of file diff --git a/doc/userguide/Graphics/DynareTitle.key/QuickLook/Thumbnail.jpg b/doc/userguide/Graphics/DynareTitle.key/QuickLook/Thumbnail.jpg deleted file mode 100644 index 8b9c696d3..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/QuickLook/Thumbnail.jpg and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/index.apxl.gz b/doc/userguide/Graphics/DynareTitle.key/index.apxl.gz deleted file mode 100644 index d15e8b38b..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/index.apxl.gz and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-0.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-0.tiff deleted file mode 100644 index c505ed680..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-0.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-12.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-12.tiff deleted file mode 100644 index d7994b2f4..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-12.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-13.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-13.tiff deleted file mode 100644 index b705926a0..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-13.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-14.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-14.tiff deleted file mode 100644 index 0ebd90b41..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-14.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-15.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-15.tiff deleted file mode 100644 index 9889227ea..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-15.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-16.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-16.tiff deleted file mode 100644 index e6b0035d0..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-16.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-17.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-17.tiff deleted file mode 100644 index 5b7867ecc..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-17.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-18.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-18.tiff deleted file mode 100644 index 25185808d..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-18.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-19.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-19.tiff deleted file mode 100644 index 1fc27922d..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-19.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-20.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-20.tiff deleted file mode 100644 index ec2d9a4ec..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-20.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-21.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-21.tiff deleted file mode 100644 index ec230af83..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-21.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-22.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-22.tiff deleted file mode 100644 index e562bd91b..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-22.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-23.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-23.tiff deleted file mode 100644 index b39d3b577..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-23.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-24.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-24.tiff deleted file mode 100644 index a5e70697e..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/mt0-24.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.key/thumbs/st0-1.tiff b/doc/userguide/Graphics/DynareTitle.key/thumbs/st0-1.tiff deleted file mode 100644 index 7f17eaa66..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.key/thumbs/st0-1.tiff and /dev/null differ diff --git a/doc/userguide/Graphics/DynareTitle.pdf b/doc/userguide/Graphics/DynareTitle.pdf deleted file mode 100644 index 7552413df..000000000 Binary files a/doc/userguide/Graphics/DynareTitle.pdf and /dev/null differ diff --git a/doc/userguide/Makefile.am b/doc/userguide/Makefile.am deleted file mode 100644 index 37e537776..000000000 --- a/doc/userguide/Makefile.am +++ /dev/null @@ -1,24 +0,0 @@ -if HAVE_PDFLATEX -if HAVE_BIBTEX -pdf-local: UserGuide.pdf -endif -endif - -SRC = UserGuide.tex Graphics/DynareTitle.pdf DynareBib.bib \ - ch-intro.tex ch-inst.tex ch-solbase.tex ch-soladv.tex ch-estbase.tex \ - ch-estadv.tex ch-solbeh.tex ch-estbeh.tex ch-ramsey.tex ch-trouble.tex \ - P_DynareStruct2.pdf P_flowest.pdf P_MH2.pdf P_ModStruct2.pdf P_ModStruct3.pdf \ - P_ModStruct4.pdf P_ModStruct5.pdf P_SchorfMod.pdf P_ShockModel2.pdf - -EXTRA_DIST = $(SRC) Graphics models - -UserGuide.pdf: $(SRC) - $(PDFLATEX) UserGuide - $(BIBTEX) UserGuide - $(PDFLATEX) UserGuide - $(PDFLATEX) UserGuide - $(PDFLATEX) UserGuide - -clean-local: - rm -f *.log *.aux *.toc *.lof *.blg *.bbl *.out - rm -f UserGuide.pdf diff --git a/doc/userguide/P_DynareStruct2.pdf b/doc/userguide/P_DynareStruct2.pdf deleted file mode 100644 index d70fa943f..000000000 Binary files a/doc/userguide/P_DynareStruct2.pdf and /dev/null differ diff --git a/doc/userguide/P_MH2.pdf b/doc/userguide/P_MH2.pdf deleted file mode 100644 index 4c9467f09..000000000 Binary files a/doc/userguide/P_MH2.pdf and /dev/null differ diff --git a/doc/userguide/P_ModStruct2.pdf b/doc/userguide/P_ModStruct2.pdf deleted file mode 100644 index 936d3010c..000000000 Binary files a/doc/userguide/P_ModStruct2.pdf and /dev/null differ diff --git a/doc/userguide/P_ModStruct3.pdf b/doc/userguide/P_ModStruct3.pdf deleted file mode 100644 index 2bc41285b..000000000 Binary files a/doc/userguide/P_ModStruct3.pdf and /dev/null differ diff --git a/doc/userguide/P_ModStruct4.pdf b/doc/userguide/P_ModStruct4.pdf deleted file mode 100644 index 68a745730..000000000 Binary files a/doc/userguide/P_ModStruct4.pdf and /dev/null differ diff --git a/doc/userguide/P_ModStruct5.pdf b/doc/userguide/P_ModStruct5.pdf deleted file mode 100644 index b5b7351ea..000000000 Binary files a/doc/userguide/P_ModStruct5.pdf and /dev/null differ diff --git a/doc/userguide/P_SchorfMod.pdf b/doc/userguide/P_SchorfMod.pdf deleted file mode 100644 index f71d50a7c..000000000 Binary files a/doc/userguide/P_SchorfMod.pdf and /dev/null differ diff --git a/doc/userguide/P_ShockModel2.pdf b/doc/userguide/P_ShockModel2.pdf deleted file mode 100644 index 1f68ecc4d..000000000 Binary files a/doc/userguide/P_ShockModel2.pdf and /dev/null differ diff --git a/doc/userguide/P_flowest.pdf b/doc/userguide/P_flowest.pdf deleted file mode 100644 index a78cf0a86..000000000 Binary files a/doc/userguide/P_flowest.pdf and /dev/null differ diff --git a/doc/userguide/UserGuide.tex b/doc/userguide/UserGuide.tex deleted file mode 100644 index 69253bf45..000000000 --- a/doc/userguide/UserGuide.tex +++ /dev/null @@ -1,119 +0,0 @@ -\documentclass[a4paper,11pt]{memoir} -\maxsecnumdepth{subsection} -\setsecnumdepth{subsection} -\maxtocdepth{subsection} -\settocdepth{subsection} -\usepackage{amsmath} -\usepackage{amsfonts} -\usepackage{amssymb} -\usepackage{rotating} -\usepackage{graphicx} -\usepackage[applemac]{inputenc} -\usepackage{amsbsy,enumerate} -\usepackage{natbib} -\usepackage{pdfpages} -%\usepackage{makeidx} -%\usepackage[pdftex]{hyperref} -%\usepackage{hyperref} -%\hypersetup{colorlinks=false} -\usepackage{hyperref} -\hypersetup{colorlinks,% -citecolor=green,% -filecolor=magenta,% -linkcolor=red,% -urlcolor=cyan,% -pdftex} - - -\newtheorem{definition}{Definition} [chapter] -\newtheorem{lemma}{Lemma} [chapter] -\newtheorem{property}{Property} [chapter] -\newtheorem{theorem}{Theorem} [chapter] -\newtheorem{remark}{Remark} [chapter] - -%\makeindex - -\begin{document} -\frontmatter - -\includepdf{Graphics/DynareTitle.pdf} - -\title{Dynare v4 - User Guide \\ÊPublic beta version} -\author{\\ \\ \\ \\ \\ \\ \\ \\ \\ \\ \\ Tommaso Mancini Griffoli\\ tommaso.mancini@stanfordalumni.org} -\date{This draft: January 2013} - -\maketitle - -\thispagestyle{empty} - -\newpage - -~\vfill - -Copyright © 2007-2013 Tommaso Mancini Griffoli - -\bigskip - -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. - -\bigskip - -A copy of the license can be found at: \url{http://www.gnu.org/licenses/fdl.txt} - -\vfill - -\newpage - -\tableofcontents -\listoffigures - -\chapter*{Work in Progress!} -This is the second version of the Dynare User Guide which is still work in progress! This means two things. First, please read this with a critical eye and send me comments! Are some areas unclear? Is anything plain wrong? Are some sections too wordy, are there enough examples, are these clear? On the contrary, are there certain parts that just click particularly well? How can others be improved? I'm very interested to get your feedback. \\ - -The second thing that a work in progress manuscript comes with is a few internal notes. These are mostly placeholders for future work, notes to myself or others of the Dynare development team, or at times notes to you - our readers - to highlight a feature not yet fully stable. Any such notes are marked with two stars (**). \\ - -Thanks very much for your patience and good ideas. Please write either direclty to myself: tommaso.mancini@stanfordalumni.org, or \textbf{preferably on the Dynare Documentation Forum} available in the \href{http://www.dynare.org/phpBB3}{Dynare Forums}. - -\chapter*{Contacts and Credits} \label{ch:contacts} -Dynare was originally developed by Michel Juillard in Paris, France. Currently, the development team of Dynare is composed of - -\begin{itemize} -\item StŽphane Adjemian \texttt{} -\item Houtan Bastani \texttt{} -\item Michel Juillard \texttt{} -\item FrŽdŽric KaramŽ \texttt{} -\item Junior Maih \texttt{} -\item Ferhat Mihoubi \texttt{} -\item George Perendia \texttt{} -\item Johannes Pfeifer \texttt{} -\item Marco Ratto \texttt{} -\item SŽbastien Villemot \texttt{} -\end{itemize} - -Several parts of Dynare use or have strongly benefited from publicly available programs by G. Anderson, F. Collard, L. Ingber, O. Kamenik, P. Klein, S. Sakata, F. Schorfheide, C. Sims, P. Soederlind and R. Wouters. - -Finally, the development of Dynare could not have come such a long ways withough an active community of users who continually pose questions, report bugs and suggest new features. The help of this community is gratefully acknowledged.\\ - -The email addresses above are provided in case you wish to contact any one of the authors of Dynare directly. We nonetheless encourage you to first use the \href{http://www.dynare.org/phpBB3}{Dynare forums} to ask your questions so that other users can benefit from them as well; remember, almost no question is specific enough to interest just one person, and yours is not the exception! - -\mainmatter - -\include{ch-intro} -\include{ch-inst} -\include{ch-solbase} -\include{ch-soladv} -\include{ch-estbase} -\include{ch-estadv} -\include{ch-solbeh} -\include{ch-estbeh} -\include{ch-ramsey} -\include{ch-trouble} - -\backmatter - -\bibliography{DynareBib} -\bibliographystyle{elsarticle-harv} -%\printindex - -\end{document} - diff --git a/doc/userguide/appendix.tex b/doc/userguide/appendix.tex deleted file mode 100644 index b3bc00269..000000000 --- a/doc/userguide/appendix.tex +++ /dev/null @@ -1,2 +0,0 @@ -\chapter{Appendix} -This is an example of an appendix! \ No newline at end of file diff --git a/doc/userguide/ch-estadv.tex b/doc/userguide/ch-estadv.tex deleted file mode 100644 index b34795059..000000000 --- a/doc/userguide/ch-estadv.tex +++ /dev/null @@ -1,311 +0,0 @@ -\chapter{Estimating DSGE models - advanced topics} \label{ch:estadv} - -This chapter focusses on advanced topics and features of Dynare in the area of model estimation. The chapter begins by presenting a more complex example than the one used for illustration purposes in chapter \ref{ch:estbase}. The goal is to show how Dynare would be used in the more ``realistic'' setting of reproducing a recent academic paper. The chapter then follows with sections on comparing models to one another, and then to BVARs, and ends with a table summarizing where output series are stored and how these can be retrieved. \\ - - -\section{Alternative and non-stationary example} -The example provided in chapter \ref{ch:estbase} is really only useful for illustration purposes. So we thought you would enjoy (and continue learning from!) a more realistic example which reproduces the work in a recent - and highly regarded - academic paper. The example shows how to use Dynare in a more realistic setting, while emphasizing techniques to deal with non-stationary observations and stochastic trends in dynamics. \\ - -\subsection{Introducing the example} -The example is drawn from \citet{Schorfheide2000}. This first section introduces the model, its basic intuitions and equations. We will then see in subsequent sections how to estimate it using Dynare. Note that the original paper by Schorfheide mainly focusses on estimation methodologies, difficulties and solutions, with a special interest in model comparison, while the mathematics and economic intuitions of the model it evaluates are drawn from \citet{CogleyNason1994}. That paper should serve as a helpful reference if anything is left unclear in the description below.\\ - -In essence, the model studied by \citet{Schorfheide2000} is one of cash in advance (CIA). The goal of the paper is to estimate the model using Bayesian techniques, while observing only output and inflation. In the model, there are several markets and actors to keep track of. So to clarify things, figure \ref{fig:schorfmod} sketches the main dynamics of the model. You may want to refer back to the figure as you read through the following sections. -\begin{figure} \label{fig:schorfmod} -\begin{center} -\includegraphics[width=1.0\textwidth]{P_SchorfMod} -\end{center} -\caption[CIA model illustration]{Continuous lines show the circulation of nominal funds, while dashed lines show the flow of real variables.} -\end{figure}\\ - -The economy is made up of three central agents and one secondary agent: households, firms and banks (representing the financial sector), and a monetary authority which plays a minor role. Households maximize their utility function which depends on consumption, $C_t$, and hours worked, $H_t$, while deciding how much money to hold next period in cash, $M_{t+1}$ and how much to deposit at the bank, $D_t$, in order to earn $R_{H,t}-1$ interest. Households therefore solve the problem -\begin{eqnarray*} -\substack{\max \\ \{C_t,H_t,M_{t+1},D_t\}} & \mathbb{E}_0 \left[ \sum_{t=0}^\infty \beta^t \left[ (1-\phi) \ln C_t + \phi \ln (1-H_t) \right] \right] \\ -\textrm{s.t.} & P_t C_t \leq M_t - D_t + W_t H_t \\ -& 0 \leq D_t \\ -& M_{t+1} = (M_t - D_t + W_tH_t - P_tC_t) + R_{H,t}D_t + F_t + B_t -\end{eqnarray*} -where the second equation spells out the cash in advance constraint including wage revenues, the third the inability to borrow from the bank and the fourth the intertemporal budget constraint emphasizing that households accumulate the money that remains after bank deposits and purchases on goods are deducted from total inflows made up of the money they receive from last period's cash balances, wages, interests, as well as dividends from firms, $F_t$, and from banks, $B_t$, which in both cases are made up of net cash inflows defined below. \\ - -Banks, on their end, receive cash deposits from households and a cash injection, $X_t$ from the central bank (which equals the net change in nominal money balances, $M_{t+1}-M_t$). It uses these funds to disburse loans to firms, $L_t$, on which they make a net return of $R_{F,t}-1$. Of course, banks are constrained in their loans by a credit market equilibrium condition $L_t \leq X_t + D_t$. Finally, bank dividends, $B_t$ are simply equal to $D_t + R_{F,t}L_t - R_{H,t}D_t - L_t + X_t$. \\ - -Finally, firms maximize the net present value of future dividends (discounted by the marginal utility of consumption, since they are owned by households) by choosing dividends, next period's capital stock, $K_{t+1}$, labor demand, $N_t$, and loans. Its problem is summarized by -\begin{eqnarray*} -\substack{\max \\ \{F_t,K_{t+1},N_{t},L_t\}} & \mathbb{E}_0 \left[ \sum_{t=0}^\infty \beta^{t+1} \frac{F_t}{C_{t+1}P_{t+1}} \right] \\ -\textrm{s.t.} & F_t \leq L_t + P_t \left[ K_t^\alpha (A_t N_t)^{1-\alpha} - K_{t+1} + (1-\delta)K_t \right] - W_tN_t-L_tR_{F,t} \\ -& W_tN_t \leq L_t\\ -\end{eqnarray*} -where the second equation makes use of the production function \mbox{$Y_t = K_t^\alpha (A_t N_t)^{1-\alpha}$} and the real aggregate accounting constraint (goods market equilibrium) \mbox{$C_t + I_t = Y_t$}, where $I_t=K_{t+1} - (1-\delta)K_t$, and where $\delta$ is the rate of depreciation. Note that it is the firms that engage in investment in this model, by trading off investment for dividends to consumers. The third equation simply specifies that bank loans are used to pay for wage costs. \\ - -To close the model, we add the usual labor and money market equilibrium equations, $H_t= N_t$ and $P_tC_t=M_t + X_t$, as well as the condition that $R_{H,t}=R_{F,t}$ due to the equal risk profiles of the loans.\\ - -More importantly, we add a stochastic elements to the model. The model allows for two sources of perturbations, one real, affecting technology and one nominal, affecting the money stock. These important equations are -\[ -\ln A_t = \gamma + \ln A_{t-1} + \epsilon_{A,t}, \qquad \epsilon_{A,t} \thicksim N(0,\sigma_A^2) -\] -and - -\[ -\ln m_t = (1-\rho)\ln m^* + \rho \ln m_{t-1} + \epsilon_{M,t}, \qquad \epsilon_{M,t} \thicksim N(0,\sigma_M^2) -\] -where $m_t \equiv M_{T+1}/M_t$ is the growth rate of the money stock. Note that theses expressions for trends are not written in the most straightforward manner nor very consistently. But we reproduced them never-the-less to make it easier to compare this example to the original paper. \\ - -The first equation is therefore a unit root with drift in the log of technology, and the second an autoregressive stationary process in the growth rate of money, but an AR(2) with a unit root in the log of the level of money. This can be seen from the definition of $m_t$ which can be rewritten as $\ln M_{t+1} = \ln M_t + \ln m_t$.\footnote{Alternatively, we could have written the AR(2) process in state space form and realized that the system has an eigenvalue of one. Otherwise said, one is a root of the second order autoregressive lag polynomial. As usual, if the logs of a variable are specified to follow a unit root process, the rate of growth of the series is a stationary stochastic process; see \citet{Hamilton1994}, chapter 15, for details.}\\ - -When the above functions are maximized, we obtain the following set of first order and equilibrium conditions. We will not dwell on the derivations here, to save space, but encourage you to browse \citet{CogleyNason1994} for additional details. We nonetheless give a brief intuitive explanation of each equation. The system comes down to -\begin{eqnarray*} -\mathbb{E}_{t}\bigg\{-\widehat{P}_{t}/\left[ \widehat{C}_{t+1}\widehat{P}_{t+1}m_{t}% -\right]\bigg\}&=&\beta e^{-\alpha (\gamma +\epsilon_{A,t+1})}P_{t+1}\Big[\alpha\widehat{K}_{t}^{\alpha -1}N_{t+1}^{1-\alpha }+ -(1-\delta )\Big]\\ -&&/\left[ -\widehat{c}_{t+2}\widehat{P}_{t+2}m_{t+1}\right] \bigg\}\\ -\widehat{W}_{t}&=&\widehat{L}_{t}/N_{t}\\ -\frac{\phi }{1-\phi }\left[ \widehat{C}_{t}\widehat{P}_{t}/\left( -1-N_{t}\right) \right]&=&\widehat{L}_{t}/N_{t}\\ -R_{t}&=&(1-\alpha )\widehat{P}_{t}e^{-\alpha (\gamma +\epsilon_{A,t+1})}\widehat{K}_{t-1}^{\alpha}N_{t}^{-\alpha }/\widehat{W}_{t}\\ -\left[ \widehat{C}_{t}\widehat{P}_{t}\right] ^{-1}&=&\beta \left[ \left( -1-\alpha \right) \widehat{P}_{t}e^{-\alpha (\gamma +\epsilon_{A,t+1})}\widehat{K}_{t-1}^{\alpha}N_{t}^{1-\alpha } -\right]\\ -&& \times \mathbb{E}_{t}\left[\widehat{L}_{t}m_{t}\widehat{C}_{t+1}\widehat{P}_{t+1}\right] ^{-1}\\ -\widehat{C}_t+\widehat{K}_t &=& e^{-\alpha(\gamma+\epsilon_{A,t})}\widehat{K}_{t-1}^\alpha N^{1-\alpha}+(1-\delta)e^{-(\gamma+\epsilon_{A,t})}\widehat{K}_{t-1}\\ -\widehat{P}_t\widehat{C} &=& m_t\\ -m_t-1+\widehat{D}_t &=& \widehat{L}_t\\ -\widehat{Y}_t &=& \widehat{K}_{t-1}^\alpha N^{1-\alpha}e^{-\alpha (\gamma+\epsilon_{A,t})}\\ -\ln(m_t) &=& (1-\rho)\ln(m^\star) + \rho\ln(m_{t-1})+\epsilon_{M,t}\\ -\frac{A_t}{A_{t-1}} \equiv dA_t & = & \exp( \gamma + \epsilon_{A,t})\\ -Y_t/Y_{t-1} &=& e^{\gamma+\epsilon_{A,t}}\widehat{Y}_t/\widehat{Y}_{t-1}\\ -P_t/P_{t-1} &=& (\widehat{P}_t/\widehat{P}_{t-1})(m_{t-1}/e^{\gamma+\epsilon_{A,t}}) -\end{eqnarray*} -where, importantly, hats over variables no longer mean deviations from steady state, but instead represent variables that have been made stationary. We come back to this important topic in details in section \ref{sec:nonstat} below. For now, we pause a moment to give some intuition for the above equations. In order, these equations correspond to: -\begin{enumerate} -\item The Euler equation in the goods market, representing the tradeoff to the economy of moving consumption goods across time. -\item The firms' borrowing constraint, also affecting labor demand, as firms use borrowed funds to pay for labor input. -\item The intertemporal labor market optimality condition, linking labor supply, labor demand, and the marginal rate of substitution between consumption and leisure. -\item The equilibrium interest rate in which the marginal revenue product of labor equals the cost of borrowing to pay for that additional unit of labor. -\item The Euler equation in the credit market, which ensures that giving up one unit of consumption today for additional savings equals the net present value of future consumption. -\item The aggregate resource constraint. -\item The money market equilibrium condition equating nominal consumption demand to money demand to money supply to current nominal balances plus money injection. -\item The credit market equilibrium condition. -\item The production function. -\item The stochastic process for money growth. -\item The stochastic process for technology. -\item The relationship between observable variables and stationary variables; more details on these last two equations appear in the following section. -\end{enumerate} - -\subsection{Declaring variables and parameters} -This block of the .mod file follows the usual conventions and would look like:\\ -\\ -\texttt{var m P c e W R k d n l Y\_obs P\_obs y dA; \\ -varexo e\_a e\_m;\\ -\\ -parameters alp, bet, gam, mst, rho, psi, del;}\\ -\\ -where the choice of upper and lower case letters is not significant, the first set of endogenous variables, up to $l$, are as specified in the model setup above, and where the last five variables are defined and explained in more details in the section below on declaring the model in Dynare. The exogenous variables are as expected and concern the shocks to the evolution of technology and money balances. \\ - -\subsection{The origin of non-stationarity} \label{sec:nonstat} -The problem of non-stationarity comes from having stochastic trends in technology and money. The non-stationarity comes out clearly when attempting to solve the model for a steady state and realizing it does not have one. It can be shown that when shocks are null, real variables grow with $A_t$ (except for labor, $N_t$, which is stationary as there is no population growth), nominal variables grow with $M_t$ and prices with $M_t/A_t$. \textbf{Detrending} therefore involves the following operations (where hats over variables represent stationary variables): for real variables, $\hat q_t=q_t/A_t$, where $q_t = [y_t, c_t, i_t, k_{t+1} ]$. For nominal variables, $\hat{Q}_t = Q_t/M_t$, where $Q_t = [ d_t, l_t, W_t ]$. And for prices, $\hat P_t = P_t \cdot A_t / M_t$. \\ - -\subsection{Stationarizing variables} -Let's illustrate this transformation on output, and leave the transformations of the remaining equations as an exercise, if you wish (\citet{CogleyNason1994} includes more details on the transformations of each equation). We stationarize output by dividing its real variables (except for labor) by $A_t$. We define $\widehat{Y}_t$ to equal $Y_t / A_t$ and $\widehat{K}_t$ as $K_t / A_t$. \textsf{\textbf{NOTE!}} Recall from section \ref{sec:modspe} in chapter \ref{ch:solbase}), that in Dynare variables take the time subscript of the period in which they are decided (in the case of the capital stock, today's capital stock is a result of yesterday's decision). Thus, in the output equation, we should actually work with $\widehat{K}_{t-1}=K_{t-1} / A_{t-1}$. The resulting equation made up of stationary variables is -\begin{eqnarray*} -\frac{Y_t}{A_t} & = & \left( \frac{K_{t-1}}{A_{t-1}} \right)^\alpha A_t^{1-\alpha} N_t^{1-\alpha} A_t^{-1} A_{t-1}^\alpha \\ -\widehat{Y}_t & = & \widehat{K}_{t-1}^\alpha N_t^{1-\alpha} \left( \frac{A_t}{A_{t-1}} \right)^{-\alpha} \\ -& = & \widehat{K}_{t-1}^\alpha N_t^{1-\alpha} \exp(-\alpha (\gamma + \epsilon_{A,t})) -\end{eqnarray*} -where we go from the second to the third line by taking the exponential of both sides of the equation of motion of technology.\\ - -The above is the equation we retain for the .mod file of Dynare into which we enter:\\ -\\ -\texttt{y=k(-1)\textasciicircum alp*n\textasciicircum (1-alp)*exp(-alp*(gam+e\_a))}\\ -\\ - -The other equations are entered into the .mod file after transforming them in exactly the same way as the one above. A final transformation to consider, that turns out to be useful since we often deal with the growth rate of technology, is to define \\ -\\ -\texttt{dA = exp(gam+e\_a)}\\ -\\ -by simply taking the exponential of both sides of the stochastic process of technology defined in the model setup above. \\ - -\subsection{Linking stationary variables to the data} -And finally, we must make a decision as to our \textbf{non-stationary observations}. We could simply stationarize them by \textbf{working with rates of growth} (which we know are constant). In the case of output, the observable variable would become $Y_t /Y_{t-1}$. We would then have to relate this observable, call it $gy\_{obs}$, to our (stationary) model's variables $\widehat Y_t$ by using the definition that $ \widehat{Y}_t \equiv Y_t/ A_t$. Thus, we add to the model block of the .mod file: \\ -\\ -\texttt{gy\_obs = dA*y/y(-1);}\\ -\\ -where, the $y$ of the .mod file are the stationary $\widehat Y_t$.\\ - -But, we could also \textbf{work with non-stationary data in levels}. This complicates things somewhat, but illustrates several features of Dynare worth highlighting; we therefore follow this path in the remainder of the example. The result is not very different, though, from what we just saw above. The goal is to add a line to the model block of our .mod file that relates the non stationary observables, call them $Y_{obs}$, to our stationary output, $\widehat Y_t$. We could simply write $Y_{obs} = \widehat Y_t A_t$. But since we don't have an $A_t$ variable, but just a $dA_t$, we we-write the above relationship in ratios. To the .mod file, we therefore add:\\ -\\ -\texttt{Y\_obs/Y\_obs(-1) = dA*y/y(-1);}\\ -\\ -We of course do the same for prices, our other observable variable, except that we use the relationship $P_{obs} = \widehat P_t M_t/A_t$ as noted earlier. The details of the correct transformations for prices are left as an exercise and can be checked against the results below.\\ - -\subsection{The resulting model block of the .mod file} - -\texttt{model;\\ -dA = exp(gam+e\_a);\\ -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\textasciicircum (alp-1)\\ -*n(+1)\textasciicircum (1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;\\ -W = l/n;\\ --(psi/(1-psi))*(c*P/(1-n))+l/n = 0;\\ -R = P*(1-alp)*exp(-alp*(gam+e\_a))*k(-1)\textasciicircum alp*n\textasciicircum (-alp)/W;\\ -1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e\_a))*k(-1)\textasciicircum alp*n\textasciicircum (1-alp)/\\ -(m*l*c(+1)*P(+1)) = 0;\\ -c+k = exp(-alp*(gam+e\_a))*k(-1)\textasciicircum alp*n\textasciicircum (1-alp)+(1-del)\\ -*exp(-(gam+e\_a))*k(-1);\\ -P*c = m;\\ -m-1+d = l;\\ -e = exp(e\_a);\\ -y = k(-1)\textasciicircum alp*n\textasciicircum (1-alp)*exp(-alp*(gam+e\_a));\\ -Y\_obs/Y\_obs(-1) = dA*y/y(-1);\\ -P\_obs/P\_obs(-1) = (p/p(-1))*m(-1)/dA;\\ -end;}\\ -\\ -where, of course, the input conventions, such as ending lines with semicolons and indicating the timing of variables in parentheses, are the same as those listed in chapter \ref{ch:solbase}. \\ - -\textsf{\textbf{TIP!}} In the above model block, notice that what we have done is in fact relegated the non-stationarity of the model to just the last two equations, concerning the observables which are, after all, non-stationary. The problem that arises, though, is that we cannot linearize the above system in levels, as the last two equations don't have a steady state. If we first take logs, though, they become linear and it doesn't matter anymore where we calculate their derivative when taking a Taylor expansion of all the equations in the system. Thus, \textbf{when dealing with non-stationary observations, you must log-linearize your model} (and not just linearize it); this is a point to which we will return later. - -\subsection{Declaring observable variables} -We begin by declaring which of our model's variables are observables. In our .mod file we write\\ -\\ -\texttt{varobs P\_obs Y\_obs;}\\ -\\ -to specify that our observable variables are indeed $P\_obs$ and $Y\_obs$ as noted in the section above. \textsf{\textbf{NOTE!}} Recall from earlier that the number of observed variables must be smaller or equal to the number of shocks such that the model be estimated. If this is not the case, you should add measurement shocks to your model where you deem most appropriate. \\ - -\subsection{Declaring trends in observable variables} - -Recall that we decided to work with the non-stationary observable variables in levels. Both output and prices exhibit stochastic trends. This can be seen explicitly by taking the difference of logs of output and prices to compute growth rates. In the case of output, we make use of the usual (by now!) relationship $Y_t=\widehat Y_t \cdot A_t$. Taking logs of both sides and subtracting the same equation scrolled back one period, we find: -\[ -\Delta \ln Y_t = \Delta \ln \widehat Y_t + \gamma + \epsilon_{A,t} -\] -emphasizing clearly the drift term $\gamma$, whereas we know $\Delta \ln \widehat Y_t$ is stationary in steady state. \\ - -In the case of prices, we apply the same manipulations to show that: -\[ -\Delta \ln P_t = \Delta \ln \widehat P_t + \ln m_{t-1} - \gamma - \epsilon_{A,t} -\] - -Note from the original equation of motion of $\ln m_t$ that in steady state, $\ln m_t=\ln m^*$, so that the drift terms in the above equation are $\ln m^* - \gamma$.\footnote{This can also be see from substituting for $\ln m_{t-1}$ in the above equation with the equation of motion of $\ln m_t$ to yield: $\Delta \ln P_t = \Delta \ln \widehat P_t + \ln m^* + \rho(\ln m_{t-2}-\ln m^*) + \epsilon_{M,t} - \gamma - \epsilon_{A,t}$ where all terms on the right hand side are constant, except for $\ln m^*$ and $\gamma$.} \\ - -In Dynare, any trends, whether deterministic or stochastic (the drift term) must be declared up front. In the case of our example, we therefore write (in a somewhat cumbersome manner)\\ -\\ -\texttt{observation\_trends;\\ -P\_obs (log(mst)-gam);\\ -Y\_obs (gam);\\ -end;}\\ - -In general, the command \texttt{observation\_trends} specifies linear trends as a function of model parameters for the observed variables in the model.\\ - - -\subsection{Specifying the steady state} -Declaring the steady state is just as explained in details and according to the same syntax explained in chapter \ref{ch:solbase}, covering the \texttt{initval}, \texttt{steady} and \texttt{check} commands. In chapter \ref{ch:estbase}, section \ref{sec:ssest}, we also discussed the usefulness of providing an external Matlab file to solve for the steady state. In this case, you can find the corresponding steady state file in the \textsl{models} folder under \textsl{UserGuide}. The file is called \textsl{fs2000ns\_steadystate.m}. There are some things to notice. First, the output of the function is the endogenous variables at steady state, the \texttt{ys} vector. The \texttt{check=0} limits steady state values to real numbers. Second, notice the declaration of parameters at the beginning; intuitive, but tedious... This functionality may be updated in later versions of Dynare. Third, note that the file is really only a sequential set of equalities, defining each variable in terms of parameters or variables solved in the lines above. So far, nothing has changed with respect to the equivalent file of chapter \ref{ch:estbase}. The only novelty is the declaration of the non-stationary variables, $P\_obs$ and $Y\_obs$ which take the value of 1. This is Dynare convention and must be the case for all your non-stationary variables. - -\subsection{Declaring priors} -We expand our .mod file with the following information: \\ -\\ -\texttt{estimated\_params;\\ -alp, beta\_pdf, 0.356, 0.02; \\ -bet, beta\_pdf, 0.993, 0.002; \\ -gam, normal\_pdf, 0.0085, 0.003; \\ -mst, normal\_pdf, 1.0002, 0.007; \\ -rho, beta\_pdf, 0.129, 0.223;\\ -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;\\ -end;}\\ -\\ - -\subsection{Launching the estimation} -We add the following commands to ask Dynare to run a basic estimation of our model:\\ -\\ -\texttt{estimation(datafile=fsdat,nobs=192,loglinear,mh\_replic=2000,\\ -mode\_compute=4,mh\_nblocks=2,mh\_drop=0.45,mh\_jscale=0.65,\\ -diffuse\_filter);}\\ - -\textsf{\textbf{NOTE!}} Since P\_obs and Y\_obs inherit the unit root characteristics of their driving variables, technology and money, we must tell Dynare to use a diffuse prior (infinite variance) for their initialization in the Kalman filter. Note that for stationary variables, the unconditional covariance matrix of these variables is used for initialization. The algorithm to compute a true diffuse prior is taken from \citet{DurbinKoopman2001}. To give these instructions to Dynare, we use the \texttt{diffuse\_filter} option. Also note that you don't need to use the diffuse filter for any non-stationary model, only for when there is a unit-root, \textit{i.e.} a stochastic trend; you don't need to use a diffuse initial condition in the case of a deterministic trend, since the variance is finite.\\ - -\textsf{\textbf{NOTE!}} As mentioned earlier, we need to instruct Dynare to log-linearize our model, since it contains non-linear equations in non-stationary variables. A simple linearization would fail as these variables do not have a steady state. Fortunately, taking the log of the equations involving non-stationary variables does the job of linearizing them.\\ - -\subsection{The complete .mod file} -We have seen each part of the .mod separately; it's now time to get a picture of what the complete file looks like. For convenience, the file also appears in the \textsl{models} folder under \textsl{UserGuide} in your Dynare installation. The file is called \texttt{fs2000ns.mod}. \\ -\\ -\texttt{var m P c e W R k d n l Y\_obs P\_obs y dA; \\ -varexo e\_a e\_m;\\ -parameters alp, bet, gam, mst, rho, psi, del;\\ -\\ -model;\\ -dA = exp(gam+e\_a);\\ -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\textasciicircum (alp-1)*n(+1)\textasciicircum (1-alp)+(1-del)\\ -*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;\\ -W = l/n;\\ --(psi/(1-psi))*(c*P/(1-n))+l/n = 0;\\ -R = P*(1-alp)*exp(-alp*(gam+e\_a))*k(-1)\textasciicircum alp*n\textasciicircum (-alp)/W;\\ -1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e\_a))*k(-1)\textasciicircum alp*n\textasciicircum (1-alp)/\\(m*l*c(+1)*P(+1)) = 0;\\ -c+k = exp(-alp*(gam+e\_a))*k(-1)\textasciicircum alp*n\textasciicircum (1-alp)+(1-del)\\*exp(-(gam+e\_a))*k(-1);\\ -P*c = m;\\ -m-1+d = l;\\ -e = exp(e\_a);\\ -y = k(-1)\textasciicircum alp*n\textasciicircum (1-alp)*exp(-alp*(gam+e\_a));\\ -Y\_obs/Y\_obs(-1) = dA*y/y(-1);\\ -P\_obs/P\_obs(-1) = (p/p(-1))*m(-1)/dA;\\ -end;\\ -\\ -varobs P\_obs Y\_obs;\\ -\\ -observation\_trends;\\ -P\_obs (log(mst)-gam);\\ -Y\_obs (gam);\\ -end;\\ -\\ -initval;\\ -k = 6;\\ -m = mst;\\ -P = 2.25;\\ -c = 0.45;\\ -e = 1;\\ -W = 4;\\ -R = 1.02;\\ -d = 0.85;\\ -n = 0.19;\\ -l = 0.86;\\ -y = 0.6;\\ -dA = exp(gam);\\ -end;\\ -\\ -// the above is really only useful if you want to do a stoch\_simul\\ -// of your model, since the estimation will use the Matlab\\ -// steady state file also provided and discussed above.\\ -\\ -estimated\_params;\\ -alp, beta\_pdf, 0.356, 0.02; \\ -bet, beta\_pdf, 0.993, 0.002; \\ -gam, normal\_pdf, 0.0085, 0.003; \\ -mst, normal\_pdf, 1.0002, 0.007; \\ -rho, beta\_pdf, 0.129, 0.223;\\ -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;\\ -end;\\ -\\ -estimation(datafile=fsdat,nobs=192,loglinear,mh\_replic=2000,\\ -mode\_compute=4,mh\_nblocks=2,mh\_drop=0.45,mh\_jscale=0.65,\\ -diffuse\_filter);}\\ -\\ - -\subsection{Summing it up} -The explanations given above of each step necessary to translate the \citet{Schorfheide2000} example into language that Dynare can understand and process was quite lengthy and involved a slew of new commands and information. It may therefore be useful, to gain a ``bird's eyeview'' on what we have just accomplished, and summarize the most important steps at a high level. This is done in figure \ref{fig:estsumm}.\\ -\begin{figure} \label{fig:estsumm} -\begin{center} -\includegraphics[width=1.0\textwidth]{P_flowest} -\end{center} -\caption[Steps of model estimation]{At a high level, there are five basic steps to translate a model into Dynare for successful estimation.} -\end{figure}\\ - - -\section{Comparing models based on their posterior distributions} -** TBD - -\section{Where is your output stored?} -The output from estimation can be extremely varied, depending on the instructions you give Dynare. The \href{http://www.dynare.org/documentation-and-support/manual}{Reference Manual} overviews the complete set of potential output files and describes where you can find each one. \ No newline at end of file diff --git a/doc/userguide/ch-estbase.tex b/doc/userguide/ch-estbase.tex deleted file mode 100644 index ad3ee7766..000000000 --- a/doc/userguide/ch-estbase.tex +++ /dev/null @@ -1,290 +0,0 @@ -\chapter{Estimating DSGE models - basics} \label{ch:estbase} - -As in the chapter \ref{ch:solbase}, this chapter is structured around an example. The goal of this chapter is to lead you through the basic functionality in Dynare to estimate models using Bayesian techniques, so that by the end of the chapter you should have the capacity to estimate a model of your own. This chapter is therefore very practically-oriented and abstracts from the underlying computations that Dynare undertakes to estimate a model; that subject is instead covered in some depth in chapter \ref{ch:estbeh}, while more advanced topics of practical appeal are discussed in chapter \ref{ch:estadv}. \\ - -\section{Introducing an example} \label{sec:modsetup} -The example introduced in this chapter is particularly basic. This is for two reasons. First, we did not want to introduce yet another example in this section; there's enough new material to keep you busy. Instead, we thought it would be easiest to simply continue working with the example introduced in chapter \ref{ch:solbase} with which you are probably already quite familiar. Second, the goal of the example in this chapter is really to explain features in context, but not necessarily to duplicate a ``real life scenario'' you would face when writing a paper. Once you feel comfortable with the content of this chapter, though, you can always move on to chapter \ref{ch:estadv} where you will find a full-fledged replication of a recent academic paper, featuring a non-stationary model. \\ - -Recall from chapter \ref{ch:solbase} that we are dealing with an RBC model with monopolistic competition. Suppose we had data on business cycle variations of output. Suppose also that we thought our little RBC model did a good job of reproducing reality. We could then use Bayesian methods to estimate the parameters of the model: $\alpha$, the capital share of output, $\beta$, the discount factor, $\delta$, the depreciation rate, $\psi$, the weight on leisure in the utility function, $\rho$, the degree of persistence in productivity, and $\epsilon$, the markup parameter. Note that in Bayesian estimation, the condition for undertaking estimation is that there be at least as many shocks as there are observables (a less stringent condition than for maximum likelihood estimation). It may be that this does not allow you to identify all your parameters - yielding posterior distributions identical to prior distributions - but the Bayesian estimation procedure would still run successfully. Let's see how to go about doing this. - -\section{Declaring variables and parameters} -To input the above model into Dynare for estimation purposes, we must first declare the model's variables in the preamble of the .mod file. This is done exactly as described in chapter \ref{ch:solbase} on solving DSGE models. We thus begin the .mod file with:\\ -\\ -\texttt{var y c k i l y\_l w r z;\\ -varexo e;\\ -\\ -parameters beta psi delta alpha rho epsilon;\\}\\ -\\ - -\section{Declaring the model} -Suppose that the equation of motion of technology is a \textbf{stationary} AR(1) with an autoregressive parameter, $\rho$, less than one. The model's variables would therefore be stationary and we can proceed without complications. The alternative scenario with \textbf{non-stationary variables} is more complicated and dealt with in chapter \ref{ch:estadv} (in the additional example). In the stationary case, our model block would look exactly as in chater \ref{ch:solbase}:\\ -\\ -\texttt{model;\\ - (1/c) = beta*(1/c(+1))*(1+r(+1)-delta);\\ - psi*c/(1-l) = w;\\ - c+i = y;\\ - y = (k(-1)\textasciicircum alpha)*(exp(z)*l)\textasciicircum (1-alpha);\\ - w = y*((epsilon-1)/epsilon)*(1-alpha)/l;\\ - r = y*((epsilon-1)/epsilon)*alpha/k(-1);\\ - i = k-(1-delta)*k(-1);\\ - y\_l = y/l;\\ - z = rho*z(-1)+e;\\ -end;}\\ -\\ - -\section{Declaring observable variables} -This should not come as a surprise. Dynare must know which variables are observable for the estimation procedure. \textsf{\textbf{NOTE!}} These variables must be available in the data file, as explained in section \ref{sec:estimate} below. For the moment, we write:\\ -\\ -\texttt{varobs y;}\\ - -\section{Specifying the steady state} \label{sec:ssest} -Before Dynare estimates a model, it first linearizes it around a steady state. Thus, a steady state must exist for the model and although Dynare can calculate it, we must give it a hand by declaring approximate values for the steady state. This is just as explained in details and according to the same syntax outlined in chapter \ref{ch:solbase}, covering the \texttt{initval}, \texttt{steady} and \texttt{check} commands. In fact, as this chapter uses the same model as that outlined in chapter \ref{ch:solbase}, the steady state block will look exactly the same.\\ - -\textsf{\textbf{TIP!}} During estimation, in finding the posterior mode, Dynare recalculates the steady state of the model at each iteration of the optimization routine (more on this later), based on the newest round of parameters available. Thus, by providing approximate initial values and relying solely on the built-in Dynare algorithm to find the steady state (a numerical procedure), you will significantly slow down the computation of the posterior mode. Dynare will end up spending 60 to 70\% of the time recalculating steady states. It is much more efficient to write an external \textbf{Matlab steady state file} and let Dynare use that file to find the steady state of your model by algebraic procedure. For more details on writing an external Matlab file to find your model's steady state, please refer to section \ref{sec:findsteady} of chapter \ref{ch:solbase}. \\ - - -\section{Declaring priors} -Priors play an important role in Bayesian estimation and consequently deserve a central role in the specification of the .mod file. Priors, in Bayesian estimation, are declared as a distribution. The general syntax to introduce priors in Dynare is the following:\\ -\\ -\texttt{estimated\_params;\\ -PARAMETER NAME, PRIOR\_SHAPE, PRIOR\_MEAN, PRIOR\_STANDARD\_ERROR [, PRIOR 3$^{\textrm{rd}}$ PARAMETER] [,PRIOR 4$^{\textrm{th}}$ PARAMETER] ; \\ -end; }\\ -\\ -where the following table defines each term more clearly\\ -\\ - \begin{tabular}{llc} - \textbf{\underline{PRIOR\_SHAPE}} & \textbf{\underline{Corresponding distribution}} & \textbf{\underline{Range}} \\ - NORMAL\_PDF & $N(\mu,\sigma)$ & $\mathbb{R}$\\ - GAMMA\_PDF & $G_2(\mu,\sigma,p_3)$ & $[p_3,+\infty)$\\ - BETA\_PDF & $B(\mu,\sigma,p_3,p_4)$ & $[p_3,p_4]$\\ - INV\_GAMMA\_PDF & $IG_1(\mu,\sigma)$ & $\mathbb R^+$\\ -UNIFORM\_PDF& $U(p_3,p_4)$ & $[p_3,p_4]$ - \end{tabular}\\ - \\ - \\ - where $\mu$ is the \texttt{PRIOR\_MEAN}, $\sigma$ is the \texttt{PRIOR\_STANDARD\_ERROR}, $p_3$ is the \texttt{PRIOR 3$^{\textrm{rd}}$ PARAMETER} (whose default is 0) and $p_4$ is the \texttt{PRIOR 4$^{\textrm{th}}$ PARAMETER} (whose default is 1). \textsf{\textbf{TIP!}} When specifying a uniform distribution between 0 and 1 as a prior for a parameter, say $\alpha$, you therefore have to put two empty spaces for parameters $\mu$ and $\sigma$, and then specify parameters $p3$ and $p4$, since the uniform distribution only takes $p3$ and $p4$ as arguments. For instance, you would write \texttt{alpha, uniform\_pdf, , , 0,1;} \\ - -For a more complete review of all possible options for declaring priors, as well as the syntax to declare priors for maximum likelihood estimation (not Bayesian), see the \href{http://www.dynare.org/documentation-and-support/manual}{Reference Manual}. Note also that if some parameters in a model are calibrated and are not to be estimated, you should declare them as such, by using the \texttt{parameters} command and its related syntax, as explained in chapter \ref{ch:solbase}. \\ - -\textsf{\textbf{TIP!}} Choosing the appropriate prior for your parameters is a tricky, yet very important endeavor. It is worth spending time on your choice of priors and to test the robustness of your results to your priors. Some considerations may prove helpful. First, think about the domain of your prior over each parameter. Should it be bounded? Should it be opened on either or both sides? Remember also that if you specify a probability of zero over a certain domain in your prior, you will necessarily also find a probability of zero in your posterior distribution. Then, think about the shape of your prior distribution. Should it be symmetric? Skewed? If so, on which side? You may also go one step further and build a distribution for each of your parameters in your mind. Ask yourself, for instance, what is the probability that your parameter is bigger than a certain value, and repeat the exercise by incrementally decreasing that value. You can then pick the standard distribution that best fits your perceived distribution. Finally, instead of describing here the shapes and properties of each standard distribution available in Dynare, you are instead encouraged to visualize these distributions yourself, either in a statistics book or on the Web. \\ - -\textsf{\textbf{TIP!}} It may at times be desirable to estimate a transformation of a parameter appearing in the model, rather than the parameter itself. In such a case, it is possible to declare the parameter to be estimated in the parameters statement and to define the transformation at the top of the model section, as a Matlab expression, by adding a pound sign (\#) at the beginning of the corresponding line. For example, you may find it easier to define a prior over the discount factor, $\beta$, than its inverse which often shows up in Euler equations. Thus you would write:\\ -\\ -\texttt{model;\\ - \# sig = 1/bet;\\ - c = sig*c(+1)*mpk;\\ - end;\\ -\\ - estimated\_params;\\ - bet,normal\_pdf,1,0.05;\\ - end;}\\ - -\textsf{\textbf{TIP!}} Finally, another useful command to use is the \texttt{estimated\_params\_init} command which declares numerical initial values for the optimizer when these are different from the prior mean. This is especially useful when redoing an estimation - if the optimizer got stuck the first time around, or needing a greater number of draws in the Metropolis-Hastings algorithm - and wanting to enter the posterior mode as initial values for the parameters instead of a prior. The \href{http://www.dynare.org/documentation-and-support/manual}{Reference Manual} gives more details as to the exact syntax of this command.\\ - -Coming back to our basic example, we would write:\\ -\\ -\texttt{estimated\_params;\\ -alpha, beta\_pdf, 0.35, 0.02; \\ -beta, beta\_pdf, 0.99, 0.002; \\ -delta, beta\_pdf, 0.025, 0.003;\\ -psi, gamma\_pdf, 1.75, 0.1;\\ -rho, beta\_pdf, 0.95, 0.05;\\ -epsilon, gamma\_pdf, 10, 0.5;\\ -stderr e, inv\_gamma\_pdf, 0.01, inf;\\ -end;}\\ - - -\section{Launching the estimation} \label{sec:estimate} -To ask Dynare to estimate a model, all that is necessary is to add the command \texttt{estimation} at the end of the .mod file. Easy enough. But the real complexity comes from the options available for the command (to be entered in parentheses and sequentially, separated by commas, after the command \texttt{estimation}). Below, we list the most common and useful options, and encourage you to view the \href{http://www.dynare.org/documentation-and-support/manual}{Reference Manual} for a complete list. \\ -\begin{enumerate} -\item datafile = FILENAME: the datafile (a .m file, a .mat file, or an .xls file). Note that observations do not need to show up in any order, but vectors of observations need to be named with the same names as those in \texttt{var\_obs}. In Excel files, for instance, observations could be ordered in columns, and variable names would show up in the first cell of each column. -\item nobs = INTEGER: the number of observations to be used (default: all observations in the file) -\item first\_obs = INTEGER: the number of the first observation to be used (default = 1). This is useful when running loops, or instance, to divide the observations into sub-periods. -\item prefilter = 1: the estimation procedure demeans the data (default=0, no prefiltering). This is useful if model variables are in deviations from steady state, for instance, and therefore have zero mean. Demeaning the observations would also impose a zero mean on the observed variables. -\item nograph: no graphs should be plotted. -\item conf\_sig = \{INTEGER | DOUBLE \}: the level for the confidence intervals reported in the results (default = 0.90) -\item mh\_replic = INTEGER: number of replication for Metropolis Hasting algorithm. For the time being, mh\_replic -should be larger than 1200 (default = 20000) -\item mh\_nblocks = INTEGER: number of parallel chains for Metropolis Hasting algorithm (default = 2). Despite this low default value, it is advisable to work with a higher value, such as 5 or more. This improves the computation of between group variance of the parameter means, one of the key criteria to evaluate the efficiency of the Metropolis-Hastings to evaluate the posterior distribution. More details on this subject appear in Chapter \ref{ch:estadv}. -\item mh\_drop = DOUBLE: the fraction of initially generated parameter vectors to be dropped before using posterior -simulations (default = 0.5; this means that the first half of the draws from the Metropolis-Hastings are discarded). -\item mh\_jscale = DOUBLE: the scale to be used for the jumping distribution in MH algorithm. The default value is -rarely satisfactory. This option must be tuned to obtain, ideally, an acceptance rate of 25\% in the Metropolis- Hastings algorithm (default = 0.2). The idea is not to reject or accept too often a candidate parameter; the literature has settled on a value of between 0.2 and 0.4. If the acceptance rate were too high, your Metropolis-Hastings iterations would never visit the tails of a distribution, while if it were too low, the iterations would get stuck in a subspace of the parameter range. Note that the acceptance rate drops if you increase the scale used in the jumping distribution and vice a versa. -\item mh\_init\_scale=DOUBLE: the scale to be used for drawing the initial value of the Metropolis-Hastings chain (default=2*mh\_jscale). The idea here is to draw initial values from a stretched out distribution in order to maximize the chances of these values not being too close together, which would defeat the purpose of running several blocks of Metropolis-Hastings chains. -\item mode\_file=FILENAME: name of the file containing previous value for the mode. When computing the mode, -Dynare stores the mode (xparam1) and the hessian (hh) in a file called MODEL NAME\_mode. This is a particularly helpful option to speed up the estimation process if you have already undertaken initial estimations and have values of the posterior mode. -\item mode\_compute=INTEGER: specifies the optimizer for the mode computation. -\subitem 0: the mode isnÕt computed. mode\_file must be specified -\subitem 1: uses Matlab fmincon (see the \href{http://www.dynare.org/documentation-and-support/manual}{Reference Manual} to set options for this command). -\subitem 2: uses Lester IngberÕs Adaptive Simulated Annealing. -\subitem 3: uses Matlab fminunc. -\subitem 4 (default): uses Chris SimÕs csminwel. -\item mode\_check: when mode\_check is set, Dynare plots the minus of the posterior density for values around the computed mode -for each estimated parameter in turn. This is helpful to diagnose problems with the optimizer. A clear indication of a problem would be that the mode is not at the trough (bottom of the minus) of the posterior distribution. -\item load\_mh\_file: when load\_mh\_file is declared, Dynare adds to previous Metropolis-Hastings simulations instead -of starting from scratch. Again, this is a useful option to speed up the process of estimation. -\item nodiagnostic: doesnÕt compute the convergence diagnostics for Metropolis-Hastings (default: diagnostics are computed and -displayed). Actually seeing if the various blocks of Metropolis-Hastings runs converge is a powerful and useful option to build confidence in your model estimation. More details on these diagnostics are given in Chapter \ref{ch:estadv}. -\item bayesian\_irf: triggers the computation of the posterior distribution of impulse response functions (IRFs). The length of the IRFs are controlled by the irf option, as specified in chapter \ref{ch:solbase} when discussing the options for \texttt{stoch\_simul}. To build the posterior distribution of the IRFs, Dynare pulls parameter and shock values from the corresponding estimated distributions and, for each set of draws, generates an IRF. Repeating this process often enough generates a distribution of IRFs. \textsf{\textbf{TIP!}} If you stop the estimation procedure after calculating the posterior mode, or carry out maximum likelihood estimation, only the corresponding parameter estimates will be used to generate the IRFs. If you instead carry out a full Metropolis-Hastings estimation, on the other hand, the IRFs will use the parameters the posterior distributions, including the variance of the shocks. -\item All options available for stoch\_simul can simply be added to the above options, separated by commas. To view a list of these options, either see the \href{http://www.dynare.org/documentation-and-support/manual}{Reference Manual} or section \ref{sec:compute} of chapter \ref{ch:solbase}. -\item moments\_varendo: triggers the computation of the posterior distribution of the theoretical moments of the endogenous variables as in \texttt{stoch\_simul} (the posterior distribution of the variance decomposition is also included). ** will be implemented shortly - if not already - in Dynare version 4. -\item filtered\_vars: triggers the computation of the posterior distribution of filtered endogenous variables and shocks. See the note below on the difference between filtered and smoothed shocks. ** will be implemented shortly - if not already - in Dynare version 4. -\item smoother: triggers the computation of the posterior distribution of smoothed endogenous variables and shocks. Smoothed shocks are a reconstruction of the values of unobserved shocks over the sample, using all the information contained in the sample of observations. Filtered shocks, instead, are built only based on knowing past information. To calculate one period ahead prediction errors, for instance, you should use filtered, not smoothed variables. -\item forecast = INTEGER: computes the posterior distribution of a forecast on INTEGER periods after the end of the sample used in estimation. The corresponding graph includes one confidence interval describing uncertainty due to parameters and one confidence interval describing uncertainty due to parameters and future shocks. Note that Dynare cannot forecast out of the posterior mode. You need to run Metropolis-Hastings iterations before being able to run forecasts on an estimated model. Finally, running a forecast is very similar to an IRF, as in \texttt{bayesian\_irf}, except that the forecast does not begin at a steady state, but simply at the point corresponding to the last set of observations. The goal of undertaking a forecast is to see how the system returns to steady state from this starting point. Of course, as observation do not exist for all variables, those necessary are reconstructed by sampling out of the posterior distribution of parameters. Again, repeating this step often enough yields a posterior distribution of the forecast. ** will be implemented shortly - if not already - in Dynare version 4. -\end{enumerate} - -\textsf{\textbf{TIP!}} Before launching estimation it is a good idea to make sure that your model is correctly declared, that a steady state exists and that it can be simulated for at least one set of parameter values. You may therefore want to create a test version of your .mod file. In this test file, you would comment out or erase the commands related to estimation, remove the prior estimates for parameter values and replace them with actual parameter values in the preamble, remove any non-stationary variables from your model, add a \texttt{shocks} block, make sure you have \texttt{steady} and possibly \texttt{check} following the \texttt{initval} block if you do not have exact steady state values and run a simulation using \texttt{stoch\_simul} at the end of your .mod file. Details on model solution and simulation can be found in Chapter \ref{ch:solbase}. \\ - -Finally, coming back to our example, we could choose a standard option:\\ -\\ -\texttt{estimation(datafile=simuldataRBC,nobs=200,first\_obs=500,\\ -mh\_replic=2000,mh\_nblocks=2,mh\_drop=0.45,mh\_jscale=0.8,\\ -mode\_compute=4); }\\ - -This ends our description of the .mod file. - -\section{The complete .mod file} -To summarize and to get a complete perspective on our work so far, here is the complete .mod file for the estimation of our very basic model. You can find the corresponding file in the \textsl{models} folder under \textsl{UserGuide} in your installation of Dynare. The file is called \textsl{RBC\_Est.mod}.\\ -\\ -\texttt{var y c k i l y\_l w r z;\\ -varexo e;\\ -parameters beta psi delta alpha rho epsilon;\\ -\\ -model;\\ - (1/c) = beta*(1/c(+1))*(1+r(+1)-delta);\\ - psi*c/(1-l) = w;\\ - c+i = y;\\ - y = (k(-1)\textasciicircum alpha)*(exp(z)*l)\textasciicircum (1-alpha);\\ - w = y*((epsilon-1)/epsilon)*(1-alpha)/l;\\ - r = y*((epsilon-1)/epsilon)*alpha/k(-1);\\ - i = k-(1-delta)*k(-1);\\ - y\_l = y/l;\\ - z = rho*z(-1)+e;\\ -end;\\ -\\ -varobs y;\\ -\\ -initval;\\ - k = 9;\\ - c = 0.76;\\ - l = 0.3;\\ - w = 2.07;\\ - r = 0.03;\\ - z = 0; \\ - e = 0;\\ -end;\\ -\\ -estimated\_params;\\ -alpha, beta\_pdf, 0.35, 0.02; \\ -beta, beta\_pdf, 0.99, 0.002; \\ -delta, beta\_pdf, 0.025, 0.003;\\ -psi, gamma\_pdf, 1.75, 0.1;\\ -rho, beta\_pdf, 0.95, 0.05;\\ -epsilon, gamma\_pdf, 10, 0.5;\\ -stderr e, inv\_gamma\_pdf, 0.01, inf;\\ -end;\\ -\\ -estimation(datafile=simuldataRBC,nobs=200,first\_obs=500,\\ -mh\_replic=2000,mh\_nblocks=2,mh\_drop=0.45,mh\_jscale=0.8,\\ -mode\_compute=4); } -\\ - - -\section{Interpreting output} - -As in the case of model solution and simulation, Dynare returns both tabular and graphical output. On the basis of the options entered in the example .mod file above, Dynare will display the following results.\\ - -\subsection{Tabular results} -The first results to be displayed (and calculated from a chronological standpoint) are the steady state results. Note the dummy values of 1 for the non-stationary variables Y\_obs and P\_obs. These results are followed by the eigenvalues of the system, presented in the order in which the endogenous variables are declared at the beginning of the .mod file. The table of eigenvalues is completed with a statement about the Blanchard-Kahn condition being met - hopefully!\\ - -The next set of results are for the numerical iterations necessary to find the posterior mode, as explained in more details in Chapter \ref{ch:estadv}. The improvement from one iteration to the next reaches zero, Dynare give the value of the objective function (the posterior Kernel) at the mode and displays two important table summarizing results from posterior maximization.\\ - -The first table summarizes results for parameter values. It includes: prior means, posterior mode, standard deviation and t-stat of the mode (based on the assumption of a Normal, probably erroneous when undertaking Bayesian estimation, as opposed to standard maximum likelihood), as well as the prior distribution and standard deviation (pstdev). It is followed by a second table summarizing the same results for the shocks. It may be entirely possible that you get an infinite value for a standard deviation, this is simply the limit case of the inverse gamma distribution.\\ - -\subsection{Graphical results} -** corresponding graphs will be reproduced below.\\ - -The first figure comes up soon after launching Dynare as little computation is necessary to generate it. The figure returns a graphical representation of the priors for each parameter of interest. \\ - -The second set of figures displays ``MCMC univariate diagnostics'', where MCMC stands for Monte Carlo Markov Chains. This is the main source of feedback to gain confidence, or spot a problem, with results. Recall that Dynare completes several runs of Metropolis-Hastings simulations (as many as determined in the option \texttt{mh\_nblocks}, each time starting from a different initial value). If the results from one chain are sensible, and the optimizer did not get stuck in an odd area of the parameter subspace, two things should happen. First, results within any of the however many iterations of Metropolis-Hastings simulation should be similar. And second, results between the various chains should be close. This is the idea of what the MCMC diagnostics track. \\ - -More specifically, the red and blue lines on the charts represent specific measures of the parameter vectors both within and between chains. For the results to be sensible, these should be relatively constant (although there will always be some variation) and they should converge. Dynare reports three measures: ``interval'', being constructed from an 80\% confidence interval around the parameter mean, ``m2'', being a measure of the variance and ``m3'' based on third moments. In each case, Dynare reports both the within and the between chains measures. The figure entitled ``multivariate diagnostic'' presents results of the same nature, except that they reflect an aggregate measure based on the eigenvalues of the variance-covariance matrix of each parameter.\\ - -In our example above, you can tell that indeed, we obtain convergence and relative stability in all measures of the parameter moments. Note that the horizontal axis represents the number of Metropolis-Hastings iterations that have been undertaken, and the vertical axis the measure of the parameter moments, with the first, corresponding to the measure at the initial value of the Metropolis-Hastings iterations.\\ - -\textsf{\textbf{TIP!}} If the plotted moments are highly unstable or do not converge, you may have a problem of poor priors. It is advisable to redo the estimation with different priors. If you have trouble coming up with a new prior, try starting with a uniform and relatively wide prior and see where the data leads the posterior distribution. Another approach is to undertake a greater number of Metropolis-Hastings simulations.\\ - -The first to last figure - figure 6 in our example - displays the most interesting set of results, towards which most of the computations undertaken by Dynare are directed: the posterior distribution. In fact, the figure compares the posterior to the prior distribution (black vs. grey lines). In addition, on the posterior distribution, Dynare plots a green line which represents the posterior mode. These allow you to make statements about your data other than simply concerning the mean and variance of the parameters; you can also discuss the probability that your parameter is larger or smaller than a certain value.\\ - -\textsf{\textbf{TIP!}} These graphs are of course especially relevant and present key results, but they can also serve as tools to detect problems or build additional confidence in your results. First, the prior and the posterior distributions should not be excessively different. Second, the posterior distributions should be close to normal, or at least not display a shape that is clearly non-normal. Third, the green mode (calculated from the numerical optimization of the posterior kernel) should not be too far away from the mode of the posterior distribution. If not, it is advisable to undertake a greater number of Metropolis-Hastings simulations. \\ - -The last figure returns the smoothed estimated shocks in a useful illustration to eye-ball the plausibility of the size and frequency of the shocks. The horizontal axis, in this case, represents the number of periods in the sample. One thing to check is the fact that shocks should be centered around zero. That is indeed the case for our example. \\ - - -\begin{comment} -\section{Dealing with non-stationary models} -Many DSGE models will embody a source of non-stationarity. This adds a layer of complication to estimating these models. In Dynare, this involves stationarizing variables, as well as several new lines of instruction. Again, the example below will be as basic as possible, building on the example used above. But you can go through a more complex example in the advanced chapter on DSGE estimation (chapter \ref{ch:estadv}). \\ - -Below, we will introduce the non-stationarity with a stochastic trend in technology diffusion. But in order to linearize and solve the DSGE model - a necessary first step before estimating it - we must have a steady state. Thus, we must write the model using stationary variables. Our task will then be to link these stationary variables to the data which, according to the model, would be non-stationary. \textsf{\textbf{NOTE!}} But whatever the data, in Dynare, \textbf{the model must be made stationary}. \\ - -\subsection{The source of non-stationarity} - - - -\section{Specifying observable variable characteristics} -A natural extension of our discussion above is to declare, in Dynare, which variables are observable and which are non-stationary. This can be done just after the model block. - -\subsection{Declaring observable variables} -We begin by declaring which of our model's variables are observables. In our .mod file we write\\ -\\ -\texttt{varobs P\_obs Y\_obs;}\\ -\\ -to specify that our observable variables are indeed P\_obs and Y\_obs as noted in the section above. \textsf{\textbf{NOTE!}} The number of unobserved variables (number of \texttt{var} minus number of \texttt{varobs}) must be smaller or equal to the number of shocks such that the model be estimated. If this is not the case, you should add measurement shocks to your model where you deem most appropriate. \\ - -\subsection{Declaring trends in observable variables} - -Recall that we decided to work with the non-stationary observable variables in levels. Both output and prices exhibit stochastic trends. This can be seen explicitly by taking the difference of logs of output and prices to compute growth rates. In the case of output, we make use of the usual (by now!) relationship $Y_t=\widehat Y_t \cdot A_t$. Taking logs of both sides and subtracting the same equation scrolled back one period, we find: -\[ -\Delta \ln Y_t = \Delta \ln \widehat Y_t + \gamma + \epsilon_{A,t} -\] -emphasizing clearly the drift term $\gamma$, whereas we know $\Delta \ln \widehat Y_t$ is stationary in steady state. \\ - -In the case of prices, we apply the same manipulations to show that: -\[ -\Delta \ln P_t = \Delta \ln \widehat P_t + \ln m_{t-1} - \gamma - \epsilon_{A,t} -\] - -Note from the original equation of motion of $\ln m_t$ that in steady state, $\ln m_t=\ln m^*$, so that the drift terms in the above equation are $\ln m^* - \gamma$.\footnote{This can also be see from substituting for $\ln m_{t-1}$ in the above equation with the equation of motion of $\ln m_t$ to yield: $\Delta \ln P_t = \Delta \ln \widehat P_t + \ln m^* + \rho(\ln m_{t-2}-\ln m^*) + \epsilon_{M,t} - \gamma - \epsilon_{A,t}$ where all terms on the right hand side are constant, except for $\ln m^*$ and $\gamma$.} \\ - -In Dynare, any trends, whether deterministic or stochastic (the drift term) must be declared up front. In the case of our example, we therefore write (in a somewhat cumbersome manner)\\ -\\ -\texttt{observation\_trends;\\ -P\_obs (log(exp(gam)/mst));\\ -Y\_obs (gam);\\ -end;}\\ - -In general, the command \texttt{observation\_trends} specifies linear trends as a function of model parameters for the observed variables in the model.\\ - -\subsection{Declaring unit roots, if any, in observable variables} - -And finally, since P\_obs and Y\_obs inherit the unit root characteristics of their driving variables, technology and money, we must tell Dynare to use a diffuse prior (infinite variance) for their initialization in the Kalman filter. Note that for stationary variables, the unconditional covariance matrix of these variables is used for initialization. The algorithm to compute a true diffuse prior is taken from \citet{DurbinKoopman2001}. To give these instructions to Dynare, we write in the .mod\\ -\\ -\texttt{unit\_root\_vars = \{'P\_obs'; 'Y\_obs' \};}\\ -\\ -\textsf{\textbf{NOTE!}} You don't need to declare unit roots for any non-stationary model. Unit roots are only related to stochastic trends. You don't need to use a diffuse initial condition in the case of a deterministic trend, since the variance is finite.\\ - -\section{SS} - -UNIT ROOT SS: The only difference with regards to model estimation is the non-stationary nature of our observable variables. In this case, the declaration of the steady state must be slightly amended in Dynare. (** fill in with the new functionality from Dynare version 4, currently the answer is to write a separate Matlab file which solves the steady state for the stationary variables and returns dummies for the non stationary variables). - - - - \end{comment} - - - - - - - - diff --git a/doc/userguide/ch-estbeh.tex b/doc/userguide/ch-estbeh.tex deleted file mode 100644 index 1f8505a3c..000000000 --- a/doc/userguide/ch-estbeh.tex +++ /dev/null @@ -1,250 +0,0 @@ -\chapter{Estimating DSGE models - Behind the scenes of Dynare} \label{ch:estbeh} - -This chapter focuses on the theory of Bayesian estimation. It begins by motivating Bayesian estimation by suggesting some arguments in favor of it as opposed to other forms of model estimation. It then attempts to shed some light on what goes on in Dynare's machinery when it estimates DSGE models. To do so, this section surveys the methodologies adopted for Bayesian estimation, including defining what are prior and posterior distributions, using the Kalman filter to find the likelihood function, estimating the posterior function thanks to the Metropolis-Hastings algorithm, and comparing models based on posterior distributions. - - -\section{Advantages of Bayesian estimation} - -Bayesian estimation is becoming increasingly popular in the field of macro-economics. Recent papers have attracted significant attention; some of these include: \citet{Schorfheide2000} which uses Bayesian methods to compare the fit of two competing DSGE models of consumption, \citet{LubikSchorfheide2003} which investigates whether central banks in small open economies respond to exchange rate movements, \citet{SmetsWouters2003} which applies Bayesian estimation techniques to a model of the Eurozone, \citet{Ireland2004} which emphasizes instead maximum likelihood estimation, \citet{VillaverdeRubioRamirez2004} which reviews the econometric properties of Bayesian estimators and compare estimation results with maximum likelihood and BVAR methodologies, \citet{LubikSchorfheide2005} which applies Bayesian estimation methods to an open macro model focussing on issues of misspecification and identification, and finally \citet{RabanalRubioRamirez2005} which compares the fit, based on posterior distributions, of four competing specifications of New Keynesian monetary models with nominal rigidities.\\ - -There are a multitude of advantages of using Bayesian methods to estimate a model, but five of these stand out as particularly important and general enough to mention here.\\ - -First, Bayesian estimation fits the complete, solved DSGE model, as opposed to GMM estimation which is based on particular equilibrium relationships such as the Euler equation in consumption. Likewise, estimation in the Bayesian case is based on the likelihood generated by the DSGE system, rather than the more indirect discrepancy between the implied DSGE and VAR impulse response functions. Of course, if your model is entirely mis-specified, estimating it using Bayesian techniques could be a disadvantage.\\ - -Second, Bayesian techniques allow the consideration of priors which work as weights in the estimation process so that the posterior distribution avoids peaking at strange points where the likelihood peaks. Indeed, due to the stylized and often misspecified nature of DSGE models, the likelihood often peaks in regions of the parameter space that are contradictory with common observations, leading to the ``dilemma of absurd parameter estimates''.\\ - -Third, the inclusion of priors also helps identifying parameters. Unfortunately, when estimating a model, the problem of identification often arises. It can be summarized by different values of structural parameters leading to the same joint distribution for observables. More technically, the problem arises when the posterior distribution is flat over a subspace of parameter values. But the weighting of the likelihood with prior densities often leads to adding just enough curvature in the posterior distribution to facilitate numerical maximization.\\ - -Fourth, Bayesian estimation explicitly addresses model misspecification by including shocks, which can be interpreted as observation errors, in the structural equations.\\ - -Sixth, Bayesian estimation naturally leads to the comparison of models based on fit. Indeed, the posterior distribution corresponding to competing models can easily be used to determine which model best fits the data. This procedure, as other topics mentioned above, is discussed more technically in the subsection below. - - -\section{The basic mechanics of Bayesian estimation} -This and the following subsections are based in great part on work by, and discussions with, StŽphane Adjemian, a member of the Dynare development team. Some of this work, although summarized in presentation format, is available in the ``Events'' page of the \href{http://www.dynare.org/events/workshop-on-learning-and-monetary-policy}{Dynare website}. Other helpful material includes \citet{AnSchorfheide2006}, which includes a clear and quite complete introduction to Bayesian estimation, illustrated by the application of a simple DSGE model. Also, the appendix of \citet{Schorfheide2000} contains details as to the exact methodology and possible difficulties encountered in Bayesian estimation. You may also want to take a glance at \citet{Hamilton1994}, chapter 12, which provides a very clear, although somewhat outdated, introduction to the basic mechanics of Bayesian estimation. Finally, the websites of \href{http://www.econ.upenn.edu/~schorf/}{Frank Schorfheide} and \href{http://www.econ.upenn.edu/~jesusfv/index.html}{Jesus Fernandez-Villaverde} contain a wide variety of very helpful material, from example files to lecture notes to related papers. Finally, remember to also check the \href{http://www.dynare.org/documentation-and-support/examples}{open online examples} of the Dynare website for examples of .mod files touching on Bayesian estimation. \\ - -At its most basic level, Bayesian estimation is a bridge between calibration and maximum likelihood. The tradition of calibrating models is inherited through the specification of priors. And the maximum likelihood approach enters through the estimation process based on confronting the model with data. Together, priors can be seen as weights on the likelihood function in order to give more importance to certain areas of the parameter subspace. More technically, these two building blocks - priors and likelihood functions - are tied together by Bayes' rule. Let's see how. \\ - -First, priors are described by a density function of the form -\[ p(\boldsymbol\theta_{\mathcal A}|\mathcal A) \] where $\mathcal A$ stands for a specific model, $\boldsymbol\theta_{\mathcal A}$ represents the parameters of model $\mathcal A$, $p(\bullet)$ stands for a probability density function (pdf) such as a normal, gamma, shifted gamma, inverse gamma, beta, generalized beta, or uniform function. \\ - -Second, the likelihood function describes the density of the observed - data, given the model and its parameters: - \[ - {\mathcal L}(\boldsymbol\theta_{\mathcal A}|\mathbf Y_T,\mathcal A) \equiv p(\mathbf Y_T | \boldsymbol\theta_{\mathcal A}, \mathcal A) - \] - where $\mathbf Y_T$ are the observations until period - $T$, and where in our case the likelihood is recursive and can be written as: - \[ - p(\mathbf Y_T | \boldsymbol\theta_{\mathcal A}, \mathcal A) = - p(y_0|\boldsymbol\theta_{\mathcal A},\mathcal A)\prod^T_{t=1}p(y_t | \mathbf Y_{t-1},\boldsymbol\theta_{\mathcal A}, \mathcal A) - \] - -We now take a step back. Generally speaking, we have a prior density $p(\boldsymbol\theta)$ on the one hand, and on the other, a likelihood $p(\mathbf Y_T | \boldsymbol\theta)$. In the end, we are interested in $p(\boldsymbol\theta | \mathbf Y_T)$, the \textbf{posterior - density}. Using the \textbf{Bayes theorem} twice we obtain this density of parameters - knowing the data. Generally, we have - \[p(\boldsymbol\theta | \mathbf Y_T) = \frac{p(\boldsymbol\theta ; \mathbf Y_T) }{p(\mathbf Y_T)}\] - -We also know that - \[ - p(\mathbf Y_T |\boldsymbol\theta ) = \frac{p(\boldsymbol\theta ; \mathbf Y_T)}{p(\boldsymbol\theta)} - \Leftrightarrow p(\boldsymbol\theta ; \mathbf Y_T) = p(\mathbf Y_T |\boldsymbol\theta)\times - p(\boldsymbol\theta) - \] - -By using these identities, we can combine the \textbf{prior density} and the \textbf{likelihood function} discussed above to get the posterior density: - \[ - p(\boldsymbol\theta_{\mathcal A} | \mathbf Y_T, \mathcal A) = \frac{p(\mathbf Y_T |\boldsymbol\theta_{\mathcal A}, \mathcal A)p(\boldsymbol\theta_{\mathcal A}|\mathcal A)}{p(\mathbf Y_T|\mathcal A)} - \] -where $p(\mathbf Y_T|\mathcal A)$ is the \textbf{marginal density} of the data - conditional on the model: - \[ - p(\mathbf Y_T|\mathcal A) = \int_{\Theta_{\mathcal A}} p(\boldsymbol\theta_{\mathcal A} ; \mathbf Y_T - |\mathcal A) d\boldsymbol\theta_{\mathcal A} - \] - -Finally, the \textbf{posterior kernel} (or un-normalized posterior density, given that the marginal density above is a constant or equal for any parameter), corresponds to the numerator of the posterior density: - \[ - p(\boldsymbol\theta_{\mathcal A} | \mathbf Y_T, \mathcal A) \propto p(\mathbf Y_T |\boldsymbol\theta_{\mathcal A}, - \mathcal A)p(\boldsymbol\theta_{\mathcal A}|\mathcal A) \equiv \mathcal K(\boldsymbol\theta_{\mathcal A} | \mathbf Y_T, \mathcal A) - \] -This is the fundamental equation that will allow us to rebuild all posterior moments of interest. The trick will be to estimate the likelihood function with the help of the \textbf{Kalman filter} and then simulate the posterior kernel using a sampling-like or Monte Carlo method such as the \textbf{Metropolis-Hastings}. These topics are covered in more details below. Before moving on, though, the subsection below gives a simple example based on the above reasoning of what we mean when we say that Bayesian estimation is ``somewhere in between calibration and maximum likelihood estimation''. The example is drawn from \citet{Zellner1971}, although other similar examples can be found in \citet{Hamilton1994}, chapter 12.\\ - -\subsection{Bayesian estimation: somewhere between calibration and maximum likelihood estimation - an example} - -Suppose a data generating process $y_t = \mu + \varepsilon_t$ for $t=1,...,T$, where $\varepsilon_t \sim \mathcal{N}(0,1)$ is gaussian white noise. Then, the likelihood is given by - \[ - p(\mathbf{Y}_T|\mu) = - (2\pi)^{-\frac{T}{2}}e^{-\frac{1}{2}\sum_{t=1}^T(y_t-\mu)^2} - \] -We know from the above that $\widehat{\mu}_{ML,T} = \frac{1}{T}\sum_{t=1}^T y_t \equiv - \overline{y}$ and that $\mathbb{V}[\widehat{\mu}_{ML,T}] = \frac{1}{T}$. \\ - -In addition, let our prior be a gaussian distribution with expectation - $\mu_0$ and variance $\sigma_{\mu}^2$. Then, the posterior density is defined, up to a constant, by: - \[ - p\left(\mu|\mathbf{Y}_T\right) \propto - (2\pi\sigma_{\mu}^2)^{-\frac{1}{2}}e^{-\frac{1}{2}\frac{(\mu-\mu_0)^2}{\sigma_{\mu}^2}}\times(2\pi)^{-\frac{T}{2}}e^{-\frac{1}{2}\sum_{t=1}^T(y_t-\mu)^2} - \] -Or equivalently, $p\left(\mu|\mathbf{Y}_T\right) \propto - e^{-\frac{\left(\mu-\mathbb{E}[\mu]\right)^2}{\mathbb{V}[\mu]}}$, with - \[ - \mathbb{V}[\mu] = \frac{1}{\left(\frac{1}{T}\right)^{-1} + - \sigma_{\mu}^{-2}} - \] - and - \[ - \mathbb{E}[\mu] = - \frac{\left(\frac{1}{T}\right)^{-1}\widehat{\mu}_{ML,T} + - \sigma_{\mu}^{-2}\mu_0}{\left(\frac{1}{T}\right)^{-1} + - \sigma_{\mu}^{-2}} - \] - -From this, we can tell that the posterior mean is a convex combination of the prior mean and the ML estimate. In particular, if $\sigma_{\mu}^2 \rightarrow \infty$ (ie, we have no prior information, so we just estimate the model) then $\mathbb{E}[\mu] \rightarrow \widehat{\mu}_{ML,T}$, the maximum likelihood estimator. But if $\sigma_{\mu}^2 \rightarrow 0$ (ie, we're sure of ourselves and we calibrate the parameter of interest, thus leaving no room for estimation) then $\mathbb{E}[\mu] \rightarrow \mu_0$, the prior mean. Most of the time, we're somewhere in the middle of these two extremes. - - -\section{DSGE models and Bayesian estimation} -\subsection{Rewriting the solution to the DSGE model} -Recall from chapter \ref{ch:solbeh} that any DSGE model, which is really a collection of first order and equilibrium conditions, can be written in the form $\mathbb{E}_t\left\{f(y_{t+1},y_t,y_{t-1},u_t)\right\}=0$, taking as a solution equations of the type $y_t = g(y_{t-1},u_t)$, which we call the decision rule. In more appropriate terms for what follows, we can rewrite the solution to a DSGE model as a system in the following manner: - \begin{eqnarray*} - y^*_t &=& M\bar y(\theta)+M\hat y_t+N(\theta)x_t+\eta_t\\ -\hat y_t &=& g_y(\theta)\hat y_{t-1}+g_u(\theta)u_t\\ -E(\eta_t \eta_t') &=& V(\theta)\\ -E(u_t u_t') &=& Q(\theta) - \end{eqnarray*} -where $\hat y_t$ are variables in deviations from steady state, $\bar y$ is the vector of steady state values and $\theta$ the vector of deep (or structural) parameters to be estimated. Other variables are described below.\\ - -The second equation is the familiar decision rule mentioned above. But the equation expresses a relationship among true endogenous variables that are not directly observed. Only $y^*_t$ is observable, and it is related to the true variables with an error $\eta_t$. Furthermore, it may have a trend, which is captured with $N(\theta)x_t$ to allow for the most general case in which the trend depends on the deep parameters. The first and second equations above therefore naturally make up a system of measurement and transition or state equations, respectively, as is typical for a Kalman filter (you guessed it, it's not a coincidence!). \\ - -\subsection{Estimating the likelihood function of the DSGE model} -The next logical step is to estimate the likelihood of the DSGE solution system mentioned above. The first apparent problem, though, is that the equations are non linear in the deep parameters. Yet, they are linear in the endogenous and exogenous variables so that the likelihood may be evaluated with a linear prediction error algorithm like the Kalman filter. This is exactly what Dynare does. As a reminder, here's what the Kalman filter recursion does.\\ - -For $t=1,\ldots,T$ and with initial values $y_1$ and $P_1$ given, the recursion follows -\begin{eqnarray*} - v_t &=& y^*_t - \bar y^* - M\hat y_t - Nx_t\\ - F_t &=& M P_t M'+V\\ - K_t &=& g_yP_tg_y'F_t^{-1}\\ - \hat y_{t+1} &=& g_y \hat y_t+K_tv_t\\ - P_{t+1} &=& g_y P_t (g_y-K_tM)'+g_uQg_u' -\end{eqnarray*} -For more details on the Kalman filter, see \citet{Hamilton1994}, chapter 13. \\ - -From the Kalman filter recursion, it is possible to derive the \textbf{log-likelihood} given by -\[ -\ln \mathcal{L}\left(\boldsymbol\theta|\mathbf Y^*_T\right) = -\frac{Tk}{2}\ln(2\pi)-\frac{1}{2}\sum_{t=1}^T|F_t|-\frac{1}{2}v_t'F_t^{-1}v_t -\] -where the vector $\boldsymbol\theta$ contains the parameters we have to estimate: $\theta$, $V(\theta)$ and $Q(\theta)$ and where $Y^*_T$ expresses the set of observable endogenous variables $y^*_t$ found in the measurement equation. \\ - -The log-likelihood above gets us one step closer to our goal of finding the posterior distribution of our parameters. Indeed, the \textbf{log posterior kernel} can be expressed as -\[ -\ln \mathcal{K}(\boldsymbol\theta|\mathbf Y^*_T) = \ln \mathcal{L}\left(\boldsymbol\theta|\mathbf Y^*_T\right) + \ln p(\boldsymbol\theta) -\] -where the first term on the right hand side is now known after carrying out the Kalman filter recursion. The second, recall, are the priors, and are also known. \\ - -\subsection{Finding the mode of the posterior distribution} -Next, to find the mode of the posterior distribution - a key parameter and an important output of Dynare - we simply maximize the above log posterior kernel with respect to $\theta$. This is done in Dynare using numerical methods. Recall that the likelihood function is not Gaussian with respect to $\theta$ but to functions of $\theta$ as they appear in the state equation. Thus, this maximization problem is not completely straightforward, but fortunately doable with modern computers. \\ - -\subsection{Estimating the posterior distribution} -Finally, we are now in a position to find the posterior distribution of our parameters. The distribution will be given by the kernel equation above, but again, it is a nonlinear and complicated function of the deep parameters $\theta$. Thus, we cannot obtain an explicit form for it. We resort, instead, to sampling-like methods, of which the Metropolis-Hastings has been retained in the literature as particularly efficient. This is indeed the method adopted by Dynare.\\ - -The general idea of the Metropolis-Hastings algorithm is to simulate the posterior distribution. It is a ``rejection sampling algorithm'' used to generate a sequence of samples (also known as a ``Markov Chain'' for reasons that will become apparent later) from a distribution that is unknown at the outset. Remember that all we have is the posterior mode; we are instead more often interested in the mean and variance of the estimators of $\theta$. To do so, the algorithm builds on the fact that under general conditions the distribution of the deep parameters will be asymptotically normal. The algorithm, in the words of An and Shorfheide, ``constructs a Gaussian approximation around the posterior mode and uses a scaled version of the asymptotic covariance matrix as the covariance matrix for the proposal distribution. This allows for an efficient exploration of the posterior distribution at least in the neighborhood of the mode'' (\citet{AnSchorfheide2006}, p. 18). More precisely, the \textbf{Metropolis-Hastings algorithm implements the following steps}: -\begin{enumerate} - \item Choose a starting point $\boldsymbol\theta^\circ$, where this is typically the posterior mode, and run a loop over - 2-3-4. - \item Draw a \emph{proposal} $\boldsymbol\theta^*$ from a \emph{jumping} distribution - \[ - J(\boldsymbol\theta^*|\boldsymbol\theta^{t-1}) = - \mathcal N(\boldsymbol\theta^{t-1},c\Sigma_{m}) - \] - where $\Sigma_{m}$ is the inverse of the Hessian computed at the posterior mode. - \item Compute the acceptance ratio - \[ - r = \frac{p(\boldsymbol\theta^*|\mathbf Y_T)}{p(\boldsymbol\theta^{t-1}|\mathbf - Y_T)} = \frac{\mathcal K(\boldsymbol\theta^*|\mathbf Y_T)}{\mathcal K(\boldsymbol\theta^{t-1}|\mathbf - Y_T)} - \] - \item Finally accept or discard the proposal $\boldsymbol\theta^*$ according to the following rule, and update, if necessary, the jumping distribution: - \[ - \boldsymbol\theta^t = \left\{ - \begin{array}{ll} - \boldsymbol\theta^* & \mbox{ with probability $\min(r,1)$}\\ - \boldsymbol\theta^{t-1} & \mbox{ otherwise.} - \end{array}\right. - \] - \end{enumerate} - -Figure \ref{fig:MH} tries to clarify the above. In step 1, choose a candidate paramter, $\theta^*$ from a Normal distribution, whose mean has been set to $\theta^{t-1}$ (this will become clear in just a moment). In step 2, compute the value of the posterior kernel for that candidate parameter, and compare it to the value of the kernel from the mean of the drawing distribution. In step 3, decide whether or not to hold on to your candidate parameter. If the acceptance ratio is greater than one, then definitely keep your candidate. Otherwise, go back to the candidate of last period (this is true in very coarse terms, notice that in fact you would keep your candidate only with a probability less than one). Then, do two things. Update the mean of your drawing distribution, and note the value of the parameter your retain. After having repeated these steps often enough, in the final step, build a histogram of those retained values. Of course, the point is for each ``bucket'' of the histogram to shrink to zero. This ``smoothed histogram'' will eventually be the posterior distribution after sufficient iterations of the above steps.\\ -\begin{figure} \label{fig:MH} -\begin{center} -\includegraphics[width=1.0\textwidth]{P_MH2} -\end{center} -\caption[Illustration of the Metropolis-Hastings algorithm]{The above sketches the Metropolis-Hastings algorithm, used to build the posterior distribution function. Imagine repeating these steps a large number of times, and smoothing the ``histogram'' such that each ``bucket'' has infinitely small width.} -\end{figure} - -But why have such a complicated acceptance rule? The point is to be able to visit the entire domain of the posterior distribution. We should not be too quick to simply throw out the candidate giving a lower value of the posterior kernel, just in case using that candidate for the mean of the drawing distribution allows us to to leave a local maximum and travel towards the global maximum. Metaphorically, the idea is to allow the search to turn away from taking a small step up, and instead take a few small steps down in the hope of being able to take a big step up in the near future. Of course, an important parameter in this searching procedure is the variance of the jumping distribution and in particular the \textbf{scale factor}. If the scale factor is too small, the \textbf{acceptance rate} (the fraction of candidate parameters that are accepted in a window of time) will be too high and the Markov Chain of candidate parameters will ``mix slowly'', meaning that the distribution will take a long time to converge to the posterior distribution since the chain is likely to get ``stuck'' around a local maximum. On the other hand, if the scale factor is too large, the acceptance rate will be very low (as the candidates are likely to land in regions of low probability density) and the chain will spend too much time in the tails of the posterior distribution. \\ - -While these steps are mathematically clear, at least to a machine needing to undertake the above calculations, several practical questions arise when carrying out Bayesian estimation. These include: How should we choose the scale factor $c$ (variance of the jumping - distribution)? What is a satisfactory acceptance rate? How many draws are ideal? How is convergence of the Metropolis-Hastings iterations assessed? These are all important questions that will come up in your usage of Dynare. They are addressed as clearly as possible in section \ref{sec:estimate} of Chapter \ref{ch:estbase}. \\ - -\section{Comparing models using posterior distributions} -As mentioned earlier, while touting the advantages of Bayesian estimation, the posterior distribution offers a particularly natural method of comparing models. Let's look at an illustration. \\ - -Suppose we have a prior distribution over two competing models: $p(\mathcal{A})$ and $p(\mathcal{B})$. Using Bayes' rule, we can compute the posterior - distribution over models, where $\mathcal{I}=\mathcal{A},\mathcal{B}$ - \[ - p(\mathcal{I}|\mathbf Y_T) = \frac{p(\mathcal{I})p(\mathbf Y_T|\mathcal{I})} - {\sum_{\mathcal{I}=\mathcal{A},\mathcal{B}}p(\mathcal{I})p(\mathbf Y_T|\mathcal{I})} - \] -where this formula may easily be generalized to a collection of $N$ models. - -Then, the comparison of the two models is done very naturally through the ratio of the posterior model distributions. We call this the \textbf{posterior odds ratio}: - \[ - \frac{p(\mathcal{A}|\mathbf Y_T)}{p(\mathcal{B}|\mathbf - Y_T)} = \frac{p(\mathcal{A})}{p(\mathcal{B})} - \frac{p(\mathbf Y_T|\mathcal{A})}{p(\mathbf Y_T|\mathcal{B})} - \] - -The only complication is finding the magrinal density of the data conditional on the model, $p(\mathbf Y_T|\mathcal{I})$, which is also the denominator of the posterior density $p(\boldsymbol\theta | \mathbf Y_T)$ discussed earlier. This requires some detailed explanations of their own. \\ - -For each model $\mathcal{I}=\mathcal{A},\mathcal{B}$ we can evaluate, at least theoretically, the marginal - density of the data conditional on the model by integrating out the deep parameters $\boldsymbol\theta_{\mathcal{I}}$ from the posterior kernel: - \[ - p(\mathbf Y_T|\mathcal{I}) = \int_{\Theta_{\mathcal{I}}} p(\boldsymbol\theta_{\mathcal{I}}; \mathbf Y_T - |\boldsymbol\theta_{\mathcal{I}},\mathcal{I}) d\boldsymbol\theta_{\mathcal{I}} = \int_{\Theta_{\mathcal{I}}} p(\boldsymbol\theta_{\mathcal{I}}|\mathcal{I})\times p(\mathbf Y_T - |\boldsymbol\theta_{\mathcal{I}},\mathcal{I}) d\boldsymbol\theta_{\mathcal{I}} - \] -Note that the expression inside the integral sign is exactly the posterior kernel. To remind you of this, you may want to glance back at the first subsection above, specifying the basic mechanics of Bayesian estimation.\\ - - To obtain the marginal density of the data conditional on the model, there are two options. The first is to assume a functional form of the posterior kernel that we can integrate. The most straightforward and the best approximation, especially for large samples, is the Gaussian (called a \textbf{Laplace approximation}). In this case, we would have the following estimator: -\[ -\widehat{p}(\mathbf Y_T|\mathcal I) = (2\pi)^{\frac{k}{2}}|\Sigma_{\boldsymbol\theta^m_{\mathcal I}}|^{\frac{1}{2}}p(\boldsymbol\theta_{\mathcal I}^m|\mathbf -Y_T,\mathcal I)p(\boldsymbol\theta_{\mathcal I}^m|\mathcal I) -\] -where $\boldsymbol\theta_{\mathcal I}^m$ is the posterior mode. The advantage of this technique is its computational efficiency: time consuming Metropolis-Hastings iterations are not necessary, only the numerically calculated posterior mode is required. \\ - -The second option is instead to use information from the Metropolis-Hastings runs and is typically referred to as the \textbf{Harmonic Mean Estimator}. The idea is to simulate the marginal density of interest and to simply take an average of these simulated values. To start, note that -\[ -p(\mathbf{Y}_T|\mathcal I)=\mathbb{E}\left[\frac{f(\boldsymbol\theta_{\mathcal I})}{p(\boldsymbol\theta_{\mathcal I}|\mathcal I) - p(\mathbf{Y}_T|\boldsymbol\theta_{\mathcal I},\mathcal I)}\biggl|\boldsymbol\theta_{\mathcal I},\mathcal I\biggr.\right]^{-1} -\] -where $f$ is a probability density function, since -\[ - \mathbb{E}\left[\frac{f(\boldsymbol\theta_{\mathcal I})}{p(\boldsymbol\theta_{\mathcal I}|\mathcal I) - p(\mathbf{Y}_T|\boldsymbol\theta_{\mathcal I},\mathcal I)}\biggl|\boldsymbol\theta_{\mathcal I},\mathcal I\biggr.\right] - = - \frac{\int_{\Theta_{\mathcal I}}f(\boldsymbol\theta)d\boldsymbol\theta}{\int_{\Theta_{\mathcal I}}p(\boldsymbol\theta_{\mathcal I}|I) - p(\mathbf{Y}_T|\boldsymbol\theta_{\mathcal I},\mathcal I)d\boldsymbol\theta_{\mathcal I}} -\] -and the numerator integrates out to one (see\citet{Geweke1999} for more details). \\ - -This suggests the following estimator of the marginal - density - \[ - \widehat{p}(\mathbf{Y}_T|\mathcal I)= \left[\frac{1}{B}\sum_{b=1}^B - \frac{f(\boldsymbol\theta_{\mathcal I}^{(b)})}{p(\boldsymbol\theta_{\mathcal I}^{(b)}|\mathcal I) - p(\mathbf{Y}_T|\boldsymbol\theta_{\mathcal I}^{(b)},\mathcal I)}\right]^{-1} - \] -where each drawn vector $\boldsymbol\theta_{\mathcal I}^{(b)}$ comes from the - Metropolis-Hastings iterations and where the probability density function $f$ can be viewed as a weights on the posterior kernel in order to downplay the importance of extreme values of $\boldsymbol\theta$. \citet{Geweke1999} suggests to use a truncated Gaussian function, leading to what is typically referred to as the \textbf{Modified Harmonic Mean Estimator}. \\ - - diff --git a/doc/userguide/ch-inst.tex b/doc/userguide/ch-inst.tex deleted file mode 100644 index 9bdd085e4..000000000 --- a/doc/userguide/ch-inst.tex +++ /dev/null @@ -1,24 +0,0 @@ -\chapter{Installing Dynare} \label{ch:inst} - -\section{Dynare versions} - -Dynare runs on both \href{http://www.mathworks.com/products/matlab/}{\textbf{MATLAB}} and \href{http://www.octave.org}{\textbf{GNU Octave}}. - -There used to be versions of Dynare for \textbf{Scilab} and \textbf{Gauss}. Development of the Scilab version stopped after Dynare version 3.02 and that for Gauss after Dynare version 1.2. - -This User Guide will exclusively \textbf{focus on Dynare version 4.0 and later}. - -You may also be interested by another program, \textbf{Dynare++}, which is a standalone C++ program specialized in computing k-order approximations of dynamic stochastic general equilibrium models. Note that Dynare++ is distributed along with Dynare since version 4.1. See the \href{http://www.dynare.org/documentation-and-support/dynarepp}{Dynare++ webpage} for more information. - -\section{System requirements} -Dynare can run on Microsoft Windows, as well as Unix-like operating systems, in particular GNU/Linux and Mac OS X. If you have questions about the support of a particular platform, please ask your question on \href{http://www.dynare.org/phpBB3}{\textbf{Dynare forums}}. - -To run Dynare, it is recommended to allocate at least 256MB of RAM to the platform running Dynare, although 512MB is preferred. Depending on the type of computations required, like the very processor intensive Metropolis Hastings algorithm, you may need up to 1GB of RAM to obtain acceptable computational times. - -\section{Installing Dynare} - -Please refer to the section entitled ``Installation and configuration'' in the \href{http://www.dynare.org/documentation-and-support/manual}{Dynare reference manual}. - -\section{MATLAB particularities} - -A question often comes up: what special MATLAB toolboxes are necessary to run Dynare? In fact, no additional toolbox is necessary for running most of Dynare, except maybe for optimal simple rules (see chapter \ref{ch:ramsey}), but even then remedies exist (see the \href{http://www.dynare.org/phpBB3}{Dynare forums} for discussions on this, or to ask your particular question). But if you do have the `optimization toolbox' installed, you will have additional options for solving for the steady state (solve\_algo option) and for searching for the posterior mode (mode\_compute option), both of which are defined later. diff --git a/doc/userguide/ch-intro.tex b/doc/userguide/ch-intro.tex deleted file mode 100644 index 37ab3212f..000000000 --- a/doc/userguide/ch-intro.tex +++ /dev/null @@ -1,86 +0,0 @@ -\chapter{Introduction} \label{ch:intro} - -Welcome to Dynare! \\ - -\section{About this Guide - approach and structure} -This User Guide \textbf{aims to help you master Dynare}'s main functionalities, from getting started to implementing advanced features. To do so, this Guide is structured around examples and offers practical advice. To root this understanding more deeply, though, this Guide also gives some background on Dynare's algorithms, methodologies and underlying theory. Thus, a secondary function of this Guide is to \textbf{serve as a basic primer} on DSGE model solving and Bayesian estimation. \\ - -This Guide will focus on the most common or useful features of the program, thus emphasizing \textbf{depth over breadth}. The idea is to get you to use 90\% of the program well and then tell you where else to look if you're interested in fine tuning or advanced customization.\\ - -This Guide is written mainly for an \textbf{advanced economist} - like a professor, graduate student or central banker - needing a powerful and flexible program to support and facilitate his or her research activities in a variety of fields. The sophisticated computer programmer, on the one hand, or the specialist of computational economics, on the other, may not find this Guide sufficiently detailed. \\ - -We recognize that the ``advanced economist'' may be either a beginning or intermediate user of Dynare. This Guide is written to accommodate both. If you're \textbf{new to Dynare}, we recommend starting with chapters \ref{ch:solbase} and \ref{ch:estbase}, which introduce the program's basic features to solve (including running impulse response functions) and estimate DSGE models, respectively. To do so, these chapters lead you through a complete hands-on example, which we recommend following from A to Z, in order to ``\textbf{learn by doing}''. Once you have read these two chapters, you will know the crux of Dynare's functionality and (hopefully!) feel comfortable using Dynare for your own work. At that point, though, you will probably find yourself coming back to the User Guide to skim over some of the content in the advanced chapters to iron out details and potential complications you may run into.\\ - -If you're instead an \textbf{intermediate user} of Dynare, you will most likely find the advanced chapters, \ref{ch:soladv} and \ref{ch:estadv}, more appropriate. These chapters cover more advanced features of Dynare and more complicated usage scenarios. The presumption is that you would skip around these chapters to focus on the topics most applicable to your needs and curiosity. Examples are therefore more concise and specific to each feature; these chapters read a bit more like a reference manual.\\ - -We also recognize that you probably have had repeated if not active exposure to programming and are likely to have a strong economic background. Thus, a black box solution to your needs is inadequate. To hopefully address this issue, the User Guide goes into some depth in covering the \textbf{theoretical underpinnings and methodologies that Dynare follows} to solve and estimate DSGE models. These are available in the ``behind the scenes of Dynare'' chapters \ref{ch:solbeh} and \ref{ch:estbeh}. These chapters can also serve as a \textbf{basic primer} if you are new to the practice of DSGE model solving and Bayesian estimation. \\ - -Finally, besides breaking up content into short chapters, we've introduced two different \textbf{markers} throughout the Guide to help streamline your reading. -\begin{itemize} -\item \textbf{\textsf{TIP!}} introduces advice to help you work more efficiently with Dynare or solve common problems. -\item \textbf{\textsf{NOTE!}} is used to draw your attention to particularly important information you should keep in mind when using Dynare. -\end{itemize} - - -\section{What is Dynare?} -Before we dive into the thick of the ``trees'', let's have a look at the ``forest'' from the top \ldots just what is Dynare? \\ - -\textbf{Dynare is a powerful and highly customizable engine, with an intuitive front-end interface, to solve, simulate and estimate DSGE models}. \\ - -In slightly less flowery words, it is a pre-processor and a collection of Matlab routines that has the great advantages of reading DSGE model equations written almost as in an academic paper. This not only facilitates the inputting of a model, but also enables you to easily share your code as it is straightforward to read by anyone.\\ -\begin{figure} \label{fig:dyn} -\begin{center} -\includegraphics[width=1.0\textwidth]{P_DynareStruct2} -\end{center} -\caption[Dynare, a bird's eyeview]{The .mod file being read by the Dynare pre-processor, which then calls the relevant Matlab routines to carry out the desired operations and display the results.} -\end{figure} - -Figure \ref{fig:dyn} gives you an overview of the way Dynare works. Basically, the model and its related attributes, like a shock structure for instance, is written equation by equation in an editor of your choice. The resulting file will be called the .mod file. That file is then called from Matlab. This initiates the Dynare pre-processor which translates the .mod file into a suitable input for the Matlab routines (more precisely, it creates intermediary Matlab or C files which are then used by Matlab code) used to either solve or estimate the model. Finally, results are presented in Matlab. Some more details on the internal files generated by Dynare is given in section \ref{sec:dynfiles} in chapter \ref{ch:soladv}. \\ - -Each of these steps will become clear as you read through the User Guide, but for now it may be helpful to summarize \textbf{what Dynare is able to do}: -\begin{itemize} -\item compute the steady state of a model -\item compute the solution of deterministic models -\item compute the first and second order approximation to solutions of stochastic models -\item estimate parameters of DSGE models using either a maximum likelihood or a Bayesian approach -\item compute optimal policies in linear-quadratic models -\end{itemize} - - -\section{Additional sources of help} -While this User Guide tries to be as complete and thorough as possible, you will certainly want to browse other material for help, as you learn about new features, struggle with adapting examples to your own work, and yearn to ask that one question whose answer seems to exist no-where. At your disposal, you have the following additional sources of help: -\begin{itemize} -\item \href{http://www.dynare.org/documentation-and-support/manual}{\textbf{Reference Manual}}: this manual covers all Dynare commands, giving a clear definition and explanation of usage for each. The User Guide will often introduce you to a command in a rather loose manner (mainly through examples); so reading corresponding command descriptions in the Reference Manual is a good idea to cover all relevant details. -\item \href{http://www.dynare.org/documentation-and-support/examples}{\textbf{Official online examples}}: the Dynare website includes other examples - usually well documented - of .mod files covering models and methodologies introduced in recent papers. -\item \href{http://www.dynare.org/phpBB3}{\textbf{Dynare forums}}: this lively online discussion forum allows you to ask your questions openly and read threads from others who might have run into similar difficulties. -\item \href{http://www.dynare.org/documentation-and-support/faq}{\textbf{Frequently Asked Questions}} (FAQ): this section of the Dynare site emphasizes a few of the most popular questions in the forums. -\item \href{http://www.dsge.net}{\textbf{DSGE.net}}: this website, run my members of the Dynare team, is a resource for all scholars working in the field of DSGE modeling. Besides allowing you to stay up to date with the most recent papers and possibly make new contacts, it conveniently lists conferences, workshops and seminars that may be of interest. -\end{itemize} - -\section{Nomenclature} -To end this introduction and avoid confusion in what follows, it is worthwhile to agree on a few \textbf{definitions of terms}. Many of these are shared with the Reference Manual. -\begin{itemize} -\item \textbf{Integer} indicates an integer number. -\item \textbf{Double} indicates a double precision number. The following syntaxes are valid: 1.1e3, 1.1E3, 1.1E-3, 1.1d3, 1.1D3 -\item \textbf{Expression} indicates a mathematical expression valid in the underlying language (e.g. Matlab). -\item \textbf{Variable name} indicates a variable name. \textbf{\textsf{NOTE!}} These must start with an alphabetical character and can only contain other alphabetical characters and digits, as well as underscores (\_). All other characters, including accents, and \textbf{spaces}, are forbidden. -\item \textbf{Parameter name} indicates a parameter name which must follow the same naming conventions as above. -\item \textbf{Filename} indicates a file name valid in your operating system. Note that Matlab requires that names of files or functions start with alphabetical characters; this concerns your Dynare .mod files. -\item \textbf{Command} is an instruction to Dynare or other program when specified. -\item \textbf{Options} or optional arguments for a command are listed in square brackets \mbox{[ ]} unless otherwise noted. If, for instance, the option must be specified in parenthesis in Dynare, it will show up in the Guide as [(option)]. -\item \textbf{\texttt{Typewritten text}} indicates text as it should appear in Dynare code. -\end{itemize} - -\section{v4, what's new and backward compatibility} -The current version of Dynare - for which this guide is written - is version 4. With respect to version 3, this new version introduces several important features, as well as improvements, optimizations of routines and bug fixes. The major new features are the following: -\begin{itemize} -\item Analytical derivatives are now used everywhere (for instance, in the Newton algorithm for deterministic models and in the linearizations necessary to solve stochastic models). This increases computational speed significantly. The drawback is that Dynare can now handle only a limited set of functions, although in nearly all economic applications this should not be a constraint. -\item Variables and parameters are now kept in the order in which they are declared whenever displayed and when used internally by Dynare. Recall that in version 3, variables and parameters where at times in their order of declaration and at times in alphabetical order. \textbf{\textsf{NOTE!}} This may cause some problems of backward compatibility if you wrote programs to run off Dynare v3 output. -\item The names of many internal variables and the organization of output variables has changed. These are enumerated in details in the relevant chapters. The names of the files internally generated by Dynare have also changed. (** more on this when explaining internal file structure - TBD) -\item The syntax for the external steady state file has changed. This is covered in more details in chapter \ref{ch:solbase}, in section \ref{sec:findsteady}. \textbf{\textsf{NOTE!}} You will unfortunately have to slightly amend any old steady state files you may have written. -\item Speed. Several large-scale improvements have been implemented to speed up Dynare. This should be most noticeable when solving deterministic models, but also apparent in other functionality. -\end{itemize} - - - - diff --git a/doc/userguide/ch-ramsey.tex b/doc/userguide/ch-ramsey.tex deleted file mode 100644 index 6a1ff1a10..000000000 --- a/doc/userguide/ch-ramsey.tex +++ /dev/null @@ -1 +0,0 @@ -\chapter{Optimal policy under commitment} \label{ch:ramsey} \ No newline at end of file diff --git a/doc/userguide/ch-soladv.tex b/doc/userguide/ch-soladv.tex deleted file mode 100644 index efed6aa83..000000000 --- a/doc/userguide/ch-soladv.tex +++ /dev/null @@ -1,266 +0,0 @@ -\chapter{Solving DSGE models - advanced topics} \label{ch:soladv} - -This chapter is a collection of topics - not all related to each other - that you will probably find interesting or at least understandable, if you have read, and/ or feel comfortable with, the earlier chapter \ref{ch:solbase} on the basics of solving DSGE models. To provide at least some consistency, this chapter is divided into three sections. \textbf{The first section} deals directly with features of Dynare, such as dealing with correlated shocks, finding and saving your output, using loops, referring to external files and dealing with infinite eigenvalues. \textbf{The second section} overviews some of the inner workings of Dynare. The goal is to provide a brief explanation of the files that are created by Dynare to help you in troubleshooting or provide a starting point in case you actually want to customize the way Dynare works. \textbf{The third section} of the chapter focusses on modeling tips optimized for Dynare, but possibly also helpful for other work.\\ - -\section{Dynare features and functionality} - -\subsection{Other examples} -Other examples of .mod files used to generate impulse response functions are available on the Dynare website. In particular, Jesus Fernandez-Villaverde has provided a series of RBC model variants (from the most basic to some including variable capacity utilization, indivisible labor and investment specific technological change). You can find these, along with helpful notes and explanations, in the \href{http://www.dynare.org/documentation-and-support/examples}{Official Examples} section of the Dynare website.\\ - -Also, don't forget to check occasionally the \href{http://www.dynare.org/phpBB3}{Dynare contributions and examples forum} to see if any other user has posted an example that could help you in your work; or maybe you would like to post an example there yourself? - -\subsection{Alternative, complete example} -The following example aims to give you an alternative example to the one in chapter \ref{ch:solbase}, to learn the workings of Dynare. It also aims to give you exposure to dealing with \textbf{several correlated shocks}. Your model may have two or more shocks, and these may be correlated to each other. The example below illustrates how you would introduce this into Dynare. Actually, the example provided is somewhat more complete than strictly necessary. This is to give you an alternative, full-blown example to the one described in chapter \ref{ch:solbase}. - -\subsubsection{The model} -The model is a simplified standard RBC model taken from \citet{CollardJuillard2003} which served as the original User Guide for Dynare. \\ - -The economy consists of an infinitely living representative agent who values consumption $c_t$ and labor services $h_t$ according to the following utility function -\[ -\mathbb{E}_t \sum_{\tau=t}^\infty \beta^{\tau-t} \left( \log (c_t) - \theta \frac{h_t^{1+\psi}}{1+\psi} \right) -\] -where, as usual, the discount factor $0<\beta<1$, the disutility of labor $\theta > 0$ and the labor supply elasticity $\psi \geq 0$. \\ - -A social planner maximizes this utility function subject to the resource constraint -\[ -c_t + i_t = y_t -\] -where $i_t$ is investment and $y_t$ output. Consumers are therefore also owners of the firms. The economy is a real economy, where part of output can be consumed and part invested to form physical capital. As is standard, the law of motion of capital is given by -\[ -k_{t+1} = \exp (b_t)i_t + (1-\delta)k_t -\] -with $0<\delta<1$, where $\delta$ is physical depreciation and $b_t$ a shock affecting incorporated technological progress. \\ - -We assume output is produced according to a standard constant returns to scale technology of the form -\[ -y_t = \exp (a_t)k_t^\alpha h_t^{1-\alpha} -\] -with $\alpha$ being the capital elasticity in the production function, with $0<\alpha<1$, and where $a_t$ represents a stochastic technological shock (or Solow residual). \\ - -Finally, we specify a \textbf{shock structure} that allows for shocks to display persistence across time and correlation in the current period. That is -\[ -\left( \begin{array}{c}a_t \\ -b_t \end{array} \right) = \left( \begin{array}{c c} \rho & \tau \\ -\tau & \rho \end{array} \right) \left( \begin{array}{c}a_{t-1} \\ -b_{t-1} \end{array} \right) + \left( \begin{array}{c}\epsilon_t \\ -\nu_t \end{array} \right) -\] -where $|\rho + \tau|<1$ and $|\rho - \tau|<1$ to ensure stationarity (we call $\rho$ the coefficient of persistence and $\tau$ that of cross-persistence). Furthermore, we assume $\mathbb{E}_t (\epsilon_t)=0$, $\mathbb{E}_t (\nu_t)=0$ and that the contemporaneous variance-covariance matrix of the innovations $\epsilon_t$ and $\nu_t$ is given by -\[ -\left( \begin{array}{c c} \sigma_\epsilon^2 & \psi \sigma_\epsilon \sigma_\nu \\ -\psi \sigma_\epsilon \sigma_\nu & \sigma_\nu^2 \end{array} \right) -\] -and where $corr(\epsilon_t \nu_s)=0$, $corr(\epsilon_t \epsilon_s)=0$ and $corr(\nu_t \nu_s)=0$ for all $t \neq s$. \\ - -This system - probably quite similar to standard RBC models you have run into - yields the following first order conditions (which are straightforward to reproduce in case you have doubts\ldots) and equilibrium conditions drawn from the description above. Note that the first equation captures the labor supply function and the second the intertemporal consumption Euler equation. -\[ -\begin{aligned} -c_t \theta h_t^{1+\psi} = (1-\alpha)y_t \\ -1= \beta \mathbb{E}_t \left[ \left( \frac{\exp(b_t)c_t}{\exp(b_{t+1})c_{t+1}} \right) \left( \exp(b_{t+1}) \alpha \frac{y_{t+1}}{k_{t+1}}+1-\delta \right) \right] \\ -y_t = \exp (a_t)k_t^\alpha h_t^{1-\alpha} \\ -k_{t+1} = \exp (b_t)i_t + (1-\delta)k_t \\ -a_t = \rho a_{t-1} + \tau b_{t-1} + \epsilon_t \\ -b_t = \tau a_{t-1} + \rho b_{t-1} + \nu_t -\end{aligned} -\] - -\subsubsection{The .mod file} -To ``translate'' the model into a language understandable by Dynare, we would follow the steps outlined in chapter \ref{ch:solbase}. We will assume that you're comfortable with these and simply present the final .mod file below. Fist, though, note that to introduce shocks into Dynare, we have two options (this was not discussed in the earlier chapter). Either write:\\ -\\ -\texttt{shocks;\\ -var e; stderr 0.009;\\ -var u; stderr 0.009;\\ -var e, u = phi*0.009*0.009;\\ -end;}\\ -\\ -where the last line specifies the contemporaneous correlation between our two exogenous variables. \\ - -Alternatively, you can also write: \\ -\\ -\texttt{shocks;\\ -var e = 0.009\textasciicircum 2;\\ -var u = 0.009\textasciicircum 2;\\ -var e, u = phi*0.009*0.009;\\ -end;}\\ - -So that you can gain experience by manipulating the entire model, here is the complete .mod file corresponding to the above example. You can find the corresponding file in the \textsl{models} folder under \textsl{UserGuide} in your installation of Dynare. The file is called \textsl{Alt\_Ex1.mod}. \\ -\\ -\\ -\texttt{var y, c, k, a, h, b;\\ -varexo e, u;\\ -parameters beta, rho, alpha, delta, theta, psi, tau;\\ -\\ -alpha = 0.36;\\ -rho = 0.95;\\ -tau = 0.025;\\ -beta = 0.99;\\ -delta = 0.025;\\ -psi = 0;\\ -theta = 2.95;\\ -\\ -phi = 0.1;\\ -\\ -model;\\ -c*theta*h\textasciicircum (1+psi)=(1-alpha)*y;\\ -k = beta*(((exp(b)*c)/(exp(b(+1))*c(+1)))\\ - *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));\\ -y = exp(a)*(k(-1)\textasciicircum alpha)*(h\textasciicircum (1-alpha));\\ -k = exp(b)*(y-c)+(1-delta)*k(-1);\\ -a = rho*a(-1)+tau*b(-1) + e;\\ -b = tau*a(-1)+rho*b(-1) + u;\\ -end;\\ -\\ -initval;\\ -y = 1.08068253095672;\\ -c = 0.80359242014163;\\ -h = 0.29175631001732;\\ -k = 5;\\ -a = 0;\\ -b = 0;\\ -e = 0;\\ -u = 0;\\ -end;\\ -\\ -shocks;\\ -var e; stderr 0.009;\\ -var u; stderr 0.009;\\ -var e, u = phi*0.009*0.009;\\ -end;\\ -\\ -stoch\_simul(periods=2100);}\\ - -\subsection{Finding, saving and viewing your output} \label{sec:FindOut} -Where is output stored? Most of the moments of interest are stored in global variable \texttt{oo\_} You can easily browse this global variable in Matlab by either calling it in the command line, or using the workspace interface. In global variable \texttt{oo\_} you will find the following (\textsf{\textbf{NOTE!}} variables will always appear in the order in which you declared them in the preamble block of your .mod file): -\begin{itemize} -\item \texttt{steady\_state}: the steady state of your variables -\item \texttt{mean}: the mean of your variables -\item \texttt{var}: the variance of your variables -\item \texttt{autocorr}: the various autocorrelation matrices of your variables. Each row of these matrices will correspond to a variables in time $t$, and columns correspond to the variables lagged 1, for the first matrix, then lagged 2 for the second matrix, and so on. Thus, the matrix of autocorrelations that is automatically displayed in the results after running \texttt{stoch\_simul} has, running down each column, the diagonal elements of each of the various autocorrelation matrices described here. -\item \texttt{gamma\_y}: the matrices of autocovariances. \texttt{gamma\_y\{1\}} represents variances, while \texttt{gamma\_y\{2\}} represents autocovariances where variables on each column are lagged by one period and so on. By default, Dynare will return autocovariances with a lag of 5. The last matrix (\texttt{gamma\_y\{7\}} in the default case) returns the \textbf{variance decomposition}, where each column captures the independent contribution of each shock to the variance of each variable. -\end{itemize} - -Furthermore, if you decide to run impulse response functions, you will find a global variable \texttt{oo\_.irfs} comprising of vectors named \texttt{endogenous variable\_exogenous variable}, like \texttt{y\_e}, reporting the values of the endogenous variables corresponding to the impulse response functions, as a result of the independent impulse of each exogenous shock. \\ - -To save your simulated variables, you can add the following command at the end of your .mod file: \texttt{dynasave (FILENAME) [variable names separated by commas]} If no variable names are specified in the optional field, Dynare will save all endogenous variables. In Matlab, variables saved with the \texttt{dynasave} command can be retrieved by using the Matlab command \texttt{load -mat FILENAME}. - -\subsection{Referring to external files} -You may find it convenient to refer to an external file, either to compute the steady state of your model, or when specifying shocks in an external file. The former is described in section \ref{sec:ssshock} of chapter \ref{ch:solbase} when discussing steady states. The advantage of using Matlab, say, to find your model's steady state was clear with respect to Dynare version 3, as the latter resorted to numerical approximations to find steady state values. But Dynare version 4 now uses the same analytical methods available in Matlab. For most usage scenarios, you should therefore do just as well to ask Dynare to compute your model's steady state (except, maybe, if you want to run loops, to vary your parameter values, for instance, in which case writing a Matlab program may be more handy).\\ - -But you may also be interested in the second possibility described above, -namely of specifying shocks in an external file, to simulate a model based on -shocks from a prior estimation, for instance. You could then retrieve the -exogenous shocks from the oo\_ file by saving them in a file called -datafile.mat. Finally, you could simulate a deterministic model with the shocks -saved from the estimation by specifying the source file for the shocks, using -the \\ \mbox{\texttt{initval\_file(filename = 'datafile.mat')}} command. -But of course, this is a bit of a workaround, since you could also use the built-in commands in Dynare to generate impulse response functions from estimated shocks, as described in chapter \ref{ch:estbase}. \\ - -\subsection{Infinite eigenvalues} -If you use the command \texttt{check} in your .mod file, Dynare will report your system's eigenvalues and tell you if these meet the Blanchard-Kahn conditions. At that point, don't worry if you get infinite eigenvalues - these are are firmly grounded in the theory of generalized eigenvalues. They have no detrimental influence on the solution algorithm. As far as Blanchard-Kahn conditions are concerned infinite eigenvalues are counted as explosive roots of modulus larger than one. \\ - -\section{Files created by Dynare} \label{sec:dynfiles} -At times, you may get a message that there is an error in a file with a new name, or you may want to have a closer look at how Dynare actually solves your model - out of curiosity or maybe to do some customization of your own. You may therefore find it helpful to get a brief overview of the internal files that Dynare generates and the function of each one. \\ - -The dynare pre-processors essentially does three successive tasks: -(i) parsing of the mod file (it checks that the mod file is syntactically -correct), and its translation into internal machine representation (in -particular, model equations are translated into expression trees), (ii) symbolic derivation of the model equations, up to the needed order -(depending on the computing needs), (iii) outputting of several files, which are used from matlab. If the mod -file is ``filename.mod", then the pre-processor creates the following -files: - -\begin{itemize} -\item \textbf{filename.m}: a matlab file containing several instructions, notably -the parameter initializations and the matlab calls corresponding to -computing tasks -\item \textbf{filename\_dynamic.m}: a matlab file containing the model equations and -their derivatives (first, second and maybe third). - Endogenous variables (resp. exogenous variables, parameters) are -contained in a ``y" (resp. ``x", ``params") vector, with an index number -depending on the declaration order. - The ``y" vector has as many entries as their are (variable, lag) -pairs in the declared model. - The model equations residuals are stored in a vector named -``residuals". - The model jacobian is put in ``g1" matrix. Second (resp. third) -derivatives are in ``g2" matrix (resp. ``g3"). - If the ``use\_dll" option has been specified in the model declaration, -the pre-processor will output a C file (with .c extension) rather than a -matlab file. It is then compiled to create a library (DLL) file. Using a -compiled C file is supposed to give better computing performance in -model simulation/estimation. -\item \textbf{filename\_static.m}: a matlab file containing the stationarized -version of the model (i.e. where lagged variables are replaced by -current variables), with its jacobian. Used to compute the steady state. -Same notations than the dynamic file. Replaced by a C file when -``use\_dll" option is specified. -\end{itemize} - -\section{Modeling tips} - -\subsection{Stationarizing your model} -Models in Dynare must be stationary, such that you can linearize them around a steady state and return to steady state after a shock. Thus, you must first stationarize your model, then linearize it, either by hand, or by letting Dynare do the work. You can then reconstruct ex-post the non-stationary simulated variables after running impulse response functions.\\ - -For deterministic models, the trick is to use only stationary variables in $t+1$. More generally, if $y_t$ is $I(1)$, you can always write $y_{t+1}$ as $y_t+dy_{t+1}$, where $dy_t= y_t-y_{t-1}$. Of course, you need to know the value of $dy_t$ at the final equilibrium.\\ - -Note that in a stationary model, it is expected that variables will eventually go back to steady state after the initial shock. If you expect to see a growing curve for a variable, you are thinking about a growth model. Because growth models are nonstationary, it is easier to work with the stationarized version of such models. Again, if you know the trend, you can always add it back after the simulation of the stationary components of the variables. - -\subsection{Expectations taken in the past} -For instance, to enter the term $\mathbb{E}_{t-1}y_t$, define $s_t=\mathbb{E}_t[y_{t+1}]$ and then use $s(-1)$ in your .mod file. Note that, because of Jensen's inequality, you cannot do this for terms that enter your equation in a non-linear fashion. If you do have non-linear terms on which you want to take expectations in the past, you would need to apply the above manipulation to the entire equation, as if $y_t$ were an equation, not just a variable. - -\subsection{Infinite sums} - -Dealing with infinite sums is tricky in general, and needs particular care when working with Dynare. The trick is to use a \textbf{recursive -representation} of the sum. For example, suppose your model included: -\[\sum^{\infty}_{j=0}\beta^j x_{t+j}=0, \] - -Note that the above can also be written by using an auxiliary variable $S_t$, defined as: -\[S_t\equiv \sum^{\infty}_{j=0}\beta^j x_{t+j},\] -which can also be written in the following recursive manner: -\[S_t\equiv \sum^{\infty}_{j=0}\beta^j x_{t+j}=x_t +\sum^{\infty}_{j=1}\beta^j -x_{t+j}=x_t+\beta\sum^{\infty}_{j=0}\beta^j x_{t+1+j} \equiv x_t + S_{t+1}\] - -This formulation turns out to be useful in problems of the following -form: - -\[\sum^{\infty}_{j=0}\beta^j x_{t+j}=p_t\sum^{\infty}_{j=0}\gamma^j y_{t+j}, \] -which can be written as a recursive system of the form: -\[S1_t=x_t+\beta S1_{t+1},\] -\[S2_t=y_t+\gamma S2_{t+1},\] -\[S1=p_t S2.\] - -This is particularly helpful, for instance, in a \textbf{Calvo type setting}, as illustrated in the following brief example. The RBC model with monopolistic competition introduced in chapter \ref{ch:solbase} involved flexible prices. The extension with sticky prices, ˆ la Calvo for instance, is instead typical of the new Keynesian monetary literature, exemplified by papers such as \citet{ClaridaGaliGertler1999}. \\ - -The optimal price for a firm resetting its price in period $t$, given that it will be able to reset its price only with probability $1-\theta$ each period, is -\[ -p_t^*(i) = \mu + (1-\beta \theta) \sum_{k=0}^\infty (\beta \theta)^k \mathbb{E}_t [mc_{t+k}^n (i)] -\] -where $\mu$ is the markup, $\beta$ is a discount factor, $i$ represents a firm of the continuum between 0 and 1, and $mc_t$ is marginal cost as described in the example in chapter \ref{ch:solbase}. The trouble, of course, is \textbf{how to input this infinite sum into Dynare}? \\ - -It turns out that the Calvo price setting implies that the aggregate price follows the equation of motion $p_t = \theta p_{t-1} + (1-\theta) p_t^*$, thus implying the following inflation relationship $\pi_t = (1-\theta) (p_t^* - p_{t-1})$. Finally, we can also rewrite the optimal price setting equation, after some algebraic manipulations, as -\[ -p_t^* - p_{t-1} = (1-\beta \theta) \sum_{k=0}^\infty (\beta \theta)^k \mathbb{E}_t [\widehat{mc}_{t+k}] + \sum_{k=0}^\infty (\beta \theta)^k \mathbb{E}_t [\pi_{t+k}] -\] -where $\widehat{mc}_{t+k} = mc_{t+k} + \mu$ is the deviation of the marginal cost from its natural rate, defined as the marginal cost when prices are perfectly flexible. \\ - -The trick now is to note that the above can be written recursively, by writing the right hand side as the first term of the sum (with $k=0$) plus the remainder of the sum, which can be written as the left hand side term scrolled forward one period and appropriately discounted. Mathematically, this yields: -\[ -p_t^* - p_{t-1} =Ê(1-\beta \theta) \widehat{mc}_{t+k} + \pi_t + \betaÊ\theta \mathbb{E}_t [p_{t+1}^* - p_t] -\] -which has gotten rid of our infinite sum! That would be enough for Dynare, but for convenience, we can go one step further and write the above as -\[ -\pi_t = \beta \mathbb{E}_t [\pi_{t+1}] + \lambda \widehat{mc}_{t} -\] -where $\lambda \equiv \frac{(1-\theta)(1-\beta\theta)}{\theta}$, which is the recognizable inflation equation in the new Keynesian (or new Neoclassical) monetary literature. - -\subsection{Infinite sums with changing timing of expectations} - -When you are not able to write an infinite sum recursively, as the index of the expectations changes with each element of the sum, as in the following example, a different approach than the one mentioned above is necessary. \\ - -Suppose your model included the following sum: -\[ -y_t=\sum_{j=0}^{\infty} \mathbb{E}_{t-j}x_t -\] -where $y_t$ and $x_t$ are endogenous variables. \\ - -In Dynare, the best way to handle this is to write out the first $k$ terms explicitly and enter each one in Dynare, such as: $\mathbb{E}_{t-1}x_t + \mathbb{E}_{t-2}x_t+\ldots + \mathbb{E}_{t-k}x_t$. diff --git a/doc/userguide/ch-solbase.tex b/doc/userguide/ch-solbase.tex deleted file mode 100644 index 996bea4ad..000000000 --- a/doc/userguide/ch-solbase.tex +++ /dev/null @@ -1,570 +0,0 @@ -\chapter{Solving DSGE models - basics} \label{ch:solbase} - -This chapter covers everything that leads to, and stems from, the solution of DSGE models; a vast terrain. That is to say that the term ``solution'' in the title of the chapter is used rather broadly. You may be interested in simply finding the solution functions to a set of first order conditions stemming from your model, but you may also want to go a bit further. Typically, you may be interested in how this system behaves in response to shocks, whether temporary or permanent. Likewise, you may want to explore how the system comes back to its steady state or moves to a new one. This chapter covers all these topics. But instead of skipping to the topic closest to your needs, we recommend that you read this chapter chronologically, to learn basic Dynare commands and the process of writing a proper .mod file - this will serve as a base to carry out any of the above computations. - -\section{A fundamental distinction} \label{sec:distcn} -Before speaking of Dynare, it is important to recognize a distinction in model types. This distinction will appear throughout the chapter; in fact, it is so fundamental, that we considered writing separate chapters altogether. But the amount of common material - Dynare commands and syntax - is notable and writing two chapters would have been overly repetitive. Enough suspense; here is the important question: \textbf{is your model stochastic or deterministic?}\\ - -The distinction hinges on \textbf{whether future shocks are known}. In deterministic models, the occurrence of all future shocks is known exactly at the time of computing the model's solution. In stochastic models, instead, only the distribution of future shocks is known. Let's consider a shock to a model's innovation only in period 1. In a deterministic context, agents will take their decisions knowing that future values of the innovations will be zero in all periods to come. In a stochastic context, agents will take their decisions knowing that the future value of innovations are random but will have zero mean. This isn't the same thing because of Jensen's inequality. Of course, if you consider only a first order linear approximation of the stochastic model, or a linear model, the two cases become practically the same, due to certainty equivalence. A second order approximation will instead lead to very different results, as the variance of shocks will matter. \\ - -The solution method for each of these model types differs significantly. In deterministic models, a highly accurate solution can be found by numerical methods. The solution is nothing more than a series of numbers that match a given set of equations. Intuitively, if an agent has perfect foresight, she can specify today - at the time of making her decision - what each of her precise actions will be in the future. In a stochastic environment, instead, the best the agent can do is specify a decision, policy or feedback rule for the future: what will her optimal actions be contingent on each possible realization of shocks. In this case, we therefore search for a function satisfying the model's first order conditions. To complicate things, this function may be non-linear and thus needs to be approximated. In control theory, solutions to deterministic models are usually called ``closed loop'' solutions, and those to stochastic models are referred to as ``open loop''.\\ - -Because this distinction will resurface again and again throughout the chapter, but also because it has been a source of significant confusion in the past, the following gives some additional details. - -\subsection{\textsf{NOTE!} Deterministic vs stochastic models} \label{sec:detstoch} - -\textbf{Deterministic} models have the following characteristics: -\begin{enumerate} -\item As the DSGE (read, ``stochastic'', i.e. not deterministic!) literature has gained attention in economics, deterministic models have become somewhat rare. Examples include OLG models without aggregate uncertainty. -\item These models are usually introduced to study the impact of a change in regime, as in the introduction of a new tax, for instance. -\item Models assume full information, perfect foresight and no uncertainty around shocks. -\item Shocks can hit the economy today or at any time in the future, in which case they would be expected with perfect foresight. They can also last one or several periods. -\item Most often, though, models introduce a positive shock today and zero shocks thereafter (with certainty). -\item The solution does not require linearization, in fact, it doesn't even really need a steady state. Instead, it involves numerical simulation to find the exact paths of endogenous variables that meet the model's first order conditions and shock structure. -\item This solution method can therefore be useful when the economy is far away from steady state (when linearization offers a poor approximation). -\end{enumerate} -\textbf{Stochastic} models, instead, have the following characteristics: -\begin{enumerate} -\item These types of models tend to be more popular in the literature. Examples include most RBC models, or new keynesian monetary models. -\item In these models, shocks hit today (with a surprise), but thereafter their expected value is zero. Expected future shocks, or permanent changes in the exogenous variables cannot be handled due to the use of Taylor approximations around a steady state. -\item Note that when these models are linearized to the first order, agents behave as if future shocks where equal to zero (since their expectation is null), which is the \textbf{certainty equivalence property}. This is an often overlooked point in the literature which misleads readers in supposing their models may be deterministic. -\end{enumerate} - - -\section{Introducing an example} -The goal of this first section is to introduce a simple example. Future sections will aim to code this example into Dynare and analyze its salient features under the influence of shocks - both in a stochastic and a deterministic environment. Note that as a general rule, the examples in the basic chapters, \ref{ch:solbase} and \ref{ch:estbase}, are kept as bare as possible, with just enough features to help illustrate Dynare commands and functionalities. More complex examples are instead presented in the advanced chapters.\\ - -The model introduced here is a basic RBC model with monopolistic competition, used widely in the literature. Its particular notation adopted below is drawn mostly from notes available on Jesus Fernandez-Villaverde's very instructive \href{http://www.econ.upenn.edu/~jesusfv/}{website}; this is a good place to look for additional information on any of the following model set-up and discussion. Note throughout this model description that the use of \textbf{expectation} signs is really only relevant in a stochastic setting, as per the earlier discussion. We will none-the-less illustrate both the stochastic and the deterministic settings on the basis of this example. Thus, when thinking of the latter, you'll have to use a bit of imagination (on top of that needed to think you have perfect foresight!) to ignore the expectation signs.\\ - -Households maximize utility over consumption, $c_t$ and leisure, $1-l_t$, where $l_t$ is labor input, according to the following utility function -\[ -\mathbb{E}_t \sum_{t=0}^{\infty} \beta \left[ \log c_t + \psi \log(1-l_t) \right] -\] -and subject to the following budget constraint -\[ -c_t + k_{t+1}=w_t l_t + r_t k_t + (1-\delta)k_t, \qquad \forall t>0 -\] -where $k_t$ is capital stock, $w_t$ real wages, $r_t$ real interest rates or cost of capital and $\delta$ the depreciation rate. \\ - -The above equation can be seen as an accounting identity, with total expenditures on the left hand side and revenues - including the liquidation value of the capital stock - on the right hand side. Alternatively, with a little more imagination, the equation can also be interpreted as a capital accumulation equation after bringing $c_t$ to the right hand side and noticing that $w_t l_t + r_t k_t$, total payments to factors, equals $y_t$, or aggregate output, by the zero profit condition. As a consequence, if we define investment as $i_t=y_t - c_t$, we obtain the intuitive result that $i_t=k_{t+1} - (1-\delta) k_{t}$, or that investment replenishes the capital stock thereby countering the effects of depreciation. In any given period, the consumer therefore faces a tradeoff between consuming and investing in order to increase the capital stock and consuming more in following periods (as we will see later, production depends on capital).\\ - -Maximization of the household problem with respect to consumption, leisure and capital stock, yields the Euler equation in consumption, capturing the intertemporal tradeoff mentioned above, and the labor supply equation linking labor positively to wages and negatively to consumption (the wealthier, the more leisure due to the decreasing marginal utility of consumption). These equation are -\[ -\frac{1}{c_t}=\beta \mathbb{E}_t \left[ \frac{1}{c_{t+1}} \left( 1 + r_{t+1} - \delta \right) \right] -\] -and -\[ -\psi \frac{c_t}{1-l_t}= w_t -\] - -The firm side of the problem is slightly more involved, due to monopolistic competition, but is presented below in the simplest possible terms, with a little hand-waiving involved, as the derivations are relatively standard. \\ - -There are two ways to introduce monopolistic competition. We can either assume that firms sell differentiated varieties of a good to consumers who aggregate these according to a CES index. Or we can postulate that there is a continuum of intermediate producers with market power who each sell a different variety to a competitive final goods producer whose production function is a CES aggregate of intermediate varieties.\\ - -If we follow the second route, the final goods producer chooses his or her optimal demand for each variety, yielding the Dixit-Stiglitz downward sloping demand curve. Intermediate producers, instead, face a two pronged decision: how much labor and capital to employ given these factors' perfectly competitive prices and how to price the variety they produce.\\ - -Production of intermediate goods follows a CRS production function defined as -\[ -y_{it} = k_{it}^\alpha (e^{z_t} l_{it})^{1-\alpha} -\] -where the $i$ subscript stands for firm $i$ of a continuum of firms between zero and one and where $\alpha$ is the capital elasticity in the production function, with $0<\alpha<1$. Also, $z_t$ captures technology which evolves according to -\[ -z_t = \rho z_{t-1} + e_t -\] -where $\rho$ is a parameter capturing the persistence of technological progress and $e_t \thicksim \mathcal{N}(0,\sigma)$. \\ - -The solution to the sourcing problem yields an optimal capital to labor ratio, or relationship between payments to factors: -\[ -k_{it}r_t=\frac{\alpha}{1-\alpha}w_tl_{it} -\] - -The solution to the pricing problem, instead, yields the well-known constant markup pricing condition of monopolistic competition: -\[ -p_{it}=\frac{\epsilon}{\epsilon -1}mc_t p_t -\] -where $p_{it}$ is firm $i$'s specific price, $mc_t$ is real marginal cost and $p_t$ is the aggregate CES price or average price. An additional step simplifies this expression: symmetric firms implies that all firms charge the same price and thus $p_{it}=p_t$; we therefore have: $mc_t = (\epsilon - 1)/\epsilon$ \\ - -But what are marginal costs equal to? To find the answer, we combine the optimal capital to labor ratio into the production function and take advantage of its CRS property to solve for the amount of labor or capital required to produce one unit of output. The real cost of using this amount of any one factor is given by $w_tl_{it} + r_tk_{it}$ where we substitute out the payments to the other factor using again the optimal capital to labor ratio. When solving for labor, for instance, we obtain -\[ -mc_t = \left( \frac{1}{1-\alpha}Ê\right)^{1-\alpha} \left( \frac{1}{\alpha}Ê\right)^\alpha \frac{1}{A_t}w_t^{1-\alpha} r_t^\alpha -\] -which does not depend on $i$; it is thus the same for all firms. \\ - -Interestingly, the above can be worked out, by using the optimal capital to labor ratio, to yield $w_t [(1-\alpha)y_{it}/l_{it}]^{-1}$, or $w_t \frac{\partial l_{it}}{\partial y_{it}}$, which is the definition of marginal cost: the cost in terms of labor input of producing an additional unit of output. This should not be a surprise since the optimal capital to labor ratio follows from the maximization of the production function (minus real costs) with respect to its factors. \\ - -Combining this result for marginal cost, as well as its counterpart in terms of capital, with the optimal pricing condition yields the final two important equations of our model -\[ -w_t = (1-\alpha) \frac{y_{it}}{l_{it}} \frac{(\epsilon-1)}{\epsilon} -\] -and -\[ -r_t = \alpha \frac{y_{it}}{k_{it}} \frac{(\epsilon-1)}{\epsilon} -\] - -To end, we aggregate the production of each individual firm to find an aggregate production function. On the supply side, we factor out the capital to labor ratio, $k_t/l_t$, which is the same for all firms and thus does not depend on $i$. On the other side, we have the Dixit-Stiglitz demand for each variety. By equating the two and integrating both side, and noting that price dispersion is null - or that, as hinted earlier, $p_{it}=p_t$ - we obtain aggregate production -\[ -y_t = A_t k_t^\alpha l_t^{1-\alpha} -\] -which can be shown is equal to the aggregate amount of varieties bought by the final good producer (according to a CES aggregation index) and, in turn, equal to the aggregate output of final good, itself equal to household consumption. Note, to close, that because the ratio of output to each factor is the same for each intermediate firm and that firm specific as well as aggregate production is CRS, we can rewrite the above two equations for $w_t$ and $r_t$ without the $i$ subscripts on the right hand side. \\ - -This ends the exposition of the example. Now, let's roll up our sleeves and see how we can input the model into Dynare and actually test how the model will respond to shocks. - -\section{Dynare .mod file structure} -Input into Dynare involves the .mod file, as mentioned loosely in the introduction of this Guide. The .mod file can be written in any editor, external or internal to Matlab. It will then be read by Matlab by first navigating within Matlab to the directory where the .mod file is stored and then by typing in the Matlab command line \texttt{Dynare filename.mod;} (although actually typing the extension .mod is not necessary). But before we get into executing a .mod file, let's start by writing one! \\ - -It is convenient to think of the .mod file as containing four distinct blocks, illustrated in figure \ref{fig:modstruct}: -\begin{itemize} -\item \textbf{preamble}: lists variables and parameters -\item \textbf{model}: spells out the model -\item \textbf{steady state or initial value}: gives indications to find the steady state of a model, or the starting point for simulations or impulse response functions based on the model's solution. -\item \textbf{shocks}: defines the shocks to the system -\item \textbf{computation}: instructs Dynare to undertake specific operations (e.g. forecasting, estimating impulse response functions) -\end{itemize} -Our exposition below will structured according to each of these blocks. -\begin{figure} \label{fig:modstruct} -\begin{center} -\includegraphics[width=1.0\textwidth]{P_ModStruct5} -\end{center} -\caption[Structure of the .mod file]{The .mod file contains five logically distinct parts.} -\end{figure} - -\section{Filling out the preamble} \label{sec:preamble} -The preamble generally involves three commands that tell Dynare what are the model's variables, which are endogenous and what are the parameters. The \textbf{commands} are: -\begin{itemize} -\item \texttt{var} starts the list of endogenous variables, to be separated by commas. -\item \texttt{varexo} starts the list of exogenous variables that will be shocked. -\item \texttt{parameters} starts the list of parameters and assigns values to each. -\end{itemize} -In the case of our example, let's differentiate between the stochastic and deterministic cases. First, we lay these out, then we discuss them. - -\subsection{The deterministic case} -The model is inherited exactly as specified in the earlier description, except that we no longer need the $e_t$ variable, as we can make $z_t$ directly exogenous. Thus, the \textbf{preamble would look like}:\\ -\\ -\texttt{var y c k i l y\_l w r;\\ -varexo z;\\ -parameters beta psi delta alpha sigma epsilon;\\ -alpha = 0.33;\\ -beta = 0.99;\\ -delta = 0.023;\\ -psi = 1.75;\\ -sigma = (0.007/(1-alpha));\\ -epsilon = 10;}\\ - -\subsection{The stochastic case} -In this case, we go back to considering the law of motion for technology, consisting of an exogenous shock, $e_t$. With respect to the above, we therefore adjust the list of endogenous and exogenous variables, and add the parameter $\rho$. Here's what the \textbf{preamble would look like}:\\ -\\ -\texttt{var y c k i l y\_l w r z;\\ -varexo e;\\ -parameters beta psi delta alpha rho sigma epsilon;\\ -alpha = 0.33;\\ -beta = 0.99;\\ -delta = 0.023;\\ -psi = 1.75;\\ -rho = 0.95; \\ -sigma = (0.007/(1-alpha));\\ -epsilon = 10;}\\ - -\subsection{Comments on your first lines of Dynare code} - -As you can tell, writing a .mod file is really quite straightforward. Two quick comments:\\ - -\textsf{\textbf{NOTE!}} Remember that each instruction of the .mod file must be terminated by a semicolon (;), although a single instruction can span two lines if you need extra space (just don't put a semicolon at the end of the first line).\\ - -\textsf{\textbf{TIP!}} You can also comment out any line by starting the line with two forward slashes (//), or comment out an entire section by starting the section with /* and ending with */. For example:\\ -\\ -\texttt{var y c k i l y\_l w r z;\\ -varexo e;\\ -parameters beta psi delta \\ -alpha rho sigma epsilon;\\ -// the above instruction reads over two lines\\ -/*\\ -the following section lists\\ -several parameters which were\\ -calibrated by my co-author. Ask\\ -her all the difficult questions!\\ -*/\\ -alpha = 0.33;\\ -beta = 0.99;\\ -delta = 0.023;\\ -psi = 1.75;\\ -rho = 0.95; \\ -sigma = (0.007/(1-alpha));\\ -epsilon = 10;}\\ -\\ - -\section{Specifying the model} \label{sec:modspe} -\subsection{Model in Dynare notation} -One of the beauties of Dynare is that you can \textbf{input your model's equations naturally}, almost as if you were writing them in an academic paper. This greatly facilitates the sharing of your Dynare files, as your colleagues will be able to understand your code in no-time. There are just a few conventions to follow. Let's first have a look at our \textbf{model in Dynare notation}, and then go through the various Dynare input conventions. What you can already try to do is glance at the model block below and see if you can recognize the equations from the earlier example. See how easy it is to read Dynare code? \\ -\\ -\texttt{model;\\ - (1/c) = beta*(1/c(+1))*(1+r(+1)-delta);\\ - psi*c/(1-l) = w;\\ - c+i = y;\\ - y = (k(-1)\textasciicircum alpha)*(exp(z)*l)\textasciicircum (1-alpha);\\ - w = y*((epsilon-1)/epsilon)*(1-alpha)/l;\\ - r = y*((epsilon-1)/epsilon)*alpha/k(-1);\\ - i = k-(1-delta)*k(-1);\\ - y\_l = y/l;\\ - z = rho*z(-1)+e;\\ -end;}\\ - -Just in case you need a hint or two to recognize these equations, here's a brief description: the first equation is the Euler equation in consumption. The second the labor supply function. The third the accounting identity. The fourth is the production function. The fifth and sixth are the marginal cost equal to markup equations. The seventh is the investment equality. The eighth an identity that may be useful and the last the equation of motion of technology. - -\textsf{\textbf{NOTE!}} that the above model specification corresponds to the \textbf{stochastic case}; indeed, notice that the law of motion for technology is included, as per our discussion of the preamble. The corresponding model for the \textbf{deterministic casce} would simply loose the last equation. - -\subsection{General conventions} -The above example illustrates the use of a few important commands and conventions to translate a model into a Dynare-readable .mod file. -\begin{itemize} -\item The first thing to notice, is that the model block of the .mod file begins with the command \texttt{model} and ends with the command \texttt{end}. -\item Second, in between, there need to be as many equations as you declared endogenous variables (this is actually one of the first things that Dynare checks; it will immediately let you know if there are any problems). -\item Third, as in the preamble and everywhere along the .mod file, each line of instruction ends with a semicolon (except when a line is too long and you want to break it across two lines. This is unlike Matlab where if you break a line you need to add \ldots). -\item Fourth, equations are entered one after the other; no matrix representation is necessary. Note that variable and parameter names used in the model block must be the same as those declared in the preamble; \textsf{\textbf{TIP!}} remember that variable and parameter names are case sensitive. -\end{itemize} - -\subsection{Notational conventions} - -\begin{itemize} -\item Variables entering the system with a time $t$ subscript are written plainly. For example, $x_t$ would be written $x$. -\item Variables entering the system with a time $t-n$ subscript are written with $(-n)$ following them. For example, $x_{t-2}$ would be written $x(-2)$ (incidentally, this would count as two backward looking variables). -\item In the same way, variables entering the system with a time $t+n$ subscript are written with $(+n)$ following them. For example, $x_{t+2}$ would be written $x(+2)$. Writing $x(2)$ is also allowed, but this notation makes it slightly harder to count by hand the number of forward looking variables (a useful measure to check); more on this below \ldots -\end{itemize} - -\subsection{Timing conventions} -\begin{itemize} -\item In Dynare, the timing of each variable reflects when that variable is decided. For instance, our capital stock is not decided today, but yesterday (recall that it is a function of yesterday's investment and capital stock); it is what we call in the jargon a \textbf{predetermined} variable. Thus, eventhough in the example presented above we wrote $k_{t+1}=i_t + (1-\delta)k_t$, as in many papers, we would translate this equation into Dynare as \texttt{k=i+(1-delta)*k(-1)}. -\item As another example, consider that in some wage negociation models, wages used during a period are set the period before. Thus, in the equation for wages, you can write wage in period $t$ (when they are set), but in the labor demand equation, wages should appear with a one period lag. -\item A slightly more roundabout way to explain the same thing is that for stock variables, you must use a ``stock at the end of the period'' concept. It is investment during period $t$ that sets stock at the end of period $t$. Be careful, a lot of papers use the ``stock at the beginning of the period'' convention, as we did (on purpose to highlight this distinction!) in the setup of the example model above. -\end{itemize} - -\subsection{Conventions specifying non-predetermined variables} -\begin{itemize} -\item A (+1) next to a variable tells Dynare to count the occurrence of that variable as a jumper or forward-looking or non-predetermined variable. -\item \textbf{Blanchard-Kahn} conditions are met only if the number of non-predetermined variables equals the number of eigenvalues greater than one. If this condition is not met, Dynare will put up a warning. -\item Note that a variable may occur both as predetermined and non-predetermined. For instance, consumption could appear with a lead in the Euler equation, but also with a lag in a habit formation equation, if you had one. In this case, the second order difference equation would have two eigenvalues, one needing to be greater and the other smaller than one for stability. -\end{itemize} - -\subsection{Linear and log-linearized models} -There are two other variants of the system's equations which Dynare accommodates. First, the \textbf{linear model} and second, the \textbf{model in exp-logs}. In the first case, all that is necessary is to write the term \texttt{(linear)} next to the command \texttt{model}. Our example, with just the equation for $y_l$ for illustration, would look like:\\ -\\ -\texttt{model (linear);\\ -yy\_l=yy - ll;\\ -end;}\\ -\\ -where repeating a letter for a variable means difference from steady state.\\ - -Otherwise, you may be interested to have Dynare take Taylor series expansions in logs rather than in levels; this turns out to be a very useful option when estimating models with unit roots, as we will see in chapter \ref{ch:estbase}. If so, simply rewrite your equations by taking the exponential and logarithm of each variable. The Dynare input convention makes this very easy to do. Our example would need to be re-written as follows (just shown for the first two equations)\\ -\\ -\texttt{model;\\ - (1/exp(cc)) = beta*(1/exp(cc(+1)))*(1+exp(rr(+1))-delta);\\ - psi*exp(cc)/(1-exp(ll)) = exp(ww);\\ - end;}\\ - \\ - where, this time, repeating a letter for a variable means log of that variable, so that the level of a variable is given by $exp(repeated variable)$. - -\section{Specifying steady states and/or initial values} \label{sec:ssshock} -Material in this section has created much confusion in the past. But with some attention to the explanations below, you should get through unscathed. Let's start by emphasizing the uses of this section of the .mod file. First, recall that stochastic models need to be linearized. Thus, they need to have a steady state. One of the functions of this section is indeed to provide these steady state values, or approximations of values. Second, irrespective of whether you're working with a stochastic or deterministic model, you may be interested to start your simulations or impulse response functions from either a steady state, or another given point. This section is also useful to specify this starting value. Let's see in more details how all this works.\\ - -In passing, though, note that the relevant commands in this section are \texttt{initval}, \texttt{endval} or, more rarely, \texttt{histval} which is covered only in the \href{http://www.dynare.org/documentation-and-support/manual}{Reference Manual}. The first two are instead covered in what follows. \\ - -\subsection{Stochastic models and steady states} -In a stochastic setting, your model will need to be linearized before it is solved. To do so, Dynare needs to know your model's steady state (more details on finding a steady state, as well as tips to do so more efficiently, are provided in section \ref{sec:findsteady} below). You can either enter exact steady state values into your .mod file, or just approximations and let Dynare find the exact steady state (which it will do using numerical methods based on your approximations). In either case, these values are entered in the \texttt{initval} block, as in the following fashion: \\ -\\ -\texttt{initval;\\ - k = 9;\\ - c = 0.7;\\ - l = 0.3;\\ - w = 2.0;\\ - r = 0;\\ - z = 0; \\ - e = 0;\\ -end;} -\\ - -Then, by using the command \texttt{steady}, you can control whether you want to start your simulations or impulse response functions from the steady state, or from the exact values you specified in the \texttt{initval} block. Adding \texttt{steady} just after your \texttt{initval} block will instruct Dynare to consider your initial values as mere approximations and start simulations or impulse response functions from the exact steady state. On the contrary, if you don't add the command \texttt{steady}, your simulations or impulse response functions will start from your initial values, even if Dynare will have calculated your model's exact steady state for the purpose of linearization. \\ - -For the case in which you would like simulations and impulse response functions to begin at the steady state, the above block would be expanded to yield:\\ -\\ -\texttt{initval;\\ - k = 9;\\ - c = 0.7;\\ - l = 0.3;\\ - w = 2.0;\\ - r = 0;\\ - z = 0; \\ - e = 0;\\ -end;\\ -\\ -steady;} -\\ - -\textsf{\textbf{TIP!}} If you're dealing with a stochastic model, remember that its linear approximation is good only in the vicinity of the steady state, thus it is strongly recommended that you start your simulations from a steady state; this means either using the command \texttt{steady} or entering exact steady state values. \\ - - -\subsection{Deterministic models and initial values} -Deterministic models do not need to be linearized in order to be solved. Thus, technically, you do not need to provide a steady state for these model. But practically, most researchers are still interested to see how a model reacts to shocks when originally in steady state. In the deterministic case, the \texttt{initval} block serves very similar functions as described above. If you wanted to shock your model starting from a steady state value, you would enter approximate (or exact) steady state values in the \texttt{initval} block, followed by the command \texttt{steady}. Otherwise, if you wanted to begin your solution path from an arbitrary point, you would enter those values in your \texttt{initval} block and not use the \texttt{steady} command. An illustration of the \texttt{initval} block in the deterministic case appears further below. \\ - -\subsection{Finding a steady state} \label{sec:findsteady} - -The difficulty in the above, of course, is calculating actual steady state values. Doing so borders on a form of art, and luck is unfortunately part of the equation. Yet, the following \textsf{\textbf{TIPS!}} may help.\\ - -As mentioned above, Dynare can help in finding your model's steady state by calling the appropriate Matlab functions. But it is usually only successful if the initial values you entered are close to the true steady state. If you have trouble finding the steady state of your model, you can begin by playing with the \textbf{options following the \texttt{steady} command}. These are: -\begin{itemize} -\item \texttt{solve\_algo = 0}: uses Matlab Optimization Toolbox FSOLVE -\item \texttt{solve\_algo = 1}: uses DynareÕs own nonlinear equation solver -\item \texttt{solve\_algo = 2}: splits the model into recursive blocks and solves each block in turn. -\item \texttt{solve\_algo = 3}: uses the Sims solver. This is the default option if none are specified. -\end{itemize} - -For complicated models, finding suitable initial values for the endogenous variables is the trickiest part of finding the equilibrium of that model. Often, it is better to start with a smaller model and add new variables one by one.\\ - -But even for simpler models, you may still run into difficulties in finding your steady state. If so, another option is to \textbf{enter your model in linear terms}. In this case, variables would be expressed in percent deviations from steady state. Thus, their initial values would all be zero. Unfortunately, if any of your original (non-linear) equations involve sums (a likely fact), your linearized equations will include ratios of steady state values, which you would still need to calculate. Yet, you may be left needing to calculate fewer steady state values than in the original, non-linear, model. \\ - -Alternatively, you could also use an \textbf{external program to calculate exact steady state values}. For instance, you could write an external \textbf{Maple} file and then enter the steady state solution by hand in Dynare. But of course, this procedure could be time consuming and bothersome, especially if you want to alter parameter values (and thus steady states) to undertake robustness checks. \\ - -The alternative is to write a \textbf{Matlab} program to find your model's steady state. Doing so has the clear advantages of being able to incorporate your Matlab program directly into your .mod file so that running loops with different parameter values, for instance, becomes seamless. \textsf{\textbf{NOTE!}} When doing so, your matlab (.m) file should have the same name as your .mod file, followed by \texttt{\_steadystate} For instance, if your .mod file is called \texttt{example.mod}, your Matlab file should be called \texttt{example\_steadystate.m} and should be saved in the same directory as your .mod file. Dynare will automatically check the directory where you've saved your .mod file to see if such a Matlab file exists. If so, it will use that file to find steady state values regardless of whether you've provided initial values in your .mod file. \\ - -Because Matlab does not work with analytical expressions, though (unless you're working with a particular toolbox), you need to do a little work to write your steady state program. It is not enough to simply input the equations as you've written them in your .mod file and ask Matlab to solve the system. You will instead need to write your steady state program as if you were solving for the steady state by hand. That is, you need to input your expressions sequentially, whereby each left-hand side variable is written in terms of known parameters or variables already solved in the lines above. For example, the steady state file corresponding to the above example, in the stochastic case, would be: (** example file to be added shortly) \\ - -\subsection{Checking system stability} -\textsf{\textbf{TIP!}} A handy command that you can add after the \texttt{initval} or \texttt{endval} block (following the \texttt{steady} command if you decide to add one) is the \texttt{check} command. This \textbf{computes and displays the eigenvalues of your system} which are used in the solution method. As mentioned earlier, a necessary condition for the uniqueness of a stable equilibrium in the neighborhood of the steady state is that there are -as many eigenvalues larger than one in modulus as there are forward looking variables in the system. If this condition is not met, Dynare will tell you that the Blanchard-Kahn conditions are not satisfied (whether or not you insert the \texttt{check} command). \\ - - -\section{Adding shocks} - -\begin{comment} -\begin{figure} \label{fig:shockmodel} -\begin{center} -\includegraphics[width=1.0\textwidth]{P_ShockModel2} -\end{center} -\caption[Shock and model-type matrix]{Depending on the model type you're working with and the desired shocks, you will need to mix and match the various steady state and shock commands.} -\end{figure} -\end{comment} - -\subsection{Deterministic models - temporary shocks} -When working with a deterministic model, you have the choice of introducing both temporary and permanent shocks. The distinction is that under a temporary shock, the model eventually comes back to steady state, while under a permanent shock, the model reaches a new steady state. In both cases, though, the shocks are entirely expected, as explained in our original discussion on stochastic and deterministic models. \\ - -To work with a \textbf{temporary shock}, you are free to set the duration and level of the shock. To specify a shock that lasts 9 periods on $z_t$, for instance, you would write:\\ -\\ -\texttt{shocks;\\ -var z;\\ -periods 1:9;\\ -values 0.1;\\ -end;}\\ - -Given the above instructions, Dynare would replace the value of $z_t$ specified in the \texttt{initval} block with the value of 0.1 entered above. If variables were in logs, this would have corresponded to a 10\% shock. Note that you can also use the \texttt{mshocks} command which multiplies the initial value of an exogenous variable by the \texttt{mshocks} value. Finally, note that we could have entered future periods in the shocks block, such as \texttt{periods 5:10}, in order to study the anticipatory behavior of agents in response to future shocks.\\ - -\subsection{Deterministic models - permanent shocks} -To study the effects of a \textbf{permanent shock} hitting the economy today, such as a structural change in your model, you would not specify actual ``shocks'', but would simply tell the system to which (steady state) values you would like it to move and let Dynare calculate the transition path. To do so, you would use the \texttt{endval} block following the usual \texttt{initval} block. For instance, you may specify all values to remain common between the two blocks, except for the value of technology which you may presume changes permanently. The corresponding instructions would be:\\ -\\ -\texttt{initval;\\ - k = 9;\\ - c = 0.7;\\ - l = 0.3;\\ - w = 2.0;\\ - r = 0;\\ - z = 0; \\ -end;\\ -steady;\\ -\\ -endval;\\ - k = 9;\\ - c = 0.7;\\ - l = 0.3;\\ - w = 2.0;\\ - r = 0;\\ - z = 0.1; \\ -end;\\ -steady;}\\ -\\ -where \texttt{steady} can also be added to the \texttt{endval} block, and serves the same functionality as described earlier (namely, of telling Dynare to start and/ or end at a steady state close to the values you entered. If you do not use \texttt{steady} after \texttt{endval}, and the latter does not list exact steady state values, you may impose on your system that it does not return to steady state. This is unusual. In this case, your problem would become a so-called two boundary problem, which, when solved, requires that the path of your endogenous variables pass through the steady state closest to your \texttt{endval} values). In our example, we make use of the second \texttt{steady} since the actual terminal steady state values are bound to be somewhat different from those entered above, which are nothing but the initial values for all variables except for technology.\\ - -In the above example, the value of technology would move to 0.1 in period 1 (tomorrow) and thereafter. But of course, the other variables - the endogenous variables - will take longer to reach their new steady state values. \textsf{\textbf{TIP!}} If you instead wanted to study the effects of a permanent but future shock (anticipated as usual), you would have to add a \texttt{shocks} block after the \texttt{endval} block to ``undo'' the first several periods of the permanent shock. For instance, suppose you wanted the value of technology to move to 0.1, but only in period 10. Then you would follow the above \texttt{endval} block with:\\ -\\ -\texttt{shocks;\\ -var z;\\ -periods 1:9;\\ -values 0;\\ -end;}\\ - -\subsection{Stochastic models} - -Recall from our earlier description of stochastic models that shocks are only allowed to be temporary. A permanent shock cannot be accommodated due to the need to stationarize the model around a steady state. Furthermore, shocks can only hit the system today, as the expectation of future shocks must be zero. With that in mind, we can however make the effect of the shock propagate slowly throughout the economy by introducing a ``latent shock variable'' such as $e_t$ in our example, that affects the model's true exogenous variable, $z_t$ in our example, which is itself an $AR(1)$, exactly as in the model we introduced from the outset. In that case, though, we would declare $z_t$ as an endogenous variable and $e_t$ as an exogenous variable, as we did in the preamble of the .mod file in section \ref{sec:preamble}. Supposing we wanted to add a shock with variance $\sigma^2$, where $\sigma$ is determined in the preamble block, we would write: \\ -\\ -\texttt{shocks;\\ -var e = sigma\textasciicircum 2;\\ -end;}\\ -\\ - -\textsf{\textbf{TIP!}} You can actually \textbf{mix in deterministic shocks} in stochastic models by using the commands \texttt{varexo\_det} and listing some shocks as lasting more than one period in the \texttt{shocks} block. For information on how to do so, please see the \href{http://www.dynare.org/documentation-and-support/manual}{Reference Manual}. This can be particularly useful if you're studying the effects of anticipated shocks in a stochastic model. For instance, you may be interested in what happens to your monetary model if agents began expecting higher inflation, or a depreciation of your currency. \\ - -\section{Selecting a computation} \label{sec:compute} -So far, we have written an instructive .mod file, but what should Dynare do with it? What are we interested in? In most cases, it will be impulse response functions (IRFs) due to the external shocks. Let's see which are the appropriate commands to give to Dynare. Again, we will distinguish between deterministic and stochastic models. \\ - -\subsection{For deterministic models} -In the deterministic case, all you need to do is add the command \texttt{simul} at the bottom of your .mod file. Note that the command takes the option \mbox{\texttt{[ (periods=INTEGER) ] }} The command \texttt{simul} triggers the computation a numerical simulation of the trajectory of the model's solution for the number of periods set in the option. To do so, it uses a Newton method to solve simultaneously all the equations for every period (see \citet{Juillard1996} for details). Note that unless you use the \texttt{endval} command, the algorithm makes the simplifying assumption that the system is back to equilibrium after the specified number of periods. Thus, you must specify a large enough number of periods such that increasing it further doesn't change the simulation for all practical purpose. In the case of a temporary shock, for instance, the trajectory will basicaly describe how the system gets back to equilibrium after being perturbed from the shocks you entered.\\ - -\subsection{For stochastic models} -In the more common case of stochastic models, the command \texttt{stoch\_simul} is appropriate. This command instructs Dynare to compute a Taylor approximation of the decision and transition functions for the model (the equations listing current values of the endogenous variables of the model as a function of the previous state of the model and current shocks), impulse response -functions and various descriptive statistics (moments, variance decomposition, correlation and autocorrelation coefficients).\footnote{For correlated shocks, the variance decomposition is computed as in the VAR literature through a Cholesky -decomposition of the covariance matrix of the exogenous variables. When the shocks are correlated, the variance -decomposition depends upon the order of the variables in the varexo command.}\\ - -Impulse response functions are the expected future path of the endogenous variables conditional on a shock in period 1 of one standard deviation.\textsf{\textbf{TIP!}} If you linearize your model up to a first order, impulse response functions are simply the algebraic forward iteration of your model's policy or decision rule. If you instead linearize to a second order, impulse response functions will be the result of actual Monte Carlo simulations of future shocks. This is because in second order linear equations, you will have cross terms involving the shocks, so that the effects of the shocks depend on the state of the system when the shocks hit. Thus, it is impossible to get algebraic average values of all future shocks and their impact. The technique is instead to pull future shocks from their distribution and see how they impact your system, and repeat this procedure a multitude of times in order to draw out an average response. That said, note that future shocks will not have a significant impact on your results, since they get averaged between each Monte Carlo trial and in the limit should sum to zero, given their mean of zero. Note that in the case of a second order approximation, Dynare will return the actual sample moments from the simulations. For first order linearizations, Dynare will instead report theoretical moments. In both cases, the return to steady state is asymptotic, \textsf{\textbf{TIP!}} thus you should make sure to specify sufficient periods in your IRFs such that you actually see your graphs return to steady state. Details on implementing this appear below.\\ - -If you're interested to peer a little further into what exactly is going on behind the scenes of Dynare's computations, have a look at Chapter \ref{ch:solbeh}. Here instead, we focus on the application of the command and reproduce below the most common options that can be added to \texttt{stoch\_simul}. For a complete list of options, please see the \href{http://www.dynare.org/documentation-and-support/manual}{Reference Manual}. \\ - -\textbf{Options following the \texttt{stoch\_simul} command:} -\begin{itemize} -\item ar = INTEGER: Order of autocorrelation coefficients to compute and to print (default = 5). -\item dr\_algo = 0 or 1: specifies the algorithm used for computing the quadratic approximation of the decision rules: $0$ uses a pure perturbation approach as in \citet{SchmittGrohe2004} (default) and 1 moves the point around which the Taylor expansion is computed toward the means of the distribution as in \citet{CollardJuillard2001a}. -\item drop = INTEGER: number of points dropped at the beginning of simulation before computing the summary -statistics (default = 100). -\item hp\_filter = INTEGER: uses HP filter with lambda = INTEGER before computing moments (default: no filter). -\item hp\_ngrid = INTEGER: number of points in the grid for the discreet Inverse Fast Fourier Transform used in the -HP filter computation. It may be necessary to increase it for highly autocorrelated processes (default = 512). -\item irf = INTEGER: number of periods on which to compute the IRFs (default = 40). Setting IRF=0, suppresses the -plotting of IRFÕs. -\item relative\_irf requests the computation of normalized IRFs in percentage of the standard error of each shock. -\item nocorr: doesnÕt print the correlation matrix (printing is the default). -\item nofunctions: doesnÕt print the coefficients of the approximated solution (printing is the default). -\item nomoments: doesnÕt print moments of the endogenous variables (printing them is the default). -\item noprint: cancel any printing; usefull for loops. -\item order = 1 or 2 : order of Taylor approximation (default = 2), unless you're working with a linear model in which case the order is automatically set to 1. -\item periods = INTEGER: specifies the number of periods to use in simulations (default = 0). \textsf{\textbf{TIP!}} A simulation is similar to running impulse response functions with a model linearized to the second order, in the way that both sample shocks from their distribution to see how the system reacts, but a simulation only repeats the process once, whereas impulse response functions run a multitude of Monte Carlo trials in order to get an average response of your system. -\item qz\_criterium = INTEGER or DOUBLE: value used to split stable from unstable eigenvalues in reordering the -Generalized Schur decomposition used for solving 1st order problems (default = 1.000001). -\item replic = INTEGER: number of simulated series used to compute the IRFs (default = 1 if order = 1, and 50 -otherwise). -\end{itemize} - -Going back to our good old example, suppose we were interested in printing all the various measures of moments of our variables, want to see impulse response functions for all variables, are basically happy with all default options and want to carry out simulations over a good number of periods. We would then end our .mod file with the following command:\\ -\\ -\texttt{stoch\_simul(periods=2100);}\\ - -\section{The complete .mod file} -For completion's sake, and for the pleasure of seeing our work bear its fruits, here are the complete .mod files corresponding to our example for the deterministic and stochastic case. You can find the corresponding files in the \textsl{models} folder under \textsl{UserGuide} in your installation of Dynare. The files are called \texttt{RBC\_Monop\_JFV.mod} for stochastic models and \texttt{RBC\_Monop\_Det.mod} for deterministic models. - -\subsection{The stochastic model} - -\texttt{var y c k i l y\_l w r z;\\ -varexo e;\\ -parameters beta psi delta alpha rho gamma sigma epsilon;\\ -\\ -alpha = 0.33;\\ -beta = 0.99;\\ -delta = 0.023;\\ -psi = 1.75;\\ -rho = 0.95;\\ -sigma = (0.007/(1-alpha));\\ -epsilon = 10;\\ -\\ -model;\\ - (1/c) = beta*(1/c(+1))*(1+r(+1)-delta);\\ - psi*c/(1-l) = w;\\ - c+i = y;\\ - y = (k(-1)\textasciicircum alpha)*(exp(z)*l)\textasciicircum (1-alpha);\\ - w = y*((epsilon-1)/epsilon)*(1-alpha)/l;\\ - r = y*((epsilon-1)/epsilon)*alpha/k(-1);\\ - i = k-(1-delta)*k(-1);\\ - y\_l = y/l;\\ - z = rho*z(-1)+e;\\ -end;\\ -\\ -initval;\\ - k = 9;\\ - c = 0.76;\\ - l = 0.3;\\ - w = 2.07;\\ - r = 0.03;\\ - z = 0;\\ - e = 0;\\ -end;\\ -\\ -steady;\\ -check;\\ -\\ -shocks;\\ -var e = sigma\textasciicircum 2;\\ -end;\\ -\\ -stoch\_simul(periods=2100);} - -\subsection{The deterministic model (case of temporary shock)} - -\texttt{var y c k i l y\_l w r ;\\ -varexo z;\\ -parameters beta psi delta alpha sigma epsilon;\\ -alpha = 0.33;\\ -beta = 0.99;\\ -delta = 0.023;\\ -psi = 1.75;\\ -sigma = (0.007/(1-alpha));\\ -epsilon = 10;\\ -\\ -model;\\ - (1/c) = beta*(1/c(+1))*(1+r(+1)-delta);\\ - psi*c/(1-l) = w;\\ - c+i = y;\\ - y = (k(-1)\textasciicircum alpha)*(exp(z)*l)\textasciicircum (1-alpha);\\ - w = y*((epsilon-1)/epsilon)*(1-alpha)/l;\\ - r = y*((epsilon-1)/epsilon)*alpha/k(-1);\\ - i = k-(1-delta)*k(-1);\\ - y\_l = y/l;\\ -end;\\ -\\ -initval;\\ - k = 9;\\ - c = 0.7;\\ - l = 0.3;\\ - w = 2.0;\\ - r = 0;\\ - z = 0; \\ -end;\\ -\\ -steady;\\ -\\ -check;\\ -\\ -shocks;\\ -var z;\\ -periods 1:9;\\ -values 0.1;\\ -end;\\ -\\ -simul(periods=2100);}\\ - -\section{File execution and results} -To see this all come to life, let's run our .mod file, which is conveniently installed by default in the Dynare ``examples'' directory (the .mod file corresponding to the stochastic model is called RBC\_Monop\_JFV.mod and that corresponding to the deterministic model is called RBC\_Monop\_Det.mod). (** note, this may not be the case when testing the beta version of Matlab version 4) \\ - -\textbf{To run a .mod file}, navigate within Matlab to the directory where the example .mod files are stored. You can do this by clicking in the ``current directory'' window of Matlab, or typing the path directly in the top white field of Matlab. Once there, all you need to do is place your cursor in the Matlab command window and type, for instance, \texttt{dynare ExSolStoch;} to execute your .mod file. \\ - -Running these .mod files should take at most 30 seconds. As a result, you should get two forms of output - tabular in the Matlab command window and graphical in one or more pop-up windows. Let's review these results.\\ - -\subsection{Results - stochastic models} -\textbf{The tabular results} can be summarized as follows: -\begin{enumerate} -\item \textbf{Model summary:} a count of the various variable types in your model (endogenous, jumpers, etc...). -\item \textbf{Eigenvalues} should be displayed, and you should see a confirmation of the Blanchard-Kahn conditions if you used the command \texttt{check} in your .mod file. -\item \textbf{Matrix of covariance of exogenous shocks:} this should square with the values of the shock variances and co-variances you provided in the .mod file. -\item \textbf{Policy and transition functions:} Solving the rational exectation model, $\mathbb{E}_t[f(y_{t+1},y_t,y_{t-1},u_t)]=0$ , means finding an unkown function, $y_t = g(y_{t-1},u_t)$ that could be plugged into the original model and satisfy the implied restrictions (the first order conditions). A first order approximation of this function can be written as $y_t = \bar{y} + g_y \hat{y}_{t-1} + g_u u_t$, with $\hat{y}_t = y_t-\bar{y}$ and $\bar{y}$ being the steadystate value of $y$, and where $g_x$ is the partial derivative of the $g$ function with respect to variable $x$. In other words, the function $g$ is a time recursive (approximated) representation of the model that can generate timeseries that will approximatively satisfy the rational expectation hypothesis contained in the original model. In Dynare, the table ``Policy and Transition function'' contains the elements of $g_y$ and $g_u$. Details on the policy and transition function can be found in Chapter \ref{ch:estadv}. -\item \textbf{Moments of simulated variables:} up to the fourth moments. -\item \textbf{Correlation of simulated variables:} these are the contemporaneous correlations, presented in a table. -\item \textbf{Autocorrelation of simulated variables:} up to the fifth lag, as specified in the options of \texttt{stoch\_simul}. -\end{enumerate} - -\textbf{The graphical results}, instead, show the actual impulse response functions for each of the endogenous variables, given that they actually moved. These can be especially useful in visualizing the shape of the transition functions and the extent to which each variable is affected. \textsf{\textbf{TIP!}} If some variables do not return to their steady state, either check that you have included enough periods in your simulations, or make sure that your model is stationary, i.e. that your steady state actually exists and is stable. If not, you should detrend your variables and rewrite your model in terms of those variables. - -\subsection{Results - deterministic models} -Automatically displayed results are much more scarce in the case of deterministic models. If you entered \texttt{steady}, you will get a list of your steady state results. If you entered \texttt{check}, eigenvalues will also be displayed and you should receive a statement that the rank condition has been satisfied, if all goes well! Finally, you will see some intermediate output: the errors at each iteration of the Newton solver used to estimate the solution to your model. \textsf{\textbf{TIP!}} You should see these errors decrease upon each iteration; if not, your model will probably not converge. If so, you may want to try to increase the periods for the transition to the new steady state (the number of simulations periods). But more often, it may be a good idea to revise your equations. Of course, although Dynare does not display a rich set of statistics and graphs corresponding to the simulated output, it does not mean that you cannot create these by hand from Matlab. To do so, you should start by looking at section \ref{sec:FindOut} of chapter \ref{ch:soladv} on finding, saving and viewing your output. - - - - - - - - - - - diff --git a/doc/userguide/ch-solbeh.tex b/doc/userguide/ch-solbeh.tex deleted file mode 100644 index 4d0aa0057..000000000 --- a/doc/userguide/ch-solbeh.tex +++ /dev/null @@ -1,86 +0,0 @@ -\chapter{Solving DSGE models - Behind the scenes of Dynare} \label{ch:solbeh} - -\section{Introduction} -The aim of this chapter is to peer behind the scenes of Dynare, or under its hood, to get an idea of the methodologies and algorithms used in its computations. Going into details would be beyond the scope of this User Guide which will instead remain at a high level. What you will find below will either comfort you in realizing that Dynare does what you expected of it - and what you would have also done if you had had to code it all yourself (with a little extra time on your hands!), or will spur your curiosity to have a look at more detailed material. If so, you may want to go through Michel Juillard's presentation on solving DSGE models to a first and second order (available on Michel Juillard's \href{http://jourdan.ens.fr/~michel/}{website}), or read \citet{CollardJuillard2001b} or \citet{SchmittGrohe2004} which gives a good overview of the most recent solution techniques based on perturbation methods. Finally, note that in this chapter we will focus on stochastic models - which is where the major complication lies, as explained in section \ref{sec:detstoch} of chapter \ref{ch:solbase}. For more details on the Newton-Raphson algorithm used in Dynare to solve deterministic models, see \citet{Juillard1996}. \\ - -\section{What is the advantage of a second order approximation?} -As noted in chapter \ref{ch:solbase} and as will become clear in the section below, linearizing a system of equations to the first order raises the issue of certainty equivalence. This is because only the first moments of the shocks enter the linearized equations, and when expectations are taken, they disappear. Thus, unconditional expectations of the endogenous variables are equal to their non-stochastic steady state values. \\ - -This may be an acceptable simplification to make. But depending on the context, it may instead be quite misleading. For instance, when using second order welfare functions to compare policies, you also need second order approximations of the policy function. Yet more clearly, in the case of asset pricing models, linearizing to the second order enables you to take risk (or the variance of shocks) into consideration - a highly desirable modeling feature. It is therefore very convenient that Dynare allows you to choose between a first or second order linearization of your model in the option of the \texttt{stoch\_simul} command. \\ - -\section{How does dynare solve stochastic DSGE models?} -In this section, we shall briefly overview the perturbation methods employed by Dynare to solve DSGE models to a first order approximation. The second order follows very much the same approach, although at a higher level of complexity. The summary below is taken mainly from Michel Juillard's presentation ``Computing first order approximations of DSGE models with Dynare'', which you should read if interested in particular details, especially regarding second order approximations (available on Michel Juillard's \href{http://jourdan.ens.fr/~michel/}{website}). \\ - -To summarize, a DSGE model is a collection of first order and equilibrium conditions that take the general form: -\[ -\mathbb{E}_t\left\{f(y_{t+1},y_t,y_{t-1},u_t)\right\}=0 -\] -\begin{eqnarray*} -\mathbb{E}(u_t) &=& 0\\ -\mathbb{E}(u_t u_t') &=& \Sigma_u -\end{eqnarray*} -and where: -\begin{description} - \item[$y$]: vector of endogenous variables of any dimension - \item[$u$]: vector of exogenous stochastic shocks of any dimension -\end{description} - -The solution to this system is a set of equations relating variables in the current period to the past state of the system and current shocks, that satisfy the original system. This is what we call the policy function. Sticking to the above notation, we can write this function as: -\[ -y_t = g(y_{t-1},u_t) -\] - -Then, it is straightforward to re-write $y_{t+1}$ as -\begin{eqnarray*} - y_{t+1} &=& g(y_t,u_{t+1})\\ - &=& g(g(y_{t-1},u_t),u_{t+1})\\ -\end{eqnarray*} - -We can then define a new function $F$, such that: -\[ -F(y_{t-1},u_t,u_{t+1}) = -f(g(g(y_{t-1},u_t),u_{t+1}),g(y_{t-1},u_t),y_{t-1},u_t)\\ -\] -which enables us to rewrite our system in terms of past variables, and current and future shocks: -\[ -\mathbb{E}_t\left[F(y_{t-1},u_t,u_{t+1})\right] = 0 -\] - -We then venture to linearize this model around a steady state defined as: -\[ -f(\bar y, \bar y, \bar y, 0) = 0 -\] -having the property that: -\[ -\bar y = g(\bar y, 0) -\] - -The first order Taylor expansion around $\bar y$ yields: -\begin{eqnarray*} -\lefteqn{\mathbb{E}_t\left\{F^{(1)}(y_{t-1},u_t,u_{t+1})\right\} =}\\ -&& \mathbb{E}_t\Big[f(\bar y, \bar y, \bar y)+f_{y_+}\left(g_y\left(g_y\hat y+g_uu \right)+g_u u' \right)\\ -&& + f_{y_0}\left(g_y\hat y+g_uu \right)+f_{y_-}\hat y+f_u u\Big]\\ -&& = 0 -\end{eqnarray*} -with $\hat y = y_{t-1} - \bar y$, $u=u_t$, $u'=u_{t+1}$, $f_{y_+}=\frac{\partial f}{\partial y_{t+1}}$, $f_{y_0}=\frac{\partial f}{\partial y_t}$, $f_{y_-}=\frac{\partial f}{\partial y_{t-1}}$, $f_{u}=\frac{\partial f}{\partial u_t}$, $g_y=\frac{\partial g}{\partial y_{t-1}}$, $g_u=\frac{\partial g}{\partial u_t}$.\\ - -Taking expectations (we're almost there!): -\begin{eqnarray*} - \lefteqn{\mathbb{E}_t\left\{F^{(1)}(y_{t-1},u_t, u_{t+1})\right\} =}\\ -&& f(\bar y, \bar y, \bar y)+f_{y_+}\left(g_y\left(g_y\hat y+g_uu \right) \right)\\ -&& + f_{y_0}\left(g_y\hat y+g_uu \right)+f_{y_-}\hat y+f_u u\Big\}\\ -&=& \left(f_{y_+}g_yg_y+f_{y_0}g_y+f_{y_-}\right)\hat y+\left(f_{y_+}g_yg_u+f_{y_0}g_u+f_{u}\right)u\\ -&=& 0\\ -\end{eqnarray*} - -As you can see, since future shocks only enter with their first moments (which are zero in expectations), they drop out when taking expectations of the linearized equations. This is technically why certainty equivalence holds in a system linearized to its first order. The second thing to note is that we have two unknown variables in the above equation: $g_y$ and $g_u$ each of which will help us recover the policy function $g$. \\ - -Since the above equation holds for any $\hat y$ and any $u$, each parenthesis must be null and we can solve each at a time. The first, yields a quadratic equation in $g_y$, which we can solve with a series of algebraic trics that are not all immediately apparent (but detailed in Michel Juillard's presentation). Incidentally, one of the conditions that comes out of the solution of this equation is the Blanchard-Kahn condition: there must be as many roots larger than one in modulus as there are forward-looking variables in the model. Having recovered $g_y$, recovering $g_u$ is then straightforward from the second parenthesis. \\ - -Finally, notice that a first order linearization of the function $g$ yields: -\[ -y_t = \bar y+g_y\hat y+g_u u -\] -And now that we have $g_y$ and $g_u$, we have solved for the (approximate) policy (or decision) function and have succeeded in solving our DSGE model. If we were interested in impulse response functions, for instance, we would simply iterate the policy function starting from an initial value given by the steady state. \\ - -The second order solution uses the same ``perturbation methods'' as above (the notion of starting from a function you can solve - like a steady state - and iterating forward), yet applies more complex algebraic techniques to recover the various partial derivatives of the policy function. But the general approach is perfectly isomorphic. Note that in the case of a second order approximation of a DSGE model, the variance of future shocks remains after taking expectations of the linearized equations and therefore affects the level of the resulting policy function.\\ diff --git a/doc/userguide/ch-trouble.tex b/doc/userguide/ch-trouble.tex deleted file mode 100644 index 7eb934337..000000000 --- a/doc/userguide/ch-trouble.tex +++ /dev/null @@ -1,3 +0,0 @@ -\chapter{Troubleshooting} \label{ch:trouble} - -To make sure this section is as user friendly as possible, the best is to compile what users have to say! Please let me know what your most common problem is with Dynare, how Dynare tells you about it and how you solve it. Thanks for your precious help! \ No newline at end of file diff --git a/doc/userguide/models/Alt_Ex1.mod b/doc/userguide/models/Alt_Ex1.mod deleted file mode 100644 index f28e9422b..000000000 --- a/doc/userguide/models/Alt_Ex1.mod +++ /dev/null @@ -1,43 +0,0 @@ -// example 1 from Collard's guide to Dynare -var y, c, k, a, h, b; -varexo e, u; -parameters beta, rho, alpha, delta, theta, psi, tau; - -alpha = 0.36; -rho = 0.95; -tau = 0.025; -beta = 0.99; -delta = 0.025; -psi = 0; -theta = 2.95; - -phi = 0.1; - -model; -c*theta*h^(1+psi)=(1-alpha)*y; -k = beta*(((exp(b)*c)/(exp(b(+1))*c(+1))) - *(exp(b(+1))*alpha*y(+1)+(1-delta)*k)); -y = exp(a)*(k(-1)^alpha)*(h^(1-alpha)); -k = exp(b)*(y-c)+(1-delta)*k(-1); -a = rho*a(-1)+tau*b(-1) + e; -b = tau*a(-1)+rho*b(-1) + u; -end; - -initval; -y = 1.08068253095672; -c = 0.80359242014163; -h = 0.29175631001732; -k = 5; -a = 0; -b = 0; -e = 0; -u = 0; -end; - -shocks; -var e; stderr 0.009; -var u; stderr 0.009; -var e, u = phi*0.009*0.009; -end; - -stoch_simul(periods=2100); \ No newline at end of file diff --git a/doc/userguide/models/RBC_DataGen.mod b/doc/userguide/models/RBC_DataGen.mod deleted file mode 100644 index 4fca5e1d8..000000000 --- a/doc/userguide/models/RBC_DataGen.mod +++ /dev/null @@ -1,69 +0,0 @@ -% Basic RBC Model with Monopolistic Competion. -% -% Jesus Fernandez-Villaverde -% Philadelphia, March 3, 2005 -%---------------------------------------------------------------- -% 0. Housekeeping -%---------------------------------------------------------------- - -close all - -%---------------------------------------------------------------- -% 1. Defining variables -%---------------------------------------------------------------- - -var y c k i l y_l w r z; -varexo e; -parameters beta psi delta alpha rho gamma sigma epsilon; - -%---------------------------------------------------------------- -% 2. Calibration -%---------------------------------------------------------------- - -alpha = 0.33; -beta = 0.99; -delta = 0.023; -psi = 1.75; -rho = 0.95; -sigma = (0.007/(1-alpha)); -epsilon = 10; - -%---------------------------------------------------------------- -% 3. Model -%---------------------------------------------------------------- - -model; - (1/c) = beta*(1/c(+1))*(1+r(+1)-delta); - psi*c/(1-l) = w; - c+i = y; - y = (k(-1)^alpha)*(exp(z)*l)^(1-alpha); - w = y*((epsilon-1)/epsilon)*(1-alpha)/l; - r = y*((epsilon-1)/epsilon)*alpha/k; - i = k-(1-delta)*k(-1); - y_l = y/l; - z = rho*z(-1)+e; -end; - -%---------------------------------------------------------------- -% 4. Computation -%---------------------------------------------------------------- - -initval; - k = 9; - c = 0.76; - l = 0.3; - w = 2.07; - r = 0.03; - z = 0; - e = 0; -end; - -shocks; -var e = sigma^2; -end; - -steady; - -stoch_simul(periods=1000,irf=0); -datatomfile('simuldataRBC',[]); -return; \ No newline at end of file diff --git a/doc/userguide/models/RBC_Est.mod b/doc/userguide/models/RBC_Est.mod deleted file mode 100644 index 21de3ec67..000000000 --- a/doc/userguide/models/RBC_Est.mod +++ /dev/null @@ -1,39 +0,0 @@ -var y c k i l y_l w r z; -varexo e; -parameters beta psi delta alpha rho epsilon; - -model; -(1/c) = beta*(1/c(+1))*(1+r(+1)-delta); -psi*c/(1-l) = w; -c+i = y; -y = (k(-1)^alpha)*(exp(z)*l)^(1-alpha); -w = y*((epsilon-1)/epsilon)*(1-alpha)/l; -r = y*((epsilon-1)/epsilon)*alpha/k(-1); -i = k-(1-delta)*k(-1); -y_l = y/l; -z = rho*z(-1)+e; -end; - -varobs y; - -initval; - k = 9; - c = 0.76; - l = 0.3; - w = 2.07; - r = 0.03; - z = 0; - e = 0; -end; - -estimated_params; -alpha, beta_pdf, 0.35, 0.02; -beta, beta_pdf, 0.99, 0.002; -delta, beta_pdf, 0.025, 0.003; -psi, gamma_pdf, 1.75, 0.1; -rho, beta_pdf, 0.95, 0.05; -epsilon, gamma_pdf, 10, 0.5; -stderr e, inv_gamma_pdf, 0.01, inf; -end; - -estimation(datafile=simuldataRBC,nobs=200,first_obs=500,mh_replic=2000,mh_nblocks=2,mh_drop=0.45,mh_jscale=0.8,mode_compute=4); diff --git a/doc/userguide/models/RBC_Monop_Det.mod b/doc/userguide/models/RBC_Monop_Det.mod deleted file mode 100644 index 0ef7275a4..000000000 --- a/doc/userguide/models/RBC_Monop_Det.mod +++ /dev/null @@ -1,42 +0,0 @@ -var y c k i l y_l w r ; -varexo z; -parameters beta psi delta alpha sigma epsilon; - -alpha = 0.33; -beta = 0.99; -delta = 0.023; -psi = 1.75; -sigma = (0.007/(1-alpha)); -epsilon = 10; - -model; - (1/c) = beta*(1/c(+1))*(1+r(+1)-delta); - psi*c/(1-l) = w; - c+i = y; - y = (k(-1)^alpha)*(exp(z)*l)^(1-alpha); - w = y*((epsilon-1)/epsilon)*(1-alpha)/l; - r = y*((epsilon-1)/epsilon)*alpha/k(-1); - i = k-(1-delta)*k(-1); - y_l = y/l; -end; - -initval; - k = 9; - c = 0.7; - l = 0.3; - w = 2.0; - r = 0; - z = 0; -end; - -steady; - -check; - -shocks; -var z; -periods 1:9; -values 0.1; -end; - -simul(periods=2100); \ No newline at end of file diff --git a/doc/userguide/models/RBC_Monop_JFV.mod b/doc/userguide/models/RBC_Monop_JFV.mod deleted file mode 100644 index 916eb9964..000000000 --- a/doc/userguide/models/RBC_Monop_JFV.mod +++ /dev/null @@ -1,43 +0,0 @@ -// Adapted from Jesus Fernandez-Villaverde, Basic RBC Model with Monopolistic Competion Philadelphia, March 3, 2005 -var y c k i l y_l w r z; -varexo e; -parameters beta psi delta alpha rho gamma sigma epsilon; - -alpha = 0.33; -beta = 0.99; -delta = 0.023; -psi = 1.75; -rho = 0.95; -sigma = (0.007/(1-alpha)); -epsilon = 10; - -model; - (1/c) = beta*(1/c(+1))*(1+r(+1)-delta); - psi*c/(1-l) = w; - c+i = y; - y = (k(-1)^alpha)*(exp(z)*l)^(1-alpha); - w = y*((epsilon-1)/epsilon)*(1-alpha)/l; - r = y*((epsilon-1)/epsilon)*alpha/k(-1); - i = k-(1-delta)*k(-1); - y_l = y/l; - z = rho*z(-1)+e; -end; - -initval; - k = 9; - c = 0.76; - l = 0.3; - w = 2.07; - r = 0.03; - z = 0; - e = 0; -end; - -steady; -check; - -shocks; -var e = sigma^2; -end; - -stoch_simul(periods=2100); diff --git a/doc/userguide/models/fs2000ns.mod b/doc/userguide/models/fs2000ns.mod deleted file mode 100644 index 002c87182..000000000 --- a/doc/userguide/models/fs2000ns.mod +++ /dev/null @@ -1,81 +0,0 @@ -// This file replicates the estimation of the CIA model from -// Frank Schorfheide (2000) "Loss function-based evaluation of DSGE models" -// Journal of Applied Econometrics, 15, 645-670. -// the data are the ones provided on Schorfheide's web site with the programs. -// http://www.econ.upenn.edu/~schorf/programs/dsgesel.ZIP -// You need to have fsdat.m in the same directory as this file. -// This file replicates: -// -the posterior mode as computed by Frank's Gauss programs -// -the parameter mean posterior estimates reported in the paper -// -the model probability (harmonic mean) reported in the paper -// This file was tested with dyn_mat_test_0218.zip -// the smooth shocks are probably stil buggy -// -// 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. -// Note that there is an initial minus sign missing in equation (A1), p. S63. -// -// Michel Juillard, February 2004 - -var m P c e W R k d n l Y_obs P_obs y dA; -varexo e_a e_m; -parameters alp bet gam mst rho psi del; - -model; -dA = exp(gam+e_a); -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; -W = l/n; --(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; -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; -c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1); -P*c = m; -m-1+d = l; -e = exp(e_a); -y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a)); -Y_obs/Y_obs(-1) = dA*y/y(-1); -P_obs/P_obs(-1) = (P/P(-1))*m(-1)/dA; -end; - -varobs P_obs Y_obs; - -observation_trends; -P_obs (log(mst)-gam); -Y_obs (gam); -end; - -initval; -k = 6; -m = mst; -P = 2.25; -c = 0.45; -e = 1; -W = 4; -R = 1.02; -d = 0.85; -n = 0.19; -l = 0.86; -y = 0.6; -dA = exp(gam); -end; - -// the above is really only useful if you want to do a stoch_simul -// of your model, since the estimation will use the Matlab -// steady state file also provided and discussed above. - -estimated_params; -alp, beta_pdf, 0.356, 0.02; -bet, beta_pdf, 0.993, 0.002; -gam, normal_pdf, 0.0085, 0.003; -mst, normal_pdf, 1.0002, 0.007; -rho, beta_pdf, 0.129, 0.223; -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; -end; - -estimation(datafile=fsdat,nobs=192,loglinear,mh_replic=2000, - mode_compute=4,mh_nblocks=2,mh_drop=0.45,mh_jscale=0.65,diffuse_filter); \ No newline at end of file diff --git a/doc/userguide/models/fs2000ns_steadystate.m b/doc/userguide/models/fs2000ns_steadystate.m deleted file mode 100644 index f9991e4d4..000000000 --- a/doc/userguide/models/fs2000ns_steadystate.m +++ /dev/null @@ -1,53 +0,0 @@ -% computes the steady state of fs2000 analyticaly -% largely inspired by the program of F. Schorfheide -function [ys,check] = fs2000ns_steadystate(ys,exe) -global M_ - -alp = M_.params(1); -bet = M_.params(2); -gam = M_.params(3); -mst = M_.params(4); -rho = M_.params(5); -psi = M_.params(6); -del = M_.params(7); - -check = 0; - -dA = exp(gam); -gst = 1/dA; -m = mst; - -khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1)); -xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1); -nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp ); -n = xist/(nust+xist); -P = xist + nust; -k = khst*n; -l = psi*mst*n/( (1-psi)*(1-n) ); -c = mst/P; -d = l - mst + 1; -y = k^alp*n^(1-alp)*gst^alp; -R = mst/bet; -W = l/n; -ist = y-c; -q = 1 - d; -e = 1; - -P_obs = 1; -Y_obs = 1; - -ys =[ - m - P - c - e - W - R - k - d - n - l - Y_obs - P_obs - y - dA ]; \ No newline at end of file diff --git a/doc/userguide/models/fsdat.m b/doc/userguide/models/fsdat.m deleted file mode 100644 index ef1279c0b..000000000 --- a/doc/userguide/models/fsdat.m +++ /dev/null @@ -1,210 +0,0 @@ -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 - ]; -%GDPD GDPQ GPOP - -series = zeros(193,2); -series(:,2) = data_q(:,1); -series(:,1) = 1000*data_q(:,2)./data_q(:,3); - -Y_obs = series(:,1); -P_obs = series(:,2); - -series = series(2:193,:)./series(1:192,:); - -gy_obs = series(:,1); -gp_obs = series(:,2); - -ti = [1950:0.25:1997.75]; \ No newline at end of file diff --git a/license.txt b/license.txt index 215a5638e..b1fdb47cd 100644 --- a/license.txt +++ b/license.txt @@ -198,10 +198,6 @@ Files: doc/dynare.texi doc/*.tex doc/*.svg doc/*.pdf doc/*.bib Copyright: 1996-2017 Dynare Team License: GFDL-NIV-1.3+ -Files: doc/userguide/*.tex doc/userguide/*.bib doc/userguide/*.pdf -Copyright: 2007-2013 Tommaso Mancini Griffoli -License: GFDL-NIV-1.3+ - Files: doc/macroprocessor/* Copyright: 2008-2015 Dynare Team License: CC-BY-SA-4.0 diff --git a/matlab/backward/backward_model_forecast.m b/matlab/backward/backward_model_forecast.m index 565648d35..64c808134 100644 --- a/matlab/backward/backward_model_forecast.m +++ b/matlab/backward/backward_model_forecast.m @@ -31,7 +31,7 @@ global M_ options_ oo_ % Check that the model is actually backward if M_.maximum_lead - error(['backward_model_irf:: The specified model is not backward looking!']) + error(['backward_model_forecast:: The specified model is not backward looking!']) end % Initialize returned argument. @@ -53,14 +53,17 @@ if nargin<4 withuncertainty = false; end -% Get full list of endogenous variables -endo_names = cellstr(M_.endo_names); +start = initialcondition.dates(end)+1; + +% Set up initial conditions +[initialcondition, periods, innovations, DynareOptions, DynareModel, DynareOutput, endonames, exonames, nx, ny1, iy1, jdx, model_dynamic, y] = ... + simul_backward_model_init(initialcondition, periods, options_, M_, oo_, zeros(periods, M_.exo_nbr)); % Get vector of indices for the selected endogenous variables. n = length(listofvariables); idy = zeros(n,1); for i=1:n - j = find(strcmp(listofvariables{i}, endo_names)); + j = find(strcmp(listofvariables{i}, endonames)); if isempty(j) error('backward_model_forecast:: Variable %s is unknown!', listofvariables{i}) else @@ -79,37 +82,28 @@ if withuncertainty sigma = transpose(chol(Sigma)); end -% Set initial condition. -if isdates(initialcondition) - if isempty(M_.endo_histval) - error('backward_model_irf: histval block for setting initial condition is missing!') - end - initialcondition = dseries(transpose(M_.endo_histval), initialcondition, endo_names, cellstr(M_.endo_names_tex)); +% Compute forecast without shock +if options_.linear + ysim__0 = simul_backward_linear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, nx, ny1, iy1, jdx, model_dynamic); +else + ysim__0 = simul_backward_nonlinear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, iy1, model_dynamic); end +forecasts.pointforecast = dseries(transpose(ysim__0(idy,:)), initialcondition.init, listofvariables); -% Put initial conditions in a vector of doubles -initialconditions = transpose(initialcondition{endo_names{:}}.data); - -% Compute forecast without shock -innovations = zeros(periods+M_.maximum_exo_lag, M_.exo_nbr); -if M_.maximum_exo_lag - if isempty(M_.exo_histval) - error('You need to set the past values for the exogenous variables!') - else - innovations(1:M_.maximum_exo_lag, :) = M_.exo_histval; - end -end - -oo__0 = simul_backward_model(initialconditions, periods, options_, M_, oo_, innovations); -forecasts.pointforecast = dseries(transpose(oo__0.endo_simul(idy,:)), initialcondition.init, listofvariables); +% Set first period of forecast +forecasts.start = start; if withuncertainty % Preallocate an array gathering the simulations. - ArrayOfForecasts = zeros(n, periods+size(initialconditions, 2), B); + ArrayOfForecasts = zeros(n, periods+initialcondition.nobs, B); for i=1:B - innovations(M_.maximum_exo_lag+1:end,:) = transpose(sigma*randn(M_.exo_nbr, periods)); - oo__ = simul_backward_model(initialconditions, periods, options_, M_, oo_, innovations); - ArrayOfForecasts(:,:,i) = oo__.endo_simul(idy,:); + innovations = transpose(sigma*randn(M_.exo_nbr, periods)); + if options_.linear + [ysim__, xsim__] = simul_backward_linear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, nx, ny1, iy1, jdx, model_dynamic); + else + [ysim__, xsim__] = simul_backward_nonlinear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, iy1, model_dynamic); + end + ArrayOfForecasts(:,:,i) = ysim__(idy,:); end % Compute mean (over future uncertainty) forecast. forecasts.meanforecast = dseries(transpose(mean(ArrayOfForecasts, 3)), initialcondition.init, listofvariables); diff --git a/matlab/backward/backward_model_irf.m b/matlab/backward/backward_model_irf.m index 581d12153..07f01e14b 100644 --- a/matlab/backward/backward_model_irf.m +++ b/matlab/backward/backward_model_irf.m @@ -58,63 +58,47 @@ else transform = varargin{2}; end -% Get list of all exogenous variables in a cell of strings -exo_names = cellstr(M_.exo_names); - -% Get the list of all exogenous variables in a cell of strings -endo_names = cellstr(M_.endo_names); - -% Set initial condition. -if isdates(initialcondition) - if isempty(M_.endo_histval) - error('backward_model_irf: histval block for setting initial condition is missing!') - end - initialcondition = dseries(transpose(M_.endo_histval), initialcondition, endo_names, cellstr(M_.endo_names_tex)); -end +% Set up initial conditions +[initialcondition, periods, innovations, DynareOptions, DynareModel, DynareOutput, endonames, exonames, nx, ny1, iy1, jdx, model_dynamic, y] = ... + simul_backward_model_init(initialcondition, periods, options_, M_, oo_, zeros(periods, M_.exo_nbr)); % Get the covariance matrix of the shocks. Sigma = M_.Sigma_e + 1e-14*eye(M_.exo_nbr); sigma = transpose(chol(Sigma)); -% Put initial conditions in a vector of doubles -initialconditions = transpose(initialcondition{endo_names{:}}.data); - % Initialization of the returned argument. Each will be a dseries object containing the IRFS for the endogenous variables listed in the third input argument. irfs = struct(); -% Get the covariance matrix of the shocks. -Sigma = M_.Sigma_e + 1e-14*eye(M_.exo_nbr); -sigma = transpose(chol(Sigma)); - % Compute the IRFs (loop over innovations). for i=1:length(listofshocks) + innovations = zeros(periods, DynareModel.exo_nbr); % Get transition paths induced by the initial condition. - innovations = zeros(periods, M_.exo_nbr); - if ~isempty(M_.exo_histval) - innovations = [transpose(M_.exo_histval); innovations]; - shift = size(M_.exo_histval, 2); + if options_.linear + ysim__0 = simul_backward_linear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, nx, ny1, iy1, jdx, model_dynamic); else - innovations = [zeros(1, M_.exo_nbr); innovations]; - shift = 1; + ysim__0 = simul_backward_nonlinear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, iy1, model_dynamic); end - oo__0 = simul_backward_model(initialconditions, periods, options_, M_, oo_, innovations); % Add the shock. - j = find(strcmp(listofshocks{i}, exo_names)); + j = find(strcmp(listofshocks{i}, exonames)); if isempty(j) error('backward_model_irf: Exogenous variable %s is unknown!', listofshocks{i}) end - innovations(shift+1,:) = transpose(sigma(:,j)); - oo__1 = simul_backward_model(initialconditions, periods, options_, M_, oo_, innovations); + innovations(1,:) = transpose(sigma(:,j)); + if options_.linear + ysim__1 = simul_backward_linear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, nx, ny1, iy1, jdx, model_dynamic); + else + ysim__1 = simul_backward_nonlinear_model_(initialcondition, periods, DynareOptions, DynareModel, DynareOutput, innovations, iy1, model_dynamic); + end % Transform the endogenous variables if notransform - endo_simul__0 = oo__0.endo_simul; - endo_simul__1 = oo__1.endo_simul; + endo_simul__0 = ysim__0; + endo_simul__1 = ysim__1; else - endo_simul__0 = feval(transform, oo__0.endo_simul); - endo_simul__1 = feval(transform, oo__1.endo_simul); + endo_simul__0 = feval(transform, ysim__0); + endo_simul__1 = feval(transform, ysim__1); end % Instantiate a dseries object (with all the endogenous variables) - allirfs = dseries(transpose(endo_simul__1-endo_simul__0), initialcondition.init, cellstr(M_.endo_names), cellstr(M_.endo_names_tex)); + allirfs = dseries(transpose(endo_simul__1-endo_simul__0), initialcondition.init, endonames, cellstr(DynareModel.endo_names_tex)); % Extract a sub-dseries object irfs.(listofshocks{i}) = allirfs{listofvariables{:}}; end \ No newline at end of file diff --git a/matlab/backward/get_lags_on_endogenous_variables.m b/matlab/backward/get_lags_on_endogenous_variables.m new file mode 100644 index 000000000..6b53dd59e --- /dev/null +++ b/matlab/backward/get_lags_on_endogenous_variables.m @@ -0,0 +1,31 @@ +function l = get_lags_on_endogenous_variables(DynareModel) + +% Returns a vector with the max lag for each endogenous variable. + +% Copyright (C) 2017 Dynare Team +% +% This file is part of Dynare. +% +% Dynare is free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% Dynare is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% You should have received a copy of the GNU General Public License +% along with Dynare. If not, see . + +l = zeros(DynareModel.orig_endo_nbr, 1); +l(find(DynareModel.lead_lag_incidence(1,1:DynareModel.orig_endo_nbr))) = -1; + +if ~isempty(DynareModel.aux_vars) + aux_var_for_lagged_endogenous = find([DynareModel.aux_vars(:).type]==1); + for i=1:length(aux_var_for_lagged_endogenous) + l(DynareModel.aux_vars(aux_var_for_lagged_endogenous(i)).orig_index) = ... + DynareModel.aux_vars(aux_var_for_lagged_endogenous(i)).orig_lead_lag; + end +end \ No newline at end of file diff --git a/matlab/backward/get_lags_on_exogenous_variables.m b/matlab/backward/get_lags_on_exogenous_variables.m new file mode 100644 index 000000000..b5465b715 --- /dev/null +++ b/matlab/backward/get_lags_on_exogenous_variables.m @@ -0,0 +1,30 @@ +function l = get_lags_on_exogenous_variables(DynareModel) + +% Returns a vector with the max lag for each exogenous variable. + +% Copyright (C) 2017 Dynare Team +% +% This file is part of Dynare. +% +% Dynare is free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% Dynare is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% You should have received a copy of the GNU General Public License +% along with Dynare. If not, see . + +l = zeros(DynareModel.exo_nbr, 1); + +if ~isempty(DynareModel.aux_vars) + aux_var_for_lagged_exogenous = find([DynareModel.aux_vars(:).type]==3); + for i=1:length(aux_var_for_lagged_exogenous) + l(DynareModel.aux_vars(aux_var_for_lagged_exogenous(i)).orig_index) = ... + DynareModel.aux_vars(aux_var_for_lagged_exogenous(i)).orig_lead_lag-1; + end +end \ No newline at end of file diff --git a/matlab/backward/simul_backward_linear_model.m b/matlab/backward/simul_backward_linear_model.m index 1d8825628..0a454a697 100644 --- a/matlab/backward/simul_backward_linear_model.m +++ b/matlab/backward/simul_backward_linear_model.m @@ -1,4 +1,4 @@ -function DynareOutput = simul_backward_linear_model(varargin) +function simulations = simul_backward_linear_model(varargin) % Simulates a stochastic linear backward looking model. % @@ -38,40 +38,9 @@ function DynareOutput = simul_backward_linear_model(varargin) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -[initialconditions, samplesize, innovations, DynareOptions, DynareModel, DynareOutput, nx, ny1, iy1, jdx, model_dynamic, y] = ... +[initialconditions, samplesize, innovations, DynareOptions, DynareModel, DynareOutput, endonames, exonames, nx, ny1, iy1, jdx, model_dynamic, y] = ... simul_backward_model_init(varargin{:}); -% initialization of the returned simulations. -DynareOutput.endo_simul = NaN(DynareModel.endo_nbr,samplesize); -if isempty(initialconditions) - if isfield(DynareModel,'endo_histval') && ~isempty(DynareModel.endo_histval) - DynareOutput.endo_simul = [DynareModel.endo_histval, DynareOutput.endo_simul]; - else - DynareOutput.endo_simul = [zeros(DynareModel.endo_nbr, DynareModel.max_lag_orig), DynareOutput.endo_simul]; - end -else - if ~isequal(size(initialconditions, 2), DynareModel.max_lag_orig) - error(['simul_backward_linear_model:: First argument should have %s columns!'], DynareModel.max_lag_orig) - end - DynareOutput.endo_simul = [initialconditions, DynareOutput.endo_simul]; -end -Y = DynareOutput.endo_simul; +[ysim, xsim] = simul_backward_linear_model_(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations, nx, ny1, iy1, jdx, model_dynamic); -DynareOutput.exo_simul = [ zeros(1, DynareModel.exo_nbr); DynareOutput.exo_simul]; - -% Get coefficients -[cst, jacob] = model_dynamic(zeros(DynareModel.endo_nbr+ny1,1), ... - zeros(DynareModel.max_lag_orig+1,DynareModel.exo_nbr), ... - DynareModel.params, ... - DynareOutput.steady_state, DynareModel.max_lag_orig+1); - -A0inv = inv(jacob(:,jdx)); -A1 = jacob(:,nonzeros(DynareModel.lead_lag_incidence(1,:))); -B = jacob(:,end-nx+1:end); - -% Simulations -for it = 1+(1:samplesize) - Y(:,it) = -A0inv*(cst + A1*Y(iy1,it-1) + B*DynareOutput.exo_simul(it,:)'); -end - -DynareOutput.endo_simul = Y; \ No newline at end of file +simulations = [dseries(ysim', initialconditions.init, endonames(1:DynareModel.orig_endo_nbr)), dseries(xsim, initialconditions.init, exonames)]; \ No newline at end of file diff --git a/matlab/backward/simul_backward_linear_model_.m b/matlab/backward/simul_backward_linear_model_.m new file mode 100644 index 000000000..d22db5228 --- /dev/null +++ b/matlab/backward/simul_backward_linear_model_.m @@ -0,0 +1,61 @@ +function [ysim, xsim] = simul_backward_linear_model_(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations, nx, ny1, iy1, jdx, model_dynamic) + +% Simulates a stochastic linear backward looking model. +% +% INPUTS +% - initialconditions [double] n*1 vector, initial conditions for the endogenous variables. +% - samplesize [integer] scalar, number of periods for the simulation. +% - DynareOptions [struct] Dynare's options_ global structure. +% - DynareModel [struct] Dynare's M_ global structure. +% - DynareOutput [struct] Dynare's oo_ global structure. +% - innovations [double] T*q matrix, innovations to be used for the simulation. +% +% OUTPUTS +% - DynareOutput [struct] Dynare's oo_ global structure. +% +% REMARKS +% [1] The innovations used for the simulation are saved in DynareOutput.exo_simul, and the resulting paths for the endogenous +% variables are saved in DynareOutput.endo_simul. +% [2] The last input argument is not mandatory. If absent we use random draws and rescale them with the informations provided +% through the shocks block. +% [3] If the first input argument is empty, the endogenous variables are initialized with 0, or if available with the informations +% provided thrtough the histval block. + +% Copyright (C) 2017 Dynare Team +% +% This file is part of Dynare. +% +% Dynare is free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% Dynare is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% You should have received a copy of the GNU General Public License +% along with Dynare. If not, see . + +if ~isempty(innovations) + DynareOutput.exo_simul(initialconditions.nobs+(1:samplesize),:) = innovations; +end + +% Get coefficients +[cst, jacob] = model_dynamic(zeros(DynareModel.endo_nbr+ny1,1), ... + zeros(DynareModel.max_lag_orig+1,DynareModel.exo_nbr), ... + DynareModel.params, ... + DynareOutput.steady_state, DynareModel.max_lag_orig+1); + +A0inv = inv(jacob(:,jdx)); +A1 = jacob(:,nonzeros(DynareModel.lead_lag_incidence(1,:))); +B = jacob(:,end-nx+1:end); + +% Simulations +for it = initialconditions.nobs+(1:samplesize) + DynareOutput.endo_simul(:,it) = -A0inv*(cst + A1*DynareOutput.endo_simul(iy1,it-1) + B*DynareOutput.exo_simul(it,:)'); +end + +ysim = DynareOutput.endo_simul(1:DynareModel.orig_endo_nbr,:); +xsim = DynareOutput.exo_simul; \ No newline at end of file diff --git a/matlab/backward/simul_backward_model.m b/matlab/backward/simul_backward_model.m index e61a9d712..d7307891e 100644 --- a/matlab/backward/simul_backward_model.m +++ b/matlab/backward/simul_backward_model.m @@ -1,4 +1,4 @@ -function DynareOutput = simul_backward_model(varargin) +function simulation = simul_backward_model(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations) % Simulates a stochastic backward looking model (with arbitrary precision). % @@ -11,7 +11,7 @@ function DynareOutput = simul_backward_model(varargin) % - innovations [double] T*q matrix, innovations to be used for the simulation. % % OUTPUTS -% - DynareOutput [struct] Dynare's oo_ global structure. +% - simulation [dseries] Simulated endogenous and exogenous variables. % % REMARKS % [1] The innovations used for the simulation are saved in DynareOutput.exo_simul, and the resulting paths for the endogenous @@ -38,10 +38,14 @@ function DynareOutput = simul_backward_model(varargin) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -[initialconditions, samplesize, innovations, DynareOptions, DynareModel, DynareOutput] = simul_backward_model_init(varargin{:}); +if nargin<6 + innovations =[]; +end + +%[initialconditions, samplesize, innovations, DynareOptions, DynareModel, DynareOutput] = simul_backward_model_init(varargin{:}); if DynareOptions.linear - DynareOutput = simul_backward_linear_model(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations); + simulation = simul_backward_linear_model(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations); else - DynareOutput = simul_backward_nonlinear_model(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations); + simulation = simul_backward_nonlinear_model(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations); end \ No newline at end of file diff --git a/matlab/backward/simul_backward_model_init.m b/matlab/backward/simul_backward_model_init.m index d45f73ff3..1e7dff7ad 100644 --- a/matlab/backward/simul_backward_model_init.m +++ b/matlab/backward/simul_backward_model_init.m @@ -1,8 +1,8 @@ -function [initialconditions, samplesize, innovations, DynareOptions, DynareModel, DynareOutput, nx, ny1, iy1, jdx, model_dynamic, y] = simul_backward_model_init(varargin) +function [initialconditions, samplesize, innovations, DynareOptions, DynareModel, DynareOutput, endonames, exonames, nx, ny1, iy1, jdx, model_dynamic, y] = simul_backward_model_init(varargin) % Initialization of the routines simulating backward models. -% Copyright (C) 2012-2017 Dynare Team +% Copyright (C) 2017 Dynare Team % % This file is part of Dynare. % @@ -20,17 +20,136 @@ function [initialconditions, samplesize, innovations, DynareOptions, DynareModel % along with Dynare. If not, see . initialconditions = varargin{1}; -samplesize = varargin{2}; +if ~isdseries(initialconditions) + error('First input argument must be a dseries object') +end + +samplesize = varargin{2}; DynareOptions = varargin{3}; DynareModel = varargin{4}; DynareOutput = varargin{5}; +% Test if the model is backward. if DynareModel.maximum_lead error('simul_backward_nonlinear_model:: The specified model is not backward looking!') end -if nargin<6 +% Test if the first argument is a dseries object. +if ~isdseries(initialconditions) + error('First input argument must be a dseries object!') +end + +% Test if the first argument contains all the lagged endogenous variables +endonames = cellstr(DynareModel.endo_names); +missingendogenousvariables = setdiff(endonames, initialconditions.name); +endolags = get_lags_on_endogenous_variables(DynareModel); +endolags_ = endolags(find(endolags)); +endowithlagnames = endonames(find(endolags)); +if ~isempty(missingendogenousvariables) + missingendogenousvariables = setdiff(endowithlagnames, initialconditions.name); + missingendogenouslaggedvariables = intersect(endowithlagnames, missingendogenousvariables); + if ~isempty(missingendogenouslaggedvariables) + disp('You have to initialize the following endogenous variables:') + msg = sprintf('%s\n', missingendogenouslaggedvariables{1:end-1}); + msg = sprintf('%s%s', msg, missingendogenouslaggedvariables{end}); + disp(msg) + skipline() + error('Please fix the dseries object used for setting the initial conditions!') + end +end + +% Test if we have enough periods in the database. +maxlag = abs(min(endolags)); +if maxlag>initialconditions.nobs + error('The dseries object provided as first input argument should at least have %s periods!', num2str(maxlag)) +end +missinginitialcondition = false; +for i = 1:length(endowithlagnames) + lags = abs(endolags_(i)); + variable = initialconditions{endowithlagnames{i}}; + nanvalues = isnan(variable.data); + if any(nanvalues(end-(lags-1):end)) + missinginitialcondition = true; + for j=variable.nobs:-1:variable.nobs-(lags-1) + if isnan(variable.data(j)) + disp(sprintf('Variable %s should not have a NaN value in period %s.', endowithlagnames{i}, date2string(variable.dates(j)))) + end + end + end +end +if missinginitialcondition + skipline() + error('Please fix the dseries object used for setting the initial conditions!') +end + +% If the model has lags on the exogenous variables, test if we have corresponding initial conditions. +exonames = cellstr(DynareModel.exo_names); +missingexogenousvariables = setdiff(exonames, initialconditions.name); +exolags = get_lags_on_exogenous_variables(DynareModel); +exolags_ = exolags(find(exolags)); +exowithlagnames = exonames(find(exolags)); +if ~isempty(missingexogenousvariables) + missingexogenousvariables = setdiff(exowithlagnames, initialconditions.name); + missingexogenouslaggedvariables = intersect(exowithlagnames, missingexogenousvariables); + if ~isempty(missingexogenouslaggedvariables) + disp('You have to initialize the following exogenous variables:') + msg = sprintf('%s\n', missingexogenouslaggedvariables{1:end-1}); + msg = sprintf('%s%s', msg, missingexogenouslaggedvariables{end}); + disp(msg) + skipline() + error('Please fix the dseries object used for setting the initial conditions!') + end +end + +% Test if we have enough periods in the database. +maxlag = abs(min(exolags)); +if maxlag>initialconditions.nobs + error('The dseries object provided as first input argument should at least have %s periods!', num2str(maxlag)) +end +missinginitialcondition = false; +for i = 1:length(exowithlagnames) + lags = abs(exolags_(i)); + variable = initialconditions{exowithlagnames{i}}; + nanvalues = isnan(variable.data); + if any(nanvalues(end-(lags-1):end)) + missinginitialcondition = true; + for j=variable.nobs:-1:variable.nobs-(lags-1) + if isnan(variable.data(j)) + disp(sprintf('Variable %s should not have a NaN value in period %s.', exowithlagnames{i}, date2string(variable.dates(j)))) + end + end + end +end +if missinginitialcondition + skipline() + error('Please fix the dseries object used for setting the initial conditions!') +end + +% Add auxiliary variables to the database. +k = 0; +for i = DynareModel.orig_endo_nbr+1:DynareModel.endo_nbr + k = k+1; + if DynareModel.aux_vars(k).type==1 + if ismember(deblank(DynareModel.endo_names(DynareModel.aux_vars(k).orig_index,:)), initialconditions.name) + initialconditions{deblank(DynareModel.endo_names(DynareModel.aux_vars(k).endo_index, :))} = ... + initialconditions{deblank(DynareModel.endo_names(DynareModel.aux_vars(k).orig_index, :))}.lag(abs(DynareModel.aux_vars(k).orig_lead_lag)); + else + error('This is a bug. Please contact Dynare Team!'); + end + elseif DynareModel.aux_vars(k).type==3 + if ismember(deblank(DynareModel.exo_names(DynareModel.aux_vars(k).orig_index, :)), initialconditions.name) + initialconditions{deblank(DynareModel.endo_names(DynareModel.aux_vars(k).endo_index,:))} = ... + initialconditions{deblank(DynareModel.exo_names(DynareModel.aux_vars(k).orig_index, :))}.lag(abs(DynareModel.aux_vars(k).orig_lead_lag)); + else + error('This is a bug. Please contact Dynare Team!'); + end + else + error('Cannot simulate the model with this type of auxiliary variables!') + end +end + +if nargin<6 || isempty(varargin{6}) % Set the covariance matrix of the structural innovations. variances = diag(DynareModel.Sigma_e); number_of_shocks = length(DynareModel.Sigma_e); @@ -52,18 +171,30 @@ if nargin<6 % Put the simulated innovations in DynareOutput.exo_simul. DynareOutput.exo_simul = zeros(samplesize,number_of_shocks); DynareOutput.exo_simul(:,positive_var_indx) = DynareOutput.bnlms.shocks; - if isfield(DynareModel,'exo_histval') && ~ isempty(DynareModel.exo_histval) - DynareOutput.exo_simul = [transpose(DynareModel.exo_histval); DynareOutput.exo_simul]; - else - DynareOutput.exo_simul = [zeros(1,number_of_shocks); DynareOutput.exo_simul]; - end innovations = DynareOutput.exo_simul; else innovations = varargin{6}; DynareOutput.exo_simul = innovations; % innovations end -if nargout>6 +% Initialization of the returned simulations. +DynareOutput.endo_simul = NaN(DynareModel.endo_nbr, samplesize+initialconditions.nobs); +for i=1:length(endonames) + if ismember(endonames{i}, initialconditions.name) + DynareOutput.endo_simul(i,1:initialconditions.nobs) = transpose(initialconditions{endonames{i}}.data); + end +end + +% Initialization of the array for the exogenous variables. +DynareOutput.exo_simul = [NaN(initialconditions.nobs, DynareModel.exo_nbr); DynareOutput.exo_simul ]; +for i=1:length(exonames) + if ismember(exonames{i}, initialconditions.name) + DynareOutput.exo_simul(1:initialconditions.nobs, i) = initialconditions{exonames{i}}.data; + end +end + + +if nargout>8 nx = size(DynareOutput.exo_simul,2); ny0 = nnz(DynareModel.lead_lag_incidence(2,:)); ny1 = nnz(DynareModel.lead_lag_incidence(1,:)); diff --git a/matlab/backward/simul_backward_nonlinear_model.m b/matlab/backward/simul_backward_nonlinear_model.m index c5061a6da..75966638e 100644 --- a/matlab/backward/simul_backward_nonlinear_model.m +++ b/matlab/backward/simul_backward_nonlinear_model.m @@ -1,4 +1,4 @@ -function DynareOutput = simul_backward_nonlinear_model(varargin) +function simulations = simul_backward_nonlinear_model(varargin) % Simulates a stochastic non linear backward looking model with arbitrary precision (a deterministic solver is used). % @@ -38,35 +38,9 @@ function DynareOutput = simul_backward_nonlinear_model(varargin) % You should have received a copy of the GNU General Public License % along with Dynare. If not, see . -[initialconditions, samplesize, innovations, DynareOptions, DynareModel, DynareOutput, nx, ny1, iy1, jdx, model_dynamic, y] = ... +[initialconditions, samplesize, innovations, DynareOptions, DynareModel, DynareOutput, endonames, exonames, nx, ny1, iy1, jdx, model_dynamic, y] = ... simul_backward_model_init(varargin{:}); -model_dynamic_s = str2func('dynamic_backward_model_for_simulation'); +[ysim, xsim] = simul_backward_nonlinear_model_(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations, iy1, model_dynamic); -% initialization of the returned simulations. -DynareOutput.endo_simul = NaN(DynareModel.endo_nbr, samplesize); -if isempty(initialconditions) - if isfield(DynareModel,'endo_histval') && ~isempty(DynareModel.endo_histval) - DynareOutput.endo_simul = [DynareModel.endo_histval, DynareOutput.endo_simul]; - else - warning('simul_backward_nonlinear_model:: Initial condition is zero for all variables! The model simulation may fail with the default initialization.') - DynareOutput.endo_simul = [zeros(DynareModel.endo_nbr, DynareModel.max_lag_orig), DynareOutput.endo_simul]; - end -else - if ~isequal(size(initialconditions, 2), DynareModel.max_lag_orig) - error(['simul_backward_nonlinear_model:: First argument should have %s columns!'], DynareModel.max_lag_orig) - end - DynareOutput.endo_simul = [initialconditions, DynareOutput.endo_simul]; -end -Y = DynareOutput.endo_simul; - -DynareOutput.exo_simul = [ zeros(1, DynareModel.exo_nbr); DynareOutput.exo_simul]; - -% Simulations (call a Newton-like algorithm for each period). -for it = 1+(1:samplesize) - ylag = Y(iy1,it-1); % Set lagged variables. - y = Y(:,it-1); % A good guess for the initial conditions is the previous values for the endogenous variables. - Y(:,it) = dynare_solve(model_dynamic_s, y, DynareOptions, model_dynamic, ylag, DynareOutput.exo_simul, DynareModel.params, DynareOutput.steady_state, it); -end - -DynareOutput.endo_simul = Y; \ No newline at end of file +simulations = [dseries(ysim', initialconditions.init, endonames(1:DynareModel.orig_endo_nbr)), dseries(xsim, initialconditions.init, exonames)]; \ No newline at end of file diff --git a/matlab/backward/simul_backward_nonlinear_model_.m b/matlab/backward/simul_backward_nonlinear_model_.m new file mode 100644 index 000000000..9a3e66c9d --- /dev/null +++ b/matlab/backward/simul_backward_nonlinear_model_.m @@ -0,0 +1,55 @@ +function [ysim, xsim] = simul_backward_nonlinear_model_(initialconditions, samplesize, DynareOptions, DynareModel, DynareOutput, innovations, iy1, model_dynamic) + +% Simulates a stochastic non linear backward looking model with arbitrary precision (a deterministic solver is used). +% +% INPUTS +% - initial_conditions [double] n*1 vector, initial conditions for the endogenous variables. +% - sample_size [integer] scalar, number of periods for the simulation. +% - DynareOptions [struct] Dynare's options_ global structure. +% - DynareModel [struct] Dynare's M_ global structure. +% - DynareOutput [struct] Dynare's oo_ global structure. +% - innovations [double] T*q matrix, innovations to be used for the simulation. +% +% OUTPUTS +% - DynareOutput [struct] Dynare's oo_ global structure. +% +% REMARKS +% [1] The innovations used for the simulation are saved in DynareOutput.exo_simul, and the resulting paths for the endogenous +% variables are saved in DynareOutput.endo_simul. +% [2] The last input argument is not mandatory. If absent we use random draws and rescale them with the informations provided +% through the shocks block. +% [3] If the first input argument is empty, the endogenous variables are initialized with 0, or if available with the informations +% provided thrtough the histval block. + +% Copyright (C) 2017 Dynare Team +% +% This file is part of Dynare. +% +% Dynare is free software: you can redistribute it and/or modify +% it under the terms of the GNU General Public License as published by +% the Free Software Foundation, either version 3 of the License, or +% (at your option) any later version. +% +% Dynare is distributed in the hope that it will be useful, +% but WITHOUT ANY WARRANTY; without even the implied warranty of +% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +% GNU General Public License for more details. +% +% You should have received a copy of the GNU General Public License +% along with Dynare. If not, see . + +model_dynamic_s = str2func('dynamic_backward_model_for_simulation'); + +if ~isempty(innovations) + DynareOutput.exo_simul(initialconditions.nobs+(1:samplesize),:) = innovations; +end + +% Simulations (call a Newton-like algorithm for each period). +for it = initialconditions.nobs+(1:samplesize) + ylag = DynareOutput.endo_simul(iy1,it-1); % Set lagged variables. + y = DynareOutput.endo_simul(:,it-1); % A good guess for the initial conditions is the previous values for the endogenous variables. + DynareOutput.endo_simul(:,it) = dynare_solve(model_dynamic_s, y, DynareOptions, model_dynamic, ylag, DynareOutput.exo_simul, DynareModel.params, DynareOutput.steady_state, it); +end + +ysim = DynareOutput.endo_simul(1:DynareModel.orig_endo_nbr,:); +xsim = DynareOutput.exo_simul; \ No newline at end of file diff --git a/matlab/dsge_simulated_theoretical_variance_decomposition.m b/matlab/dsge_simulated_theoretical_variance_decomposition.m index 3441b152e..c1c6d6207 100644 --- a/matlab/dsge_simulated_theoretical_variance_decomposition.m +++ b/matlab/dsge_simulated_theoretical_variance_decomposition.m @@ -54,7 +54,7 @@ end if posterior delete_stale_file([M_.dname '/metropolis/' M_.fname '_PosteriorVarianceDecomposition*']); else - delete_stale_file([M_.dname '/prior/moments/' M_.fname '_PosteriorVarianceDecomposition*']); + delete_stale_file([M_.dname '/prior/moments/' M_.fname '_PriorVarianceDecomposition*']); end % Set varlist (vartan) @@ -159,4 +159,4 @@ for file = 1:NumberOfDrawsFiles end end -options_.ar = nar; \ No newline at end of file +options_.ar = nar; diff --git a/matlab/one_sided_hp_filter.m b/matlab/one_sided_hp_filter.m index 9715a3351..5d2965b2c 100644 --- a/matlab/one_sided_hp_filter.m +++ b/matlab/one_sided_hp_filter.m @@ -70,7 +70,7 @@ Q=[q,0; R=1; % variance observation equation error for k=1:n %Run the Kalman filter for each variable - if nargin < 4 || isempty(x_user) %no intial value for state, extrapolate back two periods from the observations + if nargin < 3 || isempty(x_user) %no intial value for state, extrapolate back two periods from the observations x=[2*y(1,k)-y(2,k); 3*y(1,k)-2*y(2,k)]; else diff --git a/mex/build/estimation.am b/mex/build/estimation.am deleted file mode 100644 index a4a1bb83a..000000000 --- a/mex/build/estimation.am +++ /dev/null @@ -1,71 +0,0 @@ -mex_PROGRAMS = logposterior logMHMCMCposterior - -# We use shared flags so that automake does not compile things two times -AM_CPPFLAGS += -I$(top_srcdir)/../../sources/estimation/libmat -I$(top_srcdir)/../../sources/estimation/utils $(CPPFLAGS_MATIO) $(BOOST_CPPFLAGS) $(GSL_CPPFLAGS) -AM_LDFLAGS += $(LDFLAGS_MATIO) $(BOOST_LDFLAGS) $(GSL_LDFLAGS) -LDADD = $(LIBADD_DLOPEN) $(LIBADD_MATIO) $(GSL_LIBS) - -TOPDIR = $(top_srcdir)/../../sources/estimation - -MAT_SRCS = \ - $(TOPDIR)/libmat/Matrix.hh \ - $(TOPDIR)/libmat/Matrix.cc \ - $(TOPDIR)/libmat/Vector.hh \ - $(TOPDIR)/libmat/Vector.cc \ - $(TOPDIR)/libmat/BlasBindings.hh \ - $(TOPDIR)/libmat/DiscLyapFast.hh \ - $(TOPDIR)/libmat/GeneralizedSchurDecomposition.cc \ - $(TOPDIR)/libmat/GeneralizedSchurDecomposition.hh \ - $(TOPDIR)/libmat/LapackBindings.hh \ - $(TOPDIR)/libmat/LUSolver.cc \ - $(TOPDIR)/libmat/LUSolver.hh \ - $(TOPDIR)/libmat/QRDecomposition.cc \ - $(TOPDIR)/libmat/QRDecomposition.hh \ - $(TOPDIR)/libmat/VDVEigDecomposition.cc \ - $(TOPDIR)/libmat/VDVEigDecomposition.hh - -COMMON_SRCS = \ - $(MAT_SRCS) \ - $(TOPDIR)/DecisionRules.cc \ - $(TOPDIR)/DecisionRules.hh \ - $(TOPDIR)/DetrendData.cc \ - $(TOPDIR)/DetrendData.hh \ - $(TOPDIR)/EstimatedParameter.cc \ - $(TOPDIR)/EstimatedParameter.hh \ - $(TOPDIR)/EstimatedParametersDescription.cc \ - $(TOPDIR)/EstimatedParametersDescription.hh \ - $(TOPDIR)/EstimationSubsample.cc \ - $(TOPDIR)/EstimationSubsample.hh \ - $(TOPDIR)/InitializeKalmanFilter.cc \ - $(TOPDIR)/InitializeKalmanFilter.hh \ - $(TOPDIR)/KalmanFilter.cc \ - $(TOPDIR)/KalmanFilter.hh \ - $(TOPDIR)/LogLikelihoodSubSample.cc \ - $(TOPDIR)/LogLikelihoodSubSample.hh \ - $(TOPDIR)/LogLikelihoodMain.hh \ - $(TOPDIR)/LogLikelihoodMain.cc \ - $(TOPDIR)/LogPosteriorDensity.cc \ - $(TOPDIR)/LogPosteriorDensity.hh \ - $(TOPDIR)/LogPriorDensity.cc \ - $(TOPDIR)/LogPriorDensity.hh \ - $(TOPDIR)/ModelSolution.cc \ - $(TOPDIR)/ModelSolution.hh \ - $(TOPDIR)/Prior.cc \ - $(TOPDIR)/Prior.hh \ - $(TOPDIR)/SteadyStateSolver.cc \ - $(TOPDIR)/SteadyStateSolver.hh \ - $(TOPDIR)/utils/dynamic_dll.cc \ - $(TOPDIR)/utils/dynamic_dll.hh \ - $(TOPDIR)/utils/static_dll.cc \ - $(TOPDIR)/utils/static_dll.hh - -nodist_logposterior_SOURCES = \ - $(COMMON_SRCS) \ - $(TOPDIR)/logposterior.cc - -nodist_logMHMCMCposterior_SOURCES = \ - $(COMMON_SRCS) \ - $(TOPDIR)/Proposal.cc \ - $(TOPDIR)/Proposal.hh \ - $(TOPDIR)/RandomWalkMetropolisHastings.hh \ - $(TOPDIR)/logMHMCMCposterior.cc diff --git a/mex/build/matlab/Makefile.am b/mex/build/matlab/Makefile.am index ae3c50259..da02c56fc 100644 --- a/mex/build/matlab/Makefile.am +++ b/mex/build/matlab/Makefile.am @@ -10,7 +10,7 @@ SUBDIRS += k_order_perturbation dynare_simul_ endif if HAVE_GSL -SUBDIRS += ms_sbvar estimation +SUBDIRS += ms_sbvar endif if HAVE_SLICOT diff --git a/mex/build/matlab/configure.ac b/mex/build/matlab/configure.ac index 5fd9aa04d..9b4bc20bc 100644 --- a/mex/build/matlab/configure.ac +++ b/mex/build/matlab/configure.ac @@ -1,6 +1,6 @@ dnl Process this file with autoconf to produce a configure script. -dnl Copyright (C) 2009-2014 Dynare Team +dnl Copyright (C) 2009-2017 Dynare Team dnl dnl This file is part of Dynare. dnl @@ -72,15 +72,6 @@ case ${host_os} in esac AX_PTHREAD -# Check for boost libraries used in estimation DLL -AC_LANG_PUSH([C++]) -AX_BOOST_BASE([1.36], [], [AC_MSG_ERROR([Can't find Boost >= 1.36])]) -CPPFLAGS_SAVED="$CPPFLAGS" -CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS" -AC_CHECK_HEADER([boost/random/linear_congruential.hpp], [], [AC_MSG_ERROR([Can't find Boost Random Library])]) -AC_CHECK_HEADER([boost/math/distributions/beta.hpp], [], [AC_MSG_ERROR([Can't find Boost Math Library])]) -CPPFLAGS="$CPPFLAGS_SAVED" -AC_LANG_POP([C++]) # Check for dlopen(), needed by k_order_perturbation DLL AC_CHECK_LIB([dl], [dlopen], [LIBADD_DLOPEN="-ldl"], []) AC_SUBST([LIBADD_DLOPEN]) @@ -150,7 +141,7 @@ Dynare is now configured for building the following components... Binaries (with "make"): MEX files for MATLAB (except those listed below): $BUILD_MEX_MATLAB - k-order and dynare_simul MEX files for MATLAB: $BUILD_KORDER_DYNSIMUL_MEX_MATLAB + K-order and dynare_simul MEX files for MATLAB: $BUILD_KORDER_DYNSIMUL_MEX_MATLAB MS-SBVAR MEX files for MATLAB: $BUILD_MS_SBVAR_MEX_MATLAB Kalman Steady State MEX file for MATLAB: $BUILD_KALMAN_STEADY_STATE_MATLAB M2HTML documentation: $BUILD_M2HTML @@ -165,7 +156,6 @@ AC_CONFIG_FILES([Makefile gensylv/Makefile k_order_perturbation/Makefile dynare_simul_/Makefile - estimation/Makefile kalman_steady_state/Makefile ms_sbvar/Makefile block_kalman_filter/Makefile diff --git a/mex/build/matlab/estimation/Makefile.am b/mex/build/matlab/estimation/Makefile.am deleted file mode 100644 index 44c75b50f..000000000 --- a/mex/build/matlab/estimation/Makefile.am +++ /dev/null @@ -1,2 +0,0 @@ -include ../mex.am -include ../../estimation.am diff --git a/mex/build/octave/Makefile.am b/mex/build/octave/Makefile.am index 71d4639d6..c83e295ec 100644 --- a/mex/build/octave/Makefile.am +++ b/mex/build/octave/Makefile.am @@ -18,7 +18,7 @@ endif if HAVE_GSL if HAVE_MATIO -SUBDIRS += ms_sbvar estimation +SUBDIRS += ms_sbvar endif endif diff --git a/mex/build/octave/configure.ac b/mex/build/octave/configure.ac index 54351c003..c523c6a2a 100755 --- a/mex/build/octave/configure.ac +++ b/mex/build/octave/configure.ac @@ -1,6 +1,6 @@ dnl Process this file with autoconf to produce a configure script. -dnl Copyright (C) 2009-2015 Dynare Team +dnl Copyright (C) 2009-2017 Dynare Team dnl dnl This file is part of Dynare. dnl @@ -52,15 +52,6 @@ AX_PROG_LN_S AC_PROG_MKDIR_P AM_PROG_AR AX_PTHREAD -# Check for boost libraries used in estimation DLL -AC_LANG_PUSH([C++]) -AX_BOOST_BASE([1.36], [], [AC_MSG_ERROR([Can't find Boost >= 1.36])]) -CPPFLAGS_SAVED="$CPPFLAGS" -CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS" -AC_CHECK_HEADER([boost/random/linear_congruential.hpp], [], [AC_MSG_ERROR([Can't find Boost Random Library])]) -AC_CHECK_HEADER([boost/math/distributions/beta.hpp], [], [AC_MSG_ERROR([Can't find Boost Math Library])]) -CPPFLAGS="$CPPFLAGS_SAVED" -AC_LANG_POP([C++]) # Check for dlopen(), needed by k_order_perturbation DLL AC_CHECK_LIB([dl], [dlopen], [LIBADD_DLOPEN="-ldl"], []) AC_SUBST([LIBADD_DLOPEN]) @@ -68,7 +59,7 @@ AC_SUBST([LIBADD_DLOPEN]) AX_GSL AM_CONDITIONAL([HAVE_GSL], [test "x$has_gsl" = "xyes"]) -# Check for libmatio, needed by estimation DLL (only under Octave, as an alternative to MATLAB's libmat) +# Check for libmatio, needed by k-order, dynare_simul, ms-sbvar (only under Octave, as an alternative to MATLAB's libmat) AX_MATIO AM_CONDITIONAL([HAVE_MATIO], [test "x$has_matio" = "xyes"]) @@ -100,9 +91,9 @@ else fi if test "x$MKOCTFILE" != "x" -a "x$has_matio" = "xyes"; then - BUILD_ESTIMATION_KORDER_DYNSIMUL_MEX_OCTAVE="yes" + BUILD_KORDER_DYNSIMUL_MEX_OCTAVE="yes" else - BUILD_ESTIMATION_KORDER_DYNSIMUL_MEX_OCTAVE="no (missing MatIO library)" + BUILD_KORDER_DYNSIMUL_MEX_OCTAVE="no (missing MatIO library)" fi if test "x$MKOCTFILE" != "x" -a "x$has_slicot" = "xyes"; then @@ -145,7 +136,7 @@ Binaries (with "make"): MEX files for Octave (except those listed below): $BUILD_MEX_OCTAVE MS-SBVAR MEX files for Octave: $BUILD_MS_SBVAR_MEX_OCTAVE Kalman Steady State MEX file for Octave: $BUILD_KALMAN_STEADY_STATE_OCTAVE - Estimation, k-order and dynare_simul MEX for Octave: $BUILD_ESTIMATION_KORDER_DYNSIMUL_MEX_OCTAVE + K-order and dynare_simul MEX for Octave: $BUILD_KORDER_DYNSIMUL_MEX_OCTAVE Linsolve for Octave: $BUILD_LINSOLVE_OCTAVE Ordschur for Octave: $BUILD_ORDSCHUR_OCTAVE @@ -159,7 +150,6 @@ AC_CONFIG_FILES([Makefile gensylv/Makefile k_order_perturbation/Makefile dynare_simul_/Makefile - estimation/Makefile qzcomplex/Makefile ordschur/Makefile kalman_steady_state/Makefile diff --git a/mex/build/octave/estimation/Makefile.am b/mex/build/octave/estimation/Makefile.am deleted file mode 100644 index 8c2e282e7..000000000 --- a/mex/build/octave/estimation/Makefile.am +++ /dev/null @@ -1,3 +0,0 @@ -EXEEXT = .mex -include ../mex.am -include ../../estimation.am diff --git a/mex/sources/Makefile.am b/mex/sources/Makefile.am index 0639beed3..bcf4bedc0 100644 --- a/mex/sources/Makefile.am +++ b/mex/sources/Makefile.am @@ -1,5 +1,3 @@ -SUBDIRS = estimation - EXTRA_DIST = \ dynblas.h \ dynlapack.h \ diff --git a/mex/sources/estimation/DecisionRules.cc b/mex/sources/estimation/DecisionRules.cc deleted file mode 100644 index 41c095925..000000000 --- a/mex/sources/estimation/DecisionRules.cc +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include - -#include - -#include "DecisionRules.hh" - -DecisionRules::DecisionRules(size_t n_arg, size_t p_arg, - const std::vector &zeta_fwrd_arg, - const std::vector &zeta_back_arg, - const std::vector &zeta_mixed_arg, - const std::vector &zeta_static_arg, - double qz_criterium) : - n(n_arg), p(p_arg), zeta_fwrd(zeta_fwrd_arg), zeta_back(zeta_back_arg), - zeta_mixed(zeta_mixed_arg), zeta_static(zeta_static_arg), - n_fwrd(zeta_fwrd.size()), n_back(zeta_back.size()), - n_mixed(zeta_mixed.size()), n_static(zeta_static.size()), - n_back_mixed(n_back+n_mixed), n_fwrd_mixed(n_fwrd+n_mixed), - n_dynamic(n-n_static), - S(n, n_static), - A(n, n_back_mixed + n + n_fwrd_mixed), - D(n_fwrd + n_back + 2*n_mixed), - E(n_fwrd + n_back + 2*n_mixed), - Z_prime(n_fwrd + n_back + 2*n_mixed), - QR(n, n_static, n_back_mixed + n + n_fwrd_mixed), - GSD(n_fwrd + n_back + 2*n_mixed, qz_criterium), - LU1(n_fwrd_mixed), - LU2(n_back_mixed), - LU3(n_static), - Z21(n_fwrd_mixed, n_back_mixed), - g_y_back(n_back_mixed), - g_y_back_tmp(n_back_mixed), - g_y_static(n_static, n_back_mixed), - A0s(n_static), - A0d(n_static, n_dynamic), - g_y_dynamic(n_dynamic, n_back_mixed), - g_y_static_tmp(n_fwrd_mixed, n_back_mixed), - g_u_tmp1(n, n_back_mixed), - g_u_tmp2(n), - LU4(n) -{ - assert(n == n_back + n_fwrd + n_mixed + n_static); - - set_union(zeta_fwrd.begin(), zeta_fwrd.end(), - zeta_mixed.begin(), zeta_mixed.end(), - back_inserter(zeta_fwrd_mixed)); - set_union(zeta_back.begin(), zeta_back.end(), - zeta_mixed.begin(), zeta_mixed.end(), - back_inserter(zeta_back_mixed)); - set_union(zeta_back_mixed.begin(), zeta_back_mixed.end(), - zeta_fwrd.begin(), zeta_fwrd.end(), - back_inserter(zeta_dynamic)); - - // Compute beta_back and pi_back - for (size_t i = 0; i < n_back_mixed; i++) - if (find(zeta_mixed.begin(), zeta_mixed.end(), zeta_back_mixed[i]) - == zeta_mixed.end()) - pi_back.push_back(i); - else - beta_back.push_back(i); - - // Compute beta_fwrd and pi_fwrd - for (size_t i = 0; i < n_fwrd_mixed; i++) - if (find(zeta_mixed.begin(), zeta_mixed.end(), zeta_fwrd_mixed[i]) - == zeta_mixed.end()) - pi_fwrd.push_back(i); - else - beta_fwrd.push_back(i); -} - -void -DecisionRules::compute(const Matrix &jacobian, Matrix &g_y, Matrix &g_u) throw (BlanchardKahnException, GeneralizedSchurDecomposition::GSDException) -{ - assert(jacobian.getRows() == n - && jacobian.getCols() == (n_back_mixed + n + n_fwrd_mixed + p)); - assert(g_y.getRows() == n && g_y.getCols() == n_back_mixed); - assert(g_u.getRows() == n && g_u.getCols() == p); - - // Construct S, perform QR decomposition and get A = Q*jacobian - A = MatrixConstView(jacobian, 0, 0, n, n_back_mixed + n + n_fwrd_mixed); - if (n_static > 0) - { - for (size_t i = 0; i < n_static; i++) - mat::col_copy(jacobian, n_back_mixed+zeta_static[i], S, i); - - QR.computeAndLeftMultByQ(S, "T", A); - } - - // Construct matrix D - D.setAll(0.0); - for (size_t i = 0; i < n_mixed; i++) - D(n - n_static + i, beta_back[i]) = 1.0; - for (size_t j = 0; j < n_back_mixed; j++) - mat::col_copy(A, n_back_mixed + zeta_back_mixed[j], n_static, n - n_static, - D, j, 0); - MatrixView(D, 0, n_back_mixed, n - n_static, n_fwrd_mixed) = MatrixView(A, n_static, n_back_mixed + n, n - n_static, n_fwrd_mixed); - - // Construct matrix E - E.setAll(0.0); - for (size_t i = 0; i < n_mixed; i++) - E(n - n_static + i, n_back_mixed + beta_fwrd[i]) = 1.0; - MatrixView(E, 0, 0, n - n_static, n_back_mixed) = MatrixView(A, n_static, 0, n - n_static, n_back_mixed); - for (size_t j = 0; j < n_fwrd; j++) - mat::col_copy(A, n_back_mixed + zeta_fwrd_mixed[pi_fwrd[j]], n_static, n - n_static, - E, n_back_mixed + pi_fwrd[j], 0); - MatrixView E_tmp(E, 0, 0, n - n_static, n_fwrd + n_back + 2*n_mixed); - mat::negate(E_tmp); // Here we take the opposite of some of the zeros initialized in the constructor, but it is not a problem - - // Perform the generalized Schur - size_t sdim; - GSD.compute(E, D, Z_prime, sdim); - - if (n_back_mixed != sdim) - throw BlanchardKahnException(true, n_fwrd_mixed, n_fwrd + n_back + 2*n_mixed - sdim); - - // Compute DR for forward variables w.r. to endogenous - MatrixView Z21_prime(Z_prime, 0, n_back_mixed, n_back_mixed, n_fwrd_mixed), - Z22_prime(Z_prime, n_back_mixed, n_back_mixed, n_fwrd_mixed, n_fwrd_mixed); - - mat::transpose(Z21, Z21_prime); - - try - { - LU1.invMult("T", Z22_prime, Z21); - } - catch (LUSolver::LUException &e) - { - throw BlanchardKahnException(false, n_fwrd_mixed, n_fwrd + n_back + 2*n_mixed - sdim); - } - mat::negate(Z21); - const Matrix &g_y_fwrd = Z21; - - for (size_t i = 0; i < n_fwrd_mixed; i++) - mat::row_copy(g_y_fwrd, i, g_y, zeta_fwrd_mixed[i]); - - // Compute DR for backward variables w.r. to endogenous - MatrixView Z11_prime(Z_prime, 0, 0, n_back_mixed, n_back_mixed), - T11(D, 0, 0, n_back_mixed, n_back_mixed), - S11(E, 0, 0, n_back_mixed, n_back_mixed); - mat::set_identity(g_y_back); - g_y_back_tmp = Z11_prime; - LU2.invMult("N", g_y_back_tmp, g_y_back); - g_y_back_tmp = g_y_back; - blas::gemm("N", "N", 1.0, S11, g_y_back_tmp, 0.0, g_y_back); - LU2.invMult("N", T11, g_y_back); - g_y_back_tmp = g_y_back; - blas::gemm("N", "N", 1.0, Z11_prime, g_y_back_tmp, 0.0, g_y_back); - - // TODO: avoid to copy mixed variables again, rather test it... - for (size_t i = 0; i < n_back_mixed; i++) - mat::row_copy(g_y_back, i, g_y, zeta_back_mixed[i]); - - // Compute DR for static variables w.r. to endogenous - if (n_static > 0) - { - g_y_static = MatrixView(A, 0, 0, n_static, n_back_mixed); - for (size_t i = 0; i < n_dynamic; i++) - { - mat::row_copy(g_y, zeta_dynamic[i], g_y_dynamic, i); - mat::col_copy(A, n_back_mixed + zeta_dynamic[i], 0, n_static, A0d, i, 0); - } - blas::gemm("N", "N", 1.0, A0d, g_y_dynamic, 1.0, g_y_static); - blas::gemm("N", "N", 1.0, g_y_fwrd, g_y_back, 0.0, g_y_static_tmp); - blas::gemm("N", "N", 1.0, MatrixView(A, 0, n_back_mixed + n, n_static, n_fwrd_mixed), - g_y_static_tmp, 1.0, g_y_static); - for (size_t i = 0; i < n_static; i++) - mat::col_copy(A, n_back_mixed + zeta_static[i], 0, n_static, A0s, i, 0); - LU3.invMult("N", A0s, g_y_static); - mat::negate(g_y_static); - - for (size_t i = 0; i < n_static; i++) - mat::row_copy(g_y_static, i, g_y, zeta_static[i]); - } - - // Compute DR for all endogenous w.r. to shocks - blas::gemm("N", "N", 1.0, MatrixConstView(jacobian, 0, n_back_mixed + n, n, n_fwrd_mixed), g_y_fwrd, 0.0, g_u_tmp1); - g_u_tmp2 = MatrixConstView(jacobian, 0, n_back_mixed, n, n); - for (size_t i = 0; i < n_back_mixed; i++) - { - VectorView c1 = mat::get_col(g_u_tmp2, zeta_back_mixed[i]), - c2 = mat::get_col(g_u_tmp1, i); - vec::add(c1, c2); - } - g_u = MatrixConstView(jacobian, 0, n_back_mixed + n + n_fwrd_mixed, n, p); - LU4.invMult("N", g_u_tmp2, g_u); - mat::negate(g_u); -} - -std::ostream & -operator<<(std::ostream &out, const DecisionRules::BlanchardKahnException &e) -{ - if (e.order) - out << "The Blanchard-Kahn order condition is not satisfied: you have " << e.n_fwrd_vars << " forward variables for " << e.n_explosive_eigenvals << " explosive eigenvalues"; - else - out << "The Blanchard Kahn rank condition is not satisfied"; - return out; -} diff --git a/mex/sources/estimation/DecisionRules.hh b/mex/sources/estimation/DecisionRules.hh deleted file mode 100644 index 65b965aea..000000000 --- a/mex/sources/estimation/DecisionRules.hh +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include -#include - -#include "Vector.hh" -#include "Matrix.hh" -#include "QRDecomposition.hh" -#include "GeneralizedSchurDecomposition.hh" -#include "LUSolver.hh" - -class DecisionRules -{ -private: - const size_t n, p; - const std::vector zeta_fwrd, zeta_back, zeta_mixed, zeta_static; - const size_t n_fwrd, n_back, n_mixed, n_static, n_back_mixed, n_fwrd_mixed, n_dynamic; - std::vector zeta_fwrd_mixed, zeta_back_mixed, zeta_dynamic, - beta_back, beta_fwrd, pi_back, pi_fwrd; - Matrix S, A, D, E, Z_prime; - QRDecomposition QR; - GeneralizedSchurDecomposition GSD; - LUSolver LU1, LU2, LU3; - Matrix Z21, g_y_back, g_y_back_tmp; - Matrix g_y_static, A0s, A0d, g_y_dynamic, g_y_static_tmp; - Matrix g_u_tmp1, g_u_tmp2; - LUSolver LU4; -public: - class BlanchardKahnException - { - public: - //! True if the model fails the order condition. False if it fails the rank condition. - const bool order; - const int n_fwrd_vars, n_explosive_eigenvals; - BlanchardKahnException(bool order_arg, int n_fwrd_vars_arg, int n_explosive_eigenvals_arg) : order(order_arg), n_fwrd_vars(n_fwrd_vars_arg), n_explosive_eigenvals(n_explosive_eigenvals_arg) - { - }; - }; - /*! - The zetas are supposed to follow C convention (first vector index is zero). - */ - DecisionRules(size_t n_arg, size_t p_arg, const std::vector &zeta_fwrd_arg, - const std::vector &zeta_back_arg, const std::vector &zeta_mixed_arg, - const std::vector &zeta_static_arg, double qz_criterium); - virtual ~DecisionRules() - { - }; - - /*! - \param jacobian First columns are backetermined vars at t-1 (in the order of zeta_back_mixed), then all vars at t (in the orig order), then forward vars at t+1 (in the order of zeta_fwrd_mixed), then exogenous vars. - */ - void compute(const Matrix &jacobian, Matrix &g_y, Matrix &g_u) throw (BlanchardKahnException, GeneralizedSchurDecomposition::GSDException); - template - void getGeneralizedEigenvalues(Vec1 &eig_real, Vec2 &eig_cmplx); -}; - -std::ostream &operator<<(std::ostream &out, const DecisionRules::BlanchardKahnException &e); - -template -void -DecisionRules::getGeneralizedEigenvalues(Vec1 &eig_real, Vec2 &eig_cmplx) -{ - GSD.getGeneralizedEigenvalues(eig_real, eig_cmplx); -} diff --git a/mex/sources/estimation/DetrendData.cc b/mex/sources/estimation/DetrendData.cc deleted file mode 100644 index f9fa1b76d..000000000 --- a/mex/sources/estimation/DetrendData.cc +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// DetrendData.cpp -// Implementation of the Class DetrendData -// Created on: 02-Feb-2010 13:01:15 -/////////////////////////////////////////////////////////// - -#include "DetrendData.hh" - -DetrendData::DetrendData(const std::vector &varobs_arg, - bool noconstant_arg) - : varobs(varobs_arg), noconstant(noconstant_arg) -{ -}; - -void -DetrendData::detrend(const VectorView &SteadyState, const MatrixConstView &dataView, - MatrixView &detrendedDataView) -{ - if (noconstant) - detrendedDataView = dataView; - else - { - for (size_t i = 0; i < varobs.size(); i++) - for (size_t j = 0; j < dataView.getCols(); j++) - detrendedDataView(i, j) = dataView(i, j) - SteadyState(varobs[i]); - } -}; diff --git a/mex/sources/estimation/DetrendData.hh b/mex/sources/estimation/DetrendData.hh deleted file mode 100644 index 408b14a11..000000000 --- a/mex/sources/estimation/DetrendData.hh +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ -/////////////////////////////////////////////////////////// -// DetrendData.h -// Implementation of the Class DetrendData -// Created on: 02-Feb-2010 13:01:15 -/////////////////////////////////////////////////////////// - -#if !defined(DetrendData_312823A1_6248_4af0_B204_DB22F1237E9B__INCLUDED_) -#define DetrendData_312823A1_6248_4af0_B204_DB22F1237E9B__INCLUDED_ - -#include "Matrix.hh" - -class DetrendData -{ - -public: - virtual ~DetrendData() - { - }; - DetrendData(const std::vector &varobs_arg, bool noconstant_arg); - void detrend(const VectorView &SteadyState, const MatrixConstView &dataView, MatrixView &detrendedDataView); - -private: - const std::vector varobs; - const bool noconstant; - -}; - -#endif // !defined(312823A1_6248_4af0_B204_DB22F1237E9B__INCLUDED_) diff --git a/mex/sources/estimation/EstimatedParameter.cc b/mex/sources/estimation/EstimatedParameter.cc deleted file mode 100644 index 5fd2bad2b..000000000 --- a/mex/sources/estimation/EstimatedParameter.cc +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// EstimatedParameter.cpp -// Implementation of the Class EstimatedParameter -// Created on: 02-Feb-2010 13:06:35 -/////////////////////////////////////////////////////////// - -#include "EstimatedParameter.hh" - -EstimatedParameter::EstimatedParameter(const EstimatedParameter::pType type_arg, - size_t ID1_arg, size_t ID2_arg, const std::vector &subSampleIDs_arg, - double lower_bound_arg, double upper_bound_arg, Prior *prior_arg) : - ptype(type_arg), ID1(ID1_arg), ID2(ID2_arg), - lower_bound(lower_bound_arg), upper_bound(upper_bound_arg), prior(prior_arg), - subSampleIDs(subSampleIDs_arg) -{ -} - -EstimatedParameter::~EstimatedParameter() -{ -} diff --git a/mex/sources/estimation/EstimatedParameter.hh b/mex/sources/estimation/EstimatedParameter.hh deleted file mode 100644 index 52cc26187..000000000 --- a/mex/sources/estimation/EstimatedParameter.hh +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ -/////////////////////////////////////////////////////////// -// EstimatedParameter.h -// Implementation of the Class EstimatedParameter -// Created on: 02-Feb-2010 13:06:35 -/////////////////////////////////////////////////////////// - -#if !defined(D879C8AE_5B69_4fc3_83BD_FA5A99030ECF__INCLUDED_) -#define D879C8AE_5B69_4fc3_83BD_FA5A99030ECF__INCLUDED_ - -#include "Prior.hh" -#include -#include -struct EstimatedParameter -{ -public: - // parameter types - enum pType - { - shock_SD = 1, // standard deviation of a structural shock - measureErr_SD = 2, // standard deviation of a measurement error - shock_Corr = 3, // correlation betwwen two structural shocks - measureErr_Corr = 4, // correlation between two measurement errors - deepPar = 5 // deep parameter - }; - - EstimatedParameter(const EstimatedParameter::pType type, - size_t ID1, size_t ID2, const std::vector &subSampleIDs, - double lower_bound, double upper_bound, Prior *prior - ); - virtual - ~EstimatedParameter(); - - enum pType ptype; - size_t ID1; - size_t ID2; - double lower_bound; - double upper_bound; - Prior *prior; - std::vector subSampleIDs; -}; - -#endif // !defined(D879C8AE_5B69_4fc3_83BD_FA5A99030ECF__INCLUDED_) diff --git a/mex/sources/estimation/EstimatedParametersDescription.cc b/mex/sources/estimation/EstimatedParametersDescription.cc deleted file mode 100644 index ff73894cd..000000000 --- a/mex/sources/estimation/EstimatedParametersDescription.cc +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2010 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// EstimatedParametersDescription.cpp -// Implementation of the Class EstimatedParametersDescription -// Created on: 02-Feb-2010 13:06:47 -/////////////////////////////////////////////////////////// - -#include "EstimatedParametersDescription.hh" - -EstimatedParametersDescription::~EstimatedParametersDescription() -{ -} - -EstimatedParametersDescription::EstimatedParametersDescription(std::vector &INestSubsamples, std::vector &INestParams) : - estSubsamples(INestSubsamples), estParams(INestParams) -{ -} - -size_t -EstimatedParametersDescription::getNumberOfPeriods() const -{ - size_t r = 0; - for (size_t i = 0; i < estSubsamples.size(); i++) - { - size_t r2 = estSubsamples[i].endPeriod + 1; - if (r2 > r) - r = r2; - } - return r; -} diff --git a/mex/sources/estimation/EstimatedParametersDescription.hh b/mex/sources/estimation/EstimatedParametersDescription.hh deleted file mode 100644 index 2fc2ad8ea..000000000 --- a/mex/sources/estimation/EstimatedParametersDescription.hh +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ -/////////////////////////////////////////////////////////// -// EstimatedParametersDescription.h -// Implementation of the Class EstimatedParametersDescription -// Created on: 02-Feb-2010 13:06:46 -/////////////////////////////////////////////////////////// - -#if !defined(E8F2C096_A301_42e8_80FF_A643291BF995__INCLUDED_) -#define E8F2C096_A301_42e8_80FF_A643291BF995__INCLUDED_ - -#include "EstimationSubsample.hh" -#include "EstimatedParameter.hh" -#include "Prior.hh" - -/** - * all estimation periods held in the vectors of EstPeriod-s are held in the - * EstimatedParametersDescription together with the time-invariant attributes (e.g. - * IDs..) for integration.. - * - * The EstimatedParametersDescription. structure (or class with protected - * elements) integrates all parametr and time period information and makes it - * available to (friend ?) class LogPosteriorDensity on as needed basis and - * updates all parameters (inc. H and Q) when time slot xparam1 is supplied. - * - * - * - */ -class EstimatedParametersDescription -{ -public: - virtual - ~EstimatedParametersDescription(); - EstimatedParametersDescription(std::vector &estSubsamples, std::vector &estParams); - std::vector estSubsamples; - std::vector estParams; - size_t getNumberOfPeriods() const; -}; - -#endif // !defined(E8F2C096_A301_42e8_80FF_A643291BF995__INCLUDED_) diff --git a/mex/sources/estimation/EstimationSubsample.cc b/mex/sources/estimation/EstimationSubsample.cc deleted file mode 100644 index a8dba8039..000000000 --- a/mex/sources/estimation/EstimationSubsample.cc +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// EstimationSubsample.cpp -// Implementation of the Class EstimationSubsample -// Created on: 02-Feb-2010 13:06:01 -/////////////////////////////////////////////////////////// - -#include "EstimationSubsample.hh" - -EstimationSubsample::EstimationSubsample(size_t INstartPeriod, size_t INendPeriod) : - startPeriod(INstartPeriod), endPeriod(INendPeriod) -{ -} - -EstimationSubsample::~EstimationSubsample() -{ -} diff --git a/mex/sources/estimation/EstimationSubsample.hh b/mex/sources/estimation/EstimationSubsample.hh deleted file mode 100644 index d8c90723a..000000000 --- a/mex/sources/estimation/EstimationSubsample.hh +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// EstimationSubsample.h -// Implementation of the Class EstimationSubsample -// Created on: 02-Feb-2010 13:06:01 -/////////////////////////////////////////////////////////// - -#if !defined(EstSub34FB1351_4066_4993_B384_56AA65BC32C4__INCLUDED_) -#define EstSub34FB1351_4066_4993_B384_56AA65BC32C4__INCLUDED_ - -#include -#include - -/** - * Contains longest common periods for different parameters with different start - * and end periods: - * - * It defines start and end of that period.which has start higher/equal than any - * individual parameter start and its end lower|equal than any individual - * parameter end in that perod window.) integrated xparam1 and priors for that - * period - * - * All those EstPeriod-s need to be constructed at some point once at a start of - * estimation by EstPeriod costructor from the information such as invidual - * parameter start-end periods and the relevant associated priors for those - * periods. That initial info-set is held in the vector of vectors of - * EstParamSubSampleDescription - * - * it constructs and contains indices of all estimated xparam1 parameters valid - * for this period in the larger, extended xparam1x vector passed in. from the - * gradient function. - * - * The EstimatedParametersDescription. structure (or class with protected - * elements) integrates all that information and makes it available to (friend ?) - * class LogPosteriorDensity on as needed basis and updates all parameters (inc. H - * and Q) when time slot xparam1 is supplied. - * - * Time indices follow C convention: first period has index 0. - */ -class EstimationSubsample -{ -public: - EstimationSubsample(size_t startPeriod, size_t endPeriod); - virtual - ~EstimationSubsample(); - - size_t startPeriod; - size_t endPeriod; - /** - * indices of all estimated xparam1 parameters valid for this period in the larger, - * extended xparam1x vector passed in. from the gradient function will be added at a later stage of development - */ - // const std::vector subSampleParamIDs; -}; - -#endif // !defined(34FB1351_4066_4993_B384_56AA65BC32C4__INCLUDED_) diff --git a/mex/sources/estimation/InitializeKalmanFilter.cc b/mex/sources/estimation/InitializeKalmanFilter.cc deleted file mode 100644 index 095032494..000000000 --- a/mex/sources/estimation/InitializeKalmanFilter.cc +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// InitializeKalmanFilter.cpp -// Implementation of the Class InitializeKalmanFilter -// Created on: 02-Feb-2010 12:25:28 -/////////////////////////////////////////////////////////// - -#include "InitializeKalmanFilter.hh" -#include "BlasBindings.hh" - -InitializeKalmanFilter::~InitializeKalmanFilter() -{ -} - -InitializeKalmanFilter::InitializeKalmanFilter(const std::string &basename, size_t n_endo_arg, size_t n_exo_arg, - const std::vector &zeta_fwrd_arg, const std::vector &zeta_back_arg, - const std::vector &zeta_mixed_arg, const std::vector &zeta_static_arg, - const std::vector &zeta_varobs_back_mixed_arg, - const std::vector &varobs_arg, - double qz_criterium_arg, - double lyapunov_tol_arg, - bool noconstant_arg) : - lyapunov_tol(lyapunov_tol_arg), - zeta_varobs_back_mixed(zeta_varobs_back_mixed_arg), - detrendData(varobs_arg, noconstant_arg), - modelSolution(basename, n_endo_arg, n_exo_arg, zeta_fwrd_arg, zeta_back_arg, - zeta_mixed_arg, zeta_static_arg, qz_criterium_arg), - discLyapFast(zeta_varobs_back_mixed.size()), - g_x(n_endo_arg, zeta_back_arg.size() + zeta_mixed_arg.size()), - g_u(n_endo_arg, n_exo_arg), - Rt(n_exo_arg, zeta_varobs_back_mixed.size()), - RQ(zeta_varobs_back_mixed.size(), n_exo_arg) -{ - std::vector zeta_back_mixed; - set_union(zeta_back_arg.begin(), zeta_back_arg.end(), - zeta_mixed_arg.begin(), zeta_mixed_arg.end(), - back_inserter(zeta_back_mixed)); - for (size_t i = 0; i < zeta_back_mixed.size(); i++) - pi_bm_vbm.push_back(find(zeta_varobs_back_mixed.begin(), zeta_varobs_back_mixed.end(), - zeta_back_mixed[i]) - zeta_varobs_back_mixed.begin()); - -} -void -InitializeKalmanFilter::setT(Matrix &T) -{ - // Initialize the empty columns of T to zero - T.setAll(0.0); - mat::assignByVectors(T, mat::nullVec, pi_bm_vbm, g_x, zeta_varobs_back_mixed, mat::nullVec); -} - -void -InitializeKalmanFilter::setPstar(Matrix &Pstar, Matrix &Pinf, const Matrix &T, const Matrix &RQRt) throw (DiscLyapFast::DLPException) -{ - - discLyapFast.solve_lyap(T, RQRt, Pstar, lyapunov_tol, 0); - - Pinf.setAll(0.0); -} diff --git a/mex/sources/estimation/InitializeKalmanFilter.hh b/mex/sources/estimation/InitializeKalmanFilter.hh deleted file mode 100644 index a78b5970e..000000000 --- a/mex/sources/estimation/InitializeKalmanFilter.hh +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// InitializeKalmanFilter.h -// Implementation of the Class InitializeKalmanFilter -// Created on: 02-Feb-2010 12:25:28 -/////////////////////////////////////////////////////////// - -#if !defined(C3D996B8_22AB_4b77_B693_BA4777AFB091__INCLUDED_) -#define C3D996B8_22AB_4b77_B693_BA4777AFB091__INCLUDED_ - -#include "DetrendData.hh" -#include "ModelSolution.hh" -#include "DiscLyapFast.hh" -#include - -/** - * if model is declared stationary ?compute covariance matrix of endogenous - * variables () by doubling algorithm - * - */ -class InitializeKalmanFilter -{ - -public: - /*! - \param[in] zeta_varobs_back_mixed_arg The union of indices of observed, backward and mixed variables - */ - InitializeKalmanFilter(const std::string &basename, size_t n_endo, size_t n_exo, const std::vector &zeta_fwrd_arg, - const std::vector &zeta_back_arg, const std::vector &zeta_mixed_arg, const std::vector &zeta_static_arg, - const std::vector &zeta_varobs_back_mixed_arg, - const std::vector &varobs_arg, - double qz_criterium_arg, double lyapunov_tol_arg, - bool noconstant_arg); - virtual - ~InitializeKalmanFilter(); - // initialise parameter dependent KF matrices only but not Ps - template - void - initialize(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &R, - const Mat2 &Q, Matrix &RQRt, Matrix &T, - const MatrixConstView &dataView, - MatrixView &detrendedDataView) - { - modelSolution.compute(steadyState, deepParams, g_x, g_u); - detrendData.detrend(steadyState, dataView, detrendedDataView); - - setT(T); - setRQR(R, Q, RQRt); - } - - // initialise all KF matrices - template - void - initialize(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &R, - const Mat2 &Q, Matrix &RQRt, Matrix &T, Matrix &Pstar, Matrix &Pinf, - const MatrixConstView &dataView, - MatrixView &detrendedDataView) - { - initialize(steadyState, deepParams, R, Q, RQRt, T, dataView, detrendedDataView); - setPstar(Pstar, Pinf, T, RQRt); - } - -private: - const double lyapunov_tol; - const std::vector zeta_varobs_back_mixed; - //! Indices of back+mixed zetas inside varobs+back+mixed zetas - std::vector pi_bm_vbm; - - DetrendData detrendData; - ModelSolution modelSolution; - DiscLyapFast discLyapFast; //Lyapunov solver - Matrix g_x; - Matrix g_u; - Matrix Rt, RQ; - void setT(Matrix &T); - - template - void - setRQR(Mat1 &R, const Mat2 &Q, Matrix &RQRt) - { - mat::assignByVectors(R, mat::nullVec, mat::nullVec, g_u, zeta_varobs_back_mixed, mat::nullVec); - - // Matrix RQRt=R*Q*R' - blas::gemm("N", "N", 1.0, R, Q, 0.0, RQ); // R*Q - blas::gemm("N", "T", 1.0, RQ, R, 0.0, RQRt); // R*Q*R' - } - void setPstar(Matrix &Pstar, Matrix &Pinf, const Matrix &T, const Matrix &RQRt) throw (DiscLyapFast::DLPException); - -}; - -#endif // !defined(C3D996B8_22AB_4b77_B693_BA4777AFB091__INCLUDED_) diff --git a/mex/sources/estimation/KalmanFilter.cc b/mex/sources/estimation/KalmanFilter.cc deleted file mode 100644 index db9628b81..000000000 --- a/mex/sources/estimation/KalmanFilter.cc +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// KalmanFilter.cpp -// Implementation of the Class KalmanFilter -// Created on: 02-Feb-2010 12:44:41 -/////////////////////////////////////////////////////////// - -#include "KalmanFilter.hh" -#include "LapackBindings.hh" - -KalmanFilter::~KalmanFilter() -{ - -} - -KalmanFilter::KalmanFilter(const std::string &basename, size_t n_endo, size_t n_exo, - const std::vector &zeta_fwrd_arg, const std::vector &zeta_back_arg, - const std::vector &zeta_mixed_arg, const std::vector &zeta_static_arg, - double qz_criterium_arg, const std::vector &varobs_arg, - double riccati_tol_arg, double lyapunov_tol_arg, - bool noconstant_arg) : - zeta_varobs_back_mixed(compute_zeta_varobs_back_mixed(zeta_back_arg, zeta_mixed_arg, varobs_arg)), - Z(varobs_arg.size(), zeta_varobs_back_mixed.size()), Zt(Z.getCols(), Z.getRows()), T(zeta_varobs_back_mixed.size()), R(zeta_varobs_back_mixed.size(), n_exo), - Pstar(zeta_varobs_back_mixed.size(), zeta_varobs_back_mixed.size()), Pinf(zeta_varobs_back_mixed.size(), zeta_varobs_back_mixed.size()), - RQRt(zeta_varobs_back_mixed.size(), zeta_varobs_back_mixed.size()), Ptmp(zeta_varobs_back_mixed.size(), zeta_varobs_back_mixed.size()), F(varobs_arg.size(), varobs_arg.size()), - Finv(varobs_arg.size(), varobs_arg.size()), K(zeta_varobs_back_mixed.size(), varobs_arg.size()), KFinv(zeta_varobs_back_mixed.size(), varobs_arg.size()), - oldKFinv(zeta_varobs_back_mixed.size(), varobs_arg.size()), a_init(zeta_varobs_back_mixed.size()), - a_new(zeta_varobs_back_mixed.size()), vt(varobs_arg.size()), vtFinv(varobs_arg.size()), riccati_tol(riccati_tol_arg), - initKalmanFilter(basename, n_endo, n_exo, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, - zeta_static_arg, zeta_varobs_back_mixed, varobs_arg, qz_criterium_arg, lyapunov_tol_arg, noconstant_arg), - FUTP(varobs_arg.size()*(varobs_arg.size()+1)/2) -{ - Z.setAll(0.0); - Zt.setAll(0.0); - for (size_t i = 0; i < varobs_arg.size(); ++i) - { - size_t j = find(zeta_varobs_back_mixed.begin(), zeta_varobs_back_mixed.end(), - varobs_arg[i]) - zeta_varobs_back_mixed.begin(); - Z(i, j) = 1.0; - Zt(j, i) = 1.0; - } -} - -std::vector -KalmanFilter::compute_zeta_varobs_back_mixed(const std::vector &zeta_back_arg, const std::vector &zeta_mixed_arg, const std::vector &varobs_arg) -{ - std::vector varobs_sorted = varobs_arg; - sort(varobs_sorted.begin(), varobs_sorted.end()); - std::vector zeta_back_mixed, zeta_varobs_back_mixed; - set_union(zeta_back_arg.begin(), zeta_back_arg.end(), - zeta_mixed_arg.begin(), zeta_mixed_arg.end(), - back_inserter(zeta_back_mixed)); - set_union(zeta_back_mixed.begin(), zeta_back_mixed.end(), - varobs_sorted.begin(), varobs_sorted.end(), - back_inserter(zeta_varobs_back_mixed)); - return zeta_varobs_back_mixed; -} - -/** - * Multi-variate standard Kalman Filter - */ -double -KalmanFilter::filter(const MatrixView &detrendedDataView, const Matrix &H, VectorView &vll, size_t start) -{ - double loglik = 0.0, ll, logFdet = 0.0, Fdet, dvtFinvVt; - size_t p = Finv.getRows(); - bool nonstationary = true; - a_init.setAll(0.0); - int info; - - for (size_t t = 0; t < detrendedDataView.getCols(); ++t) - { - if (nonstationary) - { - // K=PZ' - //blas::gemm("N", "T", 1.0, Pstar, Z, 0.0, K); - blas::symm("L", "U", 1.0, Pstar, Zt, 0.0, K); - - //F=ZPZ' +H = ZK+H - F = H; - blas::gemm("N", "N", 1.0, Z, K, 1.0, F); - // logFdet=log|F| - - // Finv=inv(F) - mat::set_identity(Finv); - // Pack F upper trinagle as vector - for (size_t i = 1; i <= p; ++i) - for (size_t j = i; j <= p; ++j) - FUTP(i + (j-1)*j/2 -1) = F(i-1, j-1); - - info = lapack::choleskySolver(FUTP, Finv, "U"); // F now contains its Chol decomposition! - assert(info >= 0); - - if (info > 0) - { - //enforce Pstar symmetry with P=(P+P')/2=0.5P+0.5P' - mat::transpose(Ptmp, Pstar); - mat::add(Pstar, Ptmp); - for (size_t i = 0; i < Pstar.getCols(); ++i) - for (size_t j = 0; j < Pstar.getCols(); ++j) - Pstar(i, j) *= 0.5; - - // K=PZ' - //blas::gemm("N", "T", 1.0, Pstar, Z, 0.0, K); - blas::symm("L", "U", 1.0, Pstar, Zt, 0.0, K); - - //F=ZPZ' +H = ZK+H - F = H; - blas::gemm("N", "N", 1.0, Z, K, 1.0, F); - - // Finv=inv(F) - mat::set_identity(Finv); - // Pack F upper trinagle as vector - for (size_t i = 1; i <= p; ++i) - for (size_t j = i; j <= p; ++j) - FUTP(i + (j-1)*j/2 -1) = F(i-1, j-1); - - info = lapack::choleskySolver(FUTP, Finv, "U"); // F now contains - // its Chol - // decomposition! - assert(info == 0); - } - // KFinv gain matrix - blas::symm("R", "U", 1.0, Finv, K, 0.0, KFinv); - // deteminant of F: - Fdet = 1; - for (size_t d = 1; d <= p; ++d) - Fdet *= FUTP(d + (d-1)*d/2 -1); - Fdet *= Fdet; - - logFdet = log(fabs(Fdet)); - - Ptmp = Pstar; - // Pt+1= T(Pt - KFinvK')T' +RQR' - // 1) Ptmp= Pt - K*FinvK' - blas::gemm("N", "T", -1.0, KFinv, K, 1.0, Ptmp); - // 2) Ptmp= T*Ptmp - Pstar = Ptmp; - //blas::gemm("N", "N", 1.0, T, Pstar, 0.0, Ptmp); - blas::symm("R", "U", 1.0, Pstar, T, 0.0, Ptmp); - // 3) Pt+1= Ptmp*T' +RQR' - Pstar = RQRt; - blas::gemm("N", "T", 1.0, Ptmp, T, 1.0, Pstar); - - if (t > 0) - nonstationary = mat::isDiff(KFinv, oldKFinv, riccati_tol); - oldKFinv = KFinv; - } - - // err= Yt - Za - VectorConstView yt = mat::get_col(detrendedDataView, t); - vt = yt; - blas::gemv("N", -1.0, Z, a_init, 1.0, vt); - - // at+1= T(at+ KFinv *err) - blas::gemv("N", 1.0, KFinv, vt, 1.0, a_init); - blas::gemv("N", 1.0, T, a_init, 0.0, a_new); - a_init = a_new; - - /***************** - Here we calc likelihood and store results. - *****************/ - blas::symv("U", 1.0, Finv, vt, 0.0, vtFinv); - dvtFinvVt = blas::dot(vtFinv, vt); - - ll = -0.5*(p*log(2*M_PI)+logFdet+dvtFinvVt); - - vll(t) = ll; - if (t >= start) - loglik += ll; - - } - - return loglik; -} diff --git a/mex/sources/estimation/KalmanFilter.hh b/mex/sources/estimation/KalmanFilter.hh deleted file mode 100644 index 4de6e156e..000000000 --- a/mex/sources/estimation/KalmanFilter.hh +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// KalmanFilter.h -// Implementation of the Class KalmanFilter -// Created on: 02-Feb-2010 12:44:41 -/////////////////////////////////////////////////////////// - -#if !defined(KF_213B0417_532B_4027_9EDF_36C004CB4CD1__INCLUDED_) -#define KF_213B0417_532B_4027_9EDF_36C004CB4CD1__INCLUDED_ - -#include "InitializeKalmanFilter.hh" - -/** - * Vanilla Kalman filter without constant and with measurement error (use scalar - * 0 when no measurement error). - * If multivariate filter is faster, do as in Matlab: start with multivariate - * filter and switch to univariate filter only in case of singularity - * - * mamber functions: compute() and filter() - * OUTPUT - * LIK: likelihood - * - * REFERENCES - * See "Filtering and Smoothing of State Vector for Diffuse State Space - * Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series - * Analysis, vol. 24(1), pp. 85-98). - */ - -class KalmanFilter -{ - -public: - virtual - ~KalmanFilter(); - KalmanFilter(const std::string &basename, size_t n_endo, size_t n_exo, const std::vector &zeta_fwrd_arg, - const std::vector &zeta_back_arg, const std::vector &zeta_mixed_arg, const std::vector &zeta_static_arg, - double qz_criterium_arg, const std::vector &varobs_arg, - double riccati_tol_arg, double lyapunov_tol_arg, - bool noconstant_arg); - - template - double - compute(const MatrixConstView &dataView, Vec1 &steadyState, - const Mat1 &Q, const Matrix &H, const Vec2 &deepParams, - VectorView &vll, MatrixView &detrendedDataView, size_t start, size_t period) - { - if (period == 0) // initialise all KF matrices - initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T, Pstar, Pinf, - dataView, detrendedDataView); - else // initialise parameter dependent KF matrices only but not Ps - initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T, - dataView, detrendedDataView); - - return filter(detrendedDataView, H, vll, start); - } - -private: - const std::vector zeta_varobs_back_mixed; - static std::vector compute_zeta_varobs_back_mixed(const std::vector &zeta_back_arg, const std::vector &zeta_mixed_arg, const std::vector &varobs_arg); - Matrix Z, Zt; //nob*mm matrix mapping endogeneous variables and observations and its transpose - Matrix T; //mm*mm transition matrix of the state equation. - Matrix R; //mm*rr matrix, mapping structural innovations to state variables. - Matrix Pstar; //mm*mm variance-covariance matrix of stationary variables - Matrix Pinf; //mm*mm variance-covariance matrix of diffuse variables - // allocate space for intermediary matrices - Matrix RQRt, Ptmp; //mm*mm variance-covariance matrix of variable disturbances - Matrix F, Finv; // nob*nob F=ZPZt +H an inv(F) - Matrix K, KFinv, oldKFinv; // mm*nobs K=PZt and K*Finv gain matrices - Vector a_init, a_new; // state vector - Vector vt; // current observation error vectors - Vector vtFinv; // intermediate observation error *Finv vector - double riccati_tol; - InitializeKalmanFilter initKalmanFilter; //Initialise KF matrices - Vector FUTP; // F upper triangle packed as vector FUTP(i + (j-1)*j/2) = F(i,j) for 1<=i<=j; - - // Method - double filter(const MatrixView &detrendedDataView, const Matrix &H, VectorView &vll, size_t start); - -}; - -#endif // !defined(213B0417_532B_4027_9EDF_36C004CB4CD1__INCLUDED_) diff --git a/mex/sources/estimation/LogLikelihoodMain.cc b/mex/sources/estimation/LogLikelihoodMain.cc deleted file mode 100644 index e775dbc3b..000000000 --- a/mex/sources/estimation/LogLikelihoodMain.cc +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// LogLikelihoodMain.cpp -// Implementation of the Class LogLikelihoodMain -// Created on: 02-Feb-2010 12:57:09 -/////////////////////////////////////////////////////////// - -#include "LogLikelihoodMain.hh" - -LogLikelihoodMain::LogLikelihoodMain(const std::string &basename, EstimatedParametersDescription &estiParDesc, size_t n_endo, size_t n_exo, - const std::vector &zeta_fwrd_arg, const std::vector &zeta_back_arg, - const std::vector &zeta_mixed_arg, const std::vector &zeta_static_arg, const double qz_criterium, - const std::vector &varobs, double riccati_tol, double lyapunov_tol, - bool noconstant_arg) - -: estSubsamples(estiParDesc.estSubsamples), - logLikelihoodSubSample(basename, estiParDesc, n_endo, n_exo, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium, - varobs, riccati_tol, lyapunov_tol, noconstant_arg), - vll(estiParDesc.getNumberOfPeriods()), // time dimension size of data - detrendedData(varobs.size(), estiParDesc.getNumberOfPeriods()) -{ - -} - -LogLikelihoodMain::~LogLikelihoodMain() -{ - -} diff --git a/mex/sources/estimation/LogLikelihoodMain.hh b/mex/sources/estimation/LogLikelihoodMain.hh deleted file mode 100644 index 33863f336..000000000 --- a/mex/sources/estimation/LogLikelihoodMain.hh +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ -/////////////////////////////////////////////////////////// -// LogLikelihoodMain.h -// Implementation of the Class LogLikelihoodMain -// Created on: 02-Feb-2010 12:57:09 -/////////////////////////////////////////////////////////// - -#if !defined(E126AEF5_AC28_400a_821A_3BCFD1BC4C22__INCLUDED_) -#define E126AEF5_AC28_400a_821A_3BCFD1BC4C22__INCLUDED_ - -#include "LogLikelihoodSubSample.hh" - -class LogLikelihoodMain -{ -private: - std::vector &estSubsamples; // reference to member of EstimatedParametersDescription - LogLikelihoodSubSample logLikelihoodSubSample; - Vector vll; // vector of all KF step likelihoods - Matrix detrendedData; - -public: - virtual - ~LogLikelihoodMain(); - LogLikelihoodMain(const std::string &basename, EstimatedParametersDescription &estiParDesc, size_t n_endo, size_t n_exo, - const std::vector &zeta_fwrd_arg, const std::vector &zeta_back_arg, const std::vector &zeta_mixed_arg, - const std::vector &zeta_static_arg, const double qz_criterium_arg, const std::vector &varobs_arg, - double riccati_tol_arg, double lyapunov_tol_arg, - bool noconstant_arg); - - /** - * Compute method Inputs: - * Matrix &steadyState; Matrix of sub-sample periods column-vectors of steady states, one column vectro for each sub-sample period - * vectors of deep deepParams and estimated estParams - * Matrix &data input data reference - * Q and H KF matrices of shock and measurement error varinaces and covariances - * KF logLikelihood calculation start period. - */ - - template - double - compute(VEC1 &steadyState, VEC2 &estParams, VectorView &deepParams, const MatrixConstView &data, - MatrixView &Q, Matrix &H, size_t start) - { - double logLikelihood = 0; - for (size_t i = 0; i < estSubsamples.size(); ++i) - { - MatrixConstView dataView(data, 0, estSubsamples[i].startPeriod, - data.getRows(), estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1); - MatrixView detrendedDataView(detrendedData, 0, estSubsamples[i].startPeriod, - data.getRows(), estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1); - - VectorView vllView(vll, estSubsamples[i].startPeriod, estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1); - logLikelihood += logLikelihoodSubSample.compute(steadyState, dataView, estParams, deepParams, - Q, H, vllView, detrendedDataView, start, i); - } - return logLikelihood; - }; - - Vector & - getVll() - { - return vll; - }; -}; - -#endif // !defined(E126AEF5_AC28_400a_821A_3BCFD1BC4C22__INCLUDED_) diff --git a/mex/sources/estimation/LogLikelihoodSubSample.cc b/mex/sources/estimation/LogLikelihoodSubSample.cc deleted file mode 100644 index 6c647c1f8..000000000 --- a/mex/sources/estimation/LogLikelihoodSubSample.cc +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// LogLikelihoodSubSample.cpp -// Implementation of the Class LogLikelihoodSubSample -// Created on: 14-Jan-2010 22:39:14 -/////////////////////////////////////////////////////////// - -#include "LogLikelihoodSubSample.hh" - -LogLikelihoodSubSample::~LogLikelihoodSubSample() -{ -}; - -LogLikelihoodSubSample::LogLikelihoodSubSample(const std::string &basename, EstimatedParametersDescription &INestiParDesc, size_t n_endo, size_t n_exo, - const std::vector &zeta_fwrd_arg, const std::vector &zeta_back_arg, - const std::vector &zeta_mixed_arg, const std::vector &zeta_static_arg, const double qz_criterium, - const std::vector &varobs, double riccati_tol, double lyapunov_tol, bool noconstant_arg) : - estiParDesc(INestiParDesc), - kalmanFilter(basename, n_endo, n_exo, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium, - varobs, riccati_tol, lyapunov_tol, noconstant_arg), eigQ(n_exo), eigH(varobs.size()) -{ -}; diff --git a/mex/sources/estimation/LogLikelihoodSubSample.hh b/mex/sources/estimation/LogLikelihoodSubSample.hh deleted file mode 100644 index e9f0dbe9a..000000000 --- a/mex/sources/estimation/LogLikelihoodSubSample.hh +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// LogLikelihoodSubSample.h -// Implementation of the Class LogLikelihoodSubSample -// Created on: 14-Jan-2010 22:39:14 -/////////////////////////////////////////////////////////// - -#if !defined(DF8B7AF5_8169_4587_9037_2CD2C82E2DDF__INCLUDED_) -#define DF8B7AF5_8169_4587_9037_2CD2C82E2DDF__INCLUDED_ - -#include -#include "EstimatedParametersDescription.hh" -#include "KalmanFilter.hh" -#include "VDVEigDecomposition.hh" -#include "LapackBindings.hh" - -class LogLikelihoodSubSample -{ - -public: - LogLikelihoodSubSample(const std::string &basename, EstimatedParametersDescription &estiParDesc, size_t n_endo, size_t n_exo, - const std::vector &zeta_fwrd_arg, const std::vector &zeta_back_arg, - const std::vector &zeta_mixed_arg, const std::vector &zeta_static_arg, const double qz_criterium, - const std::vector &varobs_arg, double riccati_tol_in, double lyapunov_tol, bool noconstant_arg); - - template - double - compute(VEC1 &steadyState, const MatrixConstView &dataView, VEC2 &estParams, VectorView &deepParams, - MatrixView &Q, Matrix &H, VectorView &vll, MatrixView &detrendedDataView, size_t start, size_t period) - { - updateParams(estParams, deepParams, Q, H, period); - - return kalmanFilter.compute(dataView, steadyState, Q, H, deepParams, vll, detrendedDataView, start, period); - } - - virtual - ~LogLikelihoodSubSample(); - - class UpdateParamsException - { - public: - double penalty; - UpdateParamsException(double penalty_arg) : penalty(penalty_arg) - { - } - }; - -private: - EstimatedParametersDescription &estiParDesc; - KalmanFilter kalmanFilter; - VDVEigDecomposition eigQ; - VDVEigDecomposition eigH; - - // methods - template - void - updateParams(VEC &estParams, VectorView &deepParams, - MatrixView &Q, Matrix &H, size_t period) - { - size_t i, k, k1, k2; - int test; - bool found; - std::vector::const_iterator it; - - for (i = 0; i < estParams.getSize(); ++i) - { - found = false; - it = find(estiParDesc.estParams[i].subSampleIDs.begin(), - estiParDesc.estParams[i].subSampleIDs.end(), period); - if (it != estiParDesc.estParams[i].subSampleIDs.end()) - found = true; - if (found) - { - switch (estiParDesc.estParams[i].ptype) - { - case EstimatedParameter::shock_SD: - k = estiParDesc.estParams[i].ID1; - Q(k, k) = estParams(i)*estParams(i); - break; - - case EstimatedParameter::measureErr_SD: - k = estiParDesc.estParams[i].ID1; - H(k, k) = estParams(i)*estParams(i); - break; - - case EstimatedParameter::shock_Corr: - k1 = estiParDesc.estParams[i].ID1; - k2 = estiParDesc.estParams[i].ID2; - Q(k1, k2) = estParams(i)*sqrt(Q(k1, k1)*Q(k2, k2)); - Q(k2, k1) = Q(k1, k2); - // [CholQ,testQ] = chol(Q); - test = lapack::choleskyDecomp(Q, "L"); - assert(test >= 0); - - if (test > 0) - { - // The variance-covariance matrix of the structural innovations is not definite positive. - // We have to compute the eigenvalues of this matrix in order to build the penalty. - double delta = 0; - eigQ.calculate(Q); // get eigenvalues - //k = find(a < 0); - if (eigQ.hasConverged()) - { - const Vector &evQ = eigQ.getD(); - for (i = 0; i < evQ.getSize(); ++i) - if (evQ(i) < 0) - delta -= evQ(i); - } - - throw UpdateParamsException(delta); - } // if - break; - - case EstimatedParameter::measureErr_Corr: - k1 = estiParDesc.estParams[i].ID1; - k2 = estiParDesc.estParams[i].ID2; - // H(k1,k2) = xparam1(i)*sqrt(H(k1,k1)*H(k2,k2)); - // H(k2,k1) = H(k1,k2); - H(k1, k2) = estParams(i)*sqrt(H(k1, k1)*H(k2, k2)); - H(k2, k1) = H(k1, k2); - - //[CholH,testH] = chol(H); - test = lapack::choleskyDecomp(H, "L"); - assert(test >= 0); - - if (test > 0) - { - // The variance-covariance matrix of the measurement errors is not definite positive. - // We have to compute the eigenvalues of this matrix in order to build the penalty. - //a = diag(eig(H)); - double delta = 0; - eigH.calculate(H); // get eigenvalues - //k = find(a < 0); - if (eigH.hasConverged()) - { - const Vector &evH = eigH.getD(); - for (i = 0; i < evH.getSize(); ++i) - if (evH(i) < 0) - delta -= evH(i); - } - throw UpdateParamsException(delta); - } // end if - break; - - //if estim_params_.np > 0 // i.e. num of deep parameters >0 - case EstimatedParameter::deepPar: - k = estiParDesc.estParams[i].ID1; - deepParams(k) = estParams(i); - break; - default: - assert(false); - } // end switch - } // end found - } //end for - }; - -}; - -#endif // !defined(DF8B7AF5_8169_4587_9037_2CD2C82E2DDF__INCLUDED_) diff --git a/mex/sources/estimation/LogPosteriorDensity.cc b/mex/sources/estimation/LogPosteriorDensity.cc deleted file mode 100644 index c87e6dee7..000000000 --- a/mex/sources/estimation/LogPosteriorDensity.cc +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// LogPosteriorDensity.cpp -// Implementation of the Class LogPosteriorDensity -// Created on: 10-Feb-2010 20:54:18 -/////////////////////////////////////////////////////////// - -#include "LogPosteriorDensity.hh" - -LogPosteriorDensity::~LogPosteriorDensity() -{ -} - -LogPosteriorDensity::LogPosteriorDensity(const std::string &modName, EstimatedParametersDescription &estParamsDesc, size_t n_endo, size_t n_exo, - const std::vector &zeta_fwrd_arg, const std::vector &zeta_back_arg, const std::vector &zeta_mixed_arg, - const std::vector &zeta_static_arg, const double qz_criterium_arg, const std::vector &varobs_arg, - double riccati_tol_arg, double lyapunov_tol_arg, - bool noconstant_arg) : - logPriorDensity(estParamsDesc), - logLikelihoodMain(modName, estParamsDesc, n_endo, n_exo, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, - zeta_static_arg, qz_criterium_arg, varobs_arg, riccati_tol_arg, lyapunov_tol_arg, noconstant_arg) -{ - -} - -/** - * vector of log likelihoods for each Kalman step - */ -Vector & -LogPosteriorDensity::getLikVector() -{ - return logLikelihoodMain.getVll(); -} diff --git a/mex/sources/estimation/LogPosteriorDensity.hh b/mex/sources/estimation/LogPosteriorDensity.hh deleted file mode 100644 index 425eb625a..000000000 --- a/mex/sources/estimation/LogPosteriorDensity.hh +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// LogPosteriorDensity.hh -// Implementation of the Class LogPosteriorDensity -// Created on: 10-Feb-2010 20:54:18 -/////////////////////////////////////////////////////////// - -#if !defined(LPD_052A31B5_53BF_4904_AD80_863B52827973__INCLUDED_) -#define LPD_052A31B5_53BF_4904_AD80_863B52827973__INCLUDED_ - -#include "EstimatedParametersDescription.hh" -#include "LogPriorDensity.hh" -#include "LogLikelihoodMain.hh" - -/** - * Class that calculates Log Posterior Density using kalman, based on Dynare - * DsgeLikelihood.m - */ -class LogPosteriorDensity -{ - -private: - LogPriorDensity logPriorDensity; - LogLikelihoodMain logLikelihoodMain; - -public: - virtual - ~LogPosteriorDensity(); - - LogPosteriorDensity(const std::string &modName, EstimatedParametersDescription &estParamsDesc, size_t n_endo, size_t n_exo, - const std::vector &zeta_fwrd_arg, const std::vector &zeta_back_arg, const std::vector &zeta_mixed_arg, - const std::vector &zeta_static_arg, const double qz_criterium_arg, const std::vector &varobs_arg, - double riccati_tol_arg, double lyapunov_tol_arg, - bool noconstant_arg); - - template - double - compute(VEC1 &steadyState, VEC2 &estParams, VectorView &deepParams, const MatrixConstView &data, MatrixView &Q, Matrix &H, size_t presampleStart) - { - return -logLikelihoodMain.compute(steadyState, estParams, deepParams, data, Q, H, presampleStart) - -logPriorDensity.compute(estParams); - } - - Vector&getLikVector(); - -}; - -#endif // !defined(052A31B5_53BF_4904_AD80_863B52827973__INCLUDED_) diff --git a/mex/sources/estimation/LogPriorDensity.cc b/mex/sources/estimation/LogPriorDensity.cc deleted file mode 100644 index fbdcdc5ac..000000000 --- a/mex/sources/estimation/LogPriorDensity.cc +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2009-2012 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// LogPriorDensity.cpp -// Implementation of the Class LogPriorDensity -// Created on: 10-Feb-2010 20:56:08 -/////////////////////////////////////////////////////////// - -#include "LogPriorDensity.hh" -LogPriorDensity::~LogPriorDensity() -{ -}; - -LogPriorDensity::LogPriorDensity(EstimatedParametersDescription &estParsDesc_arg) : - estParsDesc(estParsDesc_arg) -{ -}; - -/** - * Return random number for prior fromits distribution - */ -void -LogPriorDensity::computeNewParams(Vector &ep) -{ - -} diff --git a/mex/sources/estimation/LogPriorDensity.hh b/mex/sources/estimation/LogPriorDensity.hh deleted file mode 100644 index c7c57a6bd..000000000 --- a/mex/sources/estimation/LogPriorDensity.hh +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// LogPriorDensity.hh -// Implementation of the Class LogPriorDensity -// Created on: 10-Feb-2010 20:56:08 -/////////////////////////////////////////////////////////// - -#if !defined(LPD_011FD4CF_17CE_4805_882B_046AA07CF443__INCLUDED_) -#define LPD_011FD4CF_17CE_4805_882B_046AA07CF443__INCLUDED_ - -//#include -#include "Vector.hh" -#include "EstimatedParametersDescription.hh" - -class LogPriorDensity -{ - -public: - LogPriorDensity(EstimatedParametersDescription &estParsDesc); - virtual - ~LogPriorDensity(); - - template - double - compute(VEC &ep) - { - assert(estParsDesc.estParams.size() == ep.getSize()); - double logPriorDensity = 0; - for (size_t i = 0; i < ep.getSize(); ++i) - { - logPriorDensity += log(((*(estParsDesc.estParams[i]).prior)).pdf(ep(i))); - if (std::isinf(fabs(logPriorDensity))) - return logPriorDensity; - } - return logPriorDensity; - }; - - void computeNewParams(Vector &newParams); - -private: - const EstimatedParametersDescription &estParsDesc; - -}; - -#endif // !defined(011FD4CF_17CE_4805_882B_046AA07CF443__INCLUDED_) diff --git a/mex/sources/estimation/Makefile.am b/mex/sources/estimation/Makefile.am deleted file mode 100644 index fd42d7bff..000000000 --- a/mex/sources/estimation/Makefile.am +++ /dev/null @@ -1,47 +0,0 @@ -SUBDIRS = libmat - -if HAVE_BLAS -if HAVE_LAPACK -SUBDIRS += tests -endif -endif - -EXTRA_DIST = \ - DecisionRules.cc \ - DecisionRules.hh \ - DetrendData.cc \ - DetrendData.hh \ - EstimatedParameter.cc \ - EstimatedParameter.hh \ - EstimatedParametersDescription.cc \ - EstimatedParametersDescription.hh \ - EstimationSubsample.cc \ - EstimationSubsample.hh \ - InitializeKalmanFilter.cc \ - InitializeKalmanFilter.hh \ - KalmanFilter.cc \ - KalmanFilter.hh \ - LogLikelihoodMain.hh \ - LogLikelihoodMain.cc \ - LogLikelihoodSubSample.cc \ - LogLikelihoodSubSample.hh \ - logMHMCMCposterior.cc \ - logposterior.cc \ - LogPosteriorDensity.cc \ - LogPosteriorDensity.hh \ - LogPriorDensity.cc \ - LogPriorDensity.hh \ - ModelSolution.cc \ - ModelSolution.hh \ - Prior.cc \ - Prior.hh \ - Proposal.cc \ - Proposal.hh \ - RandomWalkMetropolisHastings.hh \ - SteadyStateSolver.cc \ - SteadyStateSolver.hh \ - utils/dynamic_dll.cc \ - utils/dynamic_dll.hh \ - utils/static_dll.cc \ - utils/static_dll.hh \ - utils/ts_exception.h diff --git a/mex/sources/estimation/ModelSolution.cc b/mex/sources/estimation/ModelSolution.cc deleted file mode 100644 index abeb02124..000000000 --- a/mex/sources/estimation/ModelSolution.cc +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// ModelSolution.cpp -// Implementation of the Class ModelSolution -// Created on: 02-Feb-2010 13:06:35 -/////////////////////////////////////////////////////////// - -#include - -#include "ModelSolution.hh" - -/** - * compute the steady state (2nd stage), and computes first order approximation - */ -ModelSolution::ModelSolution(const std::string &basename, size_t n_endo_arg, size_t n_exo_arg, const std::vector &zeta_fwrd_arg, - const std::vector &zeta_back_arg, const std::vector &zeta_mixed_arg, - const std::vector &zeta_static_arg, double INqz_criterium) : - n_endo(n_endo_arg), n_exo(n_exo_arg), // n_jcols = Num of Jacobian columns = nStat+2*nPred+3*nBoth+2*nForw+nExog - n_jcols(n_exo+n_endo+ zeta_back_arg.size() /*nsPred*/ + zeta_fwrd_arg.size() /*nsForw*/ +2*zeta_mixed_arg.size()), - jacobian(n_endo, n_jcols), residual(n_endo), Mx(1, n_exo), - decisionRules(n_endo_arg, n_exo_arg, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, INqz_criterium), - dynamicDLLp(basename), - steadyStateSolver(basename, n_endo), - llXsteadyState(n_jcols-n_exo) -{ - Mx.setAll(0.0); - jacobian.setAll(0.0); - - set_union(zeta_fwrd_arg.begin(), zeta_fwrd_arg.end(), - zeta_mixed_arg.begin(), zeta_mixed_arg.end(), - back_inserter(zeta_fwrd_mixed)); - set_union(zeta_back_arg.begin(), zeta_back_arg.end(), - zeta_mixed_arg.begin(), zeta_mixed_arg.end(), - back_inserter(zeta_back_mixed)); -} diff --git a/mex/sources/estimation/ModelSolution.hh b/mex/sources/estimation/ModelSolution.hh deleted file mode 100644 index 8bdc4a66a..000000000 --- a/mex/sources/estimation/ModelSolution.hh +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// ComputeModelSolution.h -// Implementation of the Class ModelSolution -// Created on: 15-Jan-2010 07:37:47 -/////////////////////////////////////////////////////////// - -#if !defined(ModelSolution_5ADFF920_9C74_46f5_9FE9_88AD4D4BBF19__INCLUDED_) -#define ModelSolution_5ADFF920_9C74_46f5_9FE9_88AD4D4BBF19__INCLUDED_ - -#include "DecisionRules.hh" -#include "SteadyStateSolver.hh" -#include "dynamic_dll.hh" - -/** - * compute the steady state (2nd stage), and - * computes first order approximation - * - */ -class ModelSolution -{ - -public: - ModelSolution(const std::string &basename, size_t n_endo, size_t n_exo, const std::vector &zeta_fwrd_arg, - const std::vector &zeta_back_arg, const std::vector &zeta_mixed_arg, - const std::vector &zeta_static_arg, double qz_criterium); - virtual ~ModelSolution() - { - }; - template - void - compute(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &ghx, Mat2 &ghu) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException, SteadyStateSolver::SteadyStateException) - { - // compute Steady State - steadyStateSolver.compute(steadyState, Mx, deepParams); - - // then get jacobian and - - ComputeModelSolution(steadyState, deepParams, ghx, ghu); - - } - -private: - const size_t n_endo; - const size_t n_exo; - const size_t n_jcols; // Num of Jacobian columns - std::vector zeta_fwrd_mixed, zeta_back_mixed; - Matrix jacobian; - Vector residual; - Matrix Mx; - DecisionRules decisionRules; - DynamicModelDLL dynamicDLLp; - SteadyStateSolver steadyStateSolver; - Vector llXsteadyState; - //Matrix jacobian; - template - void - ComputeModelSolution(Vec1 &steadyState, const Vec2 &deepParams, - Mat1 &ghx, Mat2 &ghu) - throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException) - { - // set extended Steady State - - for (size_t i = 0; i < zeta_back_mixed.size(); i++) - llXsteadyState(i) = steadyState(zeta_back_mixed[i]); - - for (size_t i = 0; i < n_endo; i++) - llXsteadyState(zeta_back_mixed.size() + i) = steadyState(i); - - for (size_t i = 0; i < zeta_fwrd_mixed.size(); i++) - llXsteadyState(zeta_back_mixed.size() + n_endo + i) = steadyState(zeta_fwrd_mixed[i]); - - //get jacobian - dynamicDLLp.eval(llXsteadyState, Mx, deepParams, steadyState, residual, &jacobian, NULL, NULL); - - //compute rules - decisionRules.compute(jacobian, ghx, ghu); - } -}; - -#endif // !defined(5ADFF920_9C74_46f5_9FE9_88AD4D4BBF19__INCLUDED_) diff --git a/mex/sources/estimation/Prior.cc b/mex/sources/estimation/Prior.cc deleted file mode 100644 index fdd5207fd..000000000 --- a/mex/sources/estimation/Prior.cc +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2009-2013 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// Prior.cpp -// Implementation of the Class Prior -// Created on: 02-Feb-2010 13:06:20 -/////////////////////////////////////////////////////////// - -#include "Prior.hh" - -Prior::Prior(double mean_arg, double standard_arg, double lower_bound_arg, double upper_bound_arg, double fhp_arg, double shp_arg) : - mean(mean_arg), standard(standard_arg), lower_bound(lower_bound_arg), upper_bound(upper_bound_arg), fhp(fhp_arg), shp(shp_arg) -{ - -} - -Prior::~Prior() -{ - -} - -Prior * -Prior::constructPrior(pShape shape, double mean, double standard, double lower_bound, double upper_bound, double fhp, double shp) -{ - switch (shape) - { - case Beta: - return new BetaPrior(mean, standard, lower_bound, upper_bound, fhp, shp); - case Gamma: - return new GammaPrior(mean, standard, lower_bound, upper_bound, fhp, shp); - case Gaussian: - return new GaussianPrior(mean, standard, lower_bound, upper_bound, fhp, shp); - case Inv_gamma_1: - return new InvGamma1_Prior(mean, standard, lower_bound, upper_bound, fhp, shp); - case Uniform: - return new UniformPrior(mean, standard, lower_bound, upper_bound, fhp, shp); - case Inv_gamma_2: - return new InvGamma2_Prior(mean, standard, lower_bound, upper_bound, fhp, shp); - } - std::cerr << "Unreacheable point" << std::endl; - exit(EXIT_FAILURE); -} diff --git a/mex/sources/estimation/Prior.hh b/mex/sources/estimation/Prior.hh deleted file mode 100644 index f550e2b75..000000000 --- a/mex/sources/estimation/Prior.hh +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// Prior.h -// Implementation of the Class Prior -// Created on: 02-Feb-2010 13:06:20 -/////////////////////////////////////////////////////////// - -#if !defined(Prior_8D5F562F_C831_43f3_B390_5C4EF4433756__INCLUDED_) -#define Prior_8D5F562F_C831_43f3_B390_5C4EF4433756__INCLUDED_ - -#include -#include -#include -#include - -#include // for beta_distribution. -#include // for gamma_distribution. -#include // for normal_distribution. -#include // for uniform_distribution. - -// typedef for base_uniform_generator_type -// rend48 seems better than the basic minstd_rand but -// one my later try ecuyer1988 or taus88 which are better but not yet supported in the Boost versionwe use -typedef boost::rand48 base_uniform_generator_type; - -struct Prior -{ - -public: - //! probablity density functions - enum pShape - { - Beta = 1, - Gamma = 2, - Gaussian = 3, // i.e. Normal density - Inv_gamma_1 = 4, // Inverse gamma (type 1) density - Uniform = 5, - Inv_gamma_2 = 6 //Inverse gamma (type 2) density - }; - - Prior(double mean, double standard, double lower_bound, double upper_bound, double fhp, double shp); - virtual - ~Prior(); - - const double mean; - const double standard; - const double lower_bound; - const double upper_bound; - /** - * first shape parameter - */ - const double fhp; - /** - * second shape parameter - */ - const double shp; - virtual pShape getShape() = 0; // e.g. = Beta for beta shape? - - virtual double - pdf(double x) // probability density function value for x - { - std::cout << "Parent pdf undefined at parent level" << std::endl; - return 0.0; - }; - - virtual double - drand() // rand for density - { - std::cout << "Parent rand undefined at parent level" << std::endl; - return 0.0; - }; - - static Prior *constructPrior(pShape shape, double mean, double standard, double lower_bound, double upper_bound, double fhp, double shp); -}; - -struct BetaPrior : public Prior -{ -public: - boost::math::beta_distribution distribution; - - BetaPrior(double mean, double standard, double lower_bound, double upper_bound, double fhp, double shp) : - Prior(mean, standard, lower_bound, upper_bound, fhp, shp), - distribution(fhp, shp) - { - }; - virtual ~BetaPrior() - { - }; - virtual pShape - getShape() - { - return Prior::Beta; - }; // e.g. = Beta for beta shape? - - virtual double - pdf(double x) - { - double scalled = x; - if (lower_bound || 1.0-upper_bound) - scalled = (x- lower_bound)/(upper_bound- lower_bound); - return boost::math::pdf(distribution, scalled); - }; - - virtual double - drand() // rand for density - { - return 0.0; - }; -}; - -struct GammaPrior : public Prior -{ -public: - boost::math::gamma_distribution distribution; - - GammaPrior(double mean, double standard, - double lower_bound, double upper_bound, double fhp, double shp) : - Prior(mean, standard, lower_bound, upper_bound, fhp, shp), - distribution(fhp, shp) - { - }; - virtual ~GammaPrior() - { - }; - virtual pShape - getShape() - { - return Prior::Gamma; - }; // e.g. = Beta for beta shape? - virtual double - pdf(double x) - { - return boost::math::pdf(distribution, x- lower_bound); - }; - virtual double - drand() // rand for density - { - return 0.0; - }; -}; - -// X ~ IG1(s,nu) if X = sqrt(Y) where Y ~ IG2(s,nu) and Y = inv(Z) with Z ~ G(nu/2,2/s) (Gamma distribution) -// i.e. Dynare lpdfig1(x,s,n)= lpdfgam(1/(x*x),n/2,2/s)-2*log(x*x)+log(2*x) -struct InvGamma1_Prior : public Prior -{ -public: - boost::math::gamma_distribution distribution; - InvGamma1_Prior(double mean, double standard, - double lower_bound, double upper_bound, double fhp, double shp) : - Prior(mean, standard, lower_bound, upper_bound, fhp, shp), - distribution(shp/2, 2/fhp) - { - }; - virtual ~InvGamma1_Prior() - { - }; - virtual pShape - getShape() - { - return Prior::Inv_gamma_1; - }; // e.g. = Beta for beta shape? - virtual double - pdf(double x) - { - double scalled = ((x- lower_bound)*(x-lower_bound)); - if (x > lower_bound) - return (boost::math::pdf(distribution, 1/scalled) / (scalled*scalled))*2*(x-lower_bound); - else - return 0; - }; - virtual double - drand() // rand for density - { - return 0.0; - }; -}; - -// If x~InvGamma(a,b) , then 1/x ~Gamma(a,1/b) distribution -// i.e. Dynare lpdfig2(x*x,n,s) = lpdfgam(1/(x*x),s/2,2/n) - 2*log(x*x) -struct InvGamma2_Prior : public Prior -{ -public: - boost::math::gamma_distribution distribution; - - InvGamma2_Prior(double mean, double standard, - double lower_bound, double upper_bound, double fhp, double shp) : - Prior(mean, standard, lower_bound, upper_bound, fhp, shp), - distribution(shp/2, 2/fhp) - { - }; - virtual ~InvGamma2_Prior() - { - }; - virtual pShape - getShape() - { - return Prior::Inv_gamma_2; - }; // e.g. = Beta for beta shape? - - virtual double - pdf(double x) - { - double scalled = x - lower_bound; - if (scalled > 0) - return boost::math::pdf(distribution, 1/scalled) / (scalled*scalled); - else - return 0; - }; - virtual double - drand() // rand for density - { - return 0.0; - }; -}; - -struct GaussianPrior : public Prior -{ -private: - base_uniform_generator_type base_rng_type; - boost::normal_distribution rng_type; - boost::variate_generator > vrng; - -public: - boost::math::normal_distribution distribution; - - GaussianPrior(double mean, double standard, double lower_bound, double upper_bound, double fhp, double shp) : - Prior(mean, standard, lower_bound, upper_bound, fhp, shp), - rng_type(fhp, shp), // random number generator distribution type (mean, standard) - vrng(base_rng_type, rng_type), // random variate_generator - distribution(fhp, shp) //pdf distribution(mean, standard) - { - }; - virtual ~GaussianPrior() - { - }; - virtual pShape - getShape() - { - return Prior::Gaussian; - }; // e.g. = Beta for beta shape? - virtual double - pdf(double x) - { - if (x > lower_bound && x < upper_bound) - return boost::math::pdf(distribution, x); - else - return 0; - }; - virtual double - drand() // rand for density - { - return vrng(); - }; -}; - -struct UniformPrior : public Prior -{ -private: - base_uniform_generator_type base_rng_type; - boost::uniform_real<> rng_type; - boost::variate_generator > vrng; - -public: - boost::math::uniform_distribution distribution; - - UniformPrior(double mean, double standard, double lower_bound, double upper_bound, double fhp, double shp) : - Prior(mean, standard, lower_bound, upper_bound, fhp, shp), - rng_type(fhp, shp), // random number generator distribution type - vrng(base_rng_type, rng_type), // random variate_generator - distribution(fhp, shp) //pdf distribution(lower_bound, upper_bound) - { - }; - virtual ~UniformPrior() - { - }; - virtual pShape - getShape() - { - return Prior::Uniform; - }; // e.g. = Beta for beta shape? - virtual double - pdf(double x) - { - if (x > lower_bound && x < upper_bound) - return boost::math::pdf(distribution, x); - else - return 0; - }; - virtual double - drand() // rand for density - { - return vrng(); - }; - -}; - -#endif // !defined(8D5F562F_C831_43f3_B390_5C4EF4433756__INCLUDED_) diff --git a/mex/sources/estimation/Proposal.cc b/mex/sources/estimation/Proposal.cc deleted file mode 100644 index 8bf5933d4..000000000 --- a/mex/sources/estimation/Proposal.cc +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// Proposal.cpp -// Implementation of the Class Proposal -// Created on: 15-Dec-2010 12:43:49 -/////////////////////////////////////////////////////////// - -#include "Proposal.hh" - -Proposal::Proposal(const VectorConstView &vJscale, const MatrixConstView &covariance) : - len(covariance.getCols()), - covarianceCholeskyDecomposition(len), - newDraw(len), - uniform_rng_type(0, 1), // uniform random number generator distribution type - uniformVrng(base_rng, uniform_rng_type), // uniform random variate_generator - normal_rng_type(0, 1), // normal random number generator distribution type (mean, standard) - normalVrng(base_rng, normal_rng_type) // normal random variate_generator -{ - Matrix Jscale(len); - Matrix DD(len); - DD = covariance; - - lapack::choleskyDecomp(DD, "U"); - Jscale.setAll(0.0); - for (size_t i = 0; i < len; i++) - Jscale(i, i) = vJscale(i); - blas::gemm("N", "N", 1.0, DD, Jscale, 0.0, covarianceCholeskyDecomposition); -} - -void -Proposal::draw(Vector &mean, Vector &draw) -{ - assert(len == draw.getSize()); - assert(len == mean.getSize()); - - draw = mean; - for (size_t i = 0; i < len; ++i) - newDraw(i) = normalVrng(); - blas::gemv("T", 1.0, covarianceCholeskyDecomposition, newDraw, 1.0, draw); - -} - -Matrix & -Proposal::getVar() -{ - return covarianceCholeskyDecomposition; -} - -/** - * set or get if null arguments - */ -int -Proposal::seed() -{ - return curSeed; -} - -void -Proposal::seed(int newSeed) -{ - curSeed = newSeed; - base_rng.seed(curSeed); -} - -/** - * currently returns uniform for MH sampler, - */ -double -Proposal::selectionTestDraw() -{ - return uniformVrng(); -} diff --git a/mex/sources/estimation/Proposal.hh b/mex/sources/estimation/Proposal.hh deleted file mode 100644 index 4beb1c9dd..000000000 --- a/mex/sources/estimation/Proposal.hh +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2009-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// Proposal.hh -// Implementation of the Class Proposal -// Created on: 15-Dec-2010 12:43:49 -/////////////////////////////////////////////////////////// - -#if !defined(CABFAB46_2FA5_4178_8D1C_05DFEAFB4570__INCLUDED_) -#define CABFAB46_2FA5_4178_8D1C_05DFEAFB4570__INCLUDED_ - -/** - * Proposal class will then have the common, seed initialised base generator - * (currently congruental rand48) and member functions such as seed, reset (to - * initial,default value) and have all rand generators we need that generate from - * that common base: single uniform and normal (either single or multivariate - * determined by the size of the variance matrix) for now. - * - * The rng interfaces will be - a single, selectionTest() currently uniform for MH - * sampler, draw(mean, newDraw) - single or multivariate parameters (currently - * from Normal(mean,Sigma)) and poss. also the seed state (set and get), the - * normal Chol_variance_decomp (constructed using Chol Decomp of init Variance - * matrix) , as core members .This class will handle the main boost random rng - * intricacies. See enclosed updated diagram (if ok I will upload it) - * - */ - -#include "Matrix.hh" -#include "BlasBindings.hh" -#include "LapackBindings.hh" -#include -#include -#include -#include - -// typedef for base_uniform_generator_type -// rend48 seems better than the basic minstd_rand but -// one my later try ecuyer1988 or taus88 which are better but not yet supported in the Boost versionwe use -typedef boost::rand48 base_uniform_generator_type; - -class Proposal -{ - -public: - Proposal(); - -public: - Proposal(const VectorConstView &vJscale, const MatrixConstView &covariance); - virtual ~Proposal() - { - }; - virtual void draw(Vector &mean, Vector &draw); - virtual Matrix&getVar(); - virtual int seed(); - virtual void seed(int seedInit); - virtual double selectionTestDraw(); - -private: - size_t len; - Matrix covarianceCholeskyDecomposition; - /** - * Vector of new draws - * - */ - Vector newDraw; - - base_uniform_generator_type base_rng; - boost::uniform_real<> uniform_rng_type; - boost::variate_generator > uniformVrng; - boost::normal_distribution normal_rng_type; - boost::variate_generator > normalVrng; - - int curSeed; - -}; - -#endif // !defined(CABFAB46_2FA5_4178_8D1C_05DFEAFB4570__INCLUDED_) diff --git a/mex/sources/estimation/RandomWalkMetropolisHastings.hh b/mex/sources/estimation/RandomWalkMetropolisHastings.hh deleted file mode 100644 index c09b2c9df..000000000 --- a/mex/sources/estimation/RandomWalkMetropolisHastings.hh +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/////////////////////////////////////////////////////////// -// RandomWalkMetropolisHastings.hh -// Implementation of the Class RandomWalkMetropolisHastings -// Created on: 07-Sep-2010 15:21:40 -/////////////////////////////////////////////////////////// - -#if !defined(A6BBC5E0_598E_4863_B7FF_E87320056B80__INCLUDED_) -#define A6BBC5E0_598E_4863_B7FF_E87320056B80__INCLUDED_ - -#include -#include -#include "LogPosteriorDensity.hh" -#include "Proposal.hh" - -class RandomWalkMetropolisHastings -{ - -private: - Vector parDraw, newParDraw; - -public: - RandomWalkMetropolisHastings(size_t size) : - parDraw(size), newParDraw(size) - { - }; - virtual ~RandomWalkMetropolisHastings() - { - }; - - template - double - compute(VectorView &mhLogPostDens, MatrixView &mhParams, VEC1 &steadyState, - Vector &estParams, VectorView &deepParams, const MatrixConstView &data, MatrixView &Q, Matrix &H, - const size_t presampleStart, const size_t startDraw, size_t nMHruns, - LogPosteriorDensity &lpd, Proposal &pDD, EstimatedParametersDescription &epd) - { - //streambuf *likbuf, *drawbuf *backup; - std::ofstream urandfilestr, drawfilestr; - urandfilestr.open("urand.csv"); - drawfilestr.open("paramdraws.csv"); - - bool overbound; - double newLogpost, logpost, urand; - size_t count, accepted = 0; - parDraw = estParams; - - logpost = -lpd.compute(steadyState, estParams, deepParams, data, Q, H, presampleStart); - - for (size_t run = startDraw - 1; run < nMHruns; ++run) - { - overbound = false; - pDD.draw(parDraw, newParDraw); - for (count = 0; count < parDraw.getSize(); ++count) - { - overbound = (newParDraw(count) < epd.estParams[count].lower_bound || newParDraw(count) > epd.estParams[count].upper_bound); - if (overbound) - { - newLogpost = -INFINITY; - break; - } - } - if (!overbound) - { - try - { - newLogpost = -lpd.compute(steadyState, newParDraw, deepParams, data, Q, H, presampleStart); - } - catch (const std::exception &e) - { - throw; // for now handle the system and other errors higher-up - } - catch (...) - { - newLogpost = -INFINITY; - } - } - urand = pDD.selectionTestDraw(); - if ((newLogpost > -INFINITY) && log(urand) < newLogpost-logpost) - { - parDraw = newParDraw; - logpost = newLogpost; - accepted++; - } - mat::get_row(mhParams, run) = parDraw; - mhLogPostDens(run) = logpost; - - urandfilestr << urand << "\n"; //"," - for (size_t c = 0; c < newParDraw.getSize()-1; ++c) - drawfilestr << newParDraw(c) << ","; - drawfilestr << newParDraw(newParDraw.getSize()-1) << "\n"; - } - - urandfilestr.close(); - drawfilestr.close(); - - return (double) accepted/(nMHruns-startDraw+1); - }; - -}; - -#endif // !defined(A6BBC5E0_598E_4863_B7FF_E87320056B80__INCLUDED_) diff --git a/mex/sources/estimation/SteadyStateSolver.cc b/mex/sources/estimation/SteadyStateSolver.cc deleted file mode 100644 index a0bb7cbe0..000000000 --- a/mex/sources/estimation/SteadyStateSolver.cc +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2013-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include "SteadyStateSolver.hh" - -const double SteadyStateSolver::tolerance = 1e-7; - -SteadyStateSolver::SteadyStateSolver(const std::string &basename, size_t n_endo_arg) - : static_dll(basename), n_endo(n_endo_arg), residual(n_endo), g1(n_endo) -{ - g1.setAll(0.0); // The static file does not initialize zero elements -} - -int -SteadyStateSolver::static_f(const gsl_vector *yy, void *p, gsl_vector *F) -{ - params *pp = (params *) p; - VectorConstView deepParams(pp->deepParams, pp->n_params, 1); - MatrixConstView x(pp->x, 1, pp->n_exo, 1); - - VectorView y(yy->data, yy->size, yy->stride); - VectorView residual(F->data, F->size, F->stride); - - pp->static_dll->eval(y, x, deepParams, residual, NULL, NULL); - - return GSL_SUCCESS; -} - -int -SteadyStateSolver::static_df(const gsl_vector *yy, void *p, gsl_matrix *J) -{ - params *pp = (params *) p; - VectorConstView deepParams(pp->deepParams, pp->n_params, 1); - MatrixConstView x(pp->x, 1, pp->n_exo, 1); - - VectorView y(yy->data, yy->size, yy->stride); - - pp->static_dll->eval(y, x, deepParams, *pp->residual, pp->g1, NULL); - - assert(J->size1 == J->size2 && J->size1 == J->tda); - MatrixView g1t(J->data, J->size1, J->size2, J->tda); - mat::transpose(g1t, *pp->g1); // GSL wants row-major order - - return GSL_SUCCESS; -} - -int -SteadyStateSolver::static_fdf(const gsl_vector *yy, void *p, gsl_vector *F, gsl_matrix *J) -{ - params *pp = (params *) p; - VectorConstView deepParams(pp->deepParams, pp->n_params, 1); - MatrixConstView x(pp->x, 1, pp->n_exo, 1); - - VectorView y(yy->data, yy->size, yy->stride); - VectorView residual(F->data, F->size, F->stride); - - pp->static_dll->eval(y, x, deepParams, residual, pp->g1, NULL); - - assert(J->size1 == J->size2 && J->size1 == J->tda); - MatrixView g1t(J->data, J->size1, J->size2, J->tda); - mat::transpose(g1t, *pp->g1); // GSL wants row-major order - - return GSL_SUCCESS; -} diff --git a/mex/sources/estimation/SteadyStateSolver.hh b/mex/sources/estimation/SteadyStateSolver.hh deleted file mode 100644 index 726d8594b..000000000 --- a/mex/sources/estimation/SteadyStateSolver.hh +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (C) 2013-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include - -#include "Vector.hh" -#include "static_dll.hh" - -#include -#include - -class SteadyStateSolver -{ -private: - StaticModelDLL static_dll; - size_t n_endo; - Vector residual; // Will be discarded, only used by df() - Matrix g1; // Temporary buffer for computing transpose - - struct params - { - StaticModelDLL *static_dll; - const double *deepParams; - size_t n_params; - const double *x; - size_t n_exo; - Vector *residual; - Matrix *g1; - }; - - static int static_f(const gsl_vector *yy, void *p, gsl_vector *F); - static int static_df(const gsl_vector *yy, void *p, gsl_matrix *J); - static int static_fdf(const gsl_vector *yy, void *p, gsl_vector *F, gsl_matrix *J); - - const static double tolerance; - const static size_t max_iterations = 1000; -public: - class SteadyStateException - { - public: - std::string message; - SteadyStateException(const std::string &message_arg) : message(message_arg) - { - } - }; - - SteadyStateSolver(const std::string &basename, size_t n_endo_arg); - - template - void - compute(Vec1 &steadyState, const Mat &Mx, const Vec2 &deepParams) throw (SteadyStateException) - { - assert(steadyState.getStride() == 1); - assert(deepParams.getStride() == 1); - assert(Mx.getLd() == Mx.getRows()); - - assert(steadyState.getSize() == n_endo); - - gsl_vector_view ss = gsl_vector_view_array(steadyState.getData(), n_endo); - - params p = { &static_dll, deepParams.getData(), deepParams.getSize(), Mx.getData(), Mx.getCols(), &residual, &g1 }; - - gsl_multiroot_function_fdf f = {&static_f, &static_df, &static_fdf, - n_endo, &p}; - - const gsl_multiroot_fdfsolver_type *T = gsl_multiroot_fdfsolver_hybridsj; - gsl_multiroot_fdfsolver *s = gsl_multiroot_fdfsolver_alloc(T, n_endo); - - gsl_multiroot_fdfsolver_set(s, &f, &ss.vector); - - int status; - size_t iter = 0; - - do - { - iter++; - - status = gsl_multiroot_fdfsolver_iterate(s); - - if (status) - break; - - status = gsl_multiroot_test_residual(s->f, tolerance); - } - while (status == GSL_CONTINUE && iter < max_iterations); - - if (status != GSL_SUCCESS) - throw SteadyStateException(std::string(gsl_strerror(status))); - - gsl_vector_memcpy(&ss.vector, gsl_multiroot_fdfsolver_root(s)); - - gsl_multiroot_fdfsolver_free(s); - } -}; diff --git a/mex/sources/estimation/libmat/BlasBindings.hh b/mex/sources/estimation/libmat/BlasBindings.hh deleted file mode 100644 index d4b67ca55..000000000 --- a/mex/sources/estimation/libmat/BlasBindings.hh +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (C) 2010-2013 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#ifndef _BLAS_BINDINGS_HH -#define _BLAS_BINDINGS_HH - -#include - -#include "Vector.hh" -#include "Matrix.hh" - -namespace blas -{ - /* Level 1 */ - - //! dot product of two vectors - template - inline double - dot(const Vec1 &A, Vec2 &B) - { - assert(A.getSize() == B.getSize()); - blas_int n = A.getSize(); - blas_int lda = A.getStride(), ldb = B.getStride(); - return ddot(&n, A.getData(), &lda, B.getData(), &ldb); - } - - /* Level 2 */ - - //! Symmetric rank 1 operation: A = alpha*X*X' + A - template - inline void - syr(const char *uplo, double alpha, Vec X, Mat A) - { - assert(X.getSize() == A.getCols() && A.getCols() == A.getRows()); - blas_int n = X.getSize(); - blas_int incx = X.getStride(); - blas_int lda = A.getLd(); - dsyr(uplo, &n, &alpha, X.getData(), &incx, A.getData(), &lda); - } - - //! General matrix * vector multiplication - // c = alpha*A*b + beta*c, or c := alpha*A'*b + beta*c, - // where alpha and beta are scalars, b and c are vectors and A is an - // m by n matrix. - template - inline void - gemv(const char *transa, double alpha, const Mat1 &A, - const Vec2 &B, double beta, Vec3 &C) - { - blas_int m = A.getRows(), n = A.getCols(); - if (*transa == 'T') - { - assert(C.getSize() == A.getCols()); - assert(B.getSize() == A.getRows()); - } - else - { - assert(C.getSize() == A.getRows()); - assert(B.getSize() == A.getCols()); - } - blas_int lda = A.getLd(), ldb = B.getStride(), ldc = C.getStride(); - dgemv(transa, &m, &n, &alpha, A.getData(), &lda, - B.getData(), &ldb, &beta, C.getData(), &ldc); - } - - //! Symmetric matrix * vector multiplication - // c = alpha*A*b + beta*c, - // where alpha and beta are scalars, b and c are vectors and A is a - // m by m symmetric matrix. - template - inline void - symv(const char *uplo, double alpha, const Mat1 &A, - const Vec2 &B, double beta, Vec3 &C) - { - assert(A.getRows() == A.getCols()); - blas_int n = A.getRows(); - assert(A.getRows() == B.getSize()); - assert(A.getRows() == C.getSize()); - blas_int lda = A.getLd(), ldb = B.getStride(), ldc = C.getStride(); - dsymv(uplo, &n, &alpha, A.getData(), &lda, - B.getData(), &ldb, &beta, C.getData(), &ldc); - } - - /* Level 3 */ - - //! General matrix multiplication - template - inline void - gemm(const char *transa, const char *transb, - double alpha, const Mat1 &A, const Mat2 &B, - double beta, Mat3 &C) - { - blas_int m = A.getRows(), n = B.getCols(), k = A.getCols(); - if (*transa == 'N') - { - if (*transb == 'N') - { - assert(A.getRows() == C.getRows()); - assert(A.getCols() == B.getRows()); - assert(B.getCols() == C.getCols()); - } - else if (*transb == 'T') - { - assert(A.getRows() == C.getRows()); - assert(A.getCols() == B.getCols()); - assert(B.getRows() == C.getCols()); - n = B.getRows(); - } - } - else if (*transa == 'T') - { - m = A.getCols(); - k = A.getRows(); - if (*transb == 'N') - { - assert(A.getCols() == C.getRows()); - assert(A.getRows() == B.getRows()); - assert(B.getCols() == C.getCols()); - } - else if (*transb == 'T') - { - assert(A.getCols() == C.getRows()); - assert(A.getRows() == B.getCols()); - assert(B.getRows() == C.getCols()); - n = B.getRows(); - } - } - blas_int lda = A.getLd(), ldb = B.getLd(), ldc = C.getLd(); - dgemm(transa, transb, &m, &n, &k, &alpha, A.getData(), &lda, - B.getData(), &ldb, &beta, C.getData(), &ldc); - } - - //! Symmetric matrix A * (poss. rectangular) matrix B multiplication - template - inline void - symm(const char *side, const char *uplo, - double alpha, const Mat1 &A, const Mat2 &B, - double beta, Mat3 &C) - { - assert(A.getRows() == A.getCols()); - assert(B.getRows() == C.getRows()); - assert(B.getCols() == C.getCols()); - if (*side == 'L' || *side == 'l') - assert(A.getCols() == B.getRows()); - else if (*side == 'R' || *side == 'r') - assert(A.getRows() == B.getCols()); - - blas_int m = B.getRows(), n = B.getCols(); - blas_int lda = A.getLd(), ldb = B.getLd(), ldc = C.getLd(); - dsymm(side, uplo, &m, &n, &alpha, A.getData(), &lda, - B.getData(), &ldb, &beta, C.getData(), &ldc); - } - -} // End of namespace - -#endif diff --git a/mex/sources/estimation/libmat/DiscLyapFast.hh b/mex/sources/estimation/libmat/DiscLyapFast.hh deleted file mode 100644 index b85d73728..000000000 --- a/mex/sources/estimation/libmat/DiscLyapFast.hh +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/**************************************************************** - % a wrapper class for function X=disclyap_fast(G,V,ch) - % - % Solve the discrete Lyapunov Equation - % X=G*X*G'+V - % Using the Doubling Algorithm - % - % If ch is defined then the code will check if the resulting X - % is positive definite and generate an error message if it is not - % - % based on work of Joe Pearlman and Alejandro Justiniano - % 3/5/2005 - % C++ version 28/07/09 by Dynare team -****************************************************************/ - -#if !defined(DiscLyapFast_INCLUDE) -#define DiscLyapFast_INCLUDE - -#include "dynlapack.h" -#include "Matrix.hh" -#include "BlasBindings.hh" - -class DiscLyapFast -{ - Matrix A0, A1, Ptmp, P0, P1, I; - -public: - class DLPException - { - public: - const int info; - std::string message; - DLPException(int info_arg, std::string message_arg) : - info(info_arg), message(message_arg) - { - }; - }; - - DiscLyapFast(size_t n) : - A0(n), A1(n), Ptmp(n), P0(n), P1(n), I(n) - { - mat::set_identity(I); - }; - virtual ~DiscLyapFast() - { - }; - template - void solve_lyap(const MatG &G, const MatV &V, MatX &X, double tol = 1e-16, size_t flag_ch = 0) throw (DLPException); - -}; - -template -void -DiscLyapFast::solve_lyap(const MatG &G, const MatV &V, MatX &X, double tol, size_t flag_ch) throw (DLPException) -{ - P0 = V; - P1 = V; - A0 = G; - - const double alpha = 1.0; - const double half = 0.5; - const double omega = 0.0; - - bool matd = true; - while (matd) // matrix diff > tol - { - //P1=P0+A0*P0*A0'; - // first step Ptmp=P0*A0'; - // DGEMM: C := alpha*op( A )*op( B ) + beta*C, - blas::gemm("N", "T", alpha, P0, A0, omega, Ptmp); - // P1=P0+A0*Ptmp; - blas::gemm("N", "N", alpha, A0, Ptmp, alpha, P1); - // A1=A0*A0; - blas::gemm("N", "N", alpha, A0, A0, omega, A1); - - // ensure symmetry of P1=(P1+P1')/2; - Ptmp = P1; - blas::gemm("T", "N", half, Ptmp, I, half, P1); - - // check if max( max( abs( P1 - P0 ) ) )>tol - matd = mat::isDiffSym(P1, P0, tol); - P0 = P1; - A0 = A1; - } //end while - - // ensure symmetry of X=P0=(P0+P0')/2; - blas::gemm("T", "N", half, P1, I, half, P0); - X = P0; - - // Check that X is positive definite - if (flag_ch == 1) // calc NormCholesky (P0) - { - lapack_int lpinfo = 0; - lapack_int lrows = P0.getRows(); - lapack_int ldl = P0.getLd(); - dpotrf("L", &lrows, P0.getData(), &ldl, &lpinfo); - if (lpinfo < 0) - throw DLPException((int) lpinfo, std::string("DiscLyapFast:Internal error in NormCholesky calculator")); - else if (lpinfo > 0) - throw DLPException((int) lpinfo, std::string("DiscLyapFast:The matrix is not positive definite in NormCholesky calculator")); - - } -} - -#endif //if !defined(DiscLyapFast_INCLUDE) diff --git a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc deleted file mode 100644 index 47fc2816e..000000000 --- a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include "GeneralizedSchurDecomposition.hh" - -#include -#include - -double GeneralizedSchurDecomposition::criterium_static; - -GeneralizedSchurDecomposition::GeneralizedSchurDecomposition(size_t n_arg, double criterium_arg) : - n(n_arg), criterium(criterium_arg) -{ - alphar = new double[n]; - alphai = new double[n]; - beta = new double[n]; - - lwork = 16*n+16; // Same heuristic choice than mjdgges - work = new double[(int) lwork]; - vsl = new double[n*n]; - - bwork = new lapack_int[n]; -} - -GeneralizedSchurDecomposition::~GeneralizedSchurDecomposition() -{ - delete[] alphar; - delete[] alphai; - delete[] beta; - delete[] work; - delete[] vsl; - delete[] bwork; -} - -lapack_int -GeneralizedSchurDecomposition::selctg(const double *alphar, const double *alphai, const double *beta) -{ - return ((*alphar **alphar + *alphai **alphai) < criterium_static **beta **beta); -} - -std::ostream & -operator<<(std::ostream &out, const GeneralizedSchurDecomposition::GSDException &e) -{ - out << "DGGES return code " << e.info << ": "; - if (e.info < 0) - out << "argument " << -e.info << " has an illegal value"; - else if (e.info <= e.n) - out << "the QZ iteration failed"; - else if (e.info == e.n + 1) - out << "other than QZ iteration failed in DHGEQZ"; - else if (e.info == e.n + 2) - out << "after reordering, roundoff changed values of some complex eigenvalues so that leading eigenvalues in the Generalized Schur form no longer satisfy SELCTG=TRUE. This could also be caused due to scaling"; - else if (e.info == e.n + 3) - out << "reordering failed in DTGSEN"; - return out; -} diff --git a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh deleted file mode 100644 index e6d939604..000000000 --- a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include - -#include "Vector.hh" -#include "Matrix.hh" - -class GeneralizedSchurDecomposition -{ -private: - const size_t n; - const double criterium; - lapack_int lwork; - double *alphar, *alphai, *beta, *vsl, *work; - lapack_int *bwork; - static double criterium_static; - static lapack_int selctg(const double *alphar, const double *alphai, const double *beta); -public: - class GSDException - { - public: - const lapack_int info, n; - GSDException(lapack_int info_arg, lapack_int n_arg) : info(info_arg), n(n_arg) - { - }; - }; - //! \todo Replace heuristic choice for workspace size by a query to determine the optimal size - GeneralizedSchurDecomposition(size_t n_arg, double criterium_arg); - virtual - ~GeneralizedSchurDecomposition(); - //! \todo Add a lock around the modification of criterium_static for making it thread-safe - template - void compute(Mat1 &S, Mat2 &T, Mat3 &Z, size_t &sdim) throw (GSDException); - template - /*! - \param[out] sdim Number of non-explosive generalized eigenvalues - */ - void compute(const Mat1 &D, const Mat2 &E, Mat3 &S, Mat4 &T, Mat5 &Z, size_t &sdim) throw (GSDException); - template - void getGeneralizedEigenvalues(Vec1 &eig_real, Vec2 &eig_cmplx); -}; - -std::ostream &operator<<(std::ostream &out, const GeneralizedSchurDecomposition::GSDException &e); - -template -void -GeneralizedSchurDecomposition::compute(Mat1 &S, Mat2 &T, Mat3 &Z, size_t &sdim) throw (GSDException) -{ - assert(S.getRows() == n && S.getCols() == n - && T.getRows() == n && T.getCols() == n - && Z.getRows() == n && Z.getCols() == n); - - lapack_int n2 = n; - lapack_int info, sdim2; - lapack_int lds = S.getLd(), ldt = T.getLd(), ldz = Z.getLd(); - - criterium_static = criterium; - // Here we are forced to give space for left Schur vectors, even if we don't use them, because of a bug in dgges() - dgges("N", "V", "S", &selctg, &n2, S.getData(), &lds, T.getData(), &ldt, - &sdim2, alphar, alphai, beta, vsl, &n2, Z.getData(), &ldz, - work, &lwork, bwork, &info); - - if (info != 0) - throw GSDException(info, n2); - - sdim = sdim2; -} - -template -void -GeneralizedSchurDecomposition::compute(const Mat1 &D, const Mat2 &E, - Mat3 &S, Mat4 &T, Mat5 &Z, size_t &sdim) throw (GSDException) -{ - assert(D.getRows() == n && D.getCols() == n - && E.getRows() == n && E.getCols() == n); - S = D; - T = E; - compute(S, T, Z, sdim); -} - -template -void -GeneralizedSchurDecomposition::getGeneralizedEigenvalues(Vec1 &eig_real, Vec2 &eig_cmplx) -{ - assert(eig_real.getSize() == n && eig_cmplx.getSize() == n); - - double *par = alphar, *pai = alphai, *pb = beta, - *per = eig_real.getData(), *pei = eig_cmplx.getData(); - while (par < alphar + n) - { - *per = *par / *pb; - if (*pai == 0.0 && *pb == 0.0) - *pei = 0.0; - else - *pei = *pai / *pb; - par++; - pai++; - pb++; - per += eig_real.getStride(); - pei += eig_cmplx.getStride(); - } -} diff --git a/mex/sources/estimation/libmat/LUSolver.cc b/mex/sources/estimation/libmat/LUSolver.cc deleted file mode 100644 index 30033f1eb..000000000 --- a/mex/sources/estimation/libmat/LUSolver.cc +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (C) 2010 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include "LUSolver.hh" - -LUSolver::LUSolver(size_t dim_arg) : dim(dim_arg) -{ - ipiv = new lapack_int[dim]; -} - -LUSolver::~LUSolver() -{ - delete[] ipiv; -} diff --git a/mex/sources/estimation/libmat/LUSolver.hh b/mex/sources/estimation/libmat/LUSolver.hh deleted file mode 100644 index 16ab45dad..000000000 --- a/mex/sources/estimation/libmat/LUSolver.hh +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include -#include - -#include - -class LUSolver -{ -private: - const size_t dim; - lapack_int *ipiv; -public: - class LUException - { - public: - const lapack_int info; - LUException(lapack_int info_arg) : info(info_arg) - { - }; - }; - LUSolver(size_t dim_arg); - virtual - ~LUSolver(); - /*! - Computes A^(-1)*B (possibly transposing A). - The output is stored in B. - The input matrix A is modified. - */ - template - void invMult(const char *trans, Mat1 &A, Mat2 &B) throw (LUException); -}; - -template -void -LUSolver::invMult(const char *trans, Mat1 &A, Mat2 &B) throw (LUException) -{ - assert(A.getRows() == dim && A.getCols() == dim); - assert(B.getRows() == dim); - lapack_int n = dim, lda = A.getLd(), info; - dgetrf(&n, &n, A.getData(), &lda, ipiv, &info); - - if (info != 0) - throw LUException(info); - - lapack_int nrhs = B.getCols(), ldb = B.getLd(); - dgetrs(trans, &n, &nrhs, A.getData(), &lda, ipiv, B.getData(), &ldb, &info); - assert(info == 0); -} diff --git a/mex/sources/estimation/libmat/LapackBindings.hh b/mex/sources/estimation/libmat/LapackBindings.hh deleted file mode 100644 index 2755cf0a1..000000000 --- a/mex/sources/estimation/libmat/LapackBindings.hh +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2010-2011 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 . - */ - -#ifndef _LAPACK_BINDINGS_HH -#define _LAPACK_BINDINGS_HH - -#include - -#include "Vector.hh" -#include "Matrix.hh" - -namespace lapack -{ - // calc Cholesky Decomposition (Mat A, char "U"pper/"L"ower) - template - inline int - choleskyDecomp(Mat &A, const char *UL) - { - assert(A.getCols() == A.getRows()); - lapack_int lpinfo = 0; - lapack_int lrows = A.getRows(); - lapack_int ldl = A.getLd(); - dpotrf(UL, &lrows, A.getData(), &ldl, &lpinfo); - int info = (int) lpinfo; - return info; - } - - // calc Cholesky Decomposition based solution X to A*X=B - // for A pos. def. and symmetric supplied as uppper/lower triangle - // packed in a vector if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j; - // solutino X is returned in B and if B_in=I then B_out=X=inv(A) - // A_out contains uupper or lower Cholesky decomposition - template - inline int - choleskySolver(VecA &A, MatB &B, const char *UL) - { - //assert(A.getCols() == A.getRows()); - lapack_int lpinfo = 0; - lapack_int size = B.getRows(); - lapack_int bcols = B.getCols(); - lapack_int ldl = B.getLd(); - dppsv(UL, &size, &bcols, A.getData(), B.getData(), &ldl, &lpinfo); - int info = (int) lpinfo; - return info; - } - -} // End of namespace - -#endif diff --git a/mex/sources/estimation/libmat/Makefile.am b/mex/sources/estimation/libmat/Makefile.am deleted file mode 100644 index b73cf569f..000000000 --- a/mex/sources/estimation/libmat/Makefile.am +++ /dev/null @@ -1,22 +0,0 @@ -if HAVE_BLAS -if HAVE_LAPACK -SUBDIRS = tests -endif -endif - -EXTRA_DIST = \ - Matrix.hh \ - Matrix.cc \ - Vector.hh \ - Vector.cc \ - BlasBindings.hh \ - DiscLyapFast.hh \ - GeneralizedSchurDecomposition.cc \ - GeneralizedSchurDecomposition.hh \ - LapackBindings.hh \ - LUSolver.cc \ - LUSolver.hh \ - QRDecomposition.cc \ - QRDecomposition.hh \ - VDVEigDecomposition.cc \ - VDVEigDecomposition.hh diff --git a/mex/sources/estimation/libmat/Matrix.cc b/mex/sources/estimation/libmat/Matrix.cc deleted file mode 100644 index 9e0dffe15..000000000 --- a/mex/sources/estimation/libmat/Matrix.cc +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2010-2011 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 . - */ - -#include "Matrix.hh" - -#include -#include - -Matrix::Matrix(size_t rows_arg, size_t cols_arg) : rows(rows_arg), cols(cols_arg) -{ - data = new double[rows*cols]; -} - -Matrix::Matrix(size_t size_arg) : rows(size_arg), cols(size_arg) -{ - data = new double[rows*cols]; -} - -Matrix::Matrix(const Matrix &arg) : rows(arg.rows), cols(arg.cols) -{ - data = new double[rows*cols]; - memcpy(data, arg.data, rows*cols*sizeof(double)); -} - -Matrix::~Matrix() -{ - delete[] data; -} - -Matrix & -Matrix::operator=(const Matrix &arg) -{ - assert(rows == arg.rows && cols == arg.cols); - memcpy(data, arg.data, rows*cols*sizeof(double)); - return *this; -} - -std::ostream & -operator<<(std::ostream &out, const Matrix &M) -{ - mat::print(out, M); - return out; -} - -MatrixView::MatrixView(double *data_arg, size_t rows_arg, size_t cols_arg, size_t ld_arg) : - data(data_arg), rows(rows_arg), cols(cols_arg), ld(ld_arg) -{ -} - -std::ostream & -operator<<(std::ostream &out, const MatrixView &M) -{ - mat::print(out, M); - return out; -} - -MatrixView & -MatrixView::operator=(const MatrixView &arg) -{ - assert(rows == arg.getRows() && cols == arg.getCols()); - for (size_t j = 0; j < cols; j++) - memcpy(data + j*ld, arg.getData() + j*arg.getLd(), rows*sizeof(double)); - return *this; -} - -MatrixConstView::MatrixConstView(const double *data_arg, size_t rows_arg, size_t cols_arg, size_t ld_arg) : - data(data_arg), rows(rows_arg), cols(cols_arg), ld(ld_arg) -{ -} - -std::ostream & -operator<<(std::ostream &out, const MatrixConstView &M) -{ - mat::print(out, M); - return out; -} diff --git a/mex/sources/estimation/libmat/Matrix.hh b/mex/sources/estimation/libmat/Matrix.hh deleted file mode 100644 index b17e5b3ce..000000000 --- a/mex/sources/estimation/libmat/Matrix.hh +++ /dev/null @@ -1,788 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#ifndef _MATRIX_HH -#define _MATRIX_HH - -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "Vector.hh" - -/* - This header defines three matrix classes, which implement a "matrix concept" - (much like the concepts of the Standard Template Library or of Boost - Library). The first class is a matrix owning the data space for its - elements, and the other two are matrix "views" of another matrix, i.e. a - contiguous submatrix. This design philosophy is close to the design of the - GNU Scientific Library, but here using the syntactic power of C++ class and - templates, while achieving very high efficiency. - - These classes can be used with various templated functions, including - wrappers around the BLAS primitives. - - The expressions required to be valid for a class M implementing the "matrix concept" are: - - M.getRows(): return number of rows - - M.getCols(): return number of columns - - M.getLd(): return the leading dimension (here the offset between two columns in the data space, since we are in column-major order) - - M.getData(): return the pointer to the data space - - M(i,j): get an element of the matrix - - The expressions required to be valid for a class M implementing the "mutable matrix concept" are (in addition to those of "matrix concept"): - - M = X: assignment operator - - M(i,j) = d: assign an element of the matrix - - M.setAll(d): set all the elements of the matrix -*/ - -//! A full matrix, implements the "mutable matrix concept" -/*! Owns the data space for the elements */ -class Matrix -{ -private: - //! Stored in column-major order, as in Fortran and MATLAB - double *data; - const size_t rows, cols; -public: - Matrix(size_t rows_arg, size_t cols_arg); - Matrix(size_t size_arg); - Matrix(const Matrix &arg); - virtual - ~Matrix(); - inline size_t - getRows() const - { - return rows; - } - inline size_t - getCols() const - { - return cols; - } - inline size_t - getLd() const - { - return rows; - } - inline double * - getData() - { - return data; - } - inline const double * - getData() const - { - return data; - } - inline void - setAll(double val) - { - std::fill_n(data, rows*cols, val); - } - inline double & - operator()(size_t i, size_t j) - { - return data[i+j*rows]; - } - inline const double & - operator()(size_t i, size_t j) const - { - return data[i+j*rows]; - } - //! Assignment operator, only works for matrices of same dimension - template - Matrix & - operator=(const Mat &arg) - { - assert(rows == arg.getRows() && cols == arg.getCols()); - for (size_t j = 0; j < cols; j++) - memcpy(data + j*rows, arg.getData() + j*arg.getLd(), rows*sizeof(double)); - return *this; - } - //! The copy assignment operator, which is not generated by the template assignment operator - /*! See C++ standard, §12.8.9, in the footnote */ - Matrix &operator=(const Matrix &arg); -}; - -//! A contiguous submatrix of another matrix, implements the "mutable matrix concept" -/*! Does not own the data space for the elements, so depends on another matrix */ -class MatrixView -{ -private: - double *const data; - const size_t rows, cols, ld; -public: - MatrixView(double *data_arg, size_t rows_arg, size_t cols_arg, size_t ld_arg); - template - MatrixView(Mat &arg, size_t row_offset, size_t col_offset, - size_t rows_arg, size_t cols_arg) : - data(arg.getData() + row_offset + col_offset*arg.getLd()), rows(rows_arg), cols(cols_arg), ld(arg.getLd()) - { - assert(row_offset < arg.getRows() - && row_offset + rows_arg <= arg.getRows() - && col_offset < arg.getCols() - && col_offset + cols_arg <= arg.getCols()); - } - virtual ~MatrixView() - { - }; - inline size_t - getRows() const - { - return rows; - } - inline size_t - getCols() const - { - return cols; - } - inline size_t - getLd() const - { - return ld; - } - inline double * - getData() - { - return data; - } - inline const double * - getData() const - { - return data; - } - inline void - setAll(double val) - { - for (double *p = data; p < data + cols*ld; p += ld) - std::fill_n(p, rows, val); - } - inline double & - operator()(size_t i, size_t j) - { - return data[i+j*ld]; - } - inline const double & - operator()(size_t i, size_t j) const - { - return data[i+j*ld]; - } - //! Assignment operator, only works for matrices of same dimension - template - MatrixView & - operator=(const Mat &arg) - { - assert(rows == arg.getRows() && cols == arg.getCols()); - for (size_t j = 0; j < cols; j++) - memcpy(data + j*ld, arg.getData() + j*arg.getLd(), rows*sizeof(double)); - return *this; - } - //! The copy assignment operator, which is not generated by the template assignment operator - /*! See C++ standard, §12.8.9, in the footnote */ - MatrixView &operator=(const MatrixView &arg); -}; - -//! Like MatrixView, but cannot be modified (implements the "matrix concept") -class MatrixConstView -{ -private: - const double *const data; - const size_t rows, cols, ld; -public: - MatrixConstView(const double *data_arg, size_t rows_arg, size_t cols_arg, size_t ld_arg); - template - MatrixConstView(const Mat &arg, size_t row_offset, size_t col_offset, - size_t rows_arg, size_t cols_arg) : - data(arg.getData() + row_offset + col_offset*arg.getLd()), rows(rows_arg), cols(cols_arg), ld(arg.getLd()) - { - assert(row_offset < arg.getRows() - && row_offset + rows_arg <= arg.getRows() - && col_offset < arg.getCols() - && col_offset + cols_arg <= arg.getCols()); - } - virtual ~MatrixConstView() - { - }; - inline size_t - getRows() const - { - return rows; - } - inline size_t - getCols() const - { - return cols; - } - inline size_t - getLd() const - { - return ld; - } - inline const double * - getData() const - { - return data; - } - inline const double & - operator()(size_t i, size_t j) const - { - return data[i+j*ld]; - } -}; - -std::ostream &operator<<(std::ostream &out, const Matrix &M); -std::ostream &operator<<(std::ostream &out, const MatrixView &M); -std::ostream &operator<<(std::ostream &out, const MatrixConstView &M); - -namespace mat -{ - //define nullVec (const vector(0)) for assign and order by vector - // It is used as a proxy for the ":" matlab operator: - // i.e. zero sized int vector, nullVec, is interpreted as if one supplied ":" - const std::vector nullVec(0); - - template - void - print(std::ostream &out, const Mat &M) - { - for (size_t i = 0; i < M.getRows(); i++) - { - for (size_t j = 0; j < M.getCols(); j++) - out << std::setw(13) << std::right << M(i, j) << " "; - out << std::endl; - } - } - - template - inline VectorView - get_col(Mat &M, size_t j) - { - return VectorView(M.getData()+j*M.getLd(), M.getRows(), 1); - } - - template - inline VectorView - get_row(Mat &M, size_t i) - { - return VectorView(M.getData()+i, M.getCols(), M.getLd()); - } - - template - inline VectorConstView - get_col(const Mat &M, size_t j) - { - return VectorConstView(M.getData()+j*M.getLd(), M.getRows(), 1); - } - - template - inline VectorConstView - get_row(const Mat &M, size_t i) - { - return VectorConstView(M.getData()+i, M.getCols(), M.getLd()); - } - - template - inline void - col_copy(const Mat1 &src, size_t col_src, Mat2 &dest, size_t col_dest) - { - assert(src.getRows() == dest.getRows() - && col_src < src.getCols() && col_dest < dest.getCols()); - memcpy(dest.getData() + col_dest*dest.getLd(), - const_cast(src.getData()) + col_src*src.getLd(), - src.getRows()*sizeof(double)); - } - - template - inline void - col_copy(const Mat1 &src, size_t col_src, size_t row_offset_src, size_t row_nb, - Mat2 &dest, size_t col_dest, size_t row_offset_dest) - { - assert(col_src < src.getCols() && col_dest < dest.getCols() - && row_offset_src < src.getRows() && row_offset_src+row_nb <= src.getRows() - && row_offset_dest < dest.getRows() && row_offset_dest+row_nb <= dest.getRows()); - memcpy(dest.getData() + row_offset_dest + col_dest*dest.getLd(), - src.getData() + row_offset_src + col_src*src.getLd(), - row_nb*sizeof(double)); - } - - template - inline void - row_copy(const Mat1 &src, size_t row_src, Mat2 &dest, size_t row_dest) - { - assert(src.getCols() == dest.getCols() - && row_src < src.getRows() && row_dest < dest.getRows()); - const double *p1 = src.getData() + row_src; - double *p2 = dest.getData() + row_dest; - while (p1 < src.getData() + src.getCols() * src.getLd()) - { - *p2 = *p1; - p1 += src.getLd(); - p2 += dest.getLd(); - } - } - - template - inline void - col_set(Mat &M, size_t col, size_t row_offset, size_t row_nb, double val) - { - assert(col < M.getCols()); - assert(row_offset < M.getRows() && row_offset + row_nb <= M.getRows()); - std::fill_n(M.getData() + M.getLd()*col + row_offset, row_nb, val); - } - - //! Copy under the diagonal the elements above the diagonal - template - inline void - copy_upper_to_lower(Mat &M) - { - size_t d = std::min(M.getCols(), M.getRows()); - for (size_t i = 0; i < d; i++) - for (size_t j = 0; j < i; j++) - M(i, j) = M(j, i); - } - - //! Copy above the diagonal the elements under the diagonal - template - inline void - copy_lower_to_upper(Mat &M) - { - size_t d = std::min(M.getCols(), M.getRows()); - for (size_t i = 0; i < d; i++) - for (size_t j = 0; j < i; j++) - M(j, i) = M(i, j); - } - - //! Fill the matrix with the identity matrix - template - inline void - set_identity(Mat &M) - { - M.setAll(0.0); - size_t d = std::min(M.getCols(), M.getRows()); - for (size_t i = 0; i < d; i++) - M(i, i) = 1.0; - } - - //! In-place transpose of a square matrix - template - inline void - transpose(Mat &M) - { - assert(M.getRows() == M.getCols()); - for (size_t i = 0; i < M.getRows(); i++) - for (size_t j = 0; j < i; j++) - std::swap(M(i, j), M(j, i)); - } - - //! Computes M1 = M2' (even for rectangular matrices) - template - inline void - transpose(Mat1 &M1, const Mat2 &M2) - { - assert(M1.getRows() == M2.getCols() && M1.getCols() == M2.getRows()); - for (size_t i = 0; i < M1.getRows(); i++) - for (size_t j = 0; j < M1.getCols(); j++) - M1(i, j) = M2(j, i); - } - - //! Computes m1 = m1 + m2 - template - void - add(Mat1 &m1, const Mat2 &m2) - { - assert(m1.getRows() == m2.getRows() && m1.getCols() == m2.getCols()); - double *p1 = m1.getData(); - const double *p2 = m2.getData(); - while (p1 < m1.getData() + m1.getCols() * m1.getLd()) - { - double *pp1 = p1; - const double *pp2 = p2; - while (pp1 < p1 + m1.getRows()) - *pp1++ += *pp2++; - - p1 += m1.getLd(); - p2 += m2.getLd(); - } - } - - //! Computes m1 = m1 + number - template - void - add(Mat1 &m1, double d) - { - double *p1 = m1.getData(); - - while (p1 < m1.getData() + m1.getCols() * m1.getLd()) - { - double *pp1 = p1; - while (pp1 < p1 + m1.getRows()) - *pp1++ += d; - - p1 += m1.getLd(); - } - } - - //! Computes m1 = m1 - m2 - template - void - sub(Mat1 &m1, const Mat2 &m2) - { - assert(m1.getRows() == m2.getRows() && m1.getCols() == m2.getCols()); - double *p1 = m1.getData(); - const double *p2 = m2.getData(); - while (p1 < m1.getData() + m1.getCols() * m1.getLd()) - { - double *pp1 = p1; - const double *pp2 = p2; - while (pp1 < p1 + m1.getRows()) - *pp1++ -= *pp2++; - - p1 += m1.getLd(); - p2 += m2.getLd(); - } - } - - //! Computes m1 = m1 - number - template - void - sub(Mat1 &m1, double d) - { - add(m1, -1.0*d); - } - - //! Does m = -m - template - void - negate(Mat &m) - { - double *p = m.getData(); - while (p < m.getData() + m.getCols() * m.getLd()) - { - double *pp = p; - while (pp < p + m.getRows()) - { - *pp = -*pp; - pp++; - } - - p += m.getLd(); - } - } - - // Computes the infinite norm of a matrix - template - double - nrminf(const Mat &m) - { - double nrm = 0; - const double *p = m.getData(); - while (p < m.getData() + m.getCols() * m.getLd()) - { - const double *pp = p; - while (pp < p + m.getRows()) - { - if (fabs(*pp) > nrm) - nrm = fabs(*pp); - pp++; - } - - p += m.getLd(); - } - return nrm; - } - - // emulates Matlab command A(:,b)=B(:,d) where b,d are size_t vectors or nullVec as a proxy for ":") - // i.e. zero sized vector (or mat::nullVec) is interpreted as if one supplied ":" in matlab - template - void - reorderColumnsByVectors(Mat1 &a, const std::vector &vToCols, - const Mat2 &b, const std::vector &vcols) - { - size_t ncols = 0, toncols = 0; - const std::vector *vpToCols = 0, *vpCols = 0; - std::vector tmpvpToCols(0), tmpvpCols(0); - assert(b.getRows() == a.getRows()); - - if (vToCols.size() == 0 && vcols.size() == 0) - a = b; - else - { - if (vToCols.size() == 0) - { - toncols = a.getCols(); - tmpvpToCols.reserve(toncols); - for (size_t i = 0; i < toncols; ++i) - tmpvpToCols[i] = i; - vpToCols = (const std::vector *)&tmpvpToCols; - } - else - { - for (size_t i = 0; i < vToCols.size(); ++i) - { - assert(vToCols[i] < a.getCols()); //Negative or too large indices - toncols++; - } - assert(toncols <= a.getCols()); // check wrong dimensions for assignment by vector - vpToCols = &vToCols; - } - - if (vcols.size() == 0) - { - ncols = b.getCols(); - tmpvpCols.reserve(ncols); - for (size_t i = 0; i < ncols; ++i) - tmpvpCols[i] = i; - vpCols = (const std::vector *)&tmpvpCols; - } - else - { - for (size_t i = 0; i < vcols.size(); ++i) - { - assert(vcols[i] < b.getCols()); //Negative or too large indices - ncols++; - } - assert(ncols <= b.getCols()); // check wrong dimensions for assignment by vector - vpCols = &vcols; - } - - assert(toncols == ncols && ncols > 0); - for (size_t j = 0; j < ncols; ++j) - col_copy(b, (*vpCols)[j], a, (*vpToCols)[j]); - } - } - - // emulates Matlab command A(a,:)=B(c,:) where a,c are size_t vectors or nullVec as a proxy for ":") - // i.e. zero sized vector (or mat::nullVec) is interpreted as if one supplied ":" in matlab - template - void - reorderRowsByVectors(Mat1 &a, const std::vector &vToRows, - const Mat2 &b, const std::vector &vrows) - { - size_t nrows = 0, tonrows = 0; - const std::vector *vpToRows = 0, *vpRows = 0; - std::vector tmpvpToRows(0), tmpvpRows(0); - - //assert(b.getRows() >= a.getRows() && b.getCols() == a.getCols()); - assert(b.getCols() == a.getCols()); - if (vToRows.size() == 0 && vrows.size() == 0) - a = b; - else - { - if (vToRows.size() == 0) - { - tonrows = a.getRows(); - tmpvpToRows.reserve(tonrows); - for (size_t i = 0; i < tonrows; ++i) - tmpvpToRows[i] = i; - vpToRows = (const std::vector *)&tmpvpToRows; - } - else - { - for (size_t i = 0; i < vToRows.size(); ++i) - { - assert(vToRows[i] < a.getRows()); //Negative or too large indices - tonrows++; - } - assert(tonrows <= a.getRows()); // check wrong dimensions for assignment by vector - vpToRows = &vToRows; - } - - if (vrows.size() == 0) - { - nrows = b.getRows(); - tmpvpRows.reserve(nrows); - for (size_t i = 0; i < nrows; ++i) - tmpvpRows[i] = i; - vpRows = (const std::vector *)&tmpvpRows; - } - else - { - for (size_t i = 0; i < vrows.size(); ++i) - { - assert(vrows[i] < b.getRows()); //Negative or too large indices - nrows++; - } - assert(nrows <= b.getRows()); // check wrong dimensions for assignment by vector - vpRows = &vrows; - } - - assert(tonrows == nrows && nrows > 0); - for (size_t i = 0; i < nrows; ++i) - row_copy(b, (*vpRows)[i], a, (*vpToRows)[i]); - } - } - - // emulates Matlab command A(a,b)=B(c,d) where a,b,c,d are size_t vectors or nullVec as a proxy for ":") - // i.e. zero sized vector (or mat::nullVec) is interpreted as if one supplied ":" in matlab - template - void - assignByVectors(Mat1 &a, const std::vector &vToRows, const std::vector &vToCols, - const Mat2 &b, const std::vector &vrows, const std::vector &vcols) - { - size_t nrows = 0, ncols = 0, tonrows = 0, toncols = 0; - const std::vector *vpToCols = 0, *vpToRows = 0, *vpRows = 0, *vpCols = 0; - std::vector tmpvpToCols(0), tmpvpToRows(0), tmpvpRows(0), tmpvpCols(0); - - if (vToRows.size() == 0 && vToCols.size() == 0 && vrows.size() == 0 && vcols.size() == 0) - a = b; - else if (vToRows.size() == 0 && vrows.size() == 0) // just reorder columns - reorderColumnsByVectors(a, vToCols, b, vcols); - else if (vToCols.size() == 0 && vcols.size() == 0) // just reorder rows - reorderRowsByVectors(a, vToRows, b, vrows); - else - { - if (vToRows.size() == 0) - { - tonrows = a.getRows(); - tmpvpToRows.reserve(tonrows); - for (size_t i = 0; i < tonrows; ++i) - tmpvpToRows[i] = i; - vpToRows = (const std::vector *)&tmpvpToRows; - } - else - { - for (size_t i = 0; i < vToRows.size(); ++i) - { - assert(vToRows[i] < a.getRows()); //Negative or too large indices - tonrows++; - } - assert(tonrows <= a.getRows()); // check wrong dimensions for assignment by vector - vpToRows = &vToRows; - } - - if (vToCols.size() == 0) - { - toncols = a.getCols(); - tmpvpToCols.reserve(toncols); - for (size_t i = 0; i < toncols; ++i) - tmpvpToCols[i] = i; - vpToCols = (const std::vector *)&tmpvpToCols; - } - else - { - for (size_t i = 0; i < vToCols.size(); ++i) - { - assert(vToCols[i] < a.getCols()); //Negative or too large indices - toncols++; - } - assert(toncols <= a.getCols()); // check wrong dimensions for assignment by vector - vpToCols = &vToCols; - } - - if (vrows.size() == 0) - { - nrows = b.getRows(); - tmpvpRows.reserve(nrows); - for (size_t i = 0; i < nrows; ++i) - tmpvpRows[i] = i; - vpRows = (const std::vector *)&tmpvpRows; - } - else - { - for (size_t i = 0; i < vrows.size(); ++i) - { - assert(vrows[i] < b.getRows()); //Negative or too large indices - nrows++; - } - assert(nrows <= b.getRows()); // check wrong dimensions for assignment by vector - vpRows = &vrows; - } - - if (vcols.size() == 0) - { - ncols = b.getCols(); - tmpvpCols.reserve(ncols); - for (size_t i = 0; i < ncols; ++i) - tmpvpCols[i] = i; - vpCols = (const std::vector *)&tmpvpCols; - } - else - { - for (size_t i = 0; i < vcols.size(); ++i) - { - assert(vcols[i] < b.getCols()); //Negative or too large indices - ncols++; - } - assert(ncols <= b.getCols()); // check wrong dimensions for assignment by vector - vpCols = &vcols; - } - - assert(tonrows == nrows && toncols == ncols && nrows * ncols > 0); - for (size_t i = 0; i < nrows; ++i) - for (size_t j = 0; j < ncols; ++j) - a((*vpToRows)[i], (*vpToCols)[j]) = b((*vpRows)[i], (*vpCols)[j]); - } - } - - //emulates Matlab repmat: Mat2 = multv*multh tiled [Mat1] - template - void - repmat(Mat1 &a, size_t multv, size_t multh, Mat2 &repMat) // vertical and horisontal replicators - { - assert(repMat.getRows() == multv * a.getRows() && repMat.getCols() == multh * a.getCols()); - for (size_t i = 0; i < multv; ++i) - for (size_t j = 0; j < multh; ++j) - for (size_t k = 0; k < a.getCols(); ++k) - col_copy(a, k, 0, a.getRows(), repMat, a.getCols() * j + k, a.getRows() * i); - }; - - template - bool - isDiff(const Mat1 &m1, const Mat2 &m2, const double tol = 0.0) - { - assert(m2.getRows() == m1.getRows() && m2.getCols() == m1.getCols()); - const double *p1 = m1.getData(); - const double *p2 = m2.getData(); - while (p1 < m1.getData() + m1.getCols() * m1.getLd()) - { - const double *pp1 = p1; - const double *pp2 = p2; - while (pp1 < p1 + m1.getRows()) - if (fabs(*pp1++ - *pp2++) > tol) - return true; - - p1 += m1.getLd(); - p2 += m2.getLd(); - } - return false; - } - - //traverse the upper triangle only along diagonals where higher changes occur - template - bool - isDiffSym(const Mat1 &m1, const Mat2 &m2, const double tol = 0.0) - { - assert(m2.getRows() == m1.getRows() && m2.getCols() == m1.getCols() - && m2.getRows() == m1.getCols() && m2.getCols() == m1.getRows()); - for (size_t i = 0; i < m1.getCols(); i++) - for (size_t j = 0; i + j < m1.getCols(); j++) - if (fabs(m1(j, j + i) - m2(j, j + i)) > tol) - return true; - return false; - } - -} // End of namespace - -#endif diff --git a/mex/sources/estimation/libmat/QRDecomposition.cc b/mex/sources/estimation/libmat/QRDecomposition.cc deleted file mode 100644 index 38e3a5f57..000000000 --- a/mex/sources/estimation/libmat/QRDecomposition.cc +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2010 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include // For std::min - -#include "QRDecomposition.hh" - -QRDecomposition::QRDecomposition(size_t rows_arg, size_t cols_arg, size_t cols2_arg) : - rows(rows_arg), cols(cols_arg), mind(std::min(rows, cols)), cols2(cols2_arg), - lwork(rows*cols), lwork2(cols2) -{ - work = new double[lwork]; - work2 = new double[lwork2]; - - tau = new double[mind]; -} - -QRDecomposition::~QRDecomposition() -{ - delete[] work; - delete[] work2; - delete[] tau; -} diff --git a/mex/sources/estimation/libmat/QRDecomposition.hh b/mex/sources/estimation/libmat/QRDecomposition.hh deleted file mode 100644 index d77c2baaf..000000000 --- a/mex/sources/estimation/libmat/QRDecomposition.hh +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include // For std::min() - -#include - -#include "Vector.hh" -#include "Matrix.hh" -#include "BlasBindings.hh" - -class QRDecomposition -{ -private: - const size_t rows, cols, mind; - //! Number of columns of the matrix to be left-multiplied by Q - const size_t cols2; - lapack_int lwork, lwork2; - double *work, *work2, *tau; -public: - /*! - \todo Replace heuristic choice for workspace size by a query to determine the optimal size - \param[in] rows_arg Number of rows of the matrix to decompose - \param[in] cols_arg Number of columns of the matrix to decompose - \param[in] cols2_arg Number of columns of the matrix to be multiplied by Q - */ - QRDecomposition(size_t rows_arg, size_t cols_arg, size_t cols2_arg); - virtual - ~QRDecomposition(); - //! Performs the QR decomposition of a matrix, and left-multiplies another matrix by Q - /*! - \param[in,out] A On input, the matrix to be decomposed. On output, equals to the output of dgeqrf - \param[in] trans Specifies whether Q should be transposed before the multiplication, either "T" or "N" - \param[in,out] C The matrix to be left-multiplied by Q, modified in place - */ - template - void computeAndLeftMultByQ(Mat1 &A, const char *trans, Mat2 &C); -}; - -template -void -QRDecomposition::computeAndLeftMultByQ(Mat1 &A, const char *trans, Mat2 &C) -{ - assert(A.getRows() == rows && A.getCols() == cols); - assert(C.getRows() == rows && C.getCols() == cols2); - - lapack_int m = rows, n = cols, lda = A.getLd(); - lapack_int info; - dgeqrf(&m, &n, A.getData(), &lda, tau, work, &lwork, &info); - assert(info == 0); - - n = cols2; - lapack_int k = mind, ldc = C.getLd(); - dormqr("L", trans, &m, &n, &k, A.getData(), &lda, tau, C.getData(), &ldc, - work2, &lwork2, &info); - assert(info == 0); -} diff --git a/mex/sources/estimation/libmat/VDVEigDecomposition.cc b/mex/sources/estimation/libmat/VDVEigDecomposition.cc deleted file mode 100644 index 7e32bb094..000000000 --- a/mex/sources/estimation/libmat/VDVEigDecomposition.cc +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2010-2011 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 . - */ - -#include "VDVEigDecomposition.hh" - -VDVEigDecomposition::VDVEigDecomposition(const Matrix &m) throw (VDVEigException) : - lda(m.getLd()), n(m.getCols()), lwork(-1), - info(0), converged(false), V(m), D(n) -{ - if (m.getRows() != m.getCols()) - throw (VDVEigException(info, "Matrix is not square in VDVEigDecomposition constructor")); - - double tmpwork; - dsyev("V", "U", &n, V.getData(), &lda, D.getData(), &tmpwork, &lwork, &info); - lwork = (lapack_int) tmpwork; - work = new double[lwork]; - if (info < 0) - throw (VDVEigException(info, "Internal error in VDVEigDecomposition constructor")); -} - -VDVEigDecomposition::VDVEigDecomposition(size_t inn) throw (VDVEigException) : - lda(inn), n(inn), lwork(3*inn-1), - info(0), converged(false), V(inn), D(inn) -{ - work = new double[lwork]; -}; - -std::ostream & -operator<<(std::ostream &out, const VDVEigDecomposition::VDVEigException &e) -{ - out << " info " << e.info << ": " << e.message << "\n"; - return out; -} diff --git a/mex/sources/estimation/libmat/VDVEigDecomposition.hh b/mex/sources/estimation/libmat/VDVEigDecomposition.hh deleted file mode 100644 index d71748530..000000000 --- a/mex/sources/estimation/libmat/VDVEigDecomposition.hh +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (C) 2010-2011 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 . - */ - -/** - * Calculates vector of Eigen values D and matrix of Eigen vectors V - * of input matrix m - */ - -#if !defined(VDVEigDec_INCLUDE) -#define VDVEigDec_INCLUDE - -#include -#include "Vector.hh" -#include "Matrix.hh" -#include - -class VDVEigDecomposition -{ - lapack_int lda, n; - lapack_int lwork, info; - double *work; - bool converged; - Matrix V; - Vector D; -public: - -public: - class VDVEigException - { - public: - const lapack_int info; - std::string message; - VDVEigException(lapack_int info_arg, std::string message_arg) : - info(info_arg), message(message_arg) - { - }; - }; - - /** - * This constructor only creates optimal workspace using - * input matrix m - */ - VDVEigDecomposition(const Matrix &m) throw (VDVEigException); - - /** - * This constructoro only crates workspace using the size of - * the input matrix m - */ - VDVEigDecomposition(size_t n) throw (VDVEigException); - - virtual ~VDVEigDecomposition() - { - delete[] work; - }; - template - void calculate(const Mat &H) throw (VDVEigException); - // get eigenvalues - Vector & - getD() - { - return D; - }; - // get eigen vector - Matrix & - getV() - { - return V; - }; - // check if converged - bool - hasConverged() - { - return converged; - }; -}; - -template -void -VDVEigDecomposition::calculate(const Mat &m) throw (VDVEigException) -{ - info = 0; - if (m.getRows() != m.getCols()) - throw (VDVEigException(info, "Matrix is not square in VDVEigDecomposition calculate")); - - if (m.getCols() != (size_t) n || m.getLd() != (size_t) lda) - throw (VDVEigException(info, "Matrix not matching VDVEigDecomposition class")); - - double tmpwork; - lapack_int tmplwork = -1; - V = m; - dsyev("V", "U", &n, V.getData(), &lda, D.getData(), &tmpwork, &tmplwork, &info); - if (lwork < (lapack_int) tmpwork) - { - lwork = (lapack_int) tmpwork; - delete[] work; - work = new double[lwork]; - } - dsyev("V", "U", &n, V.getData(), &lda, D.getData(), work, &lwork, &info); - - if (info < 0) - throw (VDVEigException(info, "Internal error in VDVEigDecomposition calculation")); - converged = true; - if (info) - converged = false; -} - -std::ostream &operator<<(std::ostream &out, const VDVEigDecomposition::VDVEigException &e); - -#endif diff --git a/mex/sources/estimation/libmat/Vector.cc b/mex/sources/estimation/libmat/Vector.cc deleted file mode 100644 index 3d1603998..000000000 --- a/mex/sources/estimation/libmat/Vector.cc +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (C) 2010-2011 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 . - */ - -#include "Vector.hh" - -#include -#include - -Vector::Vector(size_t size_arg) : size(size_arg) -{ - data = new double[size]; -} - -Vector::Vector(const Vector &arg) : size(arg.size) -{ - data = new double[size]; - memcpy(data, arg.data, size*sizeof(double)); -} - -Vector::~Vector() -{ - delete[] data; -} - -Vector & -Vector::operator=(const Vector &arg) -{ - assert(size == arg.size); - memcpy(data, arg.data, size*sizeof(double)); - return *this; -} - -std::ostream & -operator<<(std::ostream &out, const Vector &V) -{ - vec::print(out, V); - return out; -} - -VectorView::VectorView(double *data_arg, size_t size_arg, size_t stride_arg) : - data(data_arg), size(size_arg), stride(stride_arg) -{ -} - -VectorView::VectorView(Vector &arg, size_t offset, size_t size_arg) : - data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) -{ - assert(offset < arg.getSize() && offset + size <= arg.getSize()); -} - -VectorView::VectorView(VectorView &arg, size_t offset, size_t size_arg) : - data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) -{ - assert(offset < arg.getSize() && offset + size <= arg.getSize()); -} - -VectorView & -VectorView::operator=(const VectorView &arg) -{ - assert(size == arg.getSize()); - double *p1; - const double *p2; - for (p1 = data, p2 = arg.getData(); p1 < data + size*stride; p1 += stride, p2 += arg.getStride()) - *p1 = *p2; - return *this; -} - -VectorConstView::VectorConstView(const double *data_arg, size_t size_arg, size_t stride_arg) : - data(data_arg), size(size_arg), stride(stride_arg) -{ -} - -VectorConstView::VectorConstView(const Vector &arg, size_t offset, size_t size_arg) : - data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) -{ - assert(offset < arg.getSize() && offset + size <= arg.getSize()); -} - -VectorConstView::VectorConstView(const VectorView &arg, size_t offset, size_t size_arg) : - data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) -{ - assert(offset < arg.getSize() && offset + size <= arg.getSize()); -} - -VectorConstView::VectorConstView(const VectorConstView &arg, size_t offset, size_t size_arg) : - data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) -{ - assert(offset < arg.getSize() && offset + size <= arg.getSize()); -} - -std::ostream & -operator<<(std::ostream &out, const VectorView &V) -{ - vec::print(out, V); - return out; -} - -std::ostream & -operator<<(std::ostream &out, const VectorConstView &V) -{ - vec::print(out, V); - return out; -} diff --git a/mex/sources/estimation/libmat/Vector.hh b/mex/sources/estimation/libmat/Vector.hh deleted file mode 100644 index f4c71c404..000000000 --- a/mex/sources/estimation/libmat/Vector.hh +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#ifndef _VECTOR_HH -#define _VECTOR_HH - -#include -#include - -#include -#include -#include - -/* - This header defines three vector classes, which implement a "vector concept" - (much like the concepts of the Standard Template Library or of Boost - Library). The first class is a vector owning the data space for its elements, - and the other two are vector "views" of something else (either a subvector of - another vector, or a row or column of a matrix). This design philosophy is - close to the design of the GNU Scientific Library, but here using the - syntactic power of C++ class and templates, while achieving very high - efficiency. - - These classes can be used with various templated functions, including - wrappers around the BLAS primitives. - - The expressions required to be valid for a class V implementing the "vector concept" are: - - V.getSize(): return number of elements - - V.getStride(): return the stride, i.e. the offset between two elements in the data space - - V.getData(): return the pointer to the data space - - V(i): get an element of the vector - - The expressions required to be valid for a class V implementing the "mutable vector concept" are (in addition to those of "vector concept"): - - V = X: assignment operator - - V(i) = d: assign an element of the vector - - V.setAll(d): set all the elements of the vector - -*/ - -//! A full vector, implements the "mutable vector concept" -/*! Owns the data space for the elements */ -class Vector -{ -private: - double *data; - const size_t size; -public: - Vector(size_t size_arg); - Vector(const Vector &arg); - virtual - ~Vector(); - inline size_t - getSize() const - { - return size; - } - inline size_t - getStride() const - { - return 1; - } - inline double * - getData() - { - return data; - } - inline const double * - getData() const - { - return data; - } - inline void - setAll(double val) - { - std::fill_n(data, size, val); - } - inline double & - operator()(size_t i) - { - return data[i]; - } - inline const double & - operator()(size_t i) const - { - return data[i]; - } - //! Assignment operator, only works for vectors of same size - template - Vector & - operator=(const Vec &arg) - { - assert(size == arg.getSize()); - const double *p2 = arg.getData(); - for (double *p1 = data; p1 < data + size; p1++) - { - *p1 = *p2; - p2 += arg.getStride(); - } - return *this; - } - //! The copy assignment operator, which is not generated by the template assignment operator - /*! See C++ standard, §12.8.9, in the footnote */ - Vector &operator=(const Vector &arg); -}; - -//! A vector view (i.e. a subvector of another vector, or a row or column of a matrix), implements the "mutable vector concept" -/*! Does not own the data space for the elements, so depends on another vector or matrix */ -class VectorView -{ -private: - double *const data; - const size_t size, stride; -public: - VectorView(double *data_arg, size_t size_arg, size_t stride_arg); - /* Can't use a template for the 2 constructors below: this would override the - constructor which uses a pointer, because the argument list is the same */ - VectorView(Vector &arg, size_t offset, size_t size_arg); - VectorView(VectorView &arg, size_t offset, size_t size_arg); - virtual ~VectorView() - { - }; - inline size_t - getSize() const - { - return size; - } - inline size_t - getStride() const - { - return stride; - } - inline double * - getData() - { - return data; - } - inline const double * - getData() const - { - return data; - } - inline void - setAll(double val) - { - for (double *p = data; p < data + size*stride; p += stride) - *p = val; - } - inline double & - operator()(size_t i) - { - return data[i*stride]; - } - inline const double & - operator()(size_t i) const - { - return data[i*stride]; - } - //! Assignment operator, only works for vectors of same size - template - VectorView & - operator=(const Vec &arg) - { - assert(size == arg.getSize()); - double *p1; - const double *p2; - for (p1 = data, p2 = arg.getData(); p1 < data + size*stride; p1 += stride, p2 += arg.getStride()) - *p1 = *p2; - return *this; - } - //! The copy assignment operator, which is not generated by the template assignment operator - /*! See C++ standard, §12.8.9, in the footnote */ - VectorView &operator=(const VectorView &arg); -}; - -//! Like a VectorView, but the data cannot be modified (implements the "vector concept") -class VectorConstView -{ -private: - const double *const data; - const size_t size, stride; -public: - VectorConstView(const double *data_arg, size_t size_arg, size_t stride_arg); - /* Can't use a template for the 3 constructors below: this would override the - constructor which uses a pointer, because the argument list is the same */ - VectorConstView(const Vector &arg, size_t offset, size_t size_arg); - VectorConstView(const VectorView &arg, size_t offset, size_t size_arg); - VectorConstView(const VectorConstView &arg, size_t offset, size_t size_arg); - - virtual ~VectorConstView() - { - }; - inline size_t - getSize() const - { - return size; - } - inline size_t - getStride() const - { - return stride; - } - inline const double * - getData() const - { - return data; - } - inline const double & - operator()(size_t i) const - { - return data[i*stride]; - } -}; - -std::ostream &operator<<(std::ostream &out, const Vector &V); -std::ostream &operator<<(std::ostream &out, const VectorView &V); -std::ostream &operator<<(std::ostream &out, const VectorConstView &V); - -namespace vec -{ - template - void - print(std::ostream &out, const Vec &V) - { - for (size_t i = 0; i < V.getSize(); i++) - out << V(i) << " "; - out << std::endl; - } - - //! Computes v1 = v1 + v2 - template - void - add(Vec1 &v1, const Vec2 &v2) - { - assert(v1.getSize() == v2.getSize()); - double *p1 = v1.getData(); - const double *p2 = v2.getData(); - while (p1 < v1.getData() + v1.getSize() * v1.getStride()) - { - *p1 += *p2; - p1 += v1.getStride(); - p2 += v2.getStride(); - } - } - - //! Computes v1 = v1 - v2 - template - void - sub(Vec1 &v1, const Vec2 &v2) - { - assert(v1.getSize() == v2.getSize()); - double *p1 = v1.getData(); - const double *p2 = v2.getData(); - while (p1 < v1.getData() + v1.getSize() * v1.getStride()) - { - *p1 -= *p2; - p1 += v1.getStride(); - p2 += v2.getStride(); - } - } - - //! Does v = -v - template - void - negate(Vec &v) - { - double *p = v.getData(); - while (p < v.getData() + v.getSize() * v.getStride()) - { - *p = -*p; - p += v.getStride(); - } - } - - // Computes the infinite norm of a vector - template - double - nrminf(const Vec &v) - { - double nrm = 0; - const double *p = v.getData(); - while (p < v.getData() + v.getSize() * v.getStride()) - { - if (fabs(*p) > nrm) - nrm = fabs(*p); - p += v.getStride(); - } - return nrm; - } - - // Computes the sum, min and max of a vector - // and returns double mean=sum/size - template - double - meanSumMinMax(double &sum, double &min, double &max, const Vec &v) - { - sum = 0; - min = max = v(0); - const double *p = v.getData(); - while (p < v.getData() + v.getSize() * v.getStride()) - { - if ((*p) > max) - max = (*p); - if ((*p) < min) - min = (*p); - sum += *p; - p += v.getStride(); - } - return sum/v.getSize(); - } -} // End of namespace - -#endif diff --git a/mex/sources/estimation/libmat/tests/Makefile.am b/mex/sources/estimation/libmat/tests/Makefile.am deleted file mode 100644 index 7223fe01d..000000000 --- a/mex/sources/estimation/libmat/tests/Makefile.am +++ /dev/null @@ -1,22 +0,0 @@ -check_PROGRAMS = test-qr test-gsd test-lu test-repmat - -test_qr_SOURCES = ../Matrix.cc ../Vector.cc ../QRDecomposition.cc test-qr.cc -test_qr_LDADD = $(LAPACK_LIBS) $(BLAS_LIBS) $(LIBS) $(FLIBS) -test_qr_CPPFLAGS = -I.. -I../../../ - -test_gsd_SOURCES = ../Matrix.cc ../Vector.cc ../GeneralizedSchurDecomposition.cc test-gsd.cc -test_gsd_LDADD = $(LAPACK_LIBS) $(BLAS_LIBS) $(LIBS) $(FLIBS) -test_gsd_CPPFLAGS = -I.. -I../../../ - -test_lu_SOURCES = ../Matrix.cc ../Vector.cc ../LUSolver.cc test-lu.cc -test_lu_LDADD = $(LAPACK_LIBS) $(BLAS_LIBS) $(LIBS) $(FLIBS) -test_lu_CPPFLAGS = -I.. -I../../../ - -test_repmat_SOURCES = ../Matrix.cc ../Vector.cc test-repmat.cc -test_repmat_CPPFLAGS = -I.. - -check-local: - ./test-qr - ./test-gsd - ./test-lu - ./test-repmat diff --git a/mex/sources/estimation/libmat/tests/test-gsd.cc b/mex/sources/estimation/libmat/tests/test-gsd.cc deleted file mode 100644 index fd8dea7f6..000000000 --- a/mex/sources/estimation/libmat/tests/test-gsd.cc +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2010 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include - -#include "GeneralizedSchurDecomposition.hh" - -int -main(int argc, char **argv) -{ - size_t n = 3; - double D_data[] = { 1, 2, 3, - 4, 5, 6, - 7, 8, 9 }; - double E_data[] = { 1, -3, 4, - -7, 9, 1, - -3, 4, 0 }; - MatrixView D(D_data, n, n, n), E(E_data, n, n, n); - - // Need to transpose because internally matrices are in column-major order - mat::transpose(D); - mat::transpose(E); - - std::cout << "D =" << std::endl << D << std::endl; - std::cout << "E =" << std::endl << E << std::endl; - - GeneralizedSchurDecomposition GSD(n, 1.00001); - - Matrix S(n), T(n), Z(n); - size_t sdim; - - GSD.compute(D, E, S, T, Z, sdim); - - std::cout << "S =" << std::endl << S << std::endl; - std::cout << "T =" << std::endl << T << std::endl; - std::cout << "Z =" << std::endl << Z << std::endl; - - Vector eig_real(n), eig_cmplx(n); - GSD.getGeneralizedEigenvalues(eig_real, eig_cmplx); - - std::cout << "Real part of generalized eigenvalues: " << std::endl << eig_real << std::endl; - std::cout << "Complex part of generalized eigenvalues: " << std::endl << eig_cmplx << std::endl; - - return 0; -} diff --git a/mex/sources/estimation/libmat/tests/test-lu.cc b/mex/sources/estimation/libmat/tests/test-lu.cc deleted file mode 100644 index b41af33b3..000000000 --- a/mex/sources/estimation/libmat/tests/test-lu.cc +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2010 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include - -#include "BlasBindings.hh" -#include "LUSolver.hh" - -int -main(int argc, char **argv) -{ - size_t m = 4, n = 3; - - double A_data[] = { -1, 2, 3, - 4, -5, 6, - 7, 8, -9 }; - double B_data[] = { 1, -3, 4, 5, - -7, 9, 1, 7, - -3, 4, 0, -2 }; - MatrixView A(A_data, n, n, n), B_prime(B_data, m, n, m); - Matrix B(n, m); - - mat::transpose(A); - mat::transpose(B, B_prime); - - std::cout << "A =" << std::endl << A << std::endl - << "B =" << std::endl << B << std::endl; - - LUSolver LU(n); - - LU.invMult("N", A, B); - - std::cout << "A\\B =" << std::endl << B; - - // Check this is the right result - double C_data[] = { -1.0500, 1.3750, 0.0833, 0.6250, - 0.3000, -0.7500, 0.8333, 0.7500, - -0.2167, -0.0417, 0.8056, 1.3750 }; - MatrixView C_prime(C_data, m, n, m); - Matrix C(n, m); - mat::transpose(C, C_prime); - mat::sub(B, C); - assert(mat::nrminf(B) < 1e-4); -} diff --git a/mex/sources/estimation/libmat/tests/test-qr.cc b/mex/sources/estimation/libmat/tests/test-qr.cc deleted file mode 100644 index f73d85488..000000000 --- a/mex/sources/estimation/libmat/tests/test-qr.cc +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (C) 2010 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include - -#include "BlasBindings.hh" -#include "QRDecomposition.hh" - -int -main(int argc, char **argv) -{ - size_t m = 4, n = 3; - Matrix S(m, n), Q(m), A(m, n), B(m), S2(m, n); - QRDecomposition QRD(m, n, m); - - for (size_t i = 0; i < m; i++) - for (size_t j = 0; j < n; j++) - S(i, j) = i*n + j + 1; - - std::cout << "Matrix to be decomposed:" << std::endl << S << std::endl; - - mat::set_identity(Q); - - S2 = S; - QRD.computeAndLeftMultByQ(S2, "N", Q); - - std::cout << "Q =" << std::endl << Q << std::endl; - - blas::gemm("T", "N", 1.0, Q, Q, 0.0, B); - - std::cout << "Q'*Q =" << std::endl << B << std::endl; - - for (size_t j = 0; j < n; j++) - mat::col_set(S2, j, j+1, m-j-1, 0); - - std::cout << "R =" << std::endl << S2 << std::endl; - - blas::gemm("N", "N", 1.0, Q, S2, 0.0, A); - - std::cout << "Q*R =" << std::endl << A << std::endl; - - // Check values - Matrix B2(m); - mat::set_identity(B2); - mat::sub(B2, B); - assert(mat::nrminf(B2) < 1e-4); - - mat::sub(A, S); - assert(mat::nrminf(A) < 1e-4); -} diff --git a/mex/sources/estimation/libmat/tests/test-repmat.cc b/mex/sources/estimation/libmat/tests/test-repmat.cc deleted file mode 100644 index f8581eea3..000000000 --- a/mex/sources/estimation/libmat/tests/test-repmat.cc +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2010 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include -#include "Matrix.hh" - -int -main(int argc, char **argv) -{ - size_t m = 4, n = 3; - Matrix S(m, n), A(5*m, 3*n), A2(5*m, 3*n); - - for (size_t i = 0; i < m; i++) - for (size_t j = 0; j < n; j++) - S(i, j) = i*n + j + 1; - - std::cout << "Matrix to be tiled:" << std::endl << S << std::endl; - - Matrix S1(m, 2 *n), S2(2*m, n); - std::vector toC(n), toR(m); - for (size_t i = 0; i < n; i++) - toC[i] = 2*i; - - for (size_t j = 0; j < m; j++) - toR[j] = m-j-1; - - mat::assignByVectors(S1, mat::nullVec, toC, S, mat::nullVec, mat::nullVec); - std::cout << "Matrix assigned and col reorder by vectors:" << std::endl << S1 << std::endl; - - mat::assignByVectors(S2, toR, mat::nullVec, S, mat::nullVec, mat::nullVec); - std::cout << "Matrix assigned and row ereorder by vectors:" << std::endl << S2 << std::endl; - - mat::assignByVectors(S1, toR, toC, S, mat::nullVec, mat::nullVec); - std::cout << "Matrix assigned by vectors:" << std::endl << S1 << std::endl; - - mat::repmat(S, 5, 3, A); - std::cout << "Tiled=" << std::endl << A << std::endl; - - A2 = A; - bool b = mat::isDiff(A, A2, 0.0000001); - std::cout << "No Diff=" << b << std::endl; - mat::add(A, 0.000001); - b = mat::isDiff(A, A2, 0.0000001); - std::cout << "Yes Diff=" << b << std::endl; - Matrix A4(5), A5(5); - A4.setAll(1.0); - A5.setAll(1.0); - b = mat::isDiffSym(A4, A5, 0.0000001); - std::cout << "No DiffSym=" << b << std::endl; - mat::sub(A4, 0.0001); - b = mat::isDiffSym(A4, A5, 0.0000001); - std::cout << "Yes DiffSym=" << b << std::endl; - -} diff --git a/mex/sources/estimation/logMHMCMCposterior.cc b/mex/sources/estimation/logMHMCMCposterior.cc deleted file mode 100644 index 6551701d8..000000000 --- a/mex/sources/estimation/logMHMCMCposterior.cc +++ /dev/null @@ -1,809 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include -#include -#include -#include - -#include "Vector.hh" -#include "Matrix.hh" -#include "LogPosteriorDensity.hh" -#include "RandomWalkMetropolisHastings.hh" - -#include -#if defined MATLAB_MEX_FILE -# include "mat.h" -#else // OCTAVE_MEX_FILE e.t.c. -# include "matio.h" -#endif - -#if defined(_WIN32) || defined(__CYGWIN32__) || defined(WINDOWS) -# define DIRECTORY_SEPARATOR "\\" -#else -# define DIRECTORY_SEPARATOR "/" -#endif - -class LogMHMCMCposteriorMexErrMsgTxtException -{ -public: - std::string errMsg; - LogMHMCMCposteriorMexErrMsgTxtException(const std::string &msg) : errMsg(msg) - { - } - inline const char * - getErrMsg() - { - return errMsg.c_str(); - } -}; - -void -fillEstParamsInfo(const mxArray *estim_params_info, EstimatedParameter::pType type, - std::vector &estParamsInfo) -{ - const mxArray *bayestopt_ = mexGetVariablePtr("global", "bayestopt_"); - const mxArray *bayestopt_ubp = mxGetField(bayestopt_, 0, "ub"); // upper bound - const mxArray *bayestopt_lbp = mxGetField(bayestopt_, 0, "lb"); // lower bound - const mxArray *bayestopt_p1p = mxGetField(bayestopt_, 0, "p1"); // prior mean - const mxArray *bayestopt_p2p = mxGetField(bayestopt_, 0, "p2"); // prior standard deviation - const mxArray *bayestopt_p3p = mxGetField(bayestopt_, 0, "p3"); // lower bound - const mxArray *bayestopt_p4p = mxGetField(bayestopt_, 0, "p4"); // upper bound - const mxArray *bayestopt_p6p = mxGetField(bayestopt_, 0, "p6"); // first hyper-parameter (\alpha for the BETA and GAMMA distributions, s for the INVERSE GAMMAs, expectation for the GAUSSIAN distribution, lower bound for the UNIFORM distribution). - const mxArray *bayestopt_p7p = mxGetField(bayestopt_, 0, "p7"); // second hyper-parameter (\beta for the BETA and GAMMA distributions, \nu for the INVERSE GAMMAs, standard deviation for the GAUSSIAN distribution, upper bound for the UNIFORM distribution). - const mxArray *bayestopt_jscalep = mxGetField(bayestopt_, 0, "jscale"); // MCMC jump scale - - const size_t bayestopt_size = mxGetM(bayestopt_); - const VectorConstView bayestopt_ub(mxGetPr(bayestopt_ubp), bayestopt_size, 1); - const VectorConstView bayestopt_lb(mxGetPr(bayestopt_lbp), bayestopt_size, 1); - const VectorConstView bayestopt_p1(mxGetPr(bayestopt_p1p), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "p1"); - const VectorConstView bayestopt_p2(mxGetPr(bayestopt_p2p), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "p2"); - const VectorConstView bayestopt_p3(mxGetPr(bayestopt_p3p), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "p3"); - const VectorConstView bayestopt_p4(mxGetPr(bayestopt_p4p), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "p4"); - const VectorConstView bayestopt_p6(mxGetPr(bayestopt_p6p), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "p6"); - const VectorConstView bayestopt_p7(mxGetPr(bayestopt_p7p), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "p7"); - const VectorConstView bayestopt_jscale(mxGetPr(bayestopt_jscalep), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "jscale"); - - // loop processsing - size_t m = mxGetM(estim_params_info), n = mxGetN(estim_params_info); - MatrixConstView epi(mxGetPr(estim_params_info), m, n, m); - size_t bayestopt_count = estParamsInfo.size(); - - for (size_t i = 0; i < m; i++) - { - size_t col = 0; - size_t id1 = (size_t) epi(i, col++) - 1; - size_t id2 = 0; - if (type == EstimatedParameter::shock_Corr - || type == EstimatedParameter::measureErr_Corr) - id2 = (size_t) epi(i, col++) - 1; - col++; // Skip init_val #2 or #3 - double par_low_bound = bayestopt_lb(bayestopt_count); col++; //#3 epi(i, col++); - double par_up_bound = bayestopt_ub(bayestopt_count); col++; //#4 epi(i, col++); - Prior::pShape shape = (Prior::pShape) epi(i, col++); - double mean = epi(i, col++); - double std = epi(i, col++); - double low_bound = bayestopt_p3(bayestopt_count); - double up_bound = bayestopt_p4(bayestopt_count); - double fhp = bayestopt_p6(bayestopt_count); // double p3 = epi(i, col++); - double shp = bayestopt_p7(bayestopt_count); // double p4 = epi(i, col++); - - Prior *p = Prior::constructPrior(shape, mean, std, low_bound, up_bound, fhp, shp); //1.0,INFINITY);//p3, p4); - - // Only one subsample - std::vector subSampleIDs; - subSampleIDs.push_back(0); - estParamsInfo.push_back(EstimatedParameter(type, id1, id2, subSampleIDs, - par_low_bound, par_up_bound, p)); - bayestopt_count++; - } -} - -int -sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, - VectorView &steadyState, VectorConstView &estParams, VectorView &deepParams, const MatrixConstView &data, - MatrixView &Q, Matrix &H, size_t presampleStart, const VectorConstView &nruns, - size_t fblock, size_t nBlocks, Proposal pdd, EstimatedParametersDescription &epd, - const std::string &resultsFileStem, size_t console_mode, size_t load_mh_file) -{ - enum {iMin, iMax}; - int iret = 0; // return value - std::vector OpenOldFile(nBlocks, 0); - size_t jloop = 0, irun, j; // counters - double dsum, dmax, dmin, sux = 0, jsux = 0; - std::string mhFName; - std::stringstream ssFName; -#if defined MATLAB_MEX_FILE - MATFile *drawmat; // MCMC draws output file pointer - int matfStatus; -#else // OCTAVE_MEX_FILE e.t.c. -# if MATIO_MAJOR_VERSION > 1 || (MATIO_MAJOR_VERSION == 1 && MATIO_MINOR_VERSION >= 5) - size_t dims[2]; - const matio_compression compression = MAT_COMPRESSION_NONE; -# else - int dims[2]; - const int compression = COMPRESSION_NONE; -# endif - mat_t *drawmat; - matvar_t *matvar; - int matfStatus; -#endif - FILE *fidlog; // log file - size_t npar = estParams.getSize(); - Matrix MinMax(npar, 2); - - const mxArray *InitSizeArrayPtr = mexGetVariablePtr("caller", "InitSizeArray"); - if (InitSizeArrayPtr == NULL) - { - mexPrintf("Metropolis-Hastings myinputs field InitSizeArrayPtr Initialisation failed!\n"); - return (-1); - } - const VectorConstView InitSizeArrayVw(mxGetPr(InitSizeArrayPtr), nBlocks, 1); - Vector InitSizeArray(InitSizeArrayVw.getSize()); - InitSizeArray = InitSizeArrayVw; - //const mxArray *flinePtr = mxGetField(myinputs, 0, "fline"); - const mxArray *flinePtr = mexGetVariable("caller", "fline"); - if (flinePtr == NULL) - { - mexPrintf("Metropolis-Hastings myinputs field fline Initialisation failed!\n"); - return (-1); - } - VectorView fline(mxGetPr(flinePtr), nBlocks, 1); - - mxArray *NewFileArrayPtr = mexGetVariable("caller", "NewFile"); - if (NewFileArrayPtr == NULL) - { - mexPrintf("Metropolis-Hastings myinputs fields NewFileArrayPtr Initialisation failed!\n"); - return (-1); - } - VectorView NewFileVw(mxGetPr(NewFileArrayPtr), nBlocks, 1); - //Vector NewFile(NewFileVw.getSize()); - //NewFile = NewFileVw; - - const mxArray *MAX_nrunsPtr = mexGetVariablePtr("caller", "MAX_nruns"); - const size_t MAX_nruns = (size_t) mxGetScalar(MAX_nrunsPtr); - - const mxArray *blockStartParamsPtr = mexGetVariable("caller", "ix2"); - MatrixView blockStartParamsMxVw(mxGetPr(blockStartParamsPtr), nBlocks, npar, nBlocks); - Vector startParams(npar); - - const mxArray *mxFirstLogLikPtr = mexGetVariable("caller", "ilogpo2"); - VectorView FirstLogLiK(mxGetPr(mxFirstLogLikPtr), nBlocks, 1); - - const mxArray *record = mexGetVariable("caller", "record"); - //const mxArray *record = mxGetField(myinputs, 0, "record"); - if (record == NULL) - { - mexPrintf("Metropolis-Hastings record Initialisation failed!\n"); - return (-1); - } - mxArray *AcceptationRatesPtr = mxGetField(record, 0, "AcceptationRates"); - if (AcceptationRatesPtr == NULL) - { - mexPrintf("Metropolis-Hastings record AcceptationRatesPtr Initialisation failed!\n"); - return (-1); - } - VectorView AcceptationRates(mxGetPr(AcceptationRatesPtr), nBlocks, 1); - - mxArray *mxLastParametersPtr = mxGetField(record, 0, "LastParameters"); - MatrixView LastParameters(mxGetPr(mxLastParametersPtr), nBlocks, npar, nBlocks); - LastParameters = blockStartParamsMxVw; - - mxArray *mxLastLogLikPtr = mxGetField(record, 0, "LastLogLiK"); - VectorView LastLogLiK(mxGetPr(mxLastLogLikPtr), nBlocks, 1); - - mxArray *mxMhLogPostDensPtr = 0; - mxArray *mxMhParamDrawsPtr = 0; - size_t currInitSizeArray = 0; - -#if defined MATLAB_MEX_FILE - // Waitbar - mxArray *waitBarRhs[3], *waitBarLhs[1]; - waitBarRhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); - std::string barTitle; - std::stringstream ssbarTitle; - if (console_mode == 0) - { - ssbarTitle.clear(); - ssbarTitle.str(""); - ssbarTitle << "Please wait... Metropolis-Hastings " << fblock << "/" << nBlocks << " ..."; - barTitle = ssbarTitle.str(); - waitBarRhs[1] = mxCreateString(barTitle.c_str()); - *mxGetPr(waitBarRhs[0]) = (double) 0.0; - mexCallMATLAB(1, waitBarLhs, 2, waitBarRhs, "waitbar"); - if (waitBarRhs[1]) - mxDestroyArray(waitBarRhs[1]); - waitBarRhs[1] = waitBarLhs[0]; - } -#endif - - for (size_t b = fblock; b <= nBlocks; ++b) - { - jloop = jloop+1; - -#if defined MATLAB_MEX_FILE - if ((load_mh_file != 0) && (fline(b) > 1) && OpenOldFile[b]) - { - // load(['./' MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) '_blck' int2str(b) '.mat']) - ssFName.clear(); - ssFName.str(""); - ssFName << resultsFileStem << DIRECTORY_SEPARATOR << "metropolis" << DIRECTORY_SEPARATOR << resultsFileStem << "_mh" << (size_t) NewFileVw(b-1) << "_blck" << b << ".mat"; - mhFName = ssFName.str(); - drawmat = matOpen(mhFName.c_str(), "r"); - mexPrintf("MHMCMC: Using interim partial draws file %s \n", mhFName.c_str()); - if (drawmat == 0) - { - fline(b) = 1; - mexPrintf("Error in MH: Can not open old draws Mat file for reading: %s \n \ - Starting a new file instead! \n", mhFName.c_str()); - } - else - { - currInitSizeArray = (size_t) InitSizeArray(b-1); - mxMhParamDrawsPtr = matGetVariable(drawmat, "x2"); - mxMhLogPostDensPtr = matGetVariable(drawmat, "logpo2"); - matClose(drawmat); - OpenOldFile[b] = 1; - } - } // end if - if (console_mode == 0) - { - ssbarTitle.clear(); - ssbarTitle.str(""); - ssbarTitle << "Please wait... Metropolis-Hastings " << b << "/" << nBlocks << " ..."; - barTitle = ssbarTitle.str(); - waitBarRhs[2] = mxCreateString(barTitle.c_str()); - //strcpy( *mxGetPr(waitBarRhs[1]), mhFName.c_str()); - *mxGetPr(waitBarRhs[0]) = (double) 0.0; - mexCallMATLAB(0, NULL, 3, waitBarRhs, "waitbar"); - mxDestroyArray(waitBarRhs[2]); - } -#else //if defined OCTAVE_MEX_FILE - if ((load_mh_file != 0) && (fline(b) > 1) && OpenOldFile[b]) - { - // load(['./' MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) '_blck' int2str(b) '.mat']) - if ((currInitSizeArray != (size_t) InitSizeArray(b-1)) && OpenOldFile[b] != 1) - { - // new or different size result arrays/matrices - currInitSizeArray = (size_t) InitSizeArray(b-1); - if (mxMhLogPostDensPtr) - mxDestroyArray(mxMhLogPostDensPtr); // log post density array - mxMhLogPostDensPtr = mxCreateDoubleMatrix(currInitSizeArray, 1, mxREAL); - if (mxMhLogPostDensPtr == NULL) - { - mexPrintf("Metropolis-Hastings mxMhLogPostDensPtr Initialisation failed!\n"); - return (-1); - } - if (mxMhParamDrawsPtr) - mxDestroyArray(mxMhParamDrawsPtr); // accepted MCMC MH draws - mxMhParamDrawsPtr = mxCreateDoubleMatrix(currInitSizeArray, npar, mxREAL); - if (mxMhParamDrawsPtr == NULL) - { - mexPrintf("Metropolis-Hastings mxMhParamDrawsPtr Initialisation failed!\n"); - return (-1); - } - } - - ssFName.clear(); - ssFName.str(""); - ssFName << resultsFileStem << DIRECTORY_SEPARATOR << "metropolis" << DIRECTORY_SEPARATOR << resultsFileStem << "_mh" << (size_t) NewFileVw(b-1) << "_blck" << b << ".mat"; - mhFName = ssFName.str(); - drawmat = Mat_Open(mhFName.c_str(), MAT_ACC_RDONLY); - if (drawmat == NULL) - { - fline(b) = 1; - mexPrintf("Error in MH: Can not open old draws Mat file for reading: %s \n \ - Starting a new file instead! \n", mhFName.c_str()); - } - else - { - int start[2] = {0, 0}, edge[2], stride[2] = {1, 1}, err = 0; - mexPrintf("MHMCMC: Using interim partial draws file %s \n", mhFName.c_str()); - // matvar = Mat_VarReadInfo(drawmat, "x2"); - matvar = Mat_VarReadInfo(drawmat, (char *) "x2"); - if (matvar == NULL) - { - fline(b) = 1; - mexPrintf("Error in MH: Can not read old draws Mat file for reading: %s \n \ - Starting a new file instead! \n", mhFName.c_str()); - } - else - { - // GetVariable(drawmat, "x2"); - edge[0] = matvar->dims[0]; - edge[1] = matvar->dims[1]; - err = Mat_VarReadData(drawmat, matvar, mxGetPr(mxMhParamDrawsPtr), start, stride, edge); - if (err) - { - fline(b) = 1; - mexPrintf("Error in MH: Can not retreive old draws from Mat file: %s \n \ - Starting a new file instead! \n", mhFName.c_str()); - } - Mat_VarFree(matvar); - } - //mxMhLogPostDensPtr = Mat_GetVariable(drawmat, "logpo2"); - matvar = Mat_VarReadInfo(drawmat, (char *) "logpo2"); - if (matvar == NULL) - { - fline(b) = 1; - mexPrintf("Error in MH: Can not read old logPos Mat file for reading: %s \n \ - Starting a new file instead! \n", mhFName.c_str()); - } - else - { - // GetVariable(drawmat, "x2"); - edge[0] = matvar->dims[0]; - edge[1] = matvar->dims[1]; - err = Mat_VarReadData(drawmat, matvar, mxGetPr(mxMhLogPostDensPtr), start, stride, edge); - if (err) - { - fline(b) = 1; - mexPrintf("Error in MH: Can not retreive old logPos from Mat file: %s \n \ - Starting a new file instead! \n", mhFName.c_str()); - } - Mat_VarFree(matvar); - } - Mat_Close(drawmat); - OpenOldFile[b] = 1; - } - } // end if - -#endif - - VectorView LastParametersRow = mat::get_row(LastParameters, b-1); - - sux = 0.0; - jsux = 0; - irun = (size_t) fline(b-1); - j = 0; //1; - while (j < nruns(b-1)) - { - if ((currInitSizeArray != (size_t) InitSizeArray(b-1)) && OpenOldFile[b] != 1) - { - // new or different size result arrays/matrices - currInitSizeArray = (size_t) InitSizeArray(b-1); - if (mxMhLogPostDensPtr) - mxDestroyArray(mxMhLogPostDensPtr); // log post density array - mxMhLogPostDensPtr = mxCreateDoubleMatrix(currInitSizeArray, 1, mxREAL); - if (mxMhLogPostDensPtr == NULL) - { - mexPrintf("Metropolis-Hastings mxMhLogPostDensPtr Initialisation failed!\n"); - return (-1); - } - if (mxMhParamDrawsPtr) - mxDestroyArray(mxMhParamDrawsPtr); // accepted MCMC MH draws - mxMhParamDrawsPtr = mxCreateDoubleMatrix(currInitSizeArray, npar, mxREAL); - if (mxMhParamDrawsPtr == NULL) - { - mexPrintf("Metropolis-Hastings mxMhParamDrawsPtr Initialisation failed!\n"); - return (-1); - } - } - startParams = LastParametersRow; - VectorView mhLogPostDens(mxGetPr(mxMhLogPostDensPtr), currInitSizeArray, (size_t) 1); - MatrixView mhParamDraws(mxGetPr(mxMhParamDrawsPtr), currInitSizeArray, npar, currInitSizeArray); - try - { - jsux = rwmh.compute(mhLogPostDens, mhParamDraws, steadyState, startParams, deepParams, data, Q, H, - presampleStart, irun, currInitSizeArray, lpd, pdd, epd); - irun = currInitSizeArray; - sux += jsux*currInitSizeArray; - j += currInitSizeArray; //j=j+1; - } - catch (const TSException &tse) - { - iret = -100; - mexPrintf(" TSException Exception in RandomWalkMH dynamic_dll: %s \n", (tse.getMessage()).c_str()); - goto cleanup; - } - catch (const DecisionRules::BlanchardKahnException &bke) - { - iret = -90; - mexPrintf(" Too many Blanchard-Kahn Exceptions in RandomWalkMH : n_fwrd_vars %d n_explosive_eigenvals %d \n", bke.n_fwrd_vars, bke.n_explosive_eigenvals); - goto cleanup; - } - catch (const GeneralizedSchurDecomposition::GSDException &gsde) - { - iret = -80; - mexPrintf(" GeneralizedSchurDecomposition Exception in RandomWalkMH: info %d, n %d \n", gsde.info, gsde.n); - goto cleanup; - } - catch (const LUSolver::LUException &lue) - { - iret = -70; - mexPrintf(" LU Exception in RandomWalkMH : info %d \n", lue.info); - goto cleanup; - } - catch (const VDVEigDecomposition::VDVEigException &vdve) - { - iret = -60; - mexPrintf(" VDV Eig Exception in RandomWalkMH : %s , info: %d\n", vdve.message.c_str(), vdve.info); - goto cleanup; - } - catch (const DiscLyapFast::DLPException &dlpe) - { - iret = -50; - mexPrintf(" Lyapunov solver Exception in RandomWalkMH : %s , info: %d\n", dlpe.message.c_str(), dlpe.info); - goto cleanup; - } - catch (const std::runtime_error &re) - { - iret = -3; - mexPrintf(" Runtime Error Exception in RandomWalkMH: %s \n", re.what()); - goto cleanup; - } - catch (const std::exception &e) - { - iret = -2; - mexPrintf(" Standard System Exception in RandomWalkMH: %s \n", e.what()); - goto cleanup; - } - catch (...) - { - iret = -1000; - mexPrintf(" Unknown unhandled Exception in RandomWalkMH! %s \n"); - goto cleanup; - } - -#if defined MATLAB_MEX_FILE - if (console_mode) - mexPrintf(" MH: Computing Metropolis-Hastings (chain %d/%d): %3.f \b%% done, acceptance rate: %3.f \b%%\r", b, nBlocks, 100 * j/nruns(b-1), 100 * sux / j); - else - { - // Waitbar - ssbarTitle.clear(); - ssbarTitle.str(""); - ssbarTitle << "Metropolis-Hastings : " << b << "/" << nBlocks << " Acceptance: " << 100 * sux/j << "%"; - barTitle = ssbarTitle.str(); - waitBarRhs[2] = mxCreateString(barTitle.c_str()); - *mxGetPr(waitBarRhs[0]) = j / nruns(b-1); - mexCallMATLAB(0, NULL, 3, waitBarRhs, "waitbar"); - mxDestroyArray(waitBarRhs[2]); - - } - - // % Now I save the simulations - // save draw 2 mat file ([MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) '_blck' int2str(b) '.mat'],'x2','logpo2'); - ssFName.clear(); - ssFName.str(""); - ssFName << resultsFileStem << DIRECTORY_SEPARATOR << "metropolis" << DIRECTORY_SEPARATOR << resultsFileStem << "_mh" << (size_t) NewFileVw(b-1) << "_blck" << b << ".mat"; - mhFName = ssFName.str(); - drawmat = matOpen(mhFName.c_str(), "w"); - if (drawmat == 0) - { - mexPrintf("Error in MH: Can not open draws Mat file for writing: %s \n", mhFName.c_str()); - exit(1); - } - matfStatus = matPutVariable(drawmat, "x2", mxMhParamDrawsPtr); - if (matfStatus) - { - mexPrintf("Error in MH: Can not use draws Mat file for writing: %s \n", mhFName.c_str()); - exit(1); - } - matfStatus = matPutVariable(drawmat, "logpo2", mxMhLogPostDensPtr); - if (matfStatus) - { - mexPrintf("Error in MH: Can not usee draws Mat file for writing: %s \n", mhFName.c_str()); - exit(1); - } - matClose(drawmat); -#else - - printf(" MH: Computing Metropolis-Hastings (chain %ld/%ld): %3.f \b%% done, acceptance rate: %3.f \b%%\r", b, nBlocks, 100 * j/nruns(b-1), 100 * sux / j); - // % Now I save the simulations - // save draw 2 mat file ([MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) '_blck' int2str(b) '.mat'],'x2','logpo2'); - ssFName.clear(); - ssFName.str(""); - ssFName << resultsFileStem << DIRECTORY_SEPARATOR << "metropolis" << DIRECTORY_SEPARATOR << resultsFileStem << "_mh" << (size_t) NewFileVw(b-1) << "_blck" << b << ".mat"; - mhFName = ssFName.str(); - - drawmat = Mat_Create(mhFName.c_str(), NULL); - if (drawmat == 0) - { - mexPrintf("Error in MH: Can not open draws Mat file for writing: %s \n", mhFName.c_str()); - exit(1); - } - dims[0] = currInitSizeArray; - dims[1] = npar; - matvar = Mat_VarCreate("x2", MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, mxGetPr(mxMhParamDrawsPtr), 0); - matfStatus = Mat_VarWrite(drawmat, matvar, compression); - Mat_VarFree(matvar); - if (matfStatus) - { - mexPrintf("Error in MH: Can not use draws Mat file for writing: %s \n", mhFName.c_str()); - exit(1); - } - //matfStatus = matPutVariable(drawmat, "logpo2", mxMhLogPostDensPtr); - dims[1] = 1; - matvar = Mat_VarCreate("logpo2", MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, mxGetPr(mxMhLogPostDensPtr), 0); - matfStatus = Mat_VarWrite(drawmat, matvar, compression); - Mat_VarFree(matvar); - if (matfStatus) - { - mexPrintf("Error in MH: Can not usee draws Mat file for writing: %s \n", mhFName.c_str()); - exit(1); - } - Mat_Close(drawmat); -#endif - - // save log to fidlog = fopen([MhDirectoryName '/metropolis.log'],'a'); - ssFName.str(""); - ssFName << resultsFileStem << DIRECTORY_SEPARATOR << "metropolis" << DIRECTORY_SEPARATOR << "metropolis.log"; - mhFName = ssFName.str(); - fidlog = fopen(mhFName.c_str(), "a"); - fprintf(fidlog, "\n"); - fprintf(fidlog, "%% Mh%dBlck%lu ( %s %s )\n", (int) NewFileVw(b-1), b, __DATE__, __TIME__); - fprintf(fidlog, " \n"); - fprintf(fidlog, " Number of simulations.: %lu \n", currInitSizeArray); // (length(logpo2)) '); - fprintf(fidlog, " Acceptation rate......: %f \n", jsux); - fprintf(fidlog, " Posterior mean........:\n"); - for (size_t i = 0; i < npar; ++i) - { - VectorView mhpdColVw = mat::get_col(mhParamDraws, i); - fprintf(fidlog, " params: %lu : %f \n", i+1, vec::meanSumMinMax(dsum, dmin, dmax, mhpdColVw)); - MinMax(i, iMin) = dmin; - MinMax(i, iMax) = dmax; - } // end - fprintf(fidlog, " log2po: %f \n", vec::meanSumMinMax(dsum, dmin, dmax, mhLogPostDens)); - fprintf(fidlog, " Minimum value.........:\n");; - for (size_t i = 0; i < npar; ++i) - fprintf(fidlog, " params: %lu : %f \n", i+1, MinMax(i, iMin)); - fprintf(fidlog, " log2po: %f \n", dmin); - fprintf(fidlog, " Maximum value.........:\n"); - for (size_t i = 0; i < npar; ++i) - fprintf(fidlog, " params: %lu : %f \n", i+1, MinMax(i, iMax)); - fprintf(fidlog, " log2po: %f \n", dmax); - fprintf(fidlog, " \n"); - fclose(fidlog); - - jsux = 0; - LastParametersRow = mat::get_row(mhParamDraws, currInitSizeArray-1); //x2(end,:); - LastLogLiK(b-1) = mhLogPostDens(currInitSizeArray-1); //logpo2(end); - InitSizeArray(b-1) = std::min((size_t) nruns(b-1)-j, MAX_nruns); - // initialization of next file if necessary - if (InitSizeArray(b-1)) - { - NewFileVw(b-1)++; // = NewFile(b-1) + 1; - irun = 1; - } // end - //irun++; - } // end while % End of the simulations for one mh-block. - //record. - AcceptationRates(b-1) = sux/j; - OpenOldFile[b] = 0; - } // end % End of the loop over the mh-blocks. - - if (mexPutVariable("caller", "record_AcceptationRates", AcceptationRatesPtr)) - mexPrintf("MH Warning: due to error record_AcceptationRates is NOT set !! \n"); - - if (mexPutVariable("caller", "record_LastParameters", mxLastParametersPtr)) - mexPrintf("MH Warning: due to error record_MhParamDraw is NOT set !! \n"); - - if (mexPutVariable("caller", "record_LastLogLiK", mxLastLogLikPtr)) - mexPrintf("MH Warning: due to error record_LastLogLiK is NOT set !! \n"); - - //NewFileVw = NewFile; - if (mexPutVariable("caller", "NewFile", NewFileArrayPtr)) - mexPrintf("MH Warning: due to error NewFile is NOT set !! \n"); - - // Cleanup - mexPrintf("MH Cleanup !! \n"); - - cleanup: - if (mxMhLogPostDensPtr) - mxDestroyArray(mxMhLogPostDensPtr); // delete log post density array - if (mxMhParamDrawsPtr) - mxDestroyArray(mxMhParamDrawsPtr); // delete accepted MCMC MH draws - -#ifdef MATLAB_MEX_FILE - // Waitbar - if (console_mode == 0) - { - // Bellow call to close waitbar seems to cause crashes and it is for - // now left commented out and the waitbar neeeds to be closed manually - // alternativelly, call with options_.console_mode=1; - //mexCallMATLAB(0, NULL, 1, waitBarLhs, "close"); - //mxDestroyArray(waitBarLhs[0]); - mxDestroyArray(waitBarRhs[1]); - mxDestroyArray(waitBarRhs[0]); - } -#endif - - // return error code or last line run in the last MH block sub-array - if (iret == 0) - iret = (int) irun; - return iret; - -} - -int -logMCMCposterior(VectorConstView &estParams, const MatrixConstView &data, - const size_t fblock, const size_t nBlocks, const VectorConstView &nMHruns, const MatrixConstView &D, - VectorView &steadyState, VectorView &deepParams, MatrixView &Q, Matrix &H) -{ - // Retrieve pointers to global variables - const mxArray *M_ = mexGetVariablePtr("global", "M_"); - const mxArray *options_ = mexGetVariablePtr("global", "options_"); - const mxArray *estim_params_ = mexGetVariablePtr("global", "estim_params_"); - const mxArray *bayestopt_ = mexGetVariablePtr("global", "bayestopt_"); - - double loglinear = *mxGetPr(mxGetField(options_, 0, "loglinear")); - if (loglinear == 1) - throw LogMHMCMCposteriorMexErrMsgTxtException("Option loglinear is not supported"); - - if (*mxGetPr(mxGetField(options_, 0, "endogenous_prior")) == 1) - throw LogMHMCMCposteriorMexErrMsgTxtException("Option endogenous_prior is not supported"); - - double with_trend = *mxGetPr(mxGetField(bayestopt_, 0, "with_trend")); - if (with_trend == 1) - throw LogMHMCMCposteriorMexErrMsgTxtException("Observation trends are not supported"); - - // Construct arguments of constructor of LogLikelihoodMain - char *fName = mxArrayToString(mxGetField(M_, 0, "fname")); - std::string resultsFileStem(fName); - std::string basename(fName); - mxFree(fName); - - size_t n_endo = (size_t) *mxGetPr(mxGetField(M_, 0, "endo_nbr")); - size_t n_exo = (size_t) *mxGetPr(mxGetField(M_, 0, "exo_nbr")); - - size_t n_estParams = estParams.getSize(); - - std::vector zeta_fwrd, zeta_back, zeta_mixed, zeta_static; - const mxArray *lli_mx = mxGetField(M_, 0, "lead_lag_incidence"); - MatrixConstView lli(mxGetPr(lli_mx), mxGetM(lli_mx), mxGetN(lli_mx), mxGetM(lli_mx)); - if (lli.getRows() != 3 || lli.getCols() != n_endo) - throw LogMHMCMCposteriorMexErrMsgTxtException("Error in logMCMCposterior: Incorrect lead/lag incidence matrix"); - for (size_t i = 0; i < n_endo; i++) - { - if (lli(0, i) == 0 && lli(2, i) == 0) - zeta_static.push_back(i); - else if (lli(0, i) != 0 && lli(2, i) == 0) - zeta_back.push_back(i); - else if (lli(0, i) == 0 && lli(2, i) != 0) - zeta_fwrd.push_back(i); - else - zeta_mixed.push_back(i); - } - - double qz_criterium = *mxGetPr(mxGetField(options_, 0, "qz_criterium")); - double lyapunov_tol = *mxGetPr(mxGetField(options_, 0, "lyapunov_complex_threshold")); - double riccati_tol = *mxGetPr(mxGetField(options_, 0, "riccati_tol")); - size_t presample = (size_t) *mxGetPr(mxGetField(options_, 0, "presample")); - size_t console_mode = (size_t) *mxGetPr(mxGetField(options_, 0, "console_mode")); - size_t load_mh_file = (size_t) *mxGetPr(mxGetField(options_, 0, "load_mh_file")); - - std::vector varobs; - const mxArray *varobs_mx = mxGetField(options_, 0, "varobs_id"); - if (mxGetM(varobs_mx) != 1) - throw LogMHMCMCposteriorMexErrMsgTxtException("Error in logMCMCposterior: options_.varobs_id must be a row vector"); - size_t n_varobs = mxGetN(varobs_mx); - std::transform(mxGetPr(varobs_mx), mxGetPr(varobs_mx) + n_varobs, back_inserter(varobs), - std::bind2nd(std::minus(), 1)); - - if (data.getRows() != n_varobs) - throw LogMHMCMCposteriorMexErrMsgTxtException("Error in logMCMCposterior: Data does not have as many rows as there are observed variables"); - - std::vector estSubsamples; - estSubsamples.push_back(EstimationSubsample(0, data.getCols() - 1)); - - std::vector estParamsInfo; - fillEstParamsInfo(mxGetField(estim_params_, 0, "var_exo"), EstimatedParameter::shock_SD, - estParamsInfo); - fillEstParamsInfo(mxGetField(estim_params_, 0, "var_endo"), EstimatedParameter::measureErr_SD, - estParamsInfo); - fillEstParamsInfo(mxGetField(estim_params_, 0, "corrx"), EstimatedParameter::shock_Corr, - estParamsInfo); - fillEstParamsInfo(mxGetField(estim_params_, 0, "corrn"), EstimatedParameter::measureErr_Corr, - estParamsInfo); - fillEstParamsInfo(mxGetField(estim_params_, 0, "param_vals"), EstimatedParameter::deepPar, - estParamsInfo); - EstimatedParametersDescription epd(estSubsamples, estParamsInfo); - - bool noconstant = (bool) *mxGetPr(mxGetField(options_, 0, "noconstant")); - - // Allocate LogPosteriorDensity object - LogPosteriorDensity lpd(basename, epd, n_endo, n_exo, zeta_fwrd, zeta_back, zeta_mixed, zeta_static, - qz_criterium, varobs, riccati_tol, lyapunov_tol, noconstant); - - // Construct MHMCMC Sampler - RandomWalkMetropolisHastings rwmh(estParams.getSize()); - // Construct GaussianPrior drawDistribution m=0, sd=1 - GaussianPrior drawGaussDist01(0.0, 1.0, -INFINITY, INFINITY, 0.0, 1.0); - // get Jscale = diag(bayestopt_.jscale); - const Matrix Jscale(n_estParams); - const VectorConstView vJscale(mxGetPr(mxGetField(bayestopt_, 0, "jscale")), n_estParams, 1); - Proposal pdd(vJscale, D); - - //sample MHMCMC draws and get get last line run in the last MH block sub-array - int lastMHblockArrayLine = sampleMHMC(lpd, rwmh, steadyState, estParams, deepParams, data, Q, H, presample, - nMHruns, fblock, nBlocks, pdd, epd, resultsFileStem, console_mode, load_mh_file); - - // Cleanups - for (std::vector::iterator it = estParamsInfo.begin(); - it != estParamsInfo.end(); it++) - delete it->prior; - - return lastMHblockArrayLine; -} - -void -mexFunction(int nlhs, mxArray *plhs[], - int nrhs, const mxArray *prhs[]) -{ - if (nrhs != 10) - DYN_MEX_FUNC_ERR_MSG_TXT("logposterior: exactly 11 arguments are required."); - if (nlhs != 2) - DYN_MEX_FUNC_ERR_MSG_TXT("logposterior: exactly two return arguments are required."); - - // Check and retrieve the arguments - - if (!mxIsDouble(prhs[0]) || mxGetN(prhs[0]) != 1) - DYN_MEX_FUNC_ERR_MSG_TXT("logposterior: First argument must be a column vector of double-precision numbers"); - - VectorConstView estParams(mxGetPr(prhs[0]), mxGetM(prhs[0]), 1); - - if (!mxIsDouble(prhs[1])) - DYN_MEX_FUNC_ERR_MSG_TXT("logposterior: Second argument must be a matrix of double-precision numbers"); - - size_t fblock = (size_t) mxGetScalar(prhs[2]); - size_t nBlocks = (size_t) mxGetScalar(prhs[3]); - VectorConstView nMHruns(mxGetPr(prhs[4]), mxGetM(prhs[4]), 1); - MatrixConstView D(mxGetPr(prhs[5]), mxGetM(prhs[5]), mxGetN(prhs[5]), mxGetM(prhs[5])); - const mxArray *dataset = prhs[6]; - const mxArray *options_ = prhs[7]; - const mxArray *M_ = prhs[8]; - const mxArray *bayestopt_ = prhs[9]; - const mxArray *oo_ = prhs[10]; - - assert(nMHruns.getSize() == nBlocks); - - mxArray *dataset_data = mxGetField(dataset, 0, "data"); - MatrixConstView data(mxGetPr(dataset_data), mxGetM(dataset_data), mxGetN(dataset_data), mxGetM(dataset_data)); - - int endo_nbr = *(int *) mxGetPr(mxGetField(M_, 0, "endo_nbr")); - int exo_nbr = *(int *) mxGetPr(mxGetField(M_, 0, "exo_nbr")); - int param_nbr = *(int *) mxGetPr(mxGetField(M_, 0, "param_nbr")); - int varobs_nbr = mxGetN(mxGetField(options_, 0, "varobs")); - - VectorView steadyState(mxGetPr(mxGetField(oo_, 0, "steady_state")), endo_nbr, 1); - VectorView deepParams(mxGetPr(mxGetField(M_, 0, "params")), param_nbr, 1); - - MatrixView Q(mxGetPr(mxGetField(M_, 0, "Sigma_e")), exo_nbr, exo_nbr, exo_nbr); - - Matrix H(varobs_nbr, varobs_nbr); - const mxArray *H_mx = mxGetField(M_, 0, "H"); - if (mxGetM(H_mx) == 1 && mxGetN(H_mx) == 1 && *mxGetPr(H_mx) == 0) - H.setAll(0.0); - else - H = MatrixConstView(mxGetPr(H_mx), varobs_nbr, varobs_nbr, varobs_nbr); - - //calculate MHMCMC draws and get get last line run in the last MH block sub-array - try - { - int lastMHblockArrayLine = logMCMCposterior(estParams, data, fblock, nBlocks, nMHruns, D, steadyState, deepParams, Q, H); - plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL); - *mxGetPr(plhs[1]) = (double) lastMHblockArrayLine; - } - catch (LogMHMCMCposteriorMexErrMsgTxtException e) - { - DYN_MEX_FUNC_ERR_MSG_TXT(e.getErrMsg()); - } - plhs[0] = mxCreateDoubleScalar(0); -} diff --git a/mex/sources/estimation/logposterior.cc b/mex/sources/estimation/logposterior.cc deleted file mode 100644 index 95e4e3cbe..000000000 --- a/mex/sources/estimation/logposterior.cc +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include -#include -#include -#include -#include - -#include "Vector.hh" -#include "Matrix.hh" -#include "LogPosteriorDensity.hh" - -#include - -class LogposteriorMexErrMsgTxtException -{ -public: - std::string errMsg; - LogposteriorMexErrMsgTxtException(const std::string &msg) : errMsg(msg) - { - } - inline const char * - getErrMsg() - { - return errMsg.c_str(); - } -}; - -void -fillEstParamsInfo(const mxArray *bayestopt_, const mxArray *estim_params_info, EstimatedParameter::pType type, - std::vector &estParamsInfo) -{ - const mxArray *bayestopt_ubp = mxGetField(bayestopt_, 0, "ub"); // upper bound - const mxArray *bayestopt_lbp = mxGetField(bayestopt_, 0, "lb"); // lower bound - const mxArray *bayestopt_p1p = mxGetField(bayestopt_, 0, "p1"); // prior mean - const mxArray *bayestopt_p2p = mxGetField(bayestopt_, 0, "p2"); // prior standard deviation - const mxArray *bayestopt_p3p = mxGetField(bayestopt_, 0, "p3"); // lower bound - const mxArray *bayestopt_p4p = mxGetField(bayestopt_, 0, "p4"); // upper bound - const mxArray *bayestopt_p6p = mxGetField(bayestopt_, 0, "p6"); // first hyper-parameter (\alpha for the BETA and GAMMA distributions, s for the INVERSE GAMMAs, expectation for the GAUSSIAN distribution, lower bound for the UNIFORM distribution). - const mxArray *bayestopt_p7p = mxGetField(bayestopt_, 0, "p7"); // second hyper-parameter (\beta for the BETA and GAMMA distributions, \nu for the INVERSE GAMMAs, standard deviation for the GAUSSIAN distribution, upper bound for the UNIFORM distribution). - const mxArray *bayestopt_jscalep = mxGetField(bayestopt_, 0, "jscale"); // MCMC jump scale - - const size_t bayestopt_size = mxGetM(bayestopt_); - const VectorConstView bayestopt_ub(mxGetPr(bayestopt_ubp), bayestopt_size, 1); - const VectorConstView bayestopt_lb(mxGetPr(bayestopt_lbp), bayestopt_size, 1); - const VectorConstView bayestopt_p1(mxGetPr(bayestopt_p1p), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "p1"); - const VectorConstView bayestopt_p2(mxGetPr(bayestopt_p2p), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "p2"); - const VectorConstView bayestopt_p3(mxGetPr(bayestopt_p3p), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "p3"); - const VectorConstView bayestopt_p4(mxGetPr(bayestopt_p4p), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "p4"); - const VectorConstView bayestopt_p6(mxGetPr(bayestopt_p6p), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "p6"); - const VectorConstView bayestopt_p7(mxGetPr(bayestopt_p7p), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "p7"); - const VectorConstView bayestopt_jscale(mxGetPr(bayestopt_jscalep), bayestopt_size, 1); //=mxGetField(bayestopt_, 0, "jscale"); - - // loop processsing - size_t m = mxGetM(estim_params_info), n = mxGetN(estim_params_info); - MatrixConstView epi(mxGetPr(estim_params_info), m, n, m); - size_t bayestopt_count = estParamsInfo.size(); - - for (size_t i = 0; i < m; i++) - { - size_t col = 0; - size_t id1 = (size_t) epi(i, col++) - 1; - size_t id2 = 0; - if (type == EstimatedParameter::shock_Corr - || type == EstimatedParameter::measureErr_Corr) - id2 = (size_t) epi(i, col++) - 1; - col++; // Skip init_val #2 or #3 - double par_low_bound = bayestopt_lb(bayestopt_count); col++; //#3 epi(i, col++); - double par_up_bound = bayestopt_ub(bayestopt_count); col++; //#4 epi(i, col++); - Prior::pShape shape = (Prior::pShape) epi(i, col++); - double mean = epi(i, col++); - double std = epi(i, col++); - double low_bound = bayestopt_p3(bayestopt_count); - double up_bound = bayestopt_p4(bayestopt_count); - double fhp = bayestopt_p6(bayestopt_count); // double p3 = epi(i, col++); - double shp = bayestopt_p7(bayestopt_count); // double p4 = epi(i, col++); - - Prior *p = Prior::constructPrior(shape, mean, std, low_bound, up_bound, fhp, shp); //1.0,INFINITY);//p3, p4); - - // Only one subsample - std::vector subSampleIDs; - subSampleIDs.push_back(0); - estParamsInfo.push_back(EstimatedParameter(type, id1, id2, subSampleIDs, - par_low_bound, par_up_bound, p)); - bayestopt_count++; - } -} - -template -double -logposterior(VEC1 &estParams, const MatrixConstView &data, - const mxArray *options_, const mxArray *M_, const mxArray *estim_params_, - const mxArray *bayestopt_, const mxArray *oo_, VEC2 &steadyState, double *trend_coeff, - VectorView &deepParams, Matrix &H, MatrixView &Q) -{ - double loglinear = *mxGetPr(mxGetField(options_, 0, "loglinear")); - if (loglinear == 1) - throw LogposteriorMexErrMsgTxtException("Option loglinear is not supported"); - - if (*mxGetPr(mxGetField(options_, 0, "endogenous_prior")) == 1) - throw LogposteriorMexErrMsgTxtException("Option endogenous_prior is not supported"); - - double with_trend = *mxGetPr(mxGetField(bayestopt_, 0, "with_trend")); - if (with_trend == 1) - throw LogposteriorMexErrMsgTxtException("Observation trends are not supported"); - - // Construct arguments of constructor of LogLikelihoodMain - char *fName = mxArrayToString(mxGetField(M_, 0, "fname")); - std::string basename(fName); - mxFree(fName); - - size_t n_endo = (size_t) *mxGetPr(mxGetField(M_, 0, "endo_nbr")); - size_t n_exo = (size_t) *mxGetPr(mxGetField(M_, 0, "exo_nbr")); - - std::vector zeta_fwrd, zeta_back, zeta_mixed, zeta_static; - const mxArray *lli_mx = mxGetField(M_, 0, "lead_lag_incidence"); - MatrixConstView lli(mxGetPr(lli_mx), mxGetM(lli_mx), mxGetN(lli_mx), mxGetM(lli_mx)); - if (lli.getRows() != 3) - throw LogposteriorMexErrMsgTxtException("Purely backward or purely forward models are not supported"); - if (lli.getCols() != n_endo) - throw LogposteriorMexErrMsgTxtException("Incorrect lead/lag incidence matrix"); - - for (size_t i = 0; i < n_endo; i++) - { - if (lli(0, i) == 0 && lli(2, i) == 0) - zeta_static.push_back(i); - else if (lli(0, i) != 0 && lli(2, i) == 0) - zeta_back.push_back(i); - else if (lli(0, i) == 0 && lli(2, i) != 0) - zeta_fwrd.push_back(i); - else - zeta_mixed.push_back(i); - } - - double qz_criterium = *mxGetPr(mxGetField(options_, 0, "qz_criterium")); - double lyapunov_tol = *mxGetPr(mxGetField(options_, 0, "lyapunov_complex_threshold")); - double riccati_tol = *mxGetPr(mxGetField(options_, 0, "riccati_tol")); - size_t presample = (size_t) *mxGetPr(mxGetField(options_, 0, "presample")); - - std::vector varobs; - const mxArray *varobs_mx = mxGetField(options_, 0, "varobs_id"); - if (mxGetM(varobs_mx) != 1) - throw LogposteriorMexErrMsgTxtException("options_.varobs_id must be a row vector"); - - size_t n_varobs = mxGetN(varobs_mx); - // substract 1.0 from obsverved variables index - std::transform(mxGetPr(varobs_mx), mxGetPr(varobs_mx) + n_varobs, back_inserter(varobs), - std::bind2nd(std::minus(), 1)); - - if (data.getRows() != n_varobs) - throw LogposteriorMexErrMsgTxtException("Data does not have as many rows as there are observed variables"); - - std::vector estSubsamples; - estSubsamples.push_back(EstimationSubsample(0, data.getCols() - 1)); - - std::vector estParamsInfo; - fillEstParamsInfo(bayestopt_, mxGetField(estim_params_, 0, "var_exo"), EstimatedParameter::shock_SD, - estParamsInfo); - fillEstParamsInfo(bayestopt_, mxGetField(estim_params_, 0, "var_endo"), EstimatedParameter::measureErr_SD, - estParamsInfo); - fillEstParamsInfo(bayestopt_, mxGetField(estim_params_, 0, "corrx"), EstimatedParameter::shock_Corr, - estParamsInfo); - fillEstParamsInfo(bayestopt_, mxGetField(estim_params_, 0, "corrn"), EstimatedParameter::measureErr_Corr, - estParamsInfo); - fillEstParamsInfo(bayestopt_, mxGetField(estim_params_, 0, "param_vals"), EstimatedParameter::deepPar, - estParamsInfo); - - EstimatedParametersDescription epd(estSubsamples, estParamsInfo); - - bool noconstant = (bool) *mxGetPr(mxGetField(options_, 0, "noconstant")); - - // Allocate LogPosteriorDensity object - LogPosteriorDensity lpd(basename, epd, n_endo, n_exo, zeta_fwrd, zeta_back, zeta_mixed, zeta_static, - qz_criterium, varobs, riccati_tol, lyapunov_tol, noconstant); - - // Construct arguments of compute() method - - // Compute the posterior - double logPD = lpd.compute(steadyState, estParams, deepParams, data, Q, H, presample); - - // Cleanups - for (std::vector::iterator it = estParamsInfo.begin(); - it != estParamsInfo.end(); it++) - delete it->prior; - - return logPD; -} - -void -mexFunction(int nlhs, mxArray *plhs[], - int nrhs, const mxArray *prhs[]) -{ - if (nrhs != 7) - DYN_MEX_FUNC_ERR_MSG_TXT("logposterior: exactly 7 input arguments are required."); - - if (nlhs > 9) - DYN_MEX_FUNC_ERR_MSG_TXT("logposterior returns 8 output arguments at the most."); - - // Check and retrieve the RHS arguments - - if (!mxIsDouble(prhs[0]) || mxGetN(prhs[0]) != 1) - DYN_MEX_FUNC_ERR_MSG_TXT("logposterior: First argument must be a column vector of double-precision numbers"); - - VectorConstView estParams(mxGetPr(prhs[0]), mxGetM(prhs[0]), 1); - - for (int i = 1; i < 7; ++i) - if (!mxIsStruct(prhs[i])) - { - std::stringstream msg; - msg << "logposterior: argument " << i+1 << " must be a Matlab structure"; - DYN_MEX_FUNC_ERR_MSG_TXT(msg.str().c_str()); - } - - const mxArray *dataset = prhs[1]; - const mxArray *options_ = prhs[2]; - const mxArray *M_ = prhs[3]; - const mxArray *estim_params_ = prhs[4]; - const mxArray *bayestopt_ = prhs[5]; - const mxArray *oo_ = prhs[6]; - - const mxArray *dataset_data = mxGetField(dataset, 0, "data"); - MatrixConstView data(mxGetPr(dataset_data), mxGetM(dataset_data), mxGetN(dataset_data), mxGetM(dataset_data)); - - // Creaete LHS arguments - - size_t endo_nbr = (size_t) *mxGetPr(mxGetField(M_, 0, "endo_nbr")); - size_t exo_nbr = (size_t) *mxGetPr(mxGetField(M_, 0, "exo_nbr")); - size_t param_nbr = (size_t) *mxGetPr(mxGetField(M_, 0, "param_nbr")); - size_t varobs_nbr = mxGetM(mxGetField(options_, 0, "varobs")); - plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); - plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL); - plhs[2] = mxCreateDoubleMatrix(endo_nbr, 1, mxREAL); - plhs[3] = mxCreateDoubleMatrix(varobs_nbr, 1, mxREAL); - plhs[4] = mxCreateDoubleMatrix(1, 1, mxREAL); - plhs[5] = mxCreateDoubleMatrix(param_nbr, 1, mxREAL); - plhs[6] = mxCreateDoubleMatrix(varobs_nbr, varobs_nbr, mxREAL); - plhs[7] = mxCreateDoubleMatrix(exo_nbr, exo_nbr, mxREAL); - double *lik = mxGetPr(plhs[0]); - double *exit_flag = mxGetPr(plhs[1]); - - VectorView steadyState(mxGetPr(mxGetField(oo_, 0, "steady_state")), endo_nbr, 1); - VectorView deepParams(mxGetPr(mxGetField(M_, 0, "params")), param_nbr, 1); - - MatrixView Q(mxGetPr(mxGetField(M_, 0, "Sigma_e")), exo_nbr, exo_nbr, exo_nbr); - - Matrix H(varobs_nbr, varobs_nbr); - const mxArray *H_mx = mxGetField(M_, 0, "H"); - if (mxGetM(H_mx) == 1 && mxGetN(H_mx) == 1 && *mxGetPr(H_mx) == 0) - H.setAll(0.0); - else - H = MatrixConstView(mxGetPr(H_mx), varobs_nbr, varobs_nbr, varobs_nbr); - - double *trend_coeff = mxGetPr(plhs[3]); - double *info_mx = mxGetPr(plhs[4]); - - // Compute and return the value - try - { - *lik = logposterior(estParams, data, options_, M_, estim_params_, bayestopt_, oo_, - steadyState, trend_coeff, deepParams, H, Q); - *info_mx = 0; - *exit_flag = 0; - } - catch (LogposteriorMexErrMsgTxtException e) - { - DYN_MEX_FUNC_ERR_MSG_TXT(e.getErrMsg()); - } - catch (SteadyStateSolver::SteadyStateException e) - { - DYN_MEX_FUNC_ERR_MSG_TXT(e.message.c_str()); - } -} diff --git a/mex/sources/estimation/tests/DsgeLikelihood.m b/mex/sources/estimation/tests/DsgeLikelihood.m deleted file mode 100644 index a39358065..000000000 --- a/mex/sources/estimation/tests/DsgeLikelihood.m +++ /dev/null @@ -1,345 +0,0 @@ -function [fval,cost_flag,ys,trend_coeff,info] = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations) -% function [fval,cost_flag,ys,trend_coeff,info] = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations) -% Evaluates the posterior kernel of a dsge model. -% -% INPUTS -% xparam1 [double] vector of model parameters. -% gend [integer] scalar specifying the number of observations. -% data [double] matrix of data -% data_index [cell] cell of column vectors -% number_of_observations [integer] -% no_more_missing_observations [integer] -% OUTPUTS -% fval : value of the posterior kernel at xparam1. -% cost_flag : zero if the function returns a penalty, one otherwise. -% ys : steady state of original endogenous variables -% trend_coeff : -% info : vector of informations about the penalty: -% 41: one (many) parameter(s) do(es) not satisfied the lower bound -% 42: one (many) parameter(s) do(es) not satisfied the upper bound -% -% SPECIAL REQUIREMENTS -% - -% Copyright (C) 2004-2012 Dynare Team -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see . - -global bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_ -fval = []; -ys = []; -trend_coeff = []; -cost_flag = 1; -nobs = size(options_.varobs,1); -%------------------------------------------------------------------------------ -% 1. Get the structural parameters & define penalties -%------------------------------------------------------------------------------ -if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb) - k = find(xparam1 < bayestopt_.lb); - fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2); - cost_flag = 0; - info = 41; - return; -end -if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub) - k = find(xparam1 > bayestopt_.ub); - fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2); - cost_flag = 0; - info = 42; - return; -end -Q = M_.Sigma_e; -H = M_.H; -for i=1:estim_params_.nvx - k =estim_params_.var_exo(i,1); - Q(k,k) = xparam1(i)*xparam1(i); -end -offset = estim_params_.nvx; -if estim_params_.nvn - for i=1:estim_params_.nvn - k = estim_params_.var_endo(i,1); - H(k,k) = xparam1(i+offset)*xparam1(i+offset); - end - offset = offset+estim_params_.nvn; -end -if estim_params_.ncx - for i=1:estim_params_.ncx - k1 =estim_params_.corrx(i,1); - k2 =estim_params_.corrx(i,2); - Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2)); - Q(k2,k1) = Q(k1,k2); - end - [CholQ,testQ] = chol(Q); - if testQ %% The variance-covariance matrix of the structural innovations is not definite positive. - %% We have to compute the eigenvalues of this matrix in order to build the penalty. - a = diag(eig(Q)); - k = find(a < 0); - if k > 0 - fval = bayestopt_.penalty+sum(-a(k)); - cost_flag = 0; - info = 43; - return - end - end - offset = offset+estim_params_.ncx; -end -if estim_params_.ncn - for i=1:estim_params_.ncn - k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1)); - k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2)); - H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2)); - H(k2,k1) = H(k1,k2); - end - [CholH,testH] = chol(H); - if testH - a = diag(eig(H)); - k = find(a < 0); - if k > 0 - fval = bayestopt_.penalty+sum(-a(k)); - cost_flag = 0; - info = 44; - return - end - end - offset = offset+estim_params_.ncn; -end -if estim_params_.np > 0 - M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end); -end -M_.Sigma_e = Q; -M_.H = H; -%------------------------------------------------------------------------------ -% 2. call model setup & reduction program -%------------------------------------------------------------------------------ -[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,... - bayestopt_.restrict_columns,... - bayestopt_.restrict_aux); -if info(1) == 1 || info(1) == 2 || info(1) == 5 - fval = bayestopt_.penalty+1; - cost_flag = 0; - return -elseif info(1) == 3 || info(1) == 4 || info(1)==6 ||info(1) == 19 || info(1) == 20 || info(1) == 21 - fval = bayestopt_.penalty+info(2); - cost_flag = 0; - return -end -bayestopt_.mf = bayestopt_.mf1; -if options_.noconstant - constant = zeros(nobs,1); -else - if options_.loglinear - constant = log(SteadyState(bayestopt_.mfys)); - else - constant = SteadyState(bayestopt_.mfys); - end -end -if bayestopt_.with_trend - trend_coeff = zeros(nobs,1); - t = options_.trend_coeffs; - for i=1:length(t) - if ~isempty(t{i}) - trend_coeff(i) = evalin('base',t{i}); - end - end - trend = repmat(constant,1,gend)+trend_coeff*[1:gend]; -else - trend = repmat(constant,1,gend); -end -start = options_.presample+1; -np = size(T,1); -mf = bayestopt_.mf; -no_missing_data_flag = (number_of_observations==gend*nobs); -%------------------------------------------------------------------------------ -% 3. Initial condition of the Kalman filter -%------------------------------------------------------------------------------ -T -R -Q -R*Q*R' -pause -options_.lik_init = 1; -kalman_algo = options_.kalman_algo; -if options_.lik_init == 1 % Kalman filter - if kalman_algo ~= 2 - kalman_algo = 1; - end - Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold); - Pinf = []; -elseif options_.lik_init == 2 % Old Diffuse Kalman filter - if kalman_algo ~= 2 - kalman_algo = 1; - end - Pstar = options_.Harvey_scale_factor*eye(np); - Pinf = []; -elseif options_.lik_init == 3 % Diffuse Kalman filter - if kalman_algo ~= 4 - kalman_algo = 3; - end - [QT,ST] = schur(T); - e1 = abs(ordeig(ST)) > 2-options_.qz_criterium; - [QT,ST] = ordschur(QT,ST,e1); - k = find(abs(ordeig(ST)) > 2-options_.qz_criterium); - nk = length(k); - nk1 = nk+1; - Pinf = zeros(np,np); - Pinf(1:nk,1:nk) = eye(nk); - Pstar = zeros(np,np); - B = QT'*R*Q*R'*QT; - for i=np:-1:nk+2 - if ST(i,i-1) == 0 - if i == np - c = zeros(np-nk,1); - else - c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... - ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); - end - q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i); - Pstar(nk1:i,i) = q\(B(nk1:i,i)+c); - Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; - else - if i == np - c = zeros(np-nk,1); - c1 = zeros(np-nk,1); - else - c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+... - ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+... - ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1); - c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+... - ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+... - ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i); - end - q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);... - -ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)]; - z = q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1]; - Pstar(nk1:i,i) = z(1:(i-nk)); - Pstar(nk1:i,i-1) = z(i-nk+1:end); - Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)'; - Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)'; - i = i - 1; - end - end - if i == nk+2 - c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1); - Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1)); - end - Z = QT(mf,:); - R1 = QT'*R; - [QQ,RR,EE] = qr(Z*ST(:,1:nk),0); - k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8); - if length(k) > 0 - k1 = EE(:,k); - dd =ones(nk,1); - dd(k1) = zeros(length(k1),1); - Pinf(1:nk,1:nk) = diag(dd); - end -end -if kalman_algo == 2 -end -kalman_tol = options_.kalman_tol; -riccati_tol = options_.riccati_tol; -mf = bayestopt_.mf1; -Y = data-trend; -Pstar -pause -%------------------------------------------------------------------------------ -% 4. Likelihood evaluation -%------------------------------------------------------------------------------ -if (kalman_algo==1)% Multivariate Kalman Filter - if no_missing_data_flag - LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol); - else - LIK = ... - missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ... - data_index,number_of_observations,no_more_missing_observations); - end - if isinf(LIK) - kalman_algo = 2; - end -end -if (kalman_algo==2)% Univariate Kalman Filter - no_correlation_flag = 1; - if length(H)==1 & H == 0 - H = zeros(nobs,1); - else - if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... - H = diag(H); - else - no_correlation_flag = 0; - end - end - if no_correlation_flag - LIK = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); - else - LIK = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations); - end -end -if (kalman_algo==3)% Multivariate Diffuse Kalman Filter - if no_missing_data_flag - LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol, ... - riccati_tol); - else - LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf, ... - Pstar,Y,start,Z,kalman_tol,riccati_tol,... - data_index,number_of_observations,... - no_more_missing_observations); - end - if isinf(LIK) - kalman_algo = 4; - end -end -if (kalman_algo==4)% Univariate Diffuse Kalman Filter - no_correlation_flag = 1; - if length(H)==1 & H == 0 - H = zeros(nobs,1); - else - if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal... - H = diag(H); - else - no_correlation_flag = 0; - end - end - if no_correlation_flag - LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y, ... - start,Z,kalman_tol,riccati_tol,data_index,... - number_of_observations,no_more_missing_observations); - else - LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar, ... - Y,start,Z,kalman_tol,riccati_tol,... - data_index,number_of_observations,... - no_more_missing_observations); - end -end -if isnan(LIK) - cost_flag = 0; - return -end -if imag(LIK)~=0 - likelihood = bayestopt_.penalty; -else - likelihood = LIK; -end -% ------------------------------------------------------------------------------ -% Adds prior if necessary -% ------------------------------------------------------------------------------ -lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4); -fval = (likelihood-lnprior); -likelihood -lnprior -fval -pause -LIKDLL=logposterior(xparam1,Y,mexext) -pause -options_.kalman_algo = kalman_algo; diff --git a/mex/sources/estimation/tests/Makefile.am b/mex/sources/estimation/tests/Makefile.am deleted file mode 100644 index 8ba8b7a84..000000000 --- a/mex/sources/estimation/tests/Makefile.am +++ /dev/null @@ -1,24 +0,0 @@ -check_PROGRAMS = test-dr testModelSolution testInitKalman testKalman testPDF - -test_dr_SOURCES = ../libmat/Matrix.cc ../libmat/Vector.cc ../libmat/QRDecomposition.cc ../libmat/GeneralizedSchurDecomposition.cc ../libmat/LUSolver.cc ../DecisionRules.cc test-dr.cc -test_dr_LDADD = $(LAPACK_LIBS) $(BLAS_LIBS) $(LIBS) $(FLIBS) -test_dr_CPPFLAGS = -I.. -I../libmat -I../../ - -testModelSolution_SOURCES = ../libmat/Matrix.cc ../libmat/Vector.cc ../libmat/QRDecomposition.cc ../libmat/GeneralizedSchurDecomposition.cc ../libmat/LUSolver.cc ../utils/dynamic_dll.cc ../DecisionRules.cc ../ModelSolution.cc testModelSolution.cc -testModelSolution_LDADD = $(LAPACK_LIBS) $(BLAS_LIBS) $(LIBS) $(FLIBS) $(LIBADD_DLOPEN) -testModelSolution_CPPFLAGS = -I.. -I../libmat -I../../ -I../utils - -testInitKalman_SOURCES = ../libmat/Matrix.cc ../libmat/Vector.cc ../libmat/QRDecomposition.cc ../libmat/GeneralizedSchurDecomposition.cc ../libmat/LUSolver.cc ../utils/dynamic_dll.cc ../DecisionRules.cc ../ModelSolution.cc ../InitializeKalmanFilter.cc ../DetrendData.cc testInitKalman.cc -testInitKalman_LDADD = $(LAPACK_LIBS) $(BLAS_LIBS) $(LIBS) $(FLIBS) $(LIBADD_DLOPEN) -testInitKalman_CPPFLAGS = -I.. -I../libmat -I../../ -I../utils - -testKalman_SOURCES = ../libmat/Matrix.cc ../libmat/Vector.cc ../libmat/QRDecomposition.cc ../libmat/GeneralizedSchurDecomposition.cc ../libmat/LUSolver.cc ../utils/dynamic_dll.cc ../DecisionRules.cc ../ModelSolution.cc ../InitializeKalmanFilter.cc ../DetrendData.cc ../KalmanFilter.cc testKalman.cc -testKalman_LDADD = $(LAPACK_LIBS) $(BLAS_LIBS) $(LIBS) $(FLIBS) $(LIBADD_DLOPEN) -testKalman_CPPFLAGS = -I.. -I../libmat -I../../ -I../utils - -testPDF_SOURCES = ../Prior.cc ../Prior.hh testPDF.cc -testPDF_CPPFLAGS = -I.. - -check-local: - ./test-dr - ./testPDF diff --git a/mex/sources/estimation/tests/fs2000k2e.mod b/mex/sources/estimation/tests/fs2000k2e.mod deleted file mode 100644 index 88cb3136f..000000000 --- a/mex/sources/estimation/tests/fs2000k2e.mod +++ /dev/null @@ -1,77 +0,0 @@ -/* Checks that, for order = 2, k_order_solver = 0 (fs2000k2a) - and k_order_solver = 1 (this file) give the same results */ - -var m P c e W R k d n l gy_obs gp_obs y dA ; -varexo e_a e_m; - -parameters alp bet gam mst rho psi del; - -alp = 0.33; -bet = 0.99; -gam = 0.003; -mst = 1.011; -rho = 0.7; -psi = 0.787; -del = 0.02; - -model (use_dll); -dA = exp(gam+e_a); -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; -W = l/n; --(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; -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; -c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1); -P*c = m; -m-1+d = l; -e = exp(e_a); -y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a)); -gy_obs = dA*y/y(-1); -gp_obs = (P/P(-1))*m(-1)/dA; -end; - -initval; -m = mst; -P = 2.25; -c = 0.45; -e = 1; -W = 4; -R = 1.02; -k = 6; -d = 0.85; -n = 0.19; -l = 0.86; -y = 0.6; -gy_obs = exp(gam); -gp_obs = exp(-gam); -dA = exp(gam); -end; - -shocks; -var e_a; stderr 0.014; -var e_m; stderr 0.005; -end; - -steady; - - -estimated_params; -alp, beta_pdf, 0.356, 0.02; -bet, beta_pdf, 0.993, 0.002; -gam, normal_pdf, 0.0085, 0.003; -mst, normal_pdf, 1.0002, 0.007; -rho, beta_pdf, 0.129, 0.223; -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; -end; - -varobs gp_obs gy_obs; - -//estimation(datafile=fsdat,nobs=192,loglinear,mh_replic=2000, -// mode_compute=4,mh_nblocks=2,mh_drop=0.45,mh_jscale=0.65); -estimation(datafile=fsdat,nobs=192,mh_replic=2000, - mode_compute=4,mh_nblocks=2,mh_drop=0.45,mh_jscale=0.65); - diff --git a/mex/sources/estimation/tests/logposterior_dll_test/random_walk_metropolis_hastings_core.m b/mex/sources/estimation/tests/logposterior_dll_test/random_walk_metropolis_hastings_core.m deleted file mode 100644 index 9dd8fc772..000000000 --- a/mex/sources/estimation/tests/logposterior_dll_test/random_walk_metropolis_hastings_core.m +++ /dev/null @@ -1,285 +0,0 @@ -function myoutput = random_walk_metropolis_hastings_core(myinputs,fblck,nblck,whoiam, ThisMatlab) -% PARALLEL CONTEXT -% This function contain the most computationally intensive portion of code in -% random_walk_metropolis_hastings (the 'for xxx = fblck:nblck' loop). The branches in 'for' -% cycle and are completely independent than suitable to be executed in parallel way. -% -% INPUTS -% o myimput [struc] The mandatory variables for local/remote -% parallel computing obtained from random_walk_metropolis_hastings.m -% function. -% o fblck and nblck [integer] The Metropolis-Hastings chains. -% o whoiam [integer] In concurrent programming a modality to refer to the differents thread running in parallel is needed. -% The integer whoaim is the integer that -% allows us to distinguish between them. Then it is the index number of this CPU among all CPUs in the -% cluster. -% o ThisMatlab [integer] Allows us to distinguish between the -% 'main' matlab, the slave matlab worker, local matlab, remote matlab, -% ... Then it is the index number of this slave machine in the cluster. -% OUTPUTS -% o myoutput [struc] -% If executed without parallel is the original output of 'for b = -% fblck:nblck' otherwise a portion of it computed on a specific core or -% remote machine. In this case: -% record; -% irun; -% NewFile; -% OutputFileName -% -% ALGORITHM -% Portion of Metropolis-Hastings. -% -% SPECIAL REQUIREMENTS. -% None. - -% PARALLEL CONTEXT -% The most computationally intensive part of this function may be executed -% in parallel. The code sutable to be executed in parallel on multi core or cluster machine, -% is removed from this function and placed in random_walk_metropolis_hastings_core.m funtion. -% Then the DYNARE parallel package contain a set of pairs matlab functios that can be executed in -% parallel and called name_function.m and name_function_core.m. -% In addition in the parallel package we have second set of functions used -% to manage the parallel computation. -% -% This function was the first function to be parallelized, later other -% functions have been parallelized using the same methodology. -% Then the comments write here can be used for all the other pairs of -% parallel functions and also for management funtions. - - -% Copyright (C) 2006-2010 Dynare Team -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see . - -if nargin<4, - whoiam=0; -end - - -global bayestopt_ estim_params_ options_ M_ oo_ - -% reshape 'myinputs' for local computation. -% In order to avoid confusion in the name space, the instruction struct2local(myinputs) is replaced by: - -TargetFun=myinputs.TargetFun; -ProposalFun=myinputs.ProposalFun; -xparam1=myinputs.xparam1; -vv=myinputs.vv; -mh_bounds=myinputs.mh_bounds; -ix2=myinputs.ix2; -ilogpo2=myinputs.ilogpo2; -ModelName=myinputs.ModelName; -fline=myinputs.fline; -npar=myinputs.npar; -nruns=myinputs.nruns; -NewFile=myinputs.NewFile; -MAX_nruns=myinputs.MAX_nruns; -d=myinputs.d; -InitSizeArray=myinputs.InitSizeArray; -record=myinputs.record; -varargin=myinputs.varargin; - -% Necessary only for remote computing! -if whoiam - Parallel=myinputs.Parallel; - % initialize persistent variables in priordens() - priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7, ... - bayestopt_.p3,bayestopt_.p4,1); -end - -% (re)Set the penalty -bayestopt_.penalty = Inf; - -MhDirectoryName = CheckPath('metropolis'); - -options_.lik_algo = 1; -OpenOldFile = ones(nblck,1); -if strcmpi(ProposalFun,'rand_multivariate_normal') - n = npar; -elseif strcmpi(ProposalFun,'rand_multivariate_student') - n = options_.student_degrees_of_freedom; -end -% load([MhDirectoryName '/' ModelName '_mh_history.mat'],'record'); -%%%% -%%%% NOW i run the (nblck-fblck+1) metropolis-hastings chains -%%%% - - -if any(isnan(bayestopt_.jscale)) - if exist([ModelName '_optimal_mh_scale_parameter.mat'])% This file is created by mode_compute=6. - load([ModelName '_optimal_mh_scale_parameter']) - proposal_covariance = d*Scale; - else - error('mh:: Something is wrong. I can''t figure out the value of the scale parameter.') - end -else - proposal_covariance = d*diag(bayestopt_.jscale); -end - - -jloop=0; - -for b = fblck:nblck, - jloop=jloop+1; - randn('state',record.Seeds(b).Normal); - rand('state',record.Seeds(b).Unifor); - if (options_.load_mh_file~=0) & (fline(b)>1) & OpenOldFile(b) - load(['./' MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) ... - '_blck' int2str(b) '.mat']) - x2 = [x2;zeros(InitSizeArray(b)-fline(b)+1,npar)]; - logpo2 = [logpo2;zeros(InitSizeArray(b)-fline(b)+1,1)]; - OpenOldFile(b) = 0; - else - x2 = zeros(InitSizeArray(b),npar); - logpo2 = zeros(InitSizeArray(b),1); - end - if exist('OCTAVE_VERSION') || options_.console_mode - diary off - disp(' ') - elseif whoiam - % keyboard; - waitbarString = ['Please wait... Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']; - % waitbarTitle=['Metropolis-Hastings ',options_.parallel(ThisMatlab).ComputerName]; - if options_.parallel(ThisMatlab).Local, - waitbarTitle=['Local ']; - else - waitbarTitle=[options_.parallel(ThisMatlab).ComputerName]; - end - fMessageStatus(0,whoiam,waitbarString, waitbarTitle, options_.parallel(ThisMatlab)); - else, - hh = waitbar(0,['Please wait... Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']); - set(hh,'Name','Metropolis-Hastings'); - - end - isux = 0; - jsux = 0; - irun = fline(b); - j = 1; - while j <= nruns(b) - par = feval(ProposalFun, ix2(b,:), proposal_covariance, n); - if all( par(:) > mh_bounds(:,1) ) & all( par(:) < mh_bounds(:,2) ) - try - logpost = - feval(TargetFun, par(:),varargin{:}); - catch - logpost = -inf; - end - % testing logposterior DLL - [junk,logpost1] = logposterior(par(:),varargin{2},mexext); - if abs(logpost+logpost1) > 1e-10; - disp ([logpost -logpost1]) - end - else - logpost = -inf; - end - if (logpost > -inf) && (log(rand) < logpost-ilogpo2(b)) - x2(irun,:) = par; - ix2(b,:) = par; - logpo2(irun) = logpost; - ilogpo2(b) = logpost; - isux = isux + 1; - jsux = jsux + 1; - else - x2(irun,:) = ix2(b,:); - logpo2(irun) = ilogpo2(b); - end - prtfrc = j/nruns(b); - if exist('OCTAVE_VERSION') || options_.console_mode - if mod(j, 10) == 0 - if exist('OCTAVE_VERSION') - printf('MH: Computing Metropolis-Hastings (chain %d/%d): %3.f%% done, acception rate: %3.f%%\r', b, nblck, 100 * prtfrc, 100 * isux / j); - else - fprintf(' MH: Computing Metropolis-Hastings (chain %d/%d): %3.f \b%% done, acceptance rate: %3.f \b%%\r', b, nblck, 100 * prtfrc, 100 * isux / j); - end - end - if mod(j,50)==0 & whoiam - % keyboard; - waitbarString = [ '(' int2str(b) '/' int2str(options_.mh_nblck) '), ' sprintf('accept. %3.f%%%%', 100 * isux/j)]; - fMessageStatus(prtfrc,whoiam,waitbarString, '', options_.parallel(ThisMatlab)); - end - else - if mod(j, 3)==0 & ~whoiam - waitbar(prtfrc,hh,[ '(' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]); - elseif mod(j,50)==0 & whoiam, - % keyboard; - waitbarString = [ '(' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]; - fMessageStatus(prtfrc,whoiam,waitbarString, waitbarTitle, options_.parallel(ThisMatlab)); - end - end - - if (irun == InitSizeArray(b)) | (j == nruns(b)) % Now I save the simulations - save([MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) '_blck' int2str(b) '.mat'],'x2','logpo2'); - fidlog = fopen([MhDirectoryName '/metropolis.log'],'a'); - fprintf(fidlog,['\n']); - fprintf(fidlog,['%% Mh' int2str(NewFile(b)) 'Blck' int2str(b) ' (' datestr(now,0) ')\n']); - fprintf(fidlog,' \n'); - fprintf(fidlog,[' Number of simulations.: ' int2str(length(logpo2)) '\n']); - fprintf(fidlog,[' Acceptation rate......: ' num2str(jsux/length(logpo2)) '\n']); - fprintf(fidlog,[' Posterior mean........:\n']); - for i=1:length(x2(1,:)) - fprintf(fidlog,[' params:' int2str(i) ': ' num2str(mean(x2(:,i))) '\n']); - end - fprintf(fidlog,[' log2po:' num2str(mean(logpo2)) '\n']); - fprintf(fidlog,[' Minimum value.........:\n']);; - for i=1:length(x2(1,:)) - fprintf(fidlog,[' params:' int2str(i) ': ' num2str(min(x2(:,i))) '\n']); - end - fprintf(fidlog,[' log2po:' num2str(min(logpo2)) '\n']); - fprintf(fidlog,[' Maximum value.........:\n']); - for i=1:length(x2(1,:)) - fprintf(fidlog,[' params:' int2str(i) ': ' num2str(max(x2(:,i))) '\n']); - end - fprintf(fidlog,[' log2po:' num2str(max(logpo2)) '\n']); - fprintf(fidlog,' \n'); - fclose(fidlog); - jsux = 0; - if j == nruns(b) % I record the last draw... - record.LastParameters(b,:) = x2(end,:); - record.LastLogLiK(b) = logpo2(end); - end - % size of next file in chain b - InitSizeArray(b) = min(nruns(b)-j,MAX_nruns); - % initialization of next file if necessary - if InitSizeArray(b) - x2 = zeros(InitSizeArray(b),npar); - logpo2 = zeros(InitSizeArray(b),1); - NewFile(b) = NewFile(b) + 1; - irun = 0; - end - end - j=j+1; - irun = irun + 1; - end% End of the simulations for one mh-block. - record.AcceptationRates(b) = isux/j; - if exist('OCTAVE_VERSION') || options_.console_mode - if exist('OCTAVE_VERSION') - printf('\n'); - else - fprintf('\n'); - end - diary on; - elseif ~whoiam - close(hh); - end - record.Seeds(b).Normal = randn('state'); - record.Seeds(b).Unifor = rand('state'); - OutputFileName(jloop,:) = {[MhDirectoryName,filesep], [ModelName '_mh*_blck' int2str(b) '.mat']}; -end% End of the loop over the mh-blocks. - - -myoutput.record = record; -myoutput.irun = irun; -myoutput.NewFile = NewFile; -myoutput.OutputFileName = OutputFileName; \ No newline at end of file diff --git a/mex/sources/estimation/tests/logposterior_dll_test/rawdata_euromodel_1.m b/mex/sources/estimation/tests/logposterior_dll_test/rawdata_euromodel_1.m deleted file mode 100644 index 6b9fee720..000000000 --- a/mex/sources/estimation/tests/logposterior_dll_test/rawdata_euromodel_1.m +++ /dev/null @@ -1,967 +0,0 @@ -C =[ - -7.4073 - -6.1860 - -6.5983 - -5.6088 - -5.0547 - -4.4774 - -3.8081 - -3.8425 - -2.4178 - -1.9835 - -1.0395 - -0.1583 - -0.0397 - 0.3505 - -0.1879 - -0.0067 - 0.0478 - -1.2247 - -1.4349 - -0.7973 - -0.0461 - 0.5844 - 1.1372 - 1.3801 - 1.8023 - 2.2972 - 2.0469 - 2.5435 - 2.8169 - 3.2007 - 2.6705 - 3.0518 - 3.2445 - 3.8443 - 3.8525 - 4.9494 - 4.2770 - 4.9532 - 5.1441 - 3.7124 - 3.9880 - 3.6926 - 2.6005 - 1.8679 - 1.9085 - 1.5563 - 1.2308 - 0.3264 - -0.2208 - -0.2483 - -0.4082 - -1.0315 - -1.6030 - -1.5499 - -1.3777 - -2.1675 - -2.5138 - -2.8820 - -2.6958 - -2.4719 - -1.9854 - -1.7954 - -2.2362 - -1.0595 - -0.8808 - -0.8548 - -1.2839 - -0.1363 - 0.2104 - 0.8810 - 0.3555 - 0.4766 - 1.3269 - 1.4506 - 1.4308 - 1.6263 - 1.9842 - 2.3948 - 2.8710 - 3.0177 - 2.9305 - 3.1739 - 3.7380 - 3.8285 - 3.3342 - 3.7447 - 3.7830 - 3.1039 - 2.8413 - 3.0338 - 0.3669 - 0.0847 - 0.0104 - 0.2115 - -0.6649 - -0.9625 - -0.7330 - -0.8664 - -1.4441 - -1.0179 - -1.2729 - -1.9539 - -1.4427 - -2.0371 - -1.9764 - -2.5654 - -2.8570 - -2.5842 - -3.0427 - -2.8312 - -2.3320 - -2.2768 - -2.1816 - -2.1043 - -1.8969 - -2.2388 - -2.1679 - -2.1172 - ]; - -E =[ - 0.6263 - 0.7368 - 0.7477 - 1.0150 - 0.6934 - 0.4135 - 0.3845 - 0.2380 - 0.2853 - 0.5999 - 0.8622 - 1.2116 - 1.4921 - 1.5816 - 1.7259 - 1.6276 - 1.2422 - 0.8084 - 0.4710 - -0.3704 - -0.6427 - -0.5323 - -0.5562 - -0.3651 - -0.4356 - -0.7164 - -0.5816 - -0.4635 - -0.8456 - -0.9708 - -0.7138 - -0.7499 - -0.6941 - -0.6656 - -0.2912 - -0.1650 - 0.0774 - 0.2307 - 0.4484 - 0.4942 - 0.4653 - 0.2196 - 0.1736 - -0.1595 - -0.3918 - -0.4611 - -0.8493 - -0.7384 - -1.0604 - -1.2166 - -1.7187 - -1.6932 - -1.7830 - -1.7035 - -2.2079 - -2.3769 - -2.2511 - -2.1093 - -2.4638 - -2.4027 - -2.1313 - -1.9199 - -1.7941 - -1.4661 - -1.2269 - -1.0392 - -1.0725 - -0.7156 - -0.4778 - -0.4233 - -0.0409 - 0.1620 - 0.4280 - 0.5873 - 1.0323 - 1.3420 - 1.6902 - 2.0680 - 2.8219 - 3.2511 - 3.2930 - 3.5633 - 3.8992 - 3.6874 - 3.2849 - 3.1614 - 2.6221 - 2.5067 - 1.9223 - 1.1777 - 0.4483 - -0.0661 - -0.4424 - -0.9000 - -1.1478 - -1.2047 - -1.1412 - -1.2383 - -1.1048 - -0.9716 - -0.9287 - -1.0057 - -1.0827 - -1.0200 - -1.0072 - -1.1740 - -1.2809 - -1.1086 - -0.9866 - -0.8947 - -0.5875 - -0.2329 - 0.1493 - 0.4906 - 0.8400 - 1.0720 - 1.2648 - 1.5431 - ]; - -I =[ - 2.6617 - 2.4325 - 1.9592 - 3.2530 - 2.9949 - 3.7918 - 4.7444 - 4.8289 - 5.5983 - 7.8923 - 9.4297 - 9.5010 - 10.0150 - 10.0413 - 9.6046 - 6.4766 - 5.9647 - 3.0114 - 0.5683 - -2.1226 - -2.1855 - -0.8329 - -1.5207 - -1.3419 - -1.7897 - -0.1476 - 0.4675 - -1.6516 - -1.5419 - -1.3050 - -1.2451 - -0.7815 - -0.7796 - -0.3612 - -2.4072 - 1.1162 - 1.1383 - 3.4132 - 5.0356 - 2.8016 - 2.1734 - 0.9366 - -0.7050 - -1.5021 - -2.9868 - -6.0237 - -6.2589 - -6.9138 - -8.2340 - -9.2589 - -9.2465 - -9.6988 - -9.7782 - -10.5645 - -10.7544 - -13.1583 - -12.2718 - -12.0131 - -13.5983 - -12.3579 - -10.9146 - -11.1572 - -12.4935 - -9.4393 - -8.5535 - -7.3723 - -10.0169 - -6.6088 - -5.2045 - -4.1024 - -2.8472 - -1.3139 - 0.0477 - 1.5629 - 3.6947 - 4.0327 - 4.1320 - 7.1400 - 9.1036 - 8.5609 - 7.6576 - 8.8022 - 8.9611 - 10.0871 - 9.4797 - 9.3964 - 10.0363 - 8.6340 - 6.6522 - 4.4471 - 0.2854 - -2.1879 - -2.9879 - -4.1021 - -2.7713 - -2.2281 - -1.2908 - -0.3250 - 0.6534 - 0.3942 - 0.3534 - -0.1532 - -1.7936 - 0.4909 - 0.3634 - 0.4290 - -0.9709 - 0.1942 - 0.6103 - 1.4426 - 2.7225 - 1.7525 - 3.2780 - 3.5985 - 4.9011 - 5.3312 - 6.4402 - 6.6529 - ]; - -L =[ - 0.6263 - 0.7368 - 0.7477 - 1.0150 - 0.6934 - 0.4135 - 0.3845 - 0.2380 - 0.2853 - 0.5999 - 0.8622 - 1.2116 - 1.4921 - 1.5816 - 1.7259 - 1.6276 - 1.2422 - 0.8084 - 0.4710 - -0.3704 - -0.6427 - -0.5323 - -0.5562 - -0.3651 - -0.4356 - -0.7164 - -0.5816 - -0.4635 - -0.8456 - -0.9708 - -0.7138 - -0.7499 - -0.6941 - -0.6656 - -0.2912 - -0.1650 - 0.0774 - 0.2307 - 0.4484 - 0.4942 - 0.4653 - 0.2196 - 0.1736 - -0.1595 - -0.3918 - -0.4611 - -0.8493 - -0.7384 - -1.0604 - -1.2166 - -1.7187 - -1.6932 - -1.7830 - -1.7035 - -2.2079 - -2.3769 - -2.2511 - -2.1093 - -2.4638 - -2.4027 - -2.1313 - -1.9199 - -1.7941 - -1.4661 - -1.2269 - -1.0392 - -1.0725 - -0.7156 - -0.4778 - -0.4233 - -0.0409 - 0.1620 - 0.4280 - 0.5873 - 1.0323 - 1.3420 - 1.6902 - 2.0680 - 2.8219 - 3.2511 - 3.2930 - 3.5633 - 3.8992 - 3.6874 - 3.2849 - 3.1614 - 2.6221 - 2.5067 - 1.9223 - 1.1777 - 0.4483 - -0.0661 - -0.4424 - -0.9000 - -1.1478 - -1.2047 - -1.1412 - -1.2383 - -1.1048 - -0.9716 - -0.9287 - -1.0057 - -1.0827 - -1.0200 - -1.0072 - -1.1740 - -1.2809 - -1.1086 - -0.9866 - -0.8947 - -0.5875 - -0.2329 - 0.1493 - 0.4906 - 0.8400 - 1.0720 - 1.2648 - 1.5431 - ]; - -PIE =[ - -1.0113 - -0.8305 - 0.2332 - -0.8746 - -0.7978 - -0.9220 - -0.2487 - -0.7749 - -0.5460 - -0.5347 - 0.5050 - -0.0334 - 0.6756 - 0.8791 - 0.7267 - 1.0997 - 1.1750 - 1.1927 - 0.4420 - 0.5357 - 0.0345 - 0.0196 - 0.3371 - 0.9379 - 1.2160 - 0.3393 - 0.5813 - 0.7410 - 0.3374 - 0.2616 - 0.4025 - 0.4799 - 0.5981 - -0.1523 - 0.4458 - 0.2182 - 0.9793 - 0.7562 - 1.0064 - 0.8203 - 0.6966 - 0.3352 - 0.6581 - 0.6111 - 0.9833 - 1.1991 - 0.9562 - 0.3868 - 0.2939 - 0.2471 - 0.8331 - 0.0715 - 0.3910 - 0.3301 - 0.2547 - -0.2702 - -0.2998 - -0.1953 - -0.2293 - -0.3284 - 0.0480 - -0.0374 - 0.3253 - -0.3434 - -0.3892 - -0.7178 - -0.4758 - -0.6794 - -0.8505 - -0.3512 - -0.4436 - -0.5101 - -0.4574 - -0.2696 - -0.1047 - -0.5745 - -0.2989 - -0.0063 - 0.0088 - -0.1184 - -0.1506 - -0.4073 - 0.2674 - 0.2896 - 0.0669 - 0.1166 - -0.1699 - -0.2518 - -0.0562 - -0.3269 - -0.0703 - -0.1046 - -0.4888 - -0.3524 - -0.2485 - -0.5870 - -0.4546 - -0.3970 - -0.2353 - -0.0352 - -0.2171 - -0.3754 - -0.4322 - -0.4572 - -0.4903 - -0.4518 - -0.6435 - -0.6304 - -0.4148 - -0.2892 - -0.4318 - -0.6010 - -0.4148 - -0.4315 - -0.3531 - -0.8053 - -0.4680 - -0.4263 - ]; - -R =[ - -1.0750 - -1.1540 - -1.3682 - -1.4569 - -1.3490 - -1.4011 - -1.6486 - -1.6968 - -1.6976 - -1.2567 - -1.1392 - -0.7783 - -0.3021 - -0.0435 - 0.0066 - -0.0043 - 0.1029 - -0.0628 - -0.5358 - -0.9627 - -1.1079 - -1.0918 - -0.9966 - -0.6223 - -0.3616 - -0.2711 - -0.0997 - -0.2810 - -0.3710 - -0.3167 - -0.5301 - -0.5826 - -0.3194 - -0.2713 - -0.5287 - -0.2432 - 0.1098 - 0.5349 - 0.7094 - 0.8415 - 0.6226 - 0.7376 - 0.9316 - 1.4370 - 1.5853 - 1.4267 - 1.1783 - 1.2046 - 0.9689 - 0.7918 - 0.6315 - 0.5950 - 0.6853 - 0.7171 - 0.5887 - 0.4873 - 0.4027 - 0.3489 - 0.2934 - 0.3060 - 0.1741 - 0.0348 - 0.0771 - -0.1005 - -0.1518 - -0.1104 - -0.0681 - -0.0059 - 0.0256 - 0.0404 - -0.1721 - -0.2002 - 0.0015 - 0.1249 - 0.3738 - 0.4320 - 0.5579 - 0.8186 - 0.8727 - 0.7356 - 0.7243 - 0.8635 - 0.9058 - 0.7656 - 0.7936 - 0.8631 - 0.9074 - 0.9547 - 1.2045 - 1.0850 - 0.9178 - 0.5242 - 0.3178 - 0.1472 - 0.0227 - -0.0799 - -0.0611 - -0.0140 - 0.1132 - 0.1774 - 0.0782 - 0.0436 - -0.1596 - -0.2691 - -0.2895 - -0.3791 - -0.4020 - -0.4166 - -0.4037 - -0.3636 - -0.4075 - -0.4311 - -0.4470 - -0.5111 - -0.6274 - -0.7261 - -0.6974 - -0.5012 - ]; - -W =[ - -14.8791 - -13.2300 - -13.5037 - -13.0249 - -11.2546 - -10.0148 - -8.8586 - -8.5739 - -7.7851 - -6.7136 - -5.5878 - -4.6881 - -3.8039 - -3.0366 - -2.7342 - -1.3135 - -0.7387 - -0.1131 - -0.2769 - 0.8696 - 1.8855 - 2.3667 - 2.4942 - 3.2049 - 3.9682 - 5.1500 - 4.7047 - 4.7827 - 5.3377 - 5.6614 - 5.2813 - 5.2967 - 5.5175 - 6.1526 - 5.6627 - 6.0694 - 6.5824 - 6.9032 - 6.7849 - 6.6896 - 6.6201 - 6.9933 - 5.8959 - 6.7419 - 6.9999 - 6.4009 - 5.5083 - 5.1054 - 5.2813 - 4.5790 - 3.9589 - 3.8599 - 3.8978 - 2.7957 - 3.2480 - 1.4634 - 1.9219 - 1.8398 - 1.9279 - 1.8316 - 1.6092 - 1.2741 - 0.2031 - -0.0236 - -0.1004 - -0.3034 - -1.0273 - -0.2205 - 0.0458 - 0.2386 - -0.0977 - -0.3145 - -0.1416 - -0.7009 - -0.9082 - -0.8802 - -0.5644 - -0.5852 - -0.5346 - 0.0652 - 0.1301 - 0.3444 - -0.3592 - 0.8096 - 0.9644 - 1.0289 - 1.2781 - 1.2298 - 2.2134 - 2.0808 - 0.4925 - 0.6506 - 0.5531 - 0.2456 - -0.5351 - -0.8183 - -0.8967 - -0.7268 - -1.0738 - -1.2844 - -1.4338 - -1.6995 - -1.7085 - -2.2889 - -2.1018 - -2.4273 - -2.4609 - -2.1407 - -2.3847 - -3.1689 - -4.5581 - -4.1027 - -4.2436 - -4.8836 - -5.9660 - -4.9971 - -5.2386 - -5.6618 - ]; - -Y =[ - -4.9347 - -4.6205 - -5.2198 - -4.5937 - -3.8015 - -3.6643 - -2.7239 - -2.7524 - -2.0634 - -1.0112 - 0.0530 - 0.7623 - 1.7927 - 2.1486 - 2.4866 - 2.1456 - 2.1671 - -0.0254 - -1.6716 - -1.9673 - -1.6109 - -1.0292 - -0.1222 - 0.7329 - 1.1234 - 2.0603 - 1.7998 - 1.4820 - 1.1732 - 1.6424 - 1.5382 - 2.1399 - 2.0127 - 2.7210 - 2.4966 - 3.5249 - 3.6237 - 4.2011 - 4.5634 - 3.3442 - 2.7761 - 1.9812 - 1.3779 - 1.4616 - 1.3029 - 0.7594 - 0.3695 - 0.0832 - -0.8118 - -1.4557 - -1.4850 - -1.2346 - -1.5696 - -1.3785 - -0.7682 - -2.0308 - -1.7778 - -1.7801 - -2.1711 - -1.7469 - -1.3413 - -1.3352 - -2.4390 - -1.2125 - -1.1695 - -1.0891 - -2.4753 - -1.3503 - -0.9412 - -0.1470 - 0.0026 - 0.1108 - 0.6890 - 1.3520 - 1.6018 - 2.0667 - 1.7625 - 2.6658 - 3.4048 - 3.2507 - 3.4251 - 3.2174 - 3.1903 - 3.3396 - 3.1358 - 2.8625 - 3.3546 - 2.4609 - 1.9534 - 0.9962 - -0.7904 - -1.1672 - -1.2586 - -1.3593 - -1.3443 - -0.9413 - -0.6023 - -0.4516 - -0.5129 - -0.8741 - -1.0784 - -1.4091 - -1.3627 - -1.5731 - -1.6037 - -1.8814 - -2.1482 - -1.3597 - -1.1855 - -1.1122 - -0.8424 - -0.9747 - -1.1385 - -1.4548 - -1.4284 - -1.4633 - -1.0621 - -0.7871 - ]; diff --git a/mex/sources/estimation/tests/logposterior_dll_test/sweuromodel_dll.mod b/mex/sources/estimation/tests/logposterior_dll_test/sweuromodel_dll.mod deleted file mode 100644 index a6a19f55b..000000000 --- a/mex/sources/estimation/tests/logposterior_dll_test/sweuromodel_dll.mod +++ /dev/null @@ -1,184 +0,0 @@ -//options_.usePartInfo=1; - -var MC E EF R_KF QF CF IF YF LF PIEF WF RF R_K Q C I Y L PIE W R EE_A PIE_BAR EE_B EE_G EE_L EE_I KF K one BIGTHETA; - -varexo E_A E_B E_G E_L E_I ETA_R E_PIE_BAR ETA_Q ETA_P ETA_W ; - -parameters -xi_e lambda_w alpha czcap beta phi_i tau sig_c hab ccs cinvs phi_y gamma_w xi_w gamma_p xi_p sig_l r_dpi -r_pie r_dy r_y rho rho_a rho_pb rho_b rho_g rho_l rho_i LMP ; - - - -alpha=.30; -beta=.99; -tau=0.025; -ccs=0.6; -cinvs=.22; //% alpha*(tau+ctrend)/R_K R_K=ctrend/beta-1+tau -lambda_w = 0.5; -phi_i= 6.771; -sig_c= 1.353; -hab= 0.573; -xi_w= 0.737; -sig_l= 2.400; -xi_p= 0.908; -xi_e= 0.599; -gamma_w= 0.763; -gamma_p= 0.469; -czcap= 0.169; -phi_y= 1.408; -r_pie= 1.684; -r_dpi= 0.14; -rho= 0.961; -r_y= 0.099; -r_dy= 0.159; -rho_a= 0.823; -rho_b= 0.855; -rho_g= 0.949; -rho_l= 0.889; -rho_i= 0.927; -rho_pb= 0.924; -LMP = 0.0 ; //NEW. - -model(linear, use_dll); - CF = (1/(1+hab))*(CF(1)+hab*CF(-1))-((1-hab)/((1+hab)*sig_c))*(RF-PIEF(1)-EE_B) ; - 0 = alpha*R_KF+(1-alpha)*WF -EE_A ; - PIEF = 0*one; - IF = (1/(1+beta))* (( IF(-1) + beta*(IF(1)))+(1/phi_i)*QF)+0*ETA_Q+EE_I ; - QF = -(RF-PIEF(1))+(1-beta*(1-tau))*((0+czcap)/czcap)*R_KF(1)+beta*(1-tau)*QF(1) +0*EE_I ; - KF = (1-tau)*KF(-1)+tau*IF(-1) ; - YF = (ccs*CF+cinvs*IF)+EE_G ; - - YF = 1*phi_y*( alpha*KF+alpha*(1/czcap)*R_KF+(1-alpha)*LF+EE_A ) ; - WF = (sig_c/(1-hab))*(CF-hab*CF(-1)) + sig_l*LF - EE_L ; - LF = R_KF*((1+czcap)/czcap)-WF+KF ; - EF = EF(-1)+EF(1)-EF+(LF-EF)*((1-xi_e)*(1-xi_e*beta)/(xi_e)); - - C = (hab/(1+hab))*C(-1)+(1/(1+hab))*C(1)-((1-hab)/((1+hab)*sig_c))*(R-PIE(1)-EE_B) ; - I = (1/(1+beta))* (( I(-1) + beta*(I(1)))+(1/phi_i)*Q )+1*ETA_Q+1*EE_I ; - Q = -(R-PIE(1))+(1-beta*(1-tau))*((0+czcap)/czcap)*R_K(1)+beta*(1-tau)*Q(1) +EE_I*0+0*ETA_Q ; - K = (1-tau)*K(-1)+tau*I(-1) ; - Y = (ccs*C+cinvs*I)+ EE_G ; - Y = phi_y*( alpha*K+alpha*(1/czcap)*R_K+(1-alpha)*L ) +phi_y*EE_A ; - PIE = (1/(1+beta*gamma_p))* - ( - (beta)*(PIE(1)) +(gamma_p)*(PIE(-1)) - +((1-xi_p)*(1-beta*xi_p)/(xi_p))*(MC) - ) + ETA_P ; - - MC = alpha*R_K+(1-alpha)*W -EE_A; - W = (1/(1+beta))*(beta*W(+1)+W(-1)) - +(beta/(1+beta))*(PIE(+1)) - -((1+beta*gamma_w)/(1+beta))*(PIE) - +(gamma_w/(1+beta))*(PIE(-1)) - -(1/(1+beta))*(((1-beta*xi_w)*(1-xi_w))/(((1+(((1+lambda_w)*sig_l)/(lambda_w))))*xi_w))*(W-sig_l*L-(sig_c/(1-hab))*(C-hab*C(-1))+EE_L) - +ETA_W; - L = R_K*((1+czcap)/czcap)-W+K ; - -// R = r_dpi*(PIE-PIE(-1)) -// +(1-rho)*(r_pie*(PIE(-1)-PIE_BAR)+r_y*(Y-YF)) -// +r_dy*(Y-YF-(Y(-1)-YF(-1))) -// +rho*(R(-1)-PIE_BAR) -// +PIE_BAR -// +ETA_R; - - - R = - -r_dpi*(PIE-PIE(-1)) - - +(1-rho)*(r_pie*(BIGTHETA)+r_y*(Y-YF)) - +r_dy*(Y-YF-(Y(-1)-YF(-1))) - +rho*(R(-1)-PIE_BAR) - +PIE_BAR - +ETA_R; - - - E = E(-1)+E(1)-E+(L-E)*((1-xi_e)*(1-xi_e*beta)/(xi_e)); - - - EE_A = (rho_a)*EE_A(-1) + E_A; - PIE_BAR = rho_pb*PIE_BAR(-1)+ E_PIE_BAR ; - EE_B = rho_b*EE_B(-1) + E_B ; - EE_G = rho_g*EE_G(-1) + E_G ; - EE_L = rho_l*EE_L(-1) + E_L ; - EE_I = rho_i*EE_I(-1) + E_I ; - one = 0*one(-1) ; - - LMP*BIGTHETA(1) = BIGTHETA - (PIE(-1) - PIE_BAR) ; - -end; - - -shocks; -var E_A; stderr 0.598; -var E_B; stderr 0.336; -var E_G; stderr 0.325; -var E_I; stderr 0.085; -var E_L; stderr 3.520; -var ETA_P; stderr 0.160; -var ETA_W; stderr 0.289; -var ETA_R; stderr 0.081; -var ETA_Q; stderr 0.604; -var E_PIE_BAR; stderr 0.017; -end; - -//stoch_simul(irf=20) Y C PIE R W R_K L Q I K ; - -// stoch_simul generates what kind of standard errors for the shocks ? - -//steady; -//check; -//stoch_simul(periods=200,irf=20,simul_seed=3) Y C PIE MC R W R_K E L I ; - -//datatomfile('ddd',[]); - -// new syntax - -estimated_params; -// PARAM NAME, INITVAL, LB, UB, PRIOR_SHAPE, PRIOR_P1, PRIOR_P2, PRIOR_P3, PRIOR_P4, JSCALE -// PRIOR_SHAPE: BETA_PDF, GAMMA_PDF, NORMAL_PDF, INV_GAMMA_PDF -stderr E_A,0.543,0.01,4,INV_GAMMA_PDF,0.4,2; -stderr E_PIE_BAR,0.072,0.001,4,INV_GAMMA_PDF,0.02,10; -stderr E_B,0.2694,0.01,4,INV_GAMMA_PDF,0.2,2; -stderr E_G,0.3052,0.01,4,INV_GAMMA_PDF,0.3,2; -stderr E_L,1.4575,0.1,6,INV_GAMMA_PDF,1,2; -stderr E_I,0.1318,0.01,4,INV_GAMMA_PDF,0.1,2; -stderr ETA_R,0.1363,0.01,4,INV_GAMMA_PDF,0.1,2; -stderr ETA_Q,0.4842,0.01,4,INV_GAMMA_PDF,0.4,2; -stderr ETA_P,0.1731,0.01,4,INV_GAMMA_PDF,0.15,2; -stderr ETA_W,0.2462,0.1,4,INV_GAMMA_PDF,0.25,2; -rho_a,.9722,.1,.9999,BETA_PDF,0.85,0.1; -rho_pb,.85,.1,.999,BETA_PDF,0.85,0.1; -rho_b,.7647,.1,.99,BETA_PDF,0.85,0.1; -rho_g,.9502,.1,.9999,BETA_PDF,0.85,0.1; -rho_l,.9542,.1,.9999,BETA_PDF,0.85,0.1; -rho_i,.6705,.1,.99,BETA_PDF,0.85,0.1; -phi_i,5.2083,1,15,NORMAL_PDF,4,1.5; -sig_c,0.9817,0.25,3,NORMAL_PDF,1,0.375; -hab,0.5612,0.3,0.95,BETA_PDF,0.7,0.1; -xi_w,0.7661,0.3,0.9,BETA_PDF,0.75,0.05; -sig_l,1.7526,0.5,5,NORMAL_PDF,2,0.75; -xi_p,0.8684,0.3,0.95,BETA_PDF,0.75,0.05; -xi_e,0.5724,0.1,0.95,BETA_PDF,0.5,0.15; -gamma_w,0.6202,0.1,0.99,BETA_PDF,0.75,0.15; -gamma_p,0.6638,0.1,0.99,BETA_PDF,0.75,0.15; -czcap,0.2516,0.01,2,NORMAL_PDF,0.2,0.075; -phi_y,1.3011,1.001,2,NORMAL_PDF,1.45,0.125; -r_pie,1.4616,1.2,2,NORMAL_PDF,1.7,0.1; -r_dpi,0.1144,0.01,0.5,NORMAL_PDF,0.3,0.1; -rho,0.8865,0.5,0.99,BETA_PDF,0.8,0.10; -r_y,0.0571,0.01,0.2,NORMAL_PDF,0.125,0.05; -r_dy,0.2228,0.05,0.5,NORMAL_PDF,0.0625,0.05; -end; - -varobs Y C I E PIE W R; - -//estimation(datafile=rawdata_euromodel_1,presample=40, first_obs=1, nobs=118, lik_init=2, mode_compute=1,mh_replic=0); -estimation(datafile=rawdata_euromodel_1,presample=40, first_obs=1, nobs=118,mh_jscale=0.2,mh_replic=1000 -//,mode_compute=0,mode_file=sweuromodel_dll_mode -); - - -//stoch_simul(periods=200,irf=20,simul_seed=3) Y C PIE R W R_K L Q I K ; - diff --git a/mex/sources/estimation/tests/random_walk_metropolis_hastings_core.m b/mex/sources/estimation/tests/random_walk_metropolis_hastings_core.m deleted file mode 100644 index 5a6158612..000000000 --- a/mex/sources/estimation/tests/random_walk_metropolis_hastings_core.m +++ /dev/null @@ -1,309 +0,0 @@ -function myoutput = random_walk_metropolis_hastings_core(myinputs,fblck,nblck,whoiam, ThisMatlab) -% PARALLEL CONTEXT -% This function contain the most computationally intensive portion of code in -% random_walk_metropolis_hastings (the 'for xxx = fblck:nblck' loop). The branches in 'for' -% cycle and are completely independent than suitable to be executed in parallel way. -% -% INPUTS -% o myimput [struc] The mandatory variables for local/remote -% parallel computing obtained from random_walk_metropolis_hastings.m -% function. -% o fblck and nblck [integer] The Metropolis-Hastings chains. -% o whoiam [integer] In concurrent programming a modality to refer to the differents thread running in parallel is needed. -% The integer whoaim is the integer that -% allows us to distinguish between them. Then it is the index number of this CPU among all CPUs in the -% cluster. -% o ThisMatlab [integer] Allows us to distinguish between the -% 'main' matlab, the slave matlab worker, local matlab, remote matlab, -% ... Then it is the index number of this slave machine in the cluster. -% OUTPUTS -% o myoutput [struc] -% If executed without parallel is the original output of 'for b = -% fblck:nblck' otherwise a portion of it computed on a specific core or -% remote machine. In this case: -% record; -% irun; -% NewFile; -% OutputFileName -% -% ALGORITHM -% Portion of Metropolis-Hastings. -% -% SPECIAL REQUIREMENTS. -% None. - -% PARALLEL CONTEXT -% The most computationally intensive part of this function may be executed -% in parallel. The code sutable to be executed in parallel on multi core or cluster machine, -% is removed from this function and placed in random_walk_metropolis_hastings_core.m funtion. -% Then the DYNARE parallel package contain a set of pairs matlab functios that can be executed in -% parallel and called name_function.m and name_function_core.m. -% In addition in the parallel package we have second set of functions used -% to manage the parallel computation. -% -% This function was the first function to be parallelized, later other -% functions have been parallelized using the same methodology. -% Then the comments write here can be used for all the other pairs of -% parallel functions and also for management funtions. - - -% Copyright (C) 2006-2010 Dynare Team -% -% This file is part of Dynare. -% -% Dynare is free software: you can redistribute it and/or modify -% it under the terms of the GNU General Public License as published by -% the Free Software Foundation, either version 3 of the License, or -% (at your option) any later version. -% -% Dynare is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -% GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with Dynare. If not, see . - -if nargin<4, - whoiam=0; -end - - -global bayestopt_ estim_params_ options_ M_ oo_ - -% reshape 'myinputs' for local computation. -% In order to avoid confusion in the name space, the instruction struct2local(myinputs) is replaced by: - -TargetFun=myinputs.TargetFun; -ProposalFun=myinputs.ProposalFun; -xparam1=myinputs.xparam1; -vv=myinputs.vv; -mh_bounds=myinputs.mh_bounds; -ix2=myinputs.ix2; -ilogpo2=myinputs.ilogpo2; -ModelName=myinputs.ModelName; -fline=myinputs.fline; -npar=myinputs.npar; -nruns=myinputs.nruns; -NewFile=myinputs.NewFile; -MAX_nruns=myinputs.MAX_nruns; -d=myinputs.d; -InitSizeArray=myinputs.InitSizeArray; -record=myinputs.record; -varargin=myinputs.varargin; - -% Necessary only for remote computing! -if whoiam - Parallel=myinputs.Parallel; - MasterName=myinputs.MasterName; - DyMo=myinputs.DyMo; - % initialize persistent variables in priordens() - priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7, ... - bayestopt_.p3,bayestopt_.p4,1); -end - -% (re)Set the penalty -bayestopt_.penalty = Inf; - -MhDirectoryName = CheckPath('metropolis'); - -options_.lik_algo = 1; -OpenOldFile = ones(nblck,1); -if strcmpi(ProposalFun,'rand_multivariate_normal') - n = npar; -elseif strcmpi(ProposalFun,'rand_multivariate_student') - n = options_.student_degrees_of_freedom; -end -% load([MhDirectoryName '/' ModelName '_mh_history.mat'],'record'); -%%%% -%%%% NOW i run the (nblck-fblck+1) metropolis-hastings chains -%%%% -jscale = diag(bayestopt_.jscale); - -jloop=0; -if options_.use_dll==1 - - %%%TEST%%% - oldoptions_console_mode=options_.console_mode; - %options_.console_mode=1; - - if exist('OCTAVE_VERSION') - oldoptions_console_mode=options_.console_mode; - options_.console_mode=1; - end - for b = fblck:nblck, - record.Seeds(b).Normal = randn('state'); - record.Seeds(b).Unifor = rand('state'); - end - % calculate draws and get last line run in the last MH block sub-array - [err irun] = logMHMCMCposterior( xparam1, varargin{2}, mexext, fblck, nblck, nruns, vv) - mexErrCheck('logMHMCMCposterior',err); - if irun<0 - error('Error in logMHMCMCposterior'); - end - for b = fblck:nblck, - record.Seeds(b).Normal = randn('state'); - record.Seeds(b).Unifor = rand('state'); - OutputFileName(b,:) = {[MhDirectoryName,filesep], [ModelName '_mh*_blck' int2str(b) '.mat']}; - end - - if exist('OCTAVE_VERSION') - options_.console_mode=oldoptions_console_mode; - options_.console_mode=1; - end - record.AcceptationRates=record_AcceptationRates; - record.LastLogLiK=record_LastLogLiK; - record.LastParameters=record_LastParameters; - options_.console_mode=oldoptions_console_mode; -else - for b = fblck:nblck, - jloop=jloop+1; - randn('state',record.Seeds(b).Normal); - rand('state',record.Seeds(b).Unifor); - if (options_.load_mh_file~=0) & (fline(b)>1) & OpenOldFile(b) - load(['./' MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) ... - '_blck' int2str(b) '.mat']) - x2 = [x2;zeros(InitSizeArray(b)-fline(b)+1,npar)]; - logpo2 = [logpo2;zeros(InitSizeArray(b)-fline(b)+1,1)]; - OpenOldFile(b) = 0; - else - x2 = zeros(InitSizeArray(b),npar); - logpo2 = zeros(InitSizeArray(b),1); - end - if exist('OCTAVE_VERSION') || options_.console_mode - diary off - disp(' ') - elseif whoiam - % keyboard; - waitbarString = ['Please wait... Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']; - % waitbarTitle=['Metropolis-Hastings ',options_.parallel(ThisMatlab).PcName]; - if options_.parallel(ThisMatlab).Local, - waitbarTitle=['Local ']; - else - waitbarTitle=[options_.parallel(ThisMatlab).PcName]; - end - fMessageStatus(0,whoiam,waitbarString, waitbarTitle, options_.parallel(ThisMatlab), MasterName, DyMo); - else, - hh = waitbar(0,['Please wait... Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']); - set(hh,'Name','Metropolis-Hastings'); - - end - isux = 0; - jsux = 0; - irun = fline(b); - j = 1; - load urand_1_1.csv - load paramdraws_1_1.csv - while j <= nruns(b) - par = feval(ProposalFun, ix2(b,:), d * jscale, n); - par=paramdraws_1_1(j,:); - if all( par(:) > mh_bounds(:,1) ) & all( par(:) < mh_bounds(:,2) ) - try - logpost = - feval(TargetFun, par(:),varargin{:}); - catch - logpost = -inf; - end - else - logpost = -inf; - end - lurand=log(urand_1_1(j)); - % if (logpost > -inf) && (log(rand) < logpost-ilogpo2(b)) - if (logpost > -inf) && (lurand < logpost-ilogpo2(b)) - x2(irun,:) = par; - ix2(b,:) = par; - logpo2(irun) = logpost; - ilogpo2(b) = logpost; - isux = isux + 1; - jsux = jsux + 1; - else - x2(irun,:) = ix2(b,:); - logpo2(irun) = ilogpo2(b); - end - prtfrc = j/nruns(b); - if exist('OCTAVE_VERSION') || options_.console_mode - if mod(j, 10) == 0 - if exist('OCTAVE_VERSION') - printf('MH: Computing Metropolis-Hastings (chain %d/%d): %3.f%% done, acception rate: %3.f%%\r', b, nblck, 100 * prtfrc, 100 * isux / j); - else - fprintf(' MH: Computing Metropolis-Hastings (chain %d/%d): %3.f \b%% done, acceptance rate: %3.f \b%%\r', b, nblck, 100 * prtfrc, 100 * isux / j); - end - end - if mod(j,50)==0 & whoiam - % keyboard; - waitbarString = [ '(' int2str(b) '/' int2str(options_.mh_nblck) '), ' sprintf('accept. %3.f%%%%', 100 * isux/j)]; - fMessageStatus(prtfrc,whoiam,waitbarString, '', options_.parallel(ThisMatlab), MasterName, DyMo) - end - else - if mod(j, 3)==0 & ~whoiam - waitbar(prtfrc,hh,[ '(' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]); - elseif mod(j,50)==0 & whoiam, - % keyboard; - waitbarString = [ '(' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]; - fMessageStatus(prtfrc,whoiam,waitbarString, waitbarTitle, options_.parallel(ThisMatlab), MasterName, DyMo) - end - end - - if (irun == InitSizeArray(b)) | (j == nruns(b)) % Now I save the simulations - save([MhDirectoryName '/' ModelName '_mh' int2str(NewFile(b)) '_blck' int2str(b) '.mat'],'x2','logpo2'); - fidlog = fopen([MhDirectoryName '/metropolis.log'],'a'); - fprintf(fidlog,['\n']); - fprintf(fidlog,['%% Mh' int2str(NewFile(b)) 'Blck' int2str(b) ' (' datestr(now,0) ')\n']); - fprintf(fidlog,' \n'); - fprintf(fidlog,[' Number of simulations.: ' int2str(length(logpo2)) '\n']); - fprintf(fidlog,[' Acceptation rate......: ' num2str(jsux/length(logpo2)) '\n']); - fprintf(fidlog,[' Posterior mean........:\n']); - for i=1:length(x2(1,:)) - fprintf(fidlog,[' params:' int2str(i) ': ' num2str(mean(x2(:,i))) '\n']); - end - fprintf(fidlog,[' log2po:' num2str(mean(logpo2)) '\n']); - fprintf(fidlog,[' Minimum value.........:\n']);; - for i=1:length(x2(1,:)) - fprintf(fidlog,[' params:' int2str(i) ': ' num2str(min(x2(:,i))) '\n']); - end - fprintf(fidlog,[' log2po:' num2str(min(logpo2)) '\n']); - fprintf(fidlog,[' Maximum value.........:\n']); - for i=1:length(x2(1,:)) - fprintf(fidlog,[' params:' int2str(i) ': ' num2str(max(x2(:,i))) '\n']); - end - fprintf(fidlog,[' log2po:' num2str(max(logpo2)) '\n']); - fprintf(fidlog,' \n'); - fclose(fidlog); - jsux = 0; - if j == nruns(b) % I record the last draw... - record.LastParameters(b,:) = x2(end,:); - record.LastLogLiK(b) = logpo2(end); - end - % size of next file in chain b - InitSizeArray(b) = min(nruns(b)-j,MAX_nruns); - % initialization of next file if necessary - if InitSizeArray(b) - x2 = zeros(InitSizeArray(b),npar); - logpo2 = zeros(InitSizeArray(b),1); - NewFile(b) = NewFile(b) + 1; - irun = 0; - end - end - j=j+1; - irun = irun + 1; - end% End of the simulations for one mh-block. - record.AcceptationRates(b) = isux/j; - if exist('OCTAVE_VERSION') || options_.console_mode - if exist('OCTAVE_VERSION') - printf('\n'); - else - fprintf('\n'); - end - diary on; - elseif ~whoiam - close(hh); - end - record.Seeds(b).Normal = randn('state'); - record.Seeds(b).Unifor = rand('state'); - OutputFileName(jloop,:) = {[MhDirectoryName,filesep], [ModelName '_mh*_blck' int2str(b) '.mat']}; - end% End of the loop over the mh-blocks. -end % if use_dll - -myoutput.record = record; -myoutput.irun = irun; -myoutput.NewFile = NewFile; -myoutput.OutputFileName = OutputFileName; diff --git a/mex/sources/estimation/tests/rawdata_euromodel_1.m b/mex/sources/estimation/tests/rawdata_euromodel_1.m deleted file mode 100644 index 6b9fee720..000000000 --- a/mex/sources/estimation/tests/rawdata_euromodel_1.m +++ /dev/null @@ -1,967 +0,0 @@ -C =[ - -7.4073 - -6.1860 - -6.5983 - -5.6088 - -5.0547 - -4.4774 - -3.8081 - -3.8425 - -2.4178 - -1.9835 - -1.0395 - -0.1583 - -0.0397 - 0.3505 - -0.1879 - -0.0067 - 0.0478 - -1.2247 - -1.4349 - -0.7973 - -0.0461 - 0.5844 - 1.1372 - 1.3801 - 1.8023 - 2.2972 - 2.0469 - 2.5435 - 2.8169 - 3.2007 - 2.6705 - 3.0518 - 3.2445 - 3.8443 - 3.8525 - 4.9494 - 4.2770 - 4.9532 - 5.1441 - 3.7124 - 3.9880 - 3.6926 - 2.6005 - 1.8679 - 1.9085 - 1.5563 - 1.2308 - 0.3264 - -0.2208 - -0.2483 - -0.4082 - -1.0315 - -1.6030 - -1.5499 - -1.3777 - -2.1675 - -2.5138 - -2.8820 - -2.6958 - -2.4719 - -1.9854 - -1.7954 - -2.2362 - -1.0595 - -0.8808 - -0.8548 - -1.2839 - -0.1363 - 0.2104 - 0.8810 - 0.3555 - 0.4766 - 1.3269 - 1.4506 - 1.4308 - 1.6263 - 1.9842 - 2.3948 - 2.8710 - 3.0177 - 2.9305 - 3.1739 - 3.7380 - 3.8285 - 3.3342 - 3.7447 - 3.7830 - 3.1039 - 2.8413 - 3.0338 - 0.3669 - 0.0847 - 0.0104 - 0.2115 - -0.6649 - -0.9625 - -0.7330 - -0.8664 - -1.4441 - -1.0179 - -1.2729 - -1.9539 - -1.4427 - -2.0371 - -1.9764 - -2.5654 - -2.8570 - -2.5842 - -3.0427 - -2.8312 - -2.3320 - -2.2768 - -2.1816 - -2.1043 - -1.8969 - -2.2388 - -2.1679 - -2.1172 - ]; - -E =[ - 0.6263 - 0.7368 - 0.7477 - 1.0150 - 0.6934 - 0.4135 - 0.3845 - 0.2380 - 0.2853 - 0.5999 - 0.8622 - 1.2116 - 1.4921 - 1.5816 - 1.7259 - 1.6276 - 1.2422 - 0.8084 - 0.4710 - -0.3704 - -0.6427 - -0.5323 - -0.5562 - -0.3651 - -0.4356 - -0.7164 - -0.5816 - -0.4635 - -0.8456 - -0.9708 - -0.7138 - -0.7499 - -0.6941 - -0.6656 - -0.2912 - -0.1650 - 0.0774 - 0.2307 - 0.4484 - 0.4942 - 0.4653 - 0.2196 - 0.1736 - -0.1595 - -0.3918 - -0.4611 - -0.8493 - -0.7384 - -1.0604 - -1.2166 - -1.7187 - -1.6932 - -1.7830 - -1.7035 - -2.2079 - -2.3769 - -2.2511 - -2.1093 - -2.4638 - -2.4027 - -2.1313 - -1.9199 - -1.7941 - -1.4661 - -1.2269 - -1.0392 - -1.0725 - -0.7156 - -0.4778 - -0.4233 - -0.0409 - 0.1620 - 0.4280 - 0.5873 - 1.0323 - 1.3420 - 1.6902 - 2.0680 - 2.8219 - 3.2511 - 3.2930 - 3.5633 - 3.8992 - 3.6874 - 3.2849 - 3.1614 - 2.6221 - 2.5067 - 1.9223 - 1.1777 - 0.4483 - -0.0661 - -0.4424 - -0.9000 - -1.1478 - -1.2047 - -1.1412 - -1.2383 - -1.1048 - -0.9716 - -0.9287 - -1.0057 - -1.0827 - -1.0200 - -1.0072 - -1.1740 - -1.2809 - -1.1086 - -0.9866 - -0.8947 - -0.5875 - -0.2329 - 0.1493 - 0.4906 - 0.8400 - 1.0720 - 1.2648 - 1.5431 - ]; - -I =[ - 2.6617 - 2.4325 - 1.9592 - 3.2530 - 2.9949 - 3.7918 - 4.7444 - 4.8289 - 5.5983 - 7.8923 - 9.4297 - 9.5010 - 10.0150 - 10.0413 - 9.6046 - 6.4766 - 5.9647 - 3.0114 - 0.5683 - -2.1226 - -2.1855 - -0.8329 - -1.5207 - -1.3419 - -1.7897 - -0.1476 - 0.4675 - -1.6516 - -1.5419 - -1.3050 - -1.2451 - -0.7815 - -0.7796 - -0.3612 - -2.4072 - 1.1162 - 1.1383 - 3.4132 - 5.0356 - 2.8016 - 2.1734 - 0.9366 - -0.7050 - -1.5021 - -2.9868 - -6.0237 - -6.2589 - -6.9138 - -8.2340 - -9.2589 - -9.2465 - -9.6988 - -9.7782 - -10.5645 - -10.7544 - -13.1583 - -12.2718 - -12.0131 - -13.5983 - -12.3579 - -10.9146 - -11.1572 - -12.4935 - -9.4393 - -8.5535 - -7.3723 - -10.0169 - -6.6088 - -5.2045 - -4.1024 - -2.8472 - -1.3139 - 0.0477 - 1.5629 - 3.6947 - 4.0327 - 4.1320 - 7.1400 - 9.1036 - 8.5609 - 7.6576 - 8.8022 - 8.9611 - 10.0871 - 9.4797 - 9.3964 - 10.0363 - 8.6340 - 6.6522 - 4.4471 - 0.2854 - -2.1879 - -2.9879 - -4.1021 - -2.7713 - -2.2281 - -1.2908 - -0.3250 - 0.6534 - 0.3942 - 0.3534 - -0.1532 - -1.7936 - 0.4909 - 0.3634 - 0.4290 - -0.9709 - 0.1942 - 0.6103 - 1.4426 - 2.7225 - 1.7525 - 3.2780 - 3.5985 - 4.9011 - 5.3312 - 6.4402 - 6.6529 - ]; - -L =[ - 0.6263 - 0.7368 - 0.7477 - 1.0150 - 0.6934 - 0.4135 - 0.3845 - 0.2380 - 0.2853 - 0.5999 - 0.8622 - 1.2116 - 1.4921 - 1.5816 - 1.7259 - 1.6276 - 1.2422 - 0.8084 - 0.4710 - -0.3704 - -0.6427 - -0.5323 - -0.5562 - -0.3651 - -0.4356 - -0.7164 - -0.5816 - -0.4635 - -0.8456 - -0.9708 - -0.7138 - -0.7499 - -0.6941 - -0.6656 - -0.2912 - -0.1650 - 0.0774 - 0.2307 - 0.4484 - 0.4942 - 0.4653 - 0.2196 - 0.1736 - -0.1595 - -0.3918 - -0.4611 - -0.8493 - -0.7384 - -1.0604 - -1.2166 - -1.7187 - -1.6932 - -1.7830 - -1.7035 - -2.2079 - -2.3769 - -2.2511 - -2.1093 - -2.4638 - -2.4027 - -2.1313 - -1.9199 - -1.7941 - -1.4661 - -1.2269 - -1.0392 - -1.0725 - -0.7156 - -0.4778 - -0.4233 - -0.0409 - 0.1620 - 0.4280 - 0.5873 - 1.0323 - 1.3420 - 1.6902 - 2.0680 - 2.8219 - 3.2511 - 3.2930 - 3.5633 - 3.8992 - 3.6874 - 3.2849 - 3.1614 - 2.6221 - 2.5067 - 1.9223 - 1.1777 - 0.4483 - -0.0661 - -0.4424 - -0.9000 - -1.1478 - -1.2047 - -1.1412 - -1.2383 - -1.1048 - -0.9716 - -0.9287 - -1.0057 - -1.0827 - -1.0200 - -1.0072 - -1.1740 - -1.2809 - -1.1086 - -0.9866 - -0.8947 - -0.5875 - -0.2329 - 0.1493 - 0.4906 - 0.8400 - 1.0720 - 1.2648 - 1.5431 - ]; - -PIE =[ - -1.0113 - -0.8305 - 0.2332 - -0.8746 - -0.7978 - -0.9220 - -0.2487 - -0.7749 - -0.5460 - -0.5347 - 0.5050 - -0.0334 - 0.6756 - 0.8791 - 0.7267 - 1.0997 - 1.1750 - 1.1927 - 0.4420 - 0.5357 - 0.0345 - 0.0196 - 0.3371 - 0.9379 - 1.2160 - 0.3393 - 0.5813 - 0.7410 - 0.3374 - 0.2616 - 0.4025 - 0.4799 - 0.5981 - -0.1523 - 0.4458 - 0.2182 - 0.9793 - 0.7562 - 1.0064 - 0.8203 - 0.6966 - 0.3352 - 0.6581 - 0.6111 - 0.9833 - 1.1991 - 0.9562 - 0.3868 - 0.2939 - 0.2471 - 0.8331 - 0.0715 - 0.3910 - 0.3301 - 0.2547 - -0.2702 - -0.2998 - -0.1953 - -0.2293 - -0.3284 - 0.0480 - -0.0374 - 0.3253 - -0.3434 - -0.3892 - -0.7178 - -0.4758 - -0.6794 - -0.8505 - -0.3512 - -0.4436 - -0.5101 - -0.4574 - -0.2696 - -0.1047 - -0.5745 - -0.2989 - -0.0063 - 0.0088 - -0.1184 - -0.1506 - -0.4073 - 0.2674 - 0.2896 - 0.0669 - 0.1166 - -0.1699 - -0.2518 - -0.0562 - -0.3269 - -0.0703 - -0.1046 - -0.4888 - -0.3524 - -0.2485 - -0.5870 - -0.4546 - -0.3970 - -0.2353 - -0.0352 - -0.2171 - -0.3754 - -0.4322 - -0.4572 - -0.4903 - -0.4518 - -0.6435 - -0.6304 - -0.4148 - -0.2892 - -0.4318 - -0.6010 - -0.4148 - -0.4315 - -0.3531 - -0.8053 - -0.4680 - -0.4263 - ]; - -R =[ - -1.0750 - -1.1540 - -1.3682 - -1.4569 - -1.3490 - -1.4011 - -1.6486 - -1.6968 - -1.6976 - -1.2567 - -1.1392 - -0.7783 - -0.3021 - -0.0435 - 0.0066 - -0.0043 - 0.1029 - -0.0628 - -0.5358 - -0.9627 - -1.1079 - -1.0918 - -0.9966 - -0.6223 - -0.3616 - -0.2711 - -0.0997 - -0.2810 - -0.3710 - -0.3167 - -0.5301 - -0.5826 - -0.3194 - -0.2713 - -0.5287 - -0.2432 - 0.1098 - 0.5349 - 0.7094 - 0.8415 - 0.6226 - 0.7376 - 0.9316 - 1.4370 - 1.5853 - 1.4267 - 1.1783 - 1.2046 - 0.9689 - 0.7918 - 0.6315 - 0.5950 - 0.6853 - 0.7171 - 0.5887 - 0.4873 - 0.4027 - 0.3489 - 0.2934 - 0.3060 - 0.1741 - 0.0348 - 0.0771 - -0.1005 - -0.1518 - -0.1104 - -0.0681 - -0.0059 - 0.0256 - 0.0404 - -0.1721 - -0.2002 - 0.0015 - 0.1249 - 0.3738 - 0.4320 - 0.5579 - 0.8186 - 0.8727 - 0.7356 - 0.7243 - 0.8635 - 0.9058 - 0.7656 - 0.7936 - 0.8631 - 0.9074 - 0.9547 - 1.2045 - 1.0850 - 0.9178 - 0.5242 - 0.3178 - 0.1472 - 0.0227 - -0.0799 - -0.0611 - -0.0140 - 0.1132 - 0.1774 - 0.0782 - 0.0436 - -0.1596 - -0.2691 - -0.2895 - -0.3791 - -0.4020 - -0.4166 - -0.4037 - -0.3636 - -0.4075 - -0.4311 - -0.4470 - -0.5111 - -0.6274 - -0.7261 - -0.6974 - -0.5012 - ]; - -W =[ - -14.8791 - -13.2300 - -13.5037 - -13.0249 - -11.2546 - -10.0148 - -8.8586 - -8.5739 - -7.7851 - -6.7136 - -5.5878 - -4.6881 - -3.8039 - -3.0366 - -2.7342 - -1.3135 - -0.7387 - -0.1131 - -0.2769 - 0.8696 - 1.8855 - 2.3667 - 2.4942 - 3.2049 - 3.9682 - 5.1500 - 4.7047 - 4.7827 - 5.3377 - 5.6614 - 5.2813 - 5.2967 - 5.5175 - 6.1526 - 5.6627 - 6.0694 - 6.5824 - 6.9032 - 6.7849 - 6.6896 - 6.6201 - 6.9933 - 5.8959 - 6.7419 - 6.9999 - 6.4009 - 5.5083 - 5.1054 - 5.2813 - 4.5790 - 3.9589 - 3.8599 - 3.8978 - 2.7957 - 3.2480 - 1.4634 - 1.9219 - 1.8398 - 1.9279 - 1.8316 - 1.6092 - 1.2741 - 0.2031 - -0.0236 - -0.1004 - -0.3034 - -1.0273 - -0.2205 - 0.0458 - 0.2386 - -0.0977 - -0.3145 - -0.1416 - -0.7009 - -0.9082 - -0.8802 - -0.5644 - -0.5852 - -0.5346 - 0.0652 - 0.1301 - 0.3444 - -0.3592 - 0.8096 - 0.9644 - 1.0289 - 1.2781 - 1.2298 - 2.2134 - 2.0808 - 0.4925 - 0.6506 - 0.5531 - 0.2456 - -0.5351 - -0.8183 - -0.8967 - -0.7268 - -1.0738 - -1.2844 - -1.4338 - -1.6995 - -1.7085 - -2.2889 - -2.1018 - -2.4273 - -2.4609 - -2.1407 - -2.3847 - -3.1689 - -4.5581 - -4.1027 - -4.2436 - -4.8836 - -5.9660 - -4.9971 - -5.2386 - -5.6618 - ]; - -Y =[ - -4.9347 - -4.6205 - -5.2198 - -4.5937 - -3.8015 - -3.6643 - -2.7239 - -2.7524 - -2.0634 - -1.0112 - 0.0530 - 0.7623 - 1.7927 - 2.1486 - 2.4866 - 2.1456 - 2.1671 - -0.0254 - -1.6716 - -1.9673 - -1.6109 - -1.0292 - -0.1222 - 0.7329 - 1.1234 - 2.0603 - 1.7998 - 1.4820 - 1.1732 - 1.6424 - 1.5382 - 2.1399 - 2.0127 - 2.7210 - 2.4966 - 3.5249 - 3.6237 - 4.2011 - 4.5634 - 3.3442 - 2.7761 - 1.9812 - 1.3779 - 1.4616 - 1.3029 - 0.7594 - 0.3695 - 0.0832 - -0.8118 - -1.4557 - -1.4850 - -1.2346 - -1.5696 - -1.3785 - -0.7682 - -2.0308 - -1.7778 - -1.7801 - -2.1711 - -1.7469 - -1.3413 - -1.3352 - -2.4390 - -1.2125 - -1.1695 - -1.0891 - -2.4753 - -1.3503 - -0.9412 - -0.1470 - 0.0026 - 0.1108 - 0.6890 - 1.3520 - 1.6018 - 2.0667 - 1.7625 - 2.6658 - 3.4048 - 3.2507 - 3.4251 - 3.2174 - 3.1903 - 3.3396 - 3.1358 - 2.8625 - 3.3546 - 2.4609 - 1.9534 - 0.9962 - -0.7904 - -1.1672 - -1.2586 - -1.3593 - -1.3443 - -0.9413 - -0.6023 - -0.4516 - -0.5129 - -0.8741 - -1.0784 - -1.4091 - -1.3627 - -1.5731 - -1.6037 - -1.8814 - -2.1482 - -1.3597 - -1.1855 - -1.1122 - -0.8424 - -0.9747 - -1.1385 - -1.4548 - -1.4284 - -1.4633 - -1.0621 - -0.7871 - ]; diff --git a/mex/sources/estimation/tests/sweuromodel_dll.mod b/mex/sources/estimation/tests/sweuromodel_dll.mod deleted file mode 100644 index 658dec00a..000000000 --- a/mex/sources/estimation/tests/sweuromodel_dll.mod +++ /dev/null @@ -1,182 +0,0 @@ -//options_.usePartInfo=1; - -var MC E EF R_KF QF CF IF YF LF PIEF WF RF R_K Q C I Y L PIE W R EE_A PIE_BAR EE_B EE_G EE_L EE_I KF K one BIGTHETA; - -varexo E_A E_B E_G E_L E_I ETA_R E_PIE_BAR ETA_Q ETA_P ETA_W ; - -parameters -xi_e lambda_w alpha czcap beta phi_i tau sig_c hab ccs cinvs phi_y gamma_w xi_w gamma_p xi_p sig_l r_dpi -r_pie r_dy r_y rho rho_a rho_pb rho_b rho_g rho_l rho_i LMP ; - - - -alpha=.30; -beta=.99; -tau=0.025; -ccs=0.6; -cinvs=.22; //% alpha*(tau+ctrend)/R_K R_K=ctrend/beta-1+tau -lambda_w = 0.5; -phi_i= 6.771; -sig_c= 1.353; -hab= 0.573; -xi_w= 0.737; -sig_l= 2.400; -xi_p= 0.908; -xi_e= 0.599; -gamma_w= 0.763; -gamma_p= 0.469; -czcap= 0.169; -phi_y= 1.408; -r_pie= 1.684; -r_dpi= 0.14; -rho= 0.961; -r_y= 0.099; -r_dy= 0.159; -rho_a= 0.823; -rho_b= 0.855; -rho_g= 0.949; -rho_l= 0.889; -rho_i= 0.927; -rho_pb= 0.924; -LMP = 0.0 ; //NEW. - -model(linear, use_dll); - CF = (1/(1+hab))*(CF(1)+hab*CF(-1))-((1-hab)/((1+hab)*sig_c))*(RF-PIEF(1)-EE_B) ; - 0 = alpha*R_KF+(1-alpha)*WF -EE_A ; - PIEF = 0*one; - IF = (1/(1+beta))* (( IF(-1) + beta*(IF(1)))+(1/phi_i)*QF)+0*ETA_Q+EE_I ; - QF = -(RF-PIEF(1))+(1-beta*(1-tau))*((0+czcap)/czcap)*R_KF(1)+beta*(1-tau)*QF(1) +0*EE_I ; - KF = (1-tau)*KF(-1)+tau*IF(-1) ; - YF = (ccs*CF+cinvs*IF)+EE_G ; - - YF = 1*phi_y*( alpha*KF+alpha*(1/czcap)*R_KF+(1-alpha)*LF+EE_A ) ; - WF = (sig_c/(1-hab))*(CF-hab*CF(-1)) + sig_l*LF - EE_L ; - LF = R_KF*((1+czcap)/czcap)-WF+KF ; - EF = EF(-1)+EF(1)-EF+(LF-EF)*((1-xi_e)*(1-xi_e*beta)/(xi_e)); - - C = (hab/(1+hab))*C(-1)+(1/(1+hab))*C(1)-((1-hab)/((1+hab)*sig_c))*(R-PIE(1)-EE_B) ; - I = (1/(1+beta))* (( I(-1) + beta*(I(1)))+(1/phi_i)*Q )+1*ETA_Q+1*EE_I ; - Q = -(R-PIE(1))+(1-beta*(1-tau))*((0+czcap)/czcap)*R_K(1)+beta*(1-tau)*Q(1) +EE_I*0+0*ETA_Q ; - K = (1-tau)*K(-1)+tau*I(-1) ; - Y = (ccs*C+cinvs*I)+ EE_G ; - Y = phi_y*( alpha*K+alpha*(1/czcap)*R_K+(1-alpha)*L ) +phi_y*EE_A ; - PIE = (1/(1+beta*gamma_p))* - ( - (beta)*(PIE(1)) +(gamma_p)*(PIE(-1)) - +((1-xi_p)*(1-beta*xi_p)/(xi_p))*(MC) - ) + ETA_P ; - - MC = alpha*R_K+(1-alpha)*W -EE_A; - W = (1/(1+beta))*(beta*W(+1)+W(-1)) - +(beta/(1+beta))*(PIE(+1)) - -((1+beta*gamma_w)/(1+beta))*(PIE) - +(gamma_w/(1+beta))*(PIE(-1)) - -(1/(1+beta))*(((1-beta*xi_w)*(1-xi_w))/(((1+(((1+lambda_w)*sig_l)/(lambda_w))))*xi_w))*(W-sig_l*L-(sig_c/(1-hab))*(C-hab*C(-1))+EE_L) - +ETA_W; - L = R_K*((1+czcap)/czcap)-W+K ; - -// R = r_dpi*(PIE-PIE(-1)) -// +(1-rho)*(r_pie*(PIE(-1)-PIE_BAR)+r_y*(Y-YF)) -// +r_dy*(Y-YF-(Y(-1)-YF(-1))) -// +rho*(R(-1)-PIE_BAR) -// +PIE_BAR -// +ETA_R; - - - R = - -r_dpi*(PIE-PIE(-1)) - - +(1-rho)*(r_pie*(BIGTHETA)+r_y*(Y-YF)) - +r_dy*(Y-YF-(Y(-1)-YF(-1))) - +rho*(R(-1)-PIE_BAR) - +PIE_BAR - +ETA_R; - - - E = E(-1)+E(1)-E+(L-E)*((1-xi_e)*(1-xi_e*beta)/(xi_e)); - - - EE_A = (rho_a)*EE_A(-1) + E_A; - PIE_BAR = rho_pb*PIE_BAR(-1)+ E_PIE_BAR ; - EE_B = rho_b*EE_B(-1) + E_B ; - EE_G = rho_g*EE_G(-1) + E_G ; - EE_L = rho_l*EE_L(-1) + E_L ; - EE_I = rho_i*EE_I(-1) + E_I ; - one = 0*one(-1) ; - - LMP*BIGTHETA(1) = BIGTHETA - (PIE(-1) - PIE_BAR) ; - -end; - - -shocks; -var E_A; stderr 0.598; -var E_B; stderr 0.336; -var E_G; stderr 0.325; -var E_I; stderr 0.085; -var E_L; stderr 3.520; -var ETA_P; stderr 0.160; -var ETA_W; stderr 0.289; -var ETA_R; stderr 0.081; -var ETA_Q; stderr 0.604; -var E_PIE_BAR; stderr 0.017; -end; - -//stoch_simul(irf=20) Y C PIE R W R_K L Q I K ; - -// stoch_simul generates what kind of standard errors for the shocks ? - -//steady; -//check; -//stoch_simul(periods=200,irf=20,simul_seed=3) Y C PIE MC R W R_K E L I ; - -//datatomfile('ddd',[]); - -// new syntax - -estimated_params; -// PARAM NAME, INITVAL, LB, UB, PRIOR_SHAPE, PRIOR_P1, PRIOR_P2, PRIOR_P3, PRIOR_P4, JSCALE -// PRIOR_SHAPE: BETA_PDF, GAMMA_PDF, NORMAL_PDF, INV_GAMMA_PDF -stderr E_A,0.543,0.01,4,INV_GAMMA_PDF,0.4,2; -stderr E_PIE_BAR,0.072,0.001,4,INV_GAMMA_PDF,0.02,10; -stderr E_B,0.2694,0.01,4,INV_GAMMA_PDF,0.2,2; -stderr E_G,0.3052,0.01,4,INV_GAMMA_PDF,0.3,2; -stderr E_L,1.4575,0.1,6,INV_GAMMA_PDF,1,2; -stderr E_I,0.1318,0.01,4,INV_GAMMA_PDF,0.1,2; -stderr ETA_R,0.1363,0.01,4,INV_GAMMA_PDF,0.1,2; -stderr ETA_Q,0.4842,0.01,4,INV_GAMMA_PDF,0.4,2; -stderr ETA_P,0.1731,0.01,4,INV_GAMMA_PDF,0.15,2; -stderr ETA_W,0.2462,0.1,4,INV_GAMMA_PDF,0.25,2; -rho_a,.9722,.1,.9999,BETA_PDF,0.85,0.1; -rho_pb,.85,.1,.999,BETA_PDF,0.85,0.1; -rho_b,.7647,.1,.99,BETA_PDF,0.85,0.1; -rho_g,.9502,.1,.9999,BETA_PDF,0.85,0.1; -rho_l,.9542,.1,.9999,BETA_PDF,0.85,0.1; -rho_i,.6705,.1,.99,BETA_PDF,0.85,0.1; -phi_i,5.2083,1,15,NORMAL_PDF,4,1.5; -sig_c,0.9817,0.25,3,NORMAL_PDF,1,0.375; -hab,0.5612,0.3,0.95,BETA_PDF,0.7,0.1; -xi_w,0.7661,0.3,0.9,BETA_PDF,0.75,0.05; -sig_l,1.7526,0.5,5,NORMAL_PDF,2,0.75; -xi_p,0.8684,0.3,0.95,BETA_PDF,0.75,0.05; -xi_e,0.5724,0.1,0.95,BETA_PDF,0.5,0.15; -gamma_w,0.6202,0.1,0.99,BETA_PDF,0.75,0.15; -gamma_p,0.6638,0.1,0.99,BETA_PDF,0.75,0.15; -czcap,0.2516,0.01,2,NORMAL_PDF,0.2,0.075; -phi_y,1.3011,1.001,2,NORMAL_PDF,1.45,0.125; -r_pie,1.4616,1.2,2,NORMAL_PDF,1.7,0.1; -r_dpi,0.1144,0.01,0.5,NORMAL_PDF,0.3,0.1; -rho,0.8865,0.5,0.99,BETA_PDF,0.8,0.10; -r_y,0.0571,0.01,0.2,NORMAL_PDF,0.125,0.05; -r_dy,0.2228,0.05,0.5,NORMAL_PDF,0.0625,0.05; -end; - -varobs Y C I E PIE W R; - -//estimation(datafile=rawdata_euromodel_1,presample=40, first_obs=1, nobs=118, lik_init=2, mode_compute=1,mh_replic=0); -estimation(datafile=rawdata_euromodel_1,presample=40, first_obs=1, nobs=118,mh_jscale=0.2,mh_replic=150000, mode_check); // - - -//stoch_simul(periods=200,irf=20,simul_seed=3) Y C PIE R W R_K L Q I K ; - diff --git a/mex/sources/estimation/tests/test-dr.cc b/mex/sources/estimation/tests/test-dr.cc deleted file mode 100644 index a931709c4..000000000 --- a/mex/sources/estimation/tests/test-dr.cc +++ /dev/null @@ -1,193 +0,0 @@ -/* - * This test of DecisionRules class is based on example1.mod. - */ - -/* - * Copyright (C) 2010-2013 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include "DecisionRules.hh" - -int -main(int argc, char **argv) -{ - size_t endo_nbr = 6, exo_nbr = 2; - - std::vector zeta_fwrd, zeta_back, zeta_mixed, zeta_static; - // y and c are purely forward - zeta_fwrd.push_back(0); - zeta_fwrd.push_back(1); - // k and a are purely backward - zeta_back.push_back(2); - zeta_back.push_back(3); - // h is static - zeta_static.push_back(4); - // b is both backward and forward - zeta_mixed.push_back(5); - - double qz_criterium = 1.000001; - - DecisionRules dr(endo_nbr, exo_nbr, zeta_fwrd, zeta_back, zeta_mixed, - zeta_static, qz_criterium); - - double jacob_data[] = { - 0.000000000000000, - 0.000000000000000, - -0.035101010101010, - -0.975000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - -0.950000000000000, - -0.025000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - -0.025000000000000, - -0.950000000000000, - -0.640000000000000, - 0.000000000000000, - 1.000000000000000, - -1.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.860681114551094, - -13.792569659442703, - 0.000000000000000, - 1.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.034750000000000, - 0.000000000000000, - 1.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - -1.080682530956729, - 0.000000000000000, - 1.000000000000000, - 0.000000000000000, - 2.370597639417809, - 0.000000000000000, - -2.370597639417800, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - -11.083604432603581, - 0.000000000000000, - -0.277090110815090, - 0.000000000000000, - 1.000000000000000, - 0.000000000000000, - -0.356400000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 13.792569659442703, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 10.698449178570606, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - -1.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - 0.000000000000000, - -1.000000000000000 - }; - - MatrixView jacob_tmp(jacob_data, 6, 14, 6); - - Matrix jacobian(6, 14), g_y(6, 3), g_u(6, 2); - jacobian = jacob_tmp; - - try - { - dr.compute(jacobian, g_y, g_u); - } - catch (GeneralizedSchurDecomposition::GSDException &e) - { - std::cerr << e << std::endl; - } - catch (DecisionRules::BlanchardKahnException &e) - { - std::cerr << e << std::endl; - } - - Vector eig_real(6), eig_cmplx(6); - dr.getGeneralizedEigenvalues(eig_real, eig_cmplx); - std::cout << "Eigenvalues (real part): " << eig_real - << "Eigenvalues (complex part): " << eig_cmplx << std::endl - << "g_y = " << std::endl << g_y << std::endl - << "g_u = " << std::endl << g_u; - - // Check the results for g_y - double real_g_y_data[] = { - 0.005358267364601, 1.836717147430803, 0.837085806295838, - 0.038541607674354, 0.424582606909411, -0.318740381721598, - 0.941816659690247, 1.419061793291772, 1.419061793291773, - -0.000000000000000, 0.950000000000000, 0.025000000000000, - -0.012546516642830, 0.341714987626857, 0.341714987626861, - 0.000000000000000, 0.025000000000000, 0.950000000000000 - }; - - MatrixView real_g_y_prime(real_g_y_data, 3, 6, 3); - Matrix real_g_y(6, 3); - mat::transpose(real_g_y, real_g_y_prime); - mat::sub(real_g_y, g_y); - - assert(mat::nrminf(real_g_y) < 1e-12); - - // Check the results for g_u - double real_g_u_data[] = { - 1.911522267389459, 0.830839736432740, - 0.456074274269694, -0.347518145871938, - 1.455447993119765, 1.455447993119767, - 1.000000000000000, 0, - 0.350476910386520, 0.350476910386525, - 0, 1.000000000000000 - }; - - MatrixView real_g_u_prime(real_g_u_data, 2, 6, 2); - Matrix real_g_u(6, 2); - mat::transpose(real_g_u, real_g_u_prime); - mat::sub(real_g_u, g_u); - - assert(mat::nrminf(real_g_u) < 1e-12); -} diff --git a/mex/sources/estimation/tests/testInitKalman.cc b/mex/sources/estimation/tests/testInitKalman.cc deleted file mode 100644 index 28139ccdb..000000000 --- a/mex/sources/estimation/tests/testInitKalman.cc +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include "InitializeKalmanFilter.hh" - -int -main(int argc, char **argv) -{ - if (argc < 2) - { - std::cerr << argv[0] << ": please provide as argument the name of the dynamic DLL generated from fs2000k2e.mod (typically fs2000k2e_dynamic.mex*)" << std::endl; - exit(EXIT_FAILURE); - } - - std::string modName = argv[1]; - const int npar = 7; //(int)mxGetM(mxFldp); - const size_t n_endo = 15, n_exo = 2; - std::vector zeta_fwrd_arg; - std::vector zeta_back_arg; - std::vector zeta_mixed_arg; - std::vector zeta_static_arg; - //std::vector - double qz_criterium = 1.000001; //1.0+1.0e-9; - Vector steadyState(n_endo), deepParams(npar); - - double dYSparams [] = { - 1.000199998312523, - 0.993250551764778, - 1.006996670195112, - 1, - 2.718562165733039, - 1.007250753636589, - 18.982191739915155, - 0.860847884886309, - 0.316729149714572, - 0.861047883198832, - 1.00853622757204, - 0.991734328394345, - 1.355876776121869, - 1.00853622757204, - 0.992853374047708 - }; - - double vcov[] = { - 0.001256631601, 0.0, - 0.0, 0.000078535044 - }; - - double dparams[] = { - 0.3560, - 0.9930, - 0.0085, - 1.0002, - 0.1290, - 0.6500, - 0.0100 - }; - - VectorView modParamsVW(dparams, npar, 1); - deepParams = modParamsVW; - VectorView steadyStateVW(dYSparams, n_endo, 1); - steadyState = steadyStateVW; - std::cout << "Vector deepParams: " << std::endl << deepParams << std::endl; - std::cout << "Vector steadyState: " << std::endl << steadyState << std::endl; - - // Set zeta vectors [0:(n-1)] from Matlab indices [1:n] so that: - // order_var = [ stat_var(:); pred_var(:); both_var(:); fwrd_var(:)]; - size_t statc[] = { 4, 5, 6, 8, 9, 10, 11, 12, 14}; - size_t back[] = {1, 7, 13}; - size_t both[] = {2}; - size_t fwd[] = { 3, 15}; - for (int i = 0; i < 9; ++i) - zeta_static_arg.push_back(statc[i]-1); - for (int i = 0; i < 3; ++i) - zeta_back_arg.push_back(back[i]-1); - for (int i = 0; i < 1; ++i) - zeta_mixed_arg.push_back(both[i]-1); - for (int i = 0; i < 2; ++i) - zeta_fwrd_arg.push_back(fwd[i]-1); - - size_t varobs[] = {12, 11}; - std::vector varobs_arg; - for (size_t i = 0; i < 2; ++i) - varobs_arg.push_back(varobs[i]-1); - - // Compute zeta_varobs_back_mixed - sort(varobs_arg.begin(), varobs_arg.end()); - std::vector zeta_back_mixed, zeta_varobs_back_mixed; - set_union(zeta_back_arg.begin(), zeta_back_arg.end(), - zeta_mixed_arg.begin(), zeta_mixed_arg.end(), - back_inserter(zeta_back_mixed)); - set_union(zeta_back_mixed.begin(), zeta_back_mixed.end(), - varobs_arg.begin(), varobs_arg.end(), - back_inserter(zeta_varobs_back_mixed)); - - size_t n_vbm = zeta_varobs_back_mixed.size(); - - Matrix T(n_vbm, n_vbm), R(n_vbm, n_exo), - RQRt(n_vbm, n_vbm), Pstar(n_vbm, n_vbm), - Pinf(n_vbm, n_vbm), Q(n_exo); - - MatrixView vCovVW(vcov, n_exo, n_exo, n_exo); - Q = vCovVW; - - double lyapunov_tol = 1e-16; - int info = 0; - size_t nobs = 2; - Matrix yView(nobs, 192); // dummy - yView.setAll(0.2); - const MatrixConstView dataView(yView, 0, 0, nobs, yView.getCols()); // dummy - Matrix yDetrendView(nobs, yView.getCols()); // dummy - MatrixView dataDetrendView(yDetrendView, 0, 0, nobs, yDetrendView.getCols()); // dummy - - const Vector xparams1(0); // dummy - double penalty = 1e8; - - InitializeKalmanFilter initializeKalmanFilter(modName, n_endo, n_exo, - zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, - zeta_varobs_back_mixed, qz_criterium, - lyapunov_tol, info); - - std::cout << "Initialize KF with Q: " << std::endl << Q << std::endl; - - initializeKalmanFilter.initialize(steadyStateVW, deepParams, R, Q, RQRt, T, Pstar, Pinf, - penalty, dataView, dataDetrendView, info); - - std::cout << "Matrix T: " << std::endl << T << std::endl; - std::cout << "Matrix R: " << std::endl << R << std::endl; - std::cout << "Matrix RQRt: " << std::endl << RQRt << std::endl; - std::cout << "Matrix Pstar: " << std::endl << Pstar << std::endl; - std::cout << "Matrix Pinf: " << std::endl << Pinf << std::endl; - -} diff --git a/mex/sources/estimation/tests/testKalman.cc b/mex/sources/estimation/tests/testKalman.cc deleted file mode 100644 index f75f3459e..000000000 --- a/mex/sources/estimation/tests/testKalman.cc +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include "KalmanFilter.hh" - -int -main(int argc, char **argv) -{ - if (argc < 2) - { - std::cerr << argv[0] << ": please provide as argument the name of the dynamic DLL generated from fs2000k2e.mod (typically fs2000k2e_dynamic.mex*)" << std::endl; - exit(EXIT_FAILURE); - } - - std::string modName = argv[1]; - const int npar = 7; //(int)mxGetM(mxFldp); - const size_t n_endo = 15, n_exo = 2; - std::vector zeta_fwrd_arg; - std::vector zeta_back_arg; - std::vector zeta_mixed_arg; - std::vector zeta_static_arg; - //std::vector - double qz_criterium = 1.000001; //1.0+1.0e-9; - Vector steadyState(n_endo), deepParams(npar); - - double dYSparams [] = { - 1.000199998312523, - 0.993250551764778, - 1.006996670195112, - 1, - 2.718562165733039, - 1.007250753636589, - 18.982191739915155, - 0.860847884886309, - 0.316729149714572, - 0.861047883198832, - 1.00853622757204, - 0.991734328394345, - 1.355876776121869, - 1.00853622757204, - 0.992853374047708 - }; - - double vcov[] = { - 0.001256631601, 0.0, - 0.0, 0.000078535044 - }; - - double dparams[] = { - 0.3560, - 0.9930, - 0.0085, - 1.0002, - 0.1290, - 0.6500, - 0.0100 - }; - - VectorView modParamsVW(dparams, npar, 1); - deepParams = modParamsVW; - VectorView steadyStateVW(dYSparams, n_endo, 1); - steadyState = steadyStateVW; - std::cout << "Vector deepParams: " << std::endl << deepParams << std::endl; - std::cout << "Vector steadyState: " << std::endl << steadyState << std::endl; - - // Set zeta vectors [0:(n-1)] from Matlab indices [1:n] so that: - // order_var = [ stat_var(:); pred_var(:); both_var(:); fwrd_var(:)]; - size_t statc[] = { 4, 5, 6, 8, 9, 10, 11, 12, 14}; - size_t back[] = {1, 7, 13}; - size_t both[] = {2}; - size_t fwd[] = { 3, 15}; - for (int i = 0; i < 9; ++i) - zeta_static_arg.push_back(statc[i]-1); - for (int i = 0; i < 3; ++i) - zeta_back_arg.push_back(back[i]-1); - for (int i = 0; i < 1; ++i) - zeta_mixed_arg.push_back(both[i]-1); - for (int i = 0; i < 2; ++i) - zeta_fwrd_arg.push_back(fwd[i]-1); - - size_t nobs = 2; - size_t varobs[] = {12, 11}; - std::vector varobs_arg; - for (size_t i = 0; i < nobs; ++i) - varobs_arg.push_back(varobs[i]-1); - - Matrix Q(n_exo), H(nobs); - H.setAll(0.0); - - MatrixView vCovVW(vcov, n_exo, n_exo, n_exo); - Q = vCovVW; - std::cout << "Matrix Q: " << std::endl << Q << std::endl; - - double lyapunov_tol = 1e-16; - double riccati_tol = 1e-16; - int info = 0; - Matrix yView(nobs, 192); // dummy - yView.setAll(0.2); - const MatrixConstView dataView(yView, 0, 0, nobs, yView.getCols()); // dummy - Matrix yDetrendView(nobs, yView.getCols()); // dummy - MatrixView dataDetrendView(yDetrendView, 0, 0, nobs, yDetrendView.getCols()); // dummy - Vector vll(yView.getCols()); - VectorView vwll(vll, 0, vll.getSize()); - - double penalty = 1e8; - - KalmanFilter kalman(modName, n_endo, n_exo, - zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium, - varobs_arg, riccati_tol, lyapunov_tol, info); - - size_t start = 0, period = 0; - double ll = kalman.compute(dataView, steadyStateVW, Q, H, deepParams, - vwll, dataDetrendView, start, period, penalty, info); - - std::cout << "ll: " << std::endl << ll << std::endl; -} diff --git a/mex/sources/estimation/tests/testModelSolution.cc b/mex/sources/estimation/tests/testModelSolution.cc deleted file mode 100644 index 45b20d831..000000000 --- a/mex/sources/estimation/tests/testModelSolution.cc +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2010-2011 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 . - */ - -// Test for ModelSolution -// Uses fs2000k2.mod and its ..._dynamic.mexw32 - -#include "ModelSolution.hh" - -int -main(int argc, char **argv) -{ - if (argc < 2) - { - std::cerr << argv[0] << ": please provide as argument the name of the dynamic DLL generated from fs2000k2.mod (typically fs2000k2_dynamic.mex*)" << std::endl; - exit(EXIT_FAILURE); - } - - std::string modName = argv[1]; - const int npar = 7; - const size_t n_endo = 15, n_exo = 2; - std::vector zeta_fwrd_arg; - std::vector zeta_back_arg; - std::vector zeta_mixed_arg; - std::vector zeta_static_arg; - double qz_criterium = 1.0+1.0e-9; - Vector deepParams(npar); - - double dYSparams [] = { - 1.0110, 2.2582, 0.4477, 1.0000, - 4.5959, 1.0212, 5.8012, 0.8494, - 0.1872, 0.8604, 1.0030, 1.0080, - 0.5808, 1.0030, 2.2093 - }; - double vcov[] = { - 0.1960e-3, 0.0, - 0.0, 0.0250e-3 - }; - int nVCVpar = 2; - MatrixView vCovVW(vcov, nVCVpar, nVCVpar, nVCVpar); - Matrix vCov(nVCVpar, nVCVpar); - vCov = vCovVW; - - double dparams[] = { 0.3300, - 0.9900, - 0.0030, - 1.0110, - 0.7000, - 0.7870, - 0.0200}; - - VectorView modParamsVW(dparams, npar, 1); - deepParams = modParamsVW; - VectorView steadyState(dYSparams, n_endo, 1); - std::cout << "Vector deepParams: " << std::endl << deepParams << std::endl; - std::cout << "Matrix vCov: " << std::endl << vCov << std::endl; - std::cout << "Vector steadyState: " << std::endl << steadyState << std::endl; - - // Set zeta vectors [0:(n-1)] from Matlab indices [1:n] - //order_var = [ stat_var(:); pred_var(:); both_var(:); fwrd_var(:)]; - size_t statc[] = { 4, 5, 6, 8, 9, 10, 11, 12, 14}; - size_t back[] = {1, 7, 13}; - size_t both[] = {2}; - size_t fwd[] = { 3, 15}; - for (int i = 0; i < 9; ++i) - zeta_static_arg.push_back(statc[i]-1); - for (int i = 0; i < 3; ++i) - zeta_back_arg.push_back(back[i]-1); - for (int i = 0; i < 1; ++i) - zeta_mixed_arg.push_back(both[i]-1); - for (int i = 0; i < 2; ++i) - zeta_fwrd_arg.push_back(fwd[i]-1); - - Matrix ghx(n_endo, zeta_back_arg.size() + zeta_mixed_arg.size()); - Matrix ghu(n_endo, n_exo); - - ModelSolution modelSolution(modName, n_endo, n_exo, - zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium); - - modelSolution.compute(steadyState, deepParams, ghx, ghu); - - std::cout << "Matrix ghx: " << std::endl << ghx << std::endl; - std::cout << "Matrix ghu: " << std::endl << ghu << std::endl; -} diff --git a/mex/sources/estimation/tests/testPDF.cc b/mex/sources/estimation/tests/testPDF.cc deleted file mode 100644 index 70bdeba9f..000000000 --- a/mex/sources/estimation/tests/testPDF.cc +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2009-2011 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 . - */ - -// test for Prior pdfs and basic random number generators - -#include "Prior.hh" - -int -main(int argc, char **argv) -{ - BetaPrior bp(0.1, 0.1, 0.0, 1.0, 5.0, 1.0); - double pdf = bp.pdf(0.5); - std::cout << "beta pdf of 5,1, 0.5: " << std::setw(13) << pdf << std::endl; - BetaPrior *bpp = new BetaPrior(0.1, 0.1, 0.0, 1.0, 1.0, 5.0); - Prior *pp = bpp; - pdf = (*pp).pdf(0.1); - std::cout << "Parent (Beta) pdf of 1,5, 0.1: " << std::setw(13) << pdf << std::endl; - - GammaPrior *gpp = new GammaPrior(0.1, 0.1, 0.0, 1.0, 1.0, 5.0); - pp = gpp; - pdf = (*pp).pdf(0.1); - std::cout << "Parent (Gamma) pdf of 1,5, 0.1: " << std::setw(13) << pdf << std::endl; - - UniformPrior up(5, 2, 1, 10, 20, 100); - std::cout << std::endl << "Uniform prior (5,2, 1,10,20,100): " << std::endl; - double ur, updf; - for (int i = 0; i < 10; i++) - { - ur = up.drand(); - updf = up.pdf(ur); - std::cout << "Uniform pdf of : " << ur << " = " << updf << std::endl; - } - - GaussianPrior gp(5, 2, 1, 10, 20, 100); - std::cout << std::endl << "Gaussian prior (5,2, 1,10,20,100): " << std::endl; - for (int i = 0; i < 10; i++) - { - ur = gp.drand(); - updf = gp.pdf(ur); - std::cout << "Gaussian pdf of : " << ur << " = " << updf << std::endl; - } - - UniformPrior up2(5, 2, 1, 100, 20, 100); - std::cout << std::endl << "Uniform prior (5,2, 1,100,20,100): " << std::endl; - for (int i = 0; i < 10; i++) - { - ur = up2.drand(); - updf = up2.pdf(ur); - std::cout << "Uniform pdf of : " << ur << " = " << updf << std::endl; - } - - GaussianPrior gp2(5, 2, 1, 100, 5, 2); - std::cout << std::endl << "Gaussian prior (5,2, 1,100,5,2): " << std::endl; - for (int i = 0; i < 10; i++) - { - ur = gp2.drand(); - updf = gp2.pdf(ur); - std::cout << "Gaussian pdf of : " << ur << " = " << updf << std::endl; - } -}; diff --git a/mex/sources/estimation/utils/dynamic_dll.cc b/mex/sources/estimation/utils/dynamic_dll.cc deleted file mode 100644 index e9d126d9e..000000000 --- a/mex/sources/estimation/utils/dynamic_dll.cc +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include "dynamic_dll.hh" - -#include - -using namespace std; - -DynamicModelDLL::DynamicModelDLL(const std::string &basename) throw (TSException) -{ - std::string fName; -#if !defined(__CYGWIN32__) && !defined(_WIN32) - if (basename[0] != '/') - fName = "./"; -#endif - fName += basename + "_dynamic" + MEXEXT; - - try - { -#if defined(__CYGWIN32__) || defined(_WIN32) - dynamicHinstance = LoadLibrary(fName.c_str()); - if (dynamicHinstance == NULL) - throw 1; - Dynamic = (DynamicFn) GetProcAddress(dynamicHinstance, "Dynamic"); - if (Dynamic == NULL) - { - FreeLibrary(dynamicHinstance); // Free the library - throw 2; - } -#else // Linux or Mac - dynamicHinstance = dlopen(fName.c_str(), RTLD_NOW); - if ((dynamicHinstance == NULL) || dlerror()) - { - cerr << dlerror() << endl; - throw 1; - } - Dynamic = (DynamicFn) dlsym(dynamicHinstance, "Dynamic"); - if ((Dynamic == NULL) || dlerror()) - { - dlclose(dynamicHinstance); // Free the library - cerr << dlerror() << endl; - throw 2; - } -#endif - - } - catch (int i) - { - std::ostringstream msg; - msg << "Error when loading " << fName << " ("; - if (i == 1) - msg << "can't dynamically load the file"; - if (i == 2) - msg << "can't locate the 'Dynamic' symbol"; - msg << ")"; - throw TSException(__FILE__, __LINE__, msg.str()); - } - catch (...) - { - throw TSException(__FILE__, __LINE__, std::string("Can't find Dynamic function in ") + fName); - } -} - -DynamicModelDLL::~DynamicModelDLL() -{ -#if defined(__CYGWIN32__) || defined(_WIN32) - bool result = FreeLibrary(dynamicHinstance); - if (result == 0) - throw TSException(__FILE__, __LINE__, std::string("Can't free the *_dynamic DLL")); -#else - dlclose(dynamicHinstance); -#endif -} diff --git a/mex/sources/estimation/utils/dynamic_dll.hh b/mex/sources/estimation/utils/dynamic_dll.hh deleted file mode 100644 index 5e19472ee..000000000 --- a/mex/sources/estimation/utils/dynamic_dll.hh +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#if defined(_WIN32) || defined(__CYGWIN32__) -# ifndef NOMINMAX -# define NOMINMAX // Do not define "min" and "max" macros -# endif -# include -#else -# include // unix/linux DLL (.so) handling routines -#endif - -#include -#include "Matrix.hh" - -#include "ts_exception.h" - -// _Dynamic DLL pointer -typedef void (*DynamicFn)(const double *y, const double *x, int nb_row_x, const double *params, const double *steady_state, - int it_, double *residual, double *g1, double *g2, double *g3); - -/** - * creates pointer to Dynamic function inside _dynamic.dll - * and handles calls to it. - **/ -class DynamicModelDLL -{ -private: - DynamicFn Dynamic; // pointer to the Dynamic function in DLL -#if defined(_WIN32) || defined(__CYGWIN32__) - HINSTANCE dynamicHinstance; // DLL instance pointer in Windows -#else - void *dynamicHinstance; // and in Linux or Mac -#endif - -public: - // construct and load Dynamic model DLL - DynamicModelDLL(const std::string &basename) throw (TSException); - virtual - ~DynamicModelDLL(); - - //! evaluate Dynamic model DLL - template - void - eval(const Vec1 &y, const Mat1 &x, const Vec2 &modParams, const Vec3 &ySteady, - Vec4 &residual, Matrix *g1, Matrix *g2, Matrix *g3) throw (TSException) - { - assert(y.getStride() == 1); - assert(x.getLd() == x.getRows()); - assert(modParams.getStride() == 1); - assert(ySteady.getStride() == 1); - assert(residual.getStride() == 1); - assert(g1->getLd() == g1->getRows()); - assert(g2->getLd() == g2->getRows()); - assert(g3->getLd() == g3->getRows()); - - Dynamic(y.getData(), x.getData(), 1, modParams.getData(), ySteady.getData(), 0, residual.getData(), - g1 == NULL ? NULL : g1->getData(), g2 == NULL ? NULL : g2->getData(), g3 == NULL ? NULL : g3->getData()); - }; -}; diff --git a/mex/sources/estimation/utils/static_dll.cc b/mex/sources/estimation/utils/static_dll.cc deleted file mode 100644 index fe3366398..000000000 --- a/mex/sources/estimation/utils/static_dll.cc +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2010-2013 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#include "static_dll.hh" - -#include - -using namespace std; - -StaticModelDLL::StaticModelDLL(const std::string &basename) throw (TSException) -{ - std::string fName; -#if !defined(__CYGWIN32__) && !defined(_WIN32) - if (basename[0] != '/') - fName = "./"; -#endif - fName += basename + "_static" + MEXEXT; - - try - { -#if defined(__CYGWIN32__) || defined(_WIN32) - staticHinstance = LoadLibrary(fName.c_str()); - if (staticHinstance == NULL) - throw 1; - Static = (StaticFn) GetProcAddress(staticHinstance, "Static"); - if (Static == NULL) - { - FreeLibrary(staticHinstance); // Free the library - throw 2; - } -#else // Linux or Mac - staticHinstance = dlopen(fName.c_str(), RTLD_NOW); - if ((staticHinstance == NULL) || dlerror()) - { - cerr << dlerror() << endl; - throw 1; - } - Static = (StaticFn) dlsym(staticHinstance, "Static"); - if ((Static == NULL) || dlerror()) - { - dlclose(staticHinstance); // Free the library - cerr << dlerror() << endl; - throw 2; - } -#endif - - } - catch (int i) - { - std::ostringstream msg; - msg << "Error when loading " << fName << " ("; - if (i == 1) - msg << "can't dynamically load the file"; - if (i == 2) - msg << "can't locate the 'Static' symbol"; - msg << ")"; - throw TSException(__FILE__, __LINE__, msg.str()); - } - catch (...) - { - throw TSException(__FILE__, __LINE__, std::string("Can't find Static function in ") + fName); - } -} - -StaticModelDLL::~StaticModelDLL() -{ -#if defined(__CYGWIN32__) || defined(_WIN32) - bool result = FreeLibrary(staticHinstance); - if (result == 0) - throw TSException(__FILE__, __LINE__, std::string("Can't free the *_static DLL")); -#else - dlclose(staticHinstance); -#endif -} diff --git a/mex/sources/estimation/utils/static_dll.hh b/mex/sources/estimation/utils/static_dll.hh deleted file mode 100644 index 36b28a9f2..000000000 --- a/mex/sources/estimation/utils/static_dll.hh +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -#if defined(_WIN32) || defined(__CYGWIN32__) -# ifndef NOMINMAX -# define NOMINMAX // Do not define "min" and "max" macros -# endif -# include -#else -# include // unix/linux DLL (.so) handling routines -#endif - -#include -#include "Matrix.hh" - -#include "ts_exception.h" - -// Pointer to the Static function in the MEX -typedef void (*StaticFn)(const double *y, const double *x, int nb_row_x, const double *params, double *residual, double *g1, double *v2); - -/** - * creates pointer to Dynamic function inside _static.dll - * and handles calls to it. - **/ -class StaticModelDLL -{ -private: - StaticFn Static; // pointer to the Dynamic function in DLL -#if defined(_WIN32) || defined(__CYGWIN32__) - HINSTANCE staticHinstance; // DLL instance pointer in Windows -#else - void *staticHinstance; // and in Linux or Mac -#endif - -public: - // construct and load Static model DLL - StaticModelDLL(const std::string &basename) throw (TSException); - virtual - ~StaticModelDLL(); - - //! evaluate Static model DLL - template - void - eval(const Vec1 &y, const Mat1 &x, const Vec2 &modParams, - Vec3 &residual, Matrix *g1, Matrix *v2) throw (TSException) - { - assert(y.getStride() == 1); - assert(x.getLd() == x.getRows()); - assert(modParams.getStride() == 1); - assert(residual.getStride() == 1); - assert(g1->getLd() == g1->getRows()); - assert(v2->getLd() == v2->getRows()); - - Static(y.getData(), x.getData(), 1, modParams.getData(), residual.getData(), - g1 == NULL ? NULL : g1->getData(), v2 == NULL ? NULL : v2->getData()); - }; -}; diff --git a/mex/sources/estimation/utils/ts_exception.h b/mex/sources/estimation/utils/ts_exception.h deleted file mode 100644 index c3d3ea3c7..000000000 --- a/mex/sources/estimation/utils/ts_exception.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2010-2017 Dynare Team - * - * This file is part of Dynare. - * - * Dynare is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Dynare is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Dynare. If not, see . - */ - -/* derived from c++kalman_filter library by O. Kamenik */ - -#ifndef TS_EXCEPTION_H -#define TS_EXCEPTION_H - -#include -#include - -#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) -# include "mex.h" -#endif - -#define TS_RAISE(mes) \ - throw TSException(__FILE__, __LINE__, mes); - -#define TS_RAISE_IF(expr, mes) \ - if (expr) throw TSException(__FILE__, __LINE__, mes); - -class TSException -{ - std::string fname; //char fname[50]; - int lnum; - std::string message; // char message[500]; -public: - TSException(const char *f, int l, const std::string &mes) - { - fname = std::string(f); // strncpy(fname,f,50);fname[49]= '\0'; - message = mes; //strncpy(message,mes,500);message[499]= '\0'; - lnum = l; - } - virtual - ~TSException() - { - }; - - virtual void - print() const - { - printf("At %s:%d:%s\n", fname.c_str(), lnum, message.c_str()); -#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) - mexPrintf("At %s:%d:%s\n", fname.c_str(), lnum, message.c_str()); -#endif - } - - virtual const std::string - getMessage() const - { - return message; - } -}; - -; -#endif diff --git a/osx/createOsxFolderForPkg.sh b/osx/createOsxFolderForPkg.sh index 2fe344f8c..3f5fa6630 100755 --- a/osx/createOsxFolderForPkg.sh +++ b/osx/createOsxFolderForPkg.sh @@ -79,7 +79,6 @@ cp $TOP_DYN_DIR/doc/guide.pdf $INSTALLDIR/doc cp $TOP_DYN_DIR/doc/macroprocessor/macroprocessor.pdf $INSTALLDIR/doc cp $TOP_DYN_DIR/doc/parallel/parallel.pdf $INSTALLDIR/doc cp $TOP_DYN_DIR/doc/preprocessor/preprocessor.pdf $INSTALLDIR/doc -cp $TOP_DYN_DIR/doc/userguide/UserGuide.pdf $INSTALLDIR/doc cp $TOP_DYN_DIR/doc/gsa/gsa.pdf $INSTALLDIR/doc # doc (dynare++) diff --git a/preprocessor/ComputingTasks.cc b/preprocessor/ComputingTasks.cc index dbdef0ec2..1af68165f 100644 --- a/preprocessor/ComputingTasks.cc +++ b/preprocessor/ComputingTasks.cc @@ -1291,8 +1291,7 @@ EstimatedParamsStatement::checkPass(ModFileStructure &mod_file_struct, WarningCo void EstimatedParamsStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const { - output << "global estim_params_" << endl - << "estim_params_.var_exo = [];" << endl + output << "estim_params_.var_exo = [];" << endl << "estim_params_.var_endo = [];" << endl << "estim_params_.corrx = [];" << endl << "estim_params_.corrn = [];" << endl diff --git a/preprocessor/ExprNode.cc b/preprocessor/ExprNode.cc index 66b479d26..c40dac37e 100644 --- a/preprocessor/ExprNode.cc +++ b/preprocessor/ExprNode.cc @@ -3511,6 +3511,16 @@ BinaryOpNode::writeJsonOutput(ostream &output, return; } + if (op_code == oPowerDeriv) + { + output << "get_power_deriv("; + arg1->writeJsonOutput(output, temporary_terms, tef_terms); + output << ","; + arg2->writeJsonOutput(output, temporary_terms, tef_terms); + output << "," << powerDerivOrder << ")"; + return; + } + int prec = precedenceJson(temporary_terms); bool close_parenthesis = false; diff --git a/preprocessor/SymbolTable.cc b/preprocessor/SymbolTable.cc index c191060be..f1409587c 100644 --- a/preprocessor/SymbolTable.cc +++ b/preprocessor/SymbolTable.cc @@ -110,7 +110,7 @@ SymbolTable::freeze() throw (FrozenException) frozen = true; - for (int i = 0; i < symbol_table.size(); i++) + for (int i = 0; i < (int) symbol_table.size(); i++) { int tsi; switch (getType(i)) diff --git a/preprocessor/SymbolTable.hh b/preprocessor/SymbolTable.hh index 8bb112200..76aa38961 100644 --- a/preprocessor/SymbolTable.hh +++ b/preprocessor/SymbolTable.hh @@ -384,7 +384,7 @@ public: inline void SymbolTable::validateSymbID(int symb_id) const throw (UnknownSymbolIDException) { - if (symb_id < 0 || symb_id > symbol_table.size()) + if (symb_id < 0 || symb_id > (int) symbol_table.size()) throw UnknownSymbolIDException(symb_id); } diff --git a/preprocessor/changed_files.txt b/preprocessor/changed_files.txt deleted file mode 100644 index 2a6f38274..000000000 --- a/preprocessor/changed_files.txt +++ /dev/null @@ -1,4 +0,0 @@ - -license.txt - -windows/dynare.nsi diff --git a/windows/dynare.nsi b/windows/dynare.nsi index 60b575149..b9b106042 100644 --- a/windows/dynare.nsi +++ b/windows/dynare.nsi @@ -126,7 +126,7 @@ SectionEnd Section "Documentation and examples (Dynare and Dynare++)" SetOutPath $INSTDIR\doc - File ..\doc\dynare.pdf ..\doc\guide.pdf ..\doc\userguide\UserGuide.pdf ..\doc\bvar-a-la-sims.pdf ..\doc\dr.pdf ..\doc\macroprocessor\macroprocessor.pdf ..\doc\preprocessor\preprocessor.pdf ..\doc\parallel\parallel.pdf ..\doc\gsa\gsa.pdf ..\doc\dseries-and-reporting\dseriesReporting.pdf + File ..\doc\dynare.pdf ..\doc\guide.pdf ..\doc\bvar-a-la-sims.pdf ..\doc\dr.pdf ..\doc\macroprocessor\macroprocessor.pdf ..\doc\preprocessor\preprocessor.pdf ..\doc\parallel\parallel.pdf ..\doc\gsa\gsa.pdf ..\doc\dseries-and-reporting\dseriesReporting.pdf SetOutPath $INSTDIR\doc\dynare.html File ..\doc\dynare.html\*.html ..\doc\dynare.html\*.png