Initial commit (contributed by Alejandro Buesa).

time-shift
Stéphane Adjemia (Scylla) 2018-10-25 16:31:53 +02:00
commit e54b57103c
Signed by untrusted user who does not match committer: stepan
GPG Key ID: A6D44CB9C64CE77B
19 changed files with 15160 additions and 0 deletions

358
dynare-domain/dynare.py Normal file
View File

@ -0,0 +1,358 @@
# -*- coding: utf-8 -*-
"""
sphinx.domains.dynare
~~~~~~~~~~~~~~~~~~~~~
The Dynare domain.
Loosely based on the JavaScript domain from the Sphinx team and the CoffeScript domain
by Stephen Sugden (available at sphinx-contrib)
"""
import re
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from sphinx import addnodes
from sphinx.domains import Domain, ObjType
from sphinx.locale import l_, _
from sphinx.directives import ObjectDescription
from sphinx.roles import XRefRole
from sphinx.util.nodes import make_refnode
from sphinx.util.docfields import Field, GroupedField, TypedField
############### Dynare Object types #######################
class DynObject(ObjectDescription):
has_arguments = True
display_prefix = None
allow_nesting = False
def handle_signature(self, sig, signode):
sig = sig.strip()
# Some variable/parameter declarations combine spaces and parenthesis
# in a strange way, so they are treated separately
if sig.startswith(('var V','varexo V','varexo_det V','parameters P','model_comparison F')):
member = sig[:sig.index(' ')]
arglist = sig[sig.index(' '):]
# General cases
elif '(' in sig:
member = sig[:sig.index('(')]
arglist = sig[sig.index('('):]
arglist = arglist.strip()
elif ' ' in sig:
member = sig[:sig.index(' ')]
arglist = sig[sig.index(' '):]
else:
member = sig
arglist = None
prefix = self.env.ref_context.get('dynare:object', None)
name = member.strip()
fullname = name
signode['object'] = prefix
signode['fullname'] = fullname
if self.display_prefix:
signode += addnodes.desc_annotation(self.display_prefix, self.display_prefix)
signode += addnodes.desc_name(name, name)
if self.has_arguments:
if not arglist:
signode += addnodes.desc_parameterlist()
else:
signode += addnodes.desc_addname(arglist,arglist)
return fullname, prefix
def add_target_and_index(self, name_obj, sig, signode):
fullname = name_obj[0]
if fullname not in self.state.document.ids:
signode['names'].append(fullname)
signode['ids'].append(fullname)
signode['first'] = not self.names
self.state.document.note_explicit_target(signode)
objects = self.env.domaindata['dynare']['objects']
if fullname in objects:
self.state_machine.reporter.warning(
'duplicate object description of %s, ' % fullname +
'other instance in ' +
self.env.doc2path(objects[fullname][0]),line=self.lineno)
objects[fullname] = (self.env.docname, self.objtype)
indextext = self.get_index_text(fullname,name_obj)
if indextext:
self.indexnode['entries'].append(('single', indextext, fullname,'', None))
def get_index_text(self, objectname, name_obj):
name, obj = name_obj
regexp = re.compile(r'\s*=\s*')
if bool(regexp.search(name)):
aux, name = re.compile(r'\s*=\s*').split(name)
if self.objtype == 'function':
return _('%s (function)') % name
elif self.objtype == 'class':
return _('%s (class)') % name
elif self.objtype == 'datesmethod':
return _('%s (dates method)') % name
elif self.objtype == 'dseriesmethod':
return _('%s (dseries method)') % name
elif self.objtype == 'repmethod':
return _('%s (report method)') % name
elif self.objtype == 'matcomm':
return _('%s (MATLAB command)') % name
elif self.objtype == 'command':
return _('%s (command)') % name
elif self.objtype == 'block':
return _('%s (block)') % name
elif self.objtype == 'confblock':
name = name[1:-1]
return _('%s (config block)') % name
elif self.objtype == 'macrodir':
name = name[2:]
return _('%s (macro directive)') % name
class DynCallable(DynObject):
has_arguments = True
doc_field_types = [
TypedField('arguments', label=l_('Arguments'),
names=('argument', 'arg', 'parameter', 'param'),
typerolename='func', typenames=('paramtype', 'type')),
Field('returnvalue', label=l_('Returns'), has_arg=False,
names=('returns', 'return')),
Field('returntype', label=l_('Return type'), has_arg=False,
names=('rtype',)),
Field('example', label=l_('Example'), has_arg=False,
names=('ex',)),
]
class DynClass(DynObject):
has_arguments = False
display_prefix = 'Dynare class: '
allow_nesting = True
doc_field_types = [
TypedField('members', label=l_('Members'),
names=('argument', 'arg', ),
typerolename='func', typenames=('type', )),
Field('example', label=l_('Example'), has_arg=False,
names=('ex',)),
]
class DynFunction(DynCallable):
display_prefix = 'Function: '
allow_nesting = True
class DatesMethod(DynCallable):
display_prefix = 'Method: '
allow_nesting = True
class DseriesMethod(DynCallable):
display_prefix = 'Method: '
allow_nesting = True
class DynRepMethod(DynCallable):
display_prefix = 'Method on report: '
allow_nesting = True
class MatComm(DynCallable):
display_prefix = 'MATLAB/Octave command: '
allow_nesting = False
class DynComm(DynCallable):
display_prefix = 'Command: '
allow_nesting = False
class DynBlock(DynCallable):
display_prefix = 'Block: '
allow_nesting = False
class DynConfBlock(DynCallable):
display_prefix = 'Configuration block: '
has_arguments = False
allow_nesting = False
class DynMacroDir(DynCallable):
display_prefix = 'Macro directive: '
allow_nesting = False
class Constructor(DynCallable):
display_prefix = 'Constructor: '
allow_nesting = False
class DynSimpleObject(ObjectDescription):
has_arguments = False
allow_nesting = False
def handle_signature(self, sig, signode):
sig = sig.strip()
member = sig
arglist = None
prefix = self.env.ref_context.get('dynare:object', None)
name = member
fullname = name
signode['object'] = prefix
signode['fullname'] = fullname
if self.display_prefix:
signode += addnodes.desc_annotation(self.display_prefix, self.display_prefix)
signode += addnodes.desc_name(name, name)
return fullname, prefix
def add_target_and_index(self, name_obj, sig, signode):
fullname = name_obj[0]
if fullname not in self.state.document.ids:
signode['names'].append(fullname)
signode['ids'].append(fullname)
signode['first'] = not self.names
self.state.document.note_explicit_target(signode)
objects = self.env.domaindata['dynare']['objects']
if fullname in objects:
self.state_machine.reporter.warning(
'duplicate object description of %s, ' % fullname +
'other instance in ' +
self.env.doc2path(objects[fullname][0]), line=self.lineno)
objects[fullname] = self.env.docname, self.objtype
indextext = self.get_index_text(fullname,name_obj)
if indextext:
self.indexnode['entries'].append(('single', indextext, fullname,'', None))
def get_index_text(self, objectname, name_obj):
name, obj = name_obj
if self.objtype == 'construct':
name, rest = name.split(' ',1)
return _('%s (constructor)') % name
elif self.objtype == 'matvar':
return _('%s (MATLAB variable)') % name
elif self.objtype == 'specvar':
return _('%s (special variable)') % name
elif self.objtype == 'operator':
endsig = name.find(' ')
name = name[0:endsig]
return _('%s (operator)') % name
elif self.objtype == 'constant':
return _('%s (constant)') % name
class MatlabVar(DynSimpleObject):
display_prefix = 'MATLAB/Octave variable: '
allow_nesting = False
class SpecialVar(MatlabVar):
display_prefix = 'Special variable: '
class Operator(MatlabVar):
display_prefix = 'Operator: '
class Constant(MatlabVar):
display_prefix = 'Constant: '
class Option(MatlabVar):
display_prefix = None
############## Cross-referencing ####################
class DynareXRefRole(XRefRole):
def process_link(self, env, refnode, has_explicit_title, title, target):
refnode['dynare:object'] = env.ref_context.get('dynare:object')
return title, target
############### Dynare domain #######################
class DynDomain(Domain):
name = 'dynare'
label = 'Dynare'
object_types = {
'function': ObjType(l_('function'), 'func'),
'datesmethod': ObjType(l_('method'), 'datmeth'),
'dseriesmethod': ObjType(l_('method'), 'dsermeth'),
'repmethod': ObjType(l_('method on report'), 'repmeth'),
'matcomm': ObjType(l_('matlab command'), 'mcomm'),
'command': ObjType(l_('command'), 'comm'),
'class': ObjType(l_('class'), 'class'),
'block': ObjType(l_('block'), 'bck'),
'confblock': ObjType(l_('config block'), 'cbck'),
'macrodir': ObjType(l_('macro directive'), 'mdir'),
'construct': ObjType(l_('constructor'), 'cstr'),
'matvar': ObjType(l_('matlab variable'), 'mvar'),
'specvar': ObjType(l_('special variable'), 'svar'),
'operator': ObjType(l_('operator'), 'op'),
'constant': ObjType(l_('constant'), 'const'),
'option': ObjType(l_('option'), 'opt'),
}
directives = {
'function': DynFunction,
'datesmethod': DatesMethod,
'dseriesmethod': DseriesMethod,
'repmethod': DynRepMethod,
'matcomm': MatComm,
'command': DynComm,
'class': DynClass,
'block': DynBlock,
'confblock': DynConfBlock,
'macrodir': DynMacroDir,
'construct': Constructor,
'matvar': MatlabVar,
'specvar': SpecialVar,
'operator': Operator,
'constant': Constant,
'option': Option,
}
roles = {
'func': DynareXRefRole(),
'datmeth': DynareXRefRole(),
'dsermeth': DynareXRefRole(),
'repmeth': DynareXRefRole(),
'mcomm': DynareXRefRole(),
'comm': DynareXRefRole(),
'class': DynareXRefRole(),
'bck': DynareXRefRole(),
'cbck': DynareXRefRole(),
'mdir': DynareXRefRole(),
'cstr': DynareXRefRole(),
'mvar': DynareXRefRole(),
'svar': DynareXRefRole(),
'op': DynareXRefRole(),
'const': DynareXRefRole(),
'opt': DynareXRefRole(),
}
initial_data = {
'objects': {},
}
def clear_doc(self, docname):
for fullname, (fn, _l) in list(self.data['objects'].items()):
if fn == docname:
del self.data['objects'][fullname]
def find_obj(self, env, obj, name, typ, searchorder=0):
objects = self.data['objects']
newname = name # None
return newname, objects.get(newname)
def merge_domaindata(self, docnames, otherdata):
for fullname, (fn, objtype) in otherdata['objects'].items():
if fn in docnames:
self.data['objects'][fullname] = (fn, objtype)
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
objectname = node.get('dynare:object')
searchorder = node.hasattr('refspecific') and 1 or 0
name, obj = self.find_obj(env, objectname, target, typ, searchorder)
if not obj:
return None
return make_refnode(builder, fromdocname, obj[0], name, contnode, name)
def get_objects(self):
for refname, (docname, type) in list(self.data['objects'].items()):
yield refname, refname, type, docname, refname, 1

102
dynare-pygment/dynare.py Normal file
View File

@ -0,0 +1,102 @@
# To be fixed:
#
# - Commands with names starting with block names not recognized
#
# - Commands not recognized when inserting newlines...prefix & suffix!
#
# - Same for other categories....really, use regex to set up prefixes and suffixes
import re
from pygments.lexer import Lexer, RegexLexer, bygroups, do_insertions, words
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
Number, Punctuation, Generic, Whitespace
# Configuration block :BOLD
#conf_blocks = ('hooks','paths','cluster','node')
__all__ = ['DynareLexer']
class DynareLexer(RegexLexer):
name = 'Dynare'
aliases = ['dynare']
filenames = ['*.mod']
commands = (
"dynare","var","varexo","varexo_det","parameters","change_type",
"predetermined_variables","trend_var","log_trend_var","external_function",
"write_latex_original_model","write_latex_dynamic_model",
"write_latex_static_model","resid","initval_file","histval_file","dsample",
"periods","steady","check","model_diagnostics","model_info",
"print_bytecode_dynamic_model"," print_bytecode_static_model",
"perfect_foresight_setup","perfect_foresight_solver","simul","stoch_simul",
"extended_path","varobs","estimation","unit_root_vars","bvar_density",
"model_comparison","shock_decomposition","realtime_shock_decomposition",
"plot_shock_decomposition","calib_smoother","forecast",
"conditional_forecast","plot_conditional_forecast","bvar_forecast",
"smoother2histval","osr","osr_params","ramsey_model","ramsey_policy",
"discretionary_policy","planner_objective","dynare_sensitivity",
"markov_switching","svar","sbvar","ms_estimation","ms_simulation",
"ms_compute_mdd","ms_compute_probabilities","ms_irf","ms_forecast",
"ms_variance_decomposition","rplot","dynatype","dynasave","set_dynare_seed",
"save_params_and_steady_state","load_params_and_steady_state",
"dynare_version","write_latex_definitions","write_latex_parameter_table",
"write_latex_prior_table","collect_latex_files","prior_function",
"posterior_function","generate_trace_plots")
report_commands = ("report","addPage","addSection","addGraph","addTable",
"addSeries","addParagraph","addVspace","write","compile")
operators = (
"STEADY_STATE","EXPECTATION")
macro_dirs = (
"@#includepath", "@#include", "@#define", "@#if",
"@#ifdef", "@#ifndef", "@#else","@#endif",
"@#for", "@#endfor", "@#echo", "@#error")
builtin_constants = (
"inf", "nan")
tokens = {
'root': [
(r'\s*(%|//).*$', Comment),
(words((
'model','steady_state_model','initval','endval','histval',
'shocks','mshocks','homotopy_setup','steady_state_model','observation_trends',
'estimated_params','estimated_params_init','estimated_params_bounds',
'shock_groups','conditional_forecast_paths','optim_weights',
'osr_params_bounds','ramsey_constraints','irf_calibration',
'moment_calibration','identification','svar_identification',
'verbatim','end','node','cluster','paths','hooks')),Keyword.Reserved),
(words(commands + report_commands,
suffix=r'\s*'), Name.Entity),
(words(operators), Operator.Word),
(words(macro_dirs,suffix=r'\s*'), Name.Function),
(words(builtin_constants), Name.Constant),
(r'\s*[a-zA-Z_]\s*', Name),
(r'\s*(\d+\.\d+|\d*\.\d+)([eEf][+-]?[0-9]+)?\s*', Number.Float),
(r'\s*\d+[eEf][+-]?[0-9]+\s*', Number.Float),
(r'\s*\d+\s*', Number.Integer),
(r'"[^"]*"', String),
(r"`[^`]*'", String),
(r"'[^']*'", String),
(r'\s*(-|\+|\*|\/|\^)\s*', Operator),
(r'\s*(==|<=|>=|~=|<|>|&&|!)\s*', Operator),
(r'\s*[\[\](){}:@.,\|]\s*', Punctuation),
(r'\s*(=|:|;|>>|#|\$)\s*', Punctuation),
]
}

20
src/Makefile Normal file
View File

@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SPHINXPROJ = Test
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

View File

@ -0,0 +1,74 @@
.. default-domain:: dynare
############
Bibliography
############
* Abramowitz, Milton and Irene A. Stegun (1964): “Handbook of Mathematical Functions”, Courier Dover Publications.
* Adjemian, Stéphane, Matthieu Darracq Parriès and Stéphane Moyen (2008): “Towards a monetary policy evaluation framework”, *European Central Bank Working Paper*, 942.
* Aguiar, Mark and Gopinath, Gita (2004): “Emerging Market Business Cycles: The Cycle is the Trend,” *NBER* Working Paper, 10734.
* Amisano, Gianni and Tristani, Oreste (2010): “Euro area inflation persistence in an estimated nonlinear DSGE model”, *Journal of Economic Dynamics and Control*, 34(10), 18371858.
* Andreasen, Martin M., Jesús Fernández-Villaverde, and Juan Rubio-Ramírez (2013): “The Pruned State-Space System for Non-Linear DSGE Models: Theory and Empirical Applications,” *NBER Working Paper*, 18983.
* Andrews, Donald W.K (1991): “Heteroskedasticity and autocorrelation consistent covariance matrix estimation”, *Econometrica*, 59(3), 817858.
* Backus, David K., Patrick J. Kehoe, and Finn E. Kydland (1992): “International Real Business Cycles,” *Journal of Political Economy*, 100(4), 745775.
* Baxter, Marianne and Robert G. King (1999): “Measuring Business Cycles: Approximate Band-pass Filters for Economic Time Series,” *Review of Economics and Statistics*, 81(4), 575593.
* Boucekkine, Raouf (1995): “An alternative methodology for solving nonlinear forward-looking models,” *Journal of Economic Dynamics and Control*, 19, 711734.
* Brooks, Stephen P., and Andrew Gelman (1998): “General methods for monitoring convergence of iterative simulations,” *Journal of Computational and Graphical Statistics*, 7, pp. 434455.
* Cardoso, Margarida F., R. L. Salcedo and S. Feyo de Azevedo (1996): “The simplex simulated annealing approach to continuous non-linear optimization,” *Computers chem. Engng*, 20(9), 1065-1080.
* Chib, Siddhartha and Srikanth Ramamurthy (2010): “Tailored randomized block MCMC methods with application to DSGE models,” *Journal of Econometrics*, 155, 1938.
* Christiano, Lawrence J., Mathias Trabandt and Karl Walentin (2011): “Introducing financial frictions and unemployment into a small open economy model,” *Journal of Economic Dynamics and Control*, 35(12), 19992041.
* Christoffel, Kai, Günter Coenen and Anders Warne (2010): “Forecasting with DSGE models,” *ECB Working Paper Series*, 1185.
* Collard, Fabrice (2001): “Stochastic simulations with Dynare: A practical guide”.
* Collard, Fabrice and Michel Juillard (2001a): “Accuracy of stochastic perturbation methods: The case of asset pricing models,” *Journal of Economic Dynamics and Control*, 25, 979999.
* Collard, Fabrice and Michel Juillard (2001b): “A Higher-Order Taylor Expansion Approach to Simulation of Stochastic Forward-Looking Models with an Application to a Non-Linear Phillips Curve,” *Computational Economics*, 17, 125139.
* Corona, Angelo, M. Marchesi, Claudio Martini, and Sandro Ridella (1987): “Minimizing multimodal functions of continuous variables with the “simulated annealing” algorithm”, *ACM Transactions on Mathematical Software*, 13(3), 262280.
* Del Negro, Marco and Franck Schorfheide (2004): “Priors from General Equilibrium Models for VARs”, *International Economic Review*, 45(2), 643673.
* Dennis, Richard (2007): “Optimal Policy In Rational Expectations Models: New Solution Algorithms”, *Macroeconomic Dynamics*, 11(1), 3155.
* Durbin, J. and S. J. Koopman (2012), *Time Series Analysis by State Space Methods*, Second Revised Edition, Oxford University Press.
* Fair, Ray and John Taylor (1983): “Solution and Maximum Likelihood Estimation of Dynamic Nonlinear Rational Expectation Models,” *Econometrica*, 51, 11691185.
* Fernández-Villaverde, Jesús and Juan Rubio-Ramírez (2004): “Comparing Dynamic Equilibrium Economies to Data: A Bayesian Approach,” *Journal of Econometrics*, 123, 153187.
* Fernández-Villaverde, Jesús and Juan Rubio-Ramírez (2005): “Estimating Dynamic Equilibrium Economies: Linear versus Nonlinear Likelihood,” *Journal of Applied Econometrics*, 20, 891910.
* Fernández-Villaverde, Jesús (2010): “The econometrics of DSGE models,” *SERIEs*, 1, 349.
* Ferris, Michael C. and Todd S. Munson (1999): “Interfaces to PATH 3.0: Design, Implementation and Usage”, *Computational Optimization and Applications*, 12(1), 207227.
* Geweke, John (1992): “Evaluating the accuracy of sampling-based approaches to the calculation of posterior moments,” in J.O. Berger, J.M. Bernardo, A.P. Dawid, and A.F.M. Smith (eds.) Proceedings of the Fourth Valencia International Meeting on Bayesian Statistics, pp. 169194, Oxford University Press.
* Geweke, John (1999): “Using simulation methods for Bayesian econometric models: Inference, development and communication,” *Econometric Reviews*, 18(1), 173.
* Giordani, Paolo, Michael Pitt, and Robert Kohn (2011): “Bayesian Inference for Time Series State Space Models” in: *The Oxford Handbook of Bayesian Econometrics*, ed. by John Geweke, Gary Koop, and Herman van Dijk, Oxford University Press, 61124.
* Goffe, William L., Gary D. Ferrier, and John Rogers (1994): “Global Optimization of Statistical Functions with Simulated Annealing,” *Journal of Econometrics*, 60(1/2), 65100.
* Hansen, Nikolaus and Stefan Kern (2004): “Evaluating the CMA Evolution Strategy on Multimodal Test Functions”. In: *Eighth International Conference on Parallel Problem Solving from Nature PPSN VIII*, Proceedings, Berlin: Springer, 282291.
* Harvey, Andrew C. and Garry D.A. Phillips (1979): “Maximum likelihood estimation of regression models with autoregressive-moving average disturbances,” *Biometrika*, 66(1), 4958.
* Herbst, Edward (2015): “Using the “Chandrasekhar Recursions” for Likelihood Evaluation of DSGE Models,” *Computational Economics*, 45(4), 693705.
* Ireland, Peter (2004): “A Method for Taking Models to the Data,” *Journal of Economic Dynamics and Control*, 28, 120526.
* Iskrev, Nikolay (2010): “Local identification in DSGE models,” *Journal of Monetary Economics*, 57(2), 189202.
* Judd, Kenneth (1996): “Approximation, Perturbation, and Projection Methods in Economic Analysis”, in *Handbook of Computational Economics*, ed. by Hans Amman, David Kendrick, and John Rust, North Holland Press, 511585.
* Juillard, Michel (1996): “Dynare: A program for the resolution and simulation of dynamic models with forward variables through the use of a relaxation algorithm,” CEPREMAP, *Couverture Orange*, 9602.
* Kim, Jinill and Sunghyun Kim (2003): “Spurious welfare reversals in international business cycle models,” *Journal of International Economics*, 60, 471500.
* Kanzow, Christian and Stefania Petra (2004): “On a semismooth least squares formulation of complementarity problems with gap reduction,” *Optimization Methods and Software*, 19, 507525.
* Kim, Jinill, Sunghyun Kim, Ernst Schaumburg, and Christopher A. Sims (2008): “Calculating and using second-order accurate solutions of discrete time dynamic equilibrium models,” *Journal of Economic Dynamics and Control*, 32(11), 33973414.
* Koop, Gary (2003), *Bayesian Econometrics*, John Wiley & Sons.
* Koopman, S. J. and J. Durbin (2000): “Fast Filtering and Smoothing for Multivariate State Space Models,” *Journal of Time Series Analysis*, 21(3), 281296.
* Koopman, S. J. and J. Durbin (2003): “Filtering and Smoothing of State Vector for Diffuse State Space Models,” *Journal of Time Series Analysis*, 24(1), 8598.
* Kuntsevich, Alexei V. and Franz Kappel (1997): “SolvOpt - The solver for local nonlinear optimization problems (version 1.1, Matlab, C, FORTRAN)”, University of Graz, Graz, Austria.
* Laffargue, Jean-Pierre (1990): “Résolution dun modèle macroéconomique avec anticipations rationnelles”, *Annales dÉconomie et Statistique*, 17, 97119.
* Liu, Jane and Mike West (2001): “Combined parameter and state estimation in simulation-based filtering”, in *Sequential Monte Carlo Methods in Practice*, Eds. Doucet, Freitas and Gordon, Springer Verlag.
* Lubik, Thomas and Frank Schorfheide (2007): “Do Central Banks Respond to Exchange Rate Movements? A Structural Investigation,” *Journal of Monetary Economics*, 54(4), 10691087.
* Mancini-Griffoli, Tommaso (2007): “Dynare User Guide: An introduction to the solution and estimation of DSGE models”.
* Murray, Lawrence M., Emlyn M. Jones and John Parslow (2013): “On Disturbance State-Space Models and the Particle Marginal Metropolis-Hastings Sampler”, *SIAM/ASA Journal on Uncertainty Quantification*, 1, 494521.
* Pearlman, Joseph, David Currie, and Paul Levine (1986): “Rational expectations models with partial information,” *Economic Modelling*, 3(2), 90105.
* Planas, Christophe, Marco Ratto and Alessandro Rossi (2015): “Slice sampling in Bayesian estimation of DSGE models”.
* Pfeifer, Johannes (2013): “A Guide to Specifying Observation Equations for the Estimation of DSGE Models”.
* Pfeifer, Johannes (2014): “An Introduction to Graphs in Dynare”.
* Rabanal, Pau and Juan Rubio-Ramirez (2003): “Comparing New Keynesian Models of the Business Cycle: A Bayesian Approach,” Federal Reserve of Atlanta, *Working Paper Series*, 2003-30.
* Raftery, Adrien E. and Steven Lewis (1992): “How many iterations in the Gibbs sampler?,” in *Bayesian Statistics, Vol. 4*, ed. J.O. Berger, J.M. Bernardo, A.P. * Dawid, and A.F.M. Smith, Clarendon Press: Oxford, pp. 763-773.
* Ratto, Marco (2008): “Analysing DSGE models with global sensitivity analysis”, *Computational Economics*, 31, 115139.
* Schorfheide, Frank (2000): “Loss Function-based evaluation of DSGE models,” *Journal of Applied Econometrics*, 15(6), 645670.
* Schmitt-Grohé, Stephanie and Martin Uríbe (2004): “Solving Dynamic General Equilibrium Models Using a Second-Order Approximation to the Policy Function,” *Journal of Economic Dynamics and Control*, 28(4), 755775.
* Schnabel, Robert B. and Elizabeth Eskow (1990): “A new modified Cholesky algorithm,” *SIAM Journal of Scientific and Statistical Computing*, 11, 11361158.
* Sims, Christopher A., Daniel F. Waggoner and Tao Zha (2008): “Methods for inference in large multiple-equation Markov-switching models,” *Journal of Econometrics*, 146, 255274.
* Skoeld, Martin and Gareth O. Roberts (2003): “Density Estimation for the Metropolis-Hastings Algorithm,” *Scandinavian Journal of Statistics*, 30, 699718.
* Smets, Frank and Rafael Wouters (2003): “An Estimated Dynamic Stochastic General Equilibrium Model of the Euro Area,” *Journal of the European Economic Association*, 1(5), 11231175.
* Stock, James H. and Mark W. Watson (1999). “Forecasting Inflation,”, *Journal of Monetary Economics*, 44(2), 293335.
* Uhlig, Harald (2001): “A Toolkit for Analysing Nonlinear Dynamic Stochastic Models Easily,” in *Computational Methods for the Study of Dynamic Economies*, Eds. Ramon Marimon and Andrew Scott, Oxford University Press, 3061.
* Villemot, Sébastien (2011): “Solving rational expectations models at first order: what Dynare does,” *Dynare Working Papers*, 2, CEPREMAP.

101
src/source/conf.py Normal file
View File

@ -0,0 +1,101 @@
# -*- coding: utf-8 -*-
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.mathjax']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Dynare'
copyright = u'2017, Dynare Team'
author = u'Dynare Team'
add_function_parentheses = False
version = u'4.6-unstable'
release = u'4.6-unstable'
language = 'en'
exclude_patterns = []
highlight_language = 'dynare'
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_logo = 'dynarelogo.png'
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'Dynaremanual'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'sphinxsetup': 'VerbatimBorderColor={rgb}{1,1,1},VerbatimColor={RGB}{240,240,240}, \
warningBorderColor={RGB}{255,50,50},OuterLinkColor={RGB}{34,139,34}, \
InnerLinkColor={RGB}{51,51,255},TitleColor={RGB}{51,51,255}',
'papersize': 'a4paper',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Manual.tex', u'Dynare Reference Manual',
u'Dynare team', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'manual', u'Dynare Reference Manual',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Dynare', u'Dynare Reference Manual',
author, 'Test', 'One line description of project.',
'Miscellaneous'),
]
def setup(sphinx):
from dynare import DynDomain
sphinx.add_domain(DynDomain)

358
src/source/dynare.py Normal file
View File

@ -0,0 +1,358 @@
# -*- coding: utf-8 -*-
"""
sphinx.domains.dynare
~~~~~~~~~~~~~~~~~~~~~
The Dynare domain.
Loosely based on the JavaScript domain from the Sphinx team and the CoffeScript domain
by Stephen Sugden (available at sphinx-contrib)
"""
import re
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from sphinx import addnodes
from sphinx.domains import Domain, ObjType
from sphinx.locale import l_, _
from sphinx.directives import ObjectDescription
from sphinx.roles import XRefRole
from sphinx.util.nodes import make_refnode
from sphinx.util.docfields import Field, GroupedField, TypedField
############### Dynare Object types #######################
class DynObject(ObjectDescription):
has_arguments = True
display_prefix = None
allow_nesting = False
def handle_signature(self, sig, signode):
sig = sig.strip()
# Some variable/parameter declarations combine spaces and parenthesis
# in a strange way, so they are treated separately
if sig.startswith(('var V','varexo V','varexo_det V','parameters P','model_comparison F')):
member = sig[:sig.index(' ')]
arglist = sig[sig.index(' '):]
# General cases
elif '(' in sig:
member = sig[:sig.index('(')]
arglist = sig[sig.index('('):]
arglist = arglist.strip()
elif ' ' in sig:
member = sig[:sig.index(' ')]
arglist = sig[sig.index(' '):]
else:
member = sig
arglist = None
prefix = self.env.ref_context.get('dynare:object', None)
name = member.strip()
fullname = name
signode['object'] = prefix
signode['fullname'] = fullname
if self.display_prefix:
signode += addnodes.desc_annotation(self.display_prefix, self.display_prefix)
signode += addnodes.desc_name(name, name)
if self.has_arguments:
if not arglist:
signode += addnodes.desc_parameterlist()
else:
signode += addnodes.desc_addname(arglist,arglist)
return fullname, prefix
def add_target_and_index(self, name_obj, sig, signode):
fullname = name_obj[0]
if fullname not in self.state.document.ids:
signode['names'].append(fullname)
signode['ids'].append(fullname)
signode['first'] = not self.names
self.state.document.note_explicit_target(signode)
objects = self.env.domaindata['dynare']['objects']
if fullname in objects:
self.state_machine.reporter.warning(
'duplicate object description of %s, ' % fullname +
'other instance in ' +
self.env.doc2path(objects[fullname][0]),line=self.lineno)
objects[fullname] = (self.env.docname, self.objtype)
indextext = self.get_index_text(fullname,name_obj)
if indextext:
self.indexnode['entries'].append(('single', indextext, fullname,'', None))
def get_index_text(self, objectname, name_obj):
name, obj = name_obj
regexp = re.compile(r'\s*=\s*')
if bool(regexp.search(name)):
aux, name = re.compile(r'\s*=\s*').split(name)
if self.objtype == 'function':
return _('%s (function)') % name
elif self.objtype == 'class':
return _('%s (class)') % name
elif self.objtype == 'datesmethod':
return _('%s (dates method)') % name
elif self.objtype == 'dseriesmethod':
return _('%s (dseries method)') % name
elif self.objtype == 'repmethod':
return _('%s (report method)') % name
elif self.objtype == 'matcomm':
return _('%s (MATLAB command)') % name
elif self.objtype == 'command':
return _('%s (command)') % name
elif self.objtype == 'block':
return _('%s (block)') % name
elif self.objtype == 'confblock':
name = name[1:-1]
return _('%s (config block)') % name
elif self.objtype == 'macrodir':
name = name[2:]
return _('%s (macro directive)') % name
class DynCallable(DynObject):
has_arguments = True
doc_field_types = [
TypedField('arguments', label=l_('Arguments'),
names=('argument', 'arg', 'parameter', 'param'),
typerolename='func', typenames=('paramtype', 'type')),
Field('returnvalue', label=l_('Returns'), has_arg=False,
names=('returns', 'return')),
Field('returntype', label=l_('Return type'), has_arg=False,
names=('rtype',)),
Field('example', label=l_('Example'), has_arg=False,
names=('ex',)),
]
class DynClass(DynObject):
has_arguments = False
display_prefix = 'Dynare class: '
allow_nesting = True
doc_field_types = [
TypedField('members', label=l_('Members'),
names=('argument', 'arg', ),
typerolename='func', typenames=('type', )),
Field('example', label=l_('Example'), has_arg=False,
names=('ex',)),
]
class DynFunction(DynCallable):
display_prefix = 'Function: '
allow_nesting = True
class DatesMethod(DynCallable):
display_prefix = 'Method: '
allow_nesting = True
class DseriesMethod(DynCallable):
display_prefix = 'Method: '
allow_nesting = True
class DynRepMethod(DynCallable):
display_prefix = 'Method on report: '
allow_nesting = True
class MatComm(DynCallable):
display_prefix = 'MATLAB/Octave command: '
allow_nesting = False
class DynComm(DynCallable):
display_prefix = 'Command: '
allow_nesting = False
class DynBlock(DynCallable):
display_prefix = 'Block: '
allow_nesting = False
class DynConfBlock(DynCallable):
display_prefix = 'Configuration block: '
has_arguments = False
allow_nesting = False
class DynMacroDir(DynCallable):
display_prefix = 'Macro directive: '
allow_nesting = False
class Constructor(DynCallable):
display_prefix = 'Constructor: '
allow_nesting = False
class DynSimpleObject(ObjectDescription):
has_arguments = False
allow_nesting = False
def handle_signature(self, sig, signode):
sig = sig.strip()
member = sig
arglist = None
prefix = self.env.ref_context.get('dynare:object', None)
name = member
fullname = name
signode['object'] = prefix
signode['fullname'] = fullname
if self.display_prefix:
signode += addnodes.desc_annotation(self.display_prefix, self.display_prefix)
signode += addnodes.desc_name(name, name)
return fullname, prefix
def add_target_and_index(self, name_obj, sig, signode):
fullname = name_obj[0]
if fullname not in self.state.document.ids:
signode['names'].append(fullname)
signode['ids'].append(fullname)
signode['first'] = not self.names
self.state.document.note_explicit_target(signode)
objects = self.env.domaindata['dynare']['objects']
if fullname in objects:
self.state_machine.reporter.warning(
'duplicate object description of %s, ' % fullname +
'other instance in ' +
self.env.doc2path(objects[fullname][0]), line=self.lineno)
objects[fullname] = self.env.docname, self.objtype
indextext = self.get_index_text(fullname,name_obj)
if indextext:
self.indexnode['entries'].append(('single', indextext, fullname,'', None))
def get_index_text(self, objectname, name_obj):
name, obj = name_obj
if self.objtype == 'construct':
name, rest = name.split(' ',1)
return _('%s (constructor)') % name
elif self.objtype == 'matvar':
return _('%s (MATLAB variable)') % name
elif self.objtype == 'specvar':
return _('%s (special variable)') % name
elif self.objtype == 'operator':
endsig = name.find(' ')
name = name[0:endsig]
return _('%s (operator)') % name
elif self.objtype == 'constant':
return _('%s (constant)') % name
class MatlabVar(DynSimpleObject):
display_prefix = 'MATLAB/Octave variable: '
allow_nesting = False
class SpecialVar(MatlabVar):
display_prefix = 'Special variable: '
class Operator(MatlabVar):
display_prefix = 'Operator: '
class Constant(MatlabVar):
display_prefix = 'Constant: '
class Option(MatlabVar):
display_prefix = None
############## Cross-referencing ####################
class DynareXRefRole(XRefRole):
def process_link(self, env, refnode, has_explicit_title, title, target):
refnode['dynare:object'] = env.ref_context.get('dynare:object')
return title, target
############### Dynare domain #######################
class DynDomain(Domain):
name = 'dynare'
label = 'Dynare'
object_types = {
'function': ObjType(l_('function'), 'func'),
'datesmethod': ObjType(l_('method'), 'datmeth'),
'dseriesmethod': ObjType(l_('method'), 'dsermeth'),
'repmethod': ObjType(l_('method on report'), 'repmeth'),
'matcomm': ObjType(l_('matlab command'), 'mcomm'),
'command': ObjType(l_('command'), 'comm'),
'class': ObjType(l_('class'), 'class'),
'block': ObjType(l_('block'), 'bck'),
'confblock': ObjType(l_('config block'), 'cbck'),
'macrodir': ObjType(l_('macro directive'), 'mdir'),
'construct': ObjType(l_('constructor'), 'cstr'),
'matvar': ObjType(l_('matlab variable'), 'mvar'),
'specvar': ObjType(l_('special variable'), 'svar'),
'operator': ObjType(l_('operator'), 'op'),
'constant': ObjType(l_('constant'), 'const'),
'option': ObjType(l_('option'), 'opt'),
}
directives = {
'function': DynFunction,
'datesmethod': DatesMethod,
'dseriesmethod': DseriesMethod,
'repmethod': DynRepMethod,
'matcomm': MatComm,
'command': DynComm,
'class': DynClass,
'block': DynBlock,
'confblock': DynConfBlock,
'macrodir': DynMacroDir,
'construct': Constructor,
'matvar': MatlabVar,
'specvar': SpecialVar,
'operator': Operator,
'constant': Constant,
'option': Option,
}
roles = {
'func': DynareXRefRole(),
'datmeth': DynareXRefRole(),
'dsermeth': DynareXRefRole(),
'repmeth': DynareXRefRole(),
'mcomm': DynareXRefRole(),
'comm': DynareXRefRole(),
'class': DynareXRefRole(),
'bck': DynareXRefRole(),
'cbck': DynareXRefRole(),
'mdir': DynareXRefRole(),
'cstr': DynareXRefRole(),
'mvar': DynareXRefRole(),
'svar': DynareXRefRole(),
'op': DynareXRefRole(),
'const': DynareXRefRole(),
'opt': DynareXRefRole(),
}
initial_data = {
'objects': {},
}
def clear_doc(self, docname):
for fullname, (fn, _l) in list(self.data['objects'].items()):
if fn == docname:
del self.data['objects'][fullname]
def find_obj(self, env, obj, name, typ, searchorder=0):
objects = self.data['objects']
newname = name # None
return newname, objects.get(newname)
def merge_domaindata(self, docnames, otherdata):
for fullname, (fn, objtype) in otherdata['objects'].items():
if fn in docnames:
self.data['objects'][fullname] = (fn, objtype)
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
objectname = node.get('dynare:object')
searchorder = node.hasattr('refspecific') and 1 or 0
name, obj = self.find_obj(env, objectname, target, typ, searchorder)
if not obj:
return None
return make_refnode(builder, fromdocname, obj[0], name, contnode, name)
def get_objects(self):
for refname, (docname, type) in list(self.data['objects'].items()):
yield refname, refname, type, docname, refname, 1

BIN
src/source/dynare.pyc Normal file

Binary file not shown.

BIN
src/source/dynarelogo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

View File

@ -0,0 +1,152 @@
.. default-domain:: dynare
####################
Dynare misc commands
####################
.. command:: prior_function(OPTIONS);
Executes a user-defined function on parameter draws from the prior distribution. Dynare returns the results of the computations for all draws in an $ndraws$ by $n$ cell array named ``oo_.prior_function_results``.
*Options*
.. option:: function = FUNCTION_NAME
The function must have the following header ``output_cell = FILENAME(xparam1,M_,options_,oo_,estim_params_,bayestopt_,dataset_,dataset_info)``, providing read-only access to all Dynare structures. The only output argument allowed is a :math:`1 \times n` cell array, which allows for storing any type of output/computations. This option is required.
.. option:: sampling_draws = INTEGER
Number of draws used for sampling. Default: 500.
.. command:: posterior_function(OPTIONS);
Same as the :comm:`prior_function` command but for the posterior distribution. Results returned in ``oo_.posterior_function_results``.
*Options*
.. option:: function = FUNCTION_NAME
See :opt:`prior_function_function <function = FUNCTION_NAME>`.
.. option:: sampling_draws = INTEGER
See :opt:`prior_function_sampling_draws <sampling_draws = INTEGER>`.
.. command:: generate_trace_plots(CHAIN_NUMBER);
Generates trace plots of the MCMC draws for all estimated parameters and the posterior density in the specified Markov Chain ``CHAIN_NUMBER``.
.. matcomm:: internals FLAG ROUTINENAME[.m]|MODFILENAME
Depending on the value of ``FLAG``, the ``internals`` command can be used to run unitary tests specific to a Matlab/Octave routine (if available), to display documentation about a Matlab/Octave routine, or to extract some informations about the state of Dynare.
*Flags*
``--test``
Performs the unitary test associated to ROUTINENAME (if this routine exists and if the matlab/octave ``.m`` file has unitary test sections).
:ex:
::
>> internals --test ROUTINENAME
if ``routine.m`` is not in the current directory, the full path has to be given::
>> internals --test ../matlab/fr/ROUTINENAME
``--info``
Prints on screen the internal documentation of ROUTINENAME (if this routine exists and if this routine has a texinfo internal documentation header). The path to ``ROUTINENAME`` has to be provided, if the routine is not in the current directory.
:ex:
::
>> internals --doc ../matlab/fr/ROUTINENAME
At this time, will work properly for only a small number of routines. At the top of the (available) Matlab/Octave routines a commented block for the internal documentation is written in the GNU texinfo documentation format. This block is processed by calling texinfo from MATLAB. Consequently, texinfo has to be installed on your machine.
``--display-mh-history``
Displays information about the previously saved MCMC draws generated by a ``.mod`` file named MODFILENAME. This file must be in the current directory.
:ex:
::
>> internals --display-mh-history MODFILENAME
``--load-mh-history``
Loads into the Matlab/Octaves workspace informations about the previously saved MCMC draws generated by a ``.mod`` file named MODFILENAME.
:ex:
::
>> internals --load-mh-history MODFILENAME
This will create a structure called ``mcmc_informations`` (in the workspace) with the following fields:
``Nblck``
The number of MCMC chains.
``InitialParameters``
A ``Nblck*n``, where ``n`` is the number of estimated parameters, array of doubles. Initial state of the MCMC.
``LastParameters``
A ``Nblck*n``, where ``n`` is the number of estimated parameters, array of doubles. Current state of the MCMC.
``InitialLogPost``
A ``Nblck*1`` array of doubles. Initial value of the posterior kernel.
``LastLogPost``
A ``Nblck*1`` array of doubles. Current value of the posterior kernel.
``InitialSeeds``
A ``1*Nblck`` structure array. Initial state of the random number generator.
``LastSeeds``
A ``1*Nblck`` structure array. Current state of the random number generator.
``AcceptanceRatio``
A ``1*Nblck`` array of doubles. Current acceptance ratios.
.. matcomm:: prior [options[, ...]];
Prints various informations about the prior distribution depending on the options. If no options are provided, the command returns the list of available options. Following options are available:
``table``
Prints a table describing the marginal prior distributions (mean, mode, std., lower and upper bounds, HPD interval).
``moments``
Computes and displays first and second order moments of the endogenous variables at the prior mode (considering the linearized version of the model).
``optimize``
Optimizes the prior density (starting from a random initial guess). The parameters such that the steady state does not exist or does not satisfy the Blanchard and Kahn conditions are penalized, as they would be when maximizing the posterior density. If a significant proportion of the prior mass is defined over such regions, the optimization algorithm may fail to converge to the true solution (the prior mode).
``simulate``
Computes the effective prior mass using a Monte-Carlo. Ideally the effective prior mass should be equal to 1, otherwise problems may arise when maximising the posterior density and model comparison based on marginal densities may be unfair. When comparing models, say :math:`A` and :math:`B`, the marginal densities, :math:`m_A` and :math:`m_B`, should be corrected for the estimated effective prior mass :math:`p_A\neq p_B \leq 1` so that the prior mass of the compared models are identical.
``plot``
Plots the marginal prior density.

42
src/source/examples.rst Normal file
View File

@ -0,0 +1,42 @@
.. default-domain:: dynare
########
Examples
########
Dynare comes with a database of example ``.mod`` files, which are designed to show a broad range of Dynare features, and are taken from academic papers for most of them. You should have these files in the ``examples`` subdirectory of your distribution.
Here is a short list of the examples included. For a more complete description, please refer to the comments inside the files themselves.
``ramst.mod``
An elementary real business cycle (RBC) model, simulated in a deterministic setup.
``example1.mod``
``example2.mod``
Two examples of a small RBC model in a stochastic setup, presented in *Collard (2001)* (see the file ``guide.pdf`` which comes with Dynare).
``example3.mod``
A small RBC model in a stochastic setup, presented in *Collard (2001)*. The steady state is solved analytically using the ``steady_state_model`` block (see :bck:`steady_state_model`).
``fs2000.mod``
A cash in advance model, estimated by *Schorfheide (2000)*. The file shows how to use Dynare for estimation.
``fs2000_nonstationary.mod``
The same model than ``fs2000.mod``, but written in non-stationary form. Detrending of the equations is done by Dynare.
``bkk.mod``
Multi-country RBC model with time to build, presented in *Backus, Kehoe and Kydland (1992)*. The file shows how to use Dynares macro-processor.
``agtrend.mod``
Small open economy RBC model with shocks to the growth trend, presented in *Aguiar and Gopinath (2004)*.
``NK_baseline.mod``
Baseline New Keynesian Model estimated in *Fernández-Villaverde (2010)*. It demonstrates how to use an explicit steady state file to update parameters and call a numerical solver.

46
src/source/index.rst Normal file
View File

@ -0,0 +1,46 @@
The Dynare Reference Manual, version 4.6-unstable.
==================================================
Currently the development team of Dynare is composed of:
* Stéphane Adjemian
* Houtan Bastani
* Alejandro Buesa
* Michel Juillard
* Frédéric Karamé
* Junior Maih
* Ferhat Mihoubi
* Johannes Pfeifer
* Marco Ratto
* Sébastien Villemot
Copyright © 1996-2017, Dynare Team.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
A copy of the license can be found at `http://www.gnu.org/licenses/fdl.txt <http://www.gnu.org/licenses/fdl.txt>`_.
.. toctree::
:numbered:
:maxdepth: 4
:caption: Contents:
introduction
installconfig
runningdynare
themodelfile
theconfigfile
timeseries
reporting
examples
dynaremisccomm
bibliography
.. only:: builder_html
Indices and tables
==================
* :ref:`genindex`

View File

@ -0,0 +1,157 @@
.. default-domain:: dynare
##############################
Installation and configuration
##############################
Software requirements
=====================
Packaged versions of Dynare are available for Windows XP/Vista/7/8, `Debian GNU/Linux <http://www.debian.org/>`_, `Ubuntu`_ and macOS 10.8 or later. Dynare should work on other systems, but some compilation steps are necessary in that case.
In order to run Dynare, you need one of the following:
* MATLAB version 7.5 (R2007b) or above (MATLAB R2009b 64-bit for macOS);
* GNU Octave version 3.6 or above.
Packages of GNU Octave can be downloaded on the `Dynare website`_.
The following optional extensions are also useful to benefit from extra features, but are in no way required:
* If under MATLAB: the Optimization Toolbox, the Statistics Toolbox, the Control System Toolbox;
* If under GNU Octave, the following `Octave-Forge <http://octave.sourceforge.net/>`_ packages: ``optim, io, statistics, control``.
Installation of Dynare
======================
After installation, Dynare can be used in any directory on your computer. It is best practice to keep your model files in directories different from the one containing the Dynare toolbox. That way you can upgrade Dynare and discard the previous version without having to worry about your own files.
On Windows
----------
Execute the automated installer called ``dynare-4.x.y-win.exe`` (where ``4.x.y`` is the version number), and follow the instructions. The default installation directory is ``c:\dynare\4.x.y``.
After installation, this directory will contain several sub-directories, among which are ``matlab``, ``mex`` and ``doc``.
The installer will also add an entry in your Start Menu with a shortcut to the documentation files and uninstaller.
Note that you can have several versions of Dynare coexisting (for example in ``c:\dynare``), as long as you correctly adjust your path settings (see see :ref:`words-warning`).
On Debian GNU/Linux and Ubuntu
------------------------------
Please refer to the `Dynare wiki`_ for detailed instructions.
Dynare will be installed under ``/usr/lib/dynare``. Documentation will be under ``/usr/share/doc/dynare-doc``.
On macOS
--------
To install Dynare for use with Matlab, execute the automated installer called ``dynare-4.x.y.pkg`` (where *4.x.y* is the version number), and follow the instructions. The default installation directory is ``/Applications/Dynare/4.x.y`` (please refer to the `Dynare wiki`_ for detailed instructions).
After installation, this directory will contain several sub-directories, among which are ``matlab``, ``mex`` and ``doc``.
Note that several versions of Dynare can coexist (by default in ``/Applications/Dynare``), as long as you correctly adjust your path settings (see :ref:`words-warning`).
To install Dynare for Octave, first install Homebrew following the instructions on their site: `https://brew.sh/ <https://brew.sh/>`_. Then install Octave, issuing the command ``brew install octave`` at the Terminal prompt. You can then install the latest stable version of Dynare by typing ``brew install dynare`` at the Terminal prompt. You can also pass options to the installation command. These options can be viewed by typing ``brew info dynare`` at the Terminal prompt.
For other systems
-----------------
You need to download Dynare source code from the `Dynare website`_ and unpack it somewhere.
Then you will need to recompile the pre-processor and the dynamic loadable libraries. Please refer to `README.md <https://github.com/DynareTeam/dynare/blob/master/README.md>`_.
.. _compil-install:
Compiler installation
=====================
Prerequisites on Windows
------------------------
If you are using MATLAB under Windows, install a C++ compiler on your machine and configure it with MATLAB. There are at least two free compilers you can use. First, there is Microsofts Visual Studio Community (`https://www.visualstudio.com/`), which has the largest history of MATLAB support, but requires much space on the hard-disk. Second, since MATLAB R2015b, MATLAB supports the MinGW-w64 C/C++ Compiler from TDM-GCC. To install this compiler, use the Add-Ons menu of MATLAB. Search for MinGW or select it from Features.
For older version of MATLAB, in particular before R2014a, it may sometimes make sense to use the ``gcc`` compiler provided by Cygwin. However, integrating it in MATLAB can be quite cumbersome and should be considered as a legacy option. For details, see `instructions on the Dynare wiki`_.
Prerequisites on Debian GNU/Linux and Ubuntu
--------------------------------------------
Users of MATLAB under Linux need to have a working compilation environment installed. If not already present, it can be installed via ``apt-get install build-essential``.
Users of Octave under Linux should install the package for MEX file compilation (under Debian or Ubuntu, it is called ``liboctave-dev``).
Prerequisites on macOS
----------------------
If you are using MATLAB under macOS, you should install the latest version of XCode: `see instructions on the Dynare wiki <http://www.dynare.org/DynareWiki/InstallOnMacOSX>`_.
Configuration
=============
For MATLAB
----------
You need to add the ``matlab`` subdirectory of your Dynare installation to MATLAB path. You have two options for doing that:
* Using the ``addpath`` command in the MATLAB command window:
Under Windows, assuming that you have installed Dynare in the standard location, and replacing ``4.x.y`` with the correct version number, type::
addpath c:/dynare/4.x.y/matlab
Under Debian GNU/Linux or Ubuntu, type::
addpath /usr/lib/dynare/matlab
Under macOS, assuming that you have installed Dynare in the standard location, and replacing ``4.x.y`` with the correct version number, type::
addpath /Applications/Dynare/4.x.y/matlab
MATLAB will not remember this setting next time you run it, and you will have to do it again.
* Via the menu entries:
Select the “Set Path” entry in the “File” menu, then click on “Add Folder…”, and select the ``matlab`` subdirectory of your Dynare installation. Note that you *should not* use “Add with Subfolders…”. Apply the settings by clicking on “Save”. Note that MATLAB will remember this setting next time you run it.
For GNU Octave
--------------
You need to add the ``matlab`` subdirectory of your Dynare installation to Octave path, using the ``addpath`` at the Octave command prompt.
Under Windows, assuming that you have installed Dynare in the standard location, and replacing “*4.x.y*” with the correct version number, type::
addpath c:/dynare/4.x.y/matlab
Under Debian GNU/Linux or Ubuntu, there is no need to use the ``addpath`` command; the packaging does it for you.
Under macOS, assuming that you have installed Dynare and Octave via Homebrew, type::
addpath /usr/local/opt/dynare/lib/dynare/matlab
If you dont want to type this command every time you run Octave, you can put it in a file called ``.octaverc`` in your home directory (under Windows this will generally be ``c:\Documents and Settings\USERNAME\`` while under macOS it is ``/Users/USERNAME/``). This file is run by Octave at every startup.
.. _words-warning:
Some words of warning
---------------------
You should be very careful about the content of your MATLAB or Octave path. You can display its content by simply typing ``path`` in the command window.
The path should normally contain system directories of MATLAB or Octave, and some subdirectories of your Dynare installation. You have to manually add the ``matlab`` subdirectory, and Dynare will automatically add a few other subdirectories at runtime (depending on your configuration). You must verify that there is no directory coming from another version of Dynare than the one you are planning to use.
You have to be aware that adding other directories to your path can potentially create problems if any of your M-files have the same name as a Dynare file. Your file would then override the Dynare file, making Dynare unusable.
.. _Ubuntu: http://www.ubuntu.com/
.. _Dynare website: http://www.dynare.org/
.. _Dynare wiki: http://www.dynare.org/
.. _instructions on the Dynare wiki : http://www.dynare.org/DynareWiki/ConfigureMatlabWindowsForMexCompilation

View File

@ -0,0 +1,54 @@
.. default-domain:: dynare
############
Introduction
############
What is Dynare?
===============
Dynare is a software platform for handling a wide class of economic models, in particular dynamic stochastic general equilibrium (DSGE) and overlapping generations (OLG) models. The models solved by Dynare include those relying on the *rational expectations* hypothesis, wherein agents form their expectations about the future in a way consistent with the model. But Dynare is also able to handle models where expectations are formed differently: on one extreme, models where agents perfectly anticipate the future; on the other extreme, models where agents have limited rationality or imperfect knowledge of the state of the economy and, hence, form their expectations through a learning process. In terms of types of agents, models solved by Dynare can incorporate consumers, productive firms, governments, monetary authorities, investors and financial intermediaries. Some degree of heterogeneity can be achieved by including several distinct classes of agents in each of the aforementioned agent categories.
Dynare offers a user-friendly and intuitive way of describing these models. It is able to perform simulations of the model given a calibration of the model parameters and is also able to estimate these parameters given a dataset. In practice, the user will write a text file containing the list of model variables, the dynamic equations linking these variables together, the computing tasks to be performed and the desired graphical or numerical outputs.
A large panel of applied mathematics and computer science techniques are internally employed by Dynare: multivariate nonlinear solving and optimization, matrix factorizations, local functional approximation, Kalman filters and smoothers, MCMC techniques for Bayesian estimation, graph algorithms, optimal control, …
Various public bodies (central banks, ministries of economy and finance, international organisations) and some private financial institutions use Dynare for performing policy analysis exercises and as a support tool for forecasting exercises. In the academic world, Dynare is used for research and teaching purposes in postgraduate macroeconomics courses.
Dynare is a free software, which means that it can be downloaded free of charge, that its source code is freely available, and that it can be used for both non-profit and for-profit purposes. Most of the source files are covered by the GNU General Public Licence (GPL) version 3 or later (there are some exceptions to this, see the file license.txt in Dynare distribution). It is available for the Windows, macOS, and Linux platforms and is fully documented through a user guide and a reference manual. Part of Dynare is programmed in C++, while the rest is written using the `MATLAB`_ programming language. The latter implies that commercially-available MATLAB software is required in order to run Dynare. However, as an alternative to MATLAB, Dynare is also able to run on top of `GNU Octave`_ (basically a free clone of MATLAB): this possibility is particularly interesting for students or institutions who cannot afford, or do not want to pay for, MATLAB and are willing to bear the concomitant performance loss.
The development of Dynare is mainly done at `CEPREMAP`_ by a core team of researchers who devote part of their time to software development. Currently the development team of Dynare is composed of Stéphane Adjemian (Université du Maine, Gains and Cepremap), Houtan Bastani (Cepremap), Alejandro Buesa (Cepremap), Michel Juillard (Banque de France), Frédéric Karamé (Université du Maine, Gains and Cepremap), Junior Maih (Norges Bank), Ferhat Mihoubi (Université Paris-Est Créteil, Epee and Cepremap), Johannes Pfeifer (University of Cologne), Marco Ratto (European Commission, Joint Research Centre - JRC) and Sébastien Villemot (OFCE Sciences Po). Increasingly, the developer base is expanding, as tools developed by researchers outside of Cepremap are integrated into Dynare. Financial support is provided by Cepremap, Banque de France and DSGE-net (an international research network for DSGE modeling). The Dynare project also received funding through the Seventh Framework Programme for Research (FP7) of the European Commissions Socio-economic Sciences and Humanities (SSH) Program from October 2008 to September 2011 under grant agreement SSH-CT-2009-225149.
Interaction between developers and users of Dynare is central to the project. A `web forum`_ is available for users who have questions about the usage of Dynare or who want to report bugs. Training sessions are given through the Dynare Summer School, which is organized every year and is attended by about 40 people. Finally, priorities in terms of future developments and features to be added are decided in cooperation with the institutions providing financial support.
Documentation sources
=====================
The present document is the reference manual for Dynare. It documents all commands and features in a systematic fashion.
New users should rather begin with Dynare User Guide (*Mancini (2007)*), distributed with Dynare and also available from the `official Dynare website`_.
Other useful sources of information include the `Dynare wiki`_ and the `Dynare forums`_.
Citing Dynare in your research
==============================
If you would like to refer to Dynare in a research article, the recommended way is to cite the present manual, as follows:
Stéphane Adjemian, Houtan Bastani, Michel Juillard, Frédéric Karamé, Ferhat Mihoubi, George Perendia, Johannes Pfeifer, Marco Ratto and Sébastien Villemot (2011), “Dynare: Reference Manual, Version 4,” *Dynare Working Papers*, 1, CEPREMAP
Note that citing the Dynare Reference Manual in your research is a good way to help the Dynare project.
If you want to give a URL, use the address of the Dynare website: http://www.dynare.org.
.. _MATLAB: http://www.mathworks.com/products/matlab/
.. _GNU Octave: http://www.octave.org/
.. _CEPREMAP: http://www.cepremap.org/
.. _web forum: http://www.dynare.org/phpBB3
.. _official Dynare website: http://www.dynare.org/
.. _Dynare wiki: http://www.dynare.org/
.. _Dynare forums: http://www.dynare.org/phpBB3

645
src/source/reporting.rst Normal file
View File

@ -0,0 +1,645 @@
.. default-domain:: dynare
#########
Reporting
#########
Dynare provides a simple interface for creating LaTeX reports, comprised of LaTeX tables and ``PGFPLOTS/TikZ graphs``. You can use the report as created through Dynare or pick out the pieces (tables and graphs) you want for inclusion in your own paper. Though Dynare provides a subset of options available through ``PGFPLOTS/TikZ``, you can easily modify the graphs created by Dynare using the options available in the ``PGFPLOTS/TikZ`` manual. You can either do this manually or by passing the options to :opt:`miscTikzAxisOptions <miscTikzAxisOptions, STRING>` or :opt:`graphMiscTikzAddPlotOptions <graphMiscTikzAddPlotOptions, STRING>`.
Reports are created and modified by calling methods on class objects. The objects are hierarchical, with the following order (from highest to lowest): ``Report``, ``Page``, ``Section``, ``Graph/Table/Vspace``, ``Series``. For simplicity of syntax, we abstract away from these classes, allowing you to operate directly on a ``Report`` object, while maintaining the names of these classes in the ``Report`` Class methods you will use.
The report is created sequentially, command by command, hence the order of the commands matters. When an object of a certain hierarchy is inserted, all methods will function on that object until an object of equal or greater hierarchy is added. Hence, once you add a ``Page`` to the report, every time you add a ``Section`` object, it will be added to this ``Page`` until another ``Page`` is added to the report (via :repmeth:`addPage`). This will become more clear with the example at the end of the section.
**Options to the methods are passed differently than those to Dynare commands**. They take the form of named options to Matlab functions where the arguments come in pairs (e.g. ``function_name(`option_1_name', `option_1_value', `option_2_name', `option_2_value',`` ...), where ``option_X_name`` is the name of the option while ``option_X_value`` is the value assigned to that option). The ordering of the option pairs matters only in the unusual case when an option is provided twice (probably erroneously). In this case, the last value passed is the one that is used.
Below, you will see a list of methods available for the Report class and a clarifying example.
.. repmethod:: report
Instantiates a ``Report`` object.
*Options*
.. option:: compiler, FILENAME
The full path to the LaTeX compiler on your system. If this option is not provided, Dynare will try to find the appropriate program to compile LaTeX on your system. Default is system dependent:
* Windows: the result of findtexmf ```--file-type=exe pdflatex``.
* macOS and Linux: the result of ``which pdflatex``.
.. option:: showDate, BOOLEAN
Display the date and time when the report was compiled. Default: ``true``.
.. option:: fileName, FILENAME
The file name to use when saving this report. Default: ``report.tex``.
.. option:: header, STRING
The valid LaTeX code to be included in the report before ``\begin{document}``. Default: ``empty``.
.. option:: margin, DOUBLE
The margin size. Default: ``2.5``.
.. option:: marginUnit, `cm' | `in'
Units associated with the margin. Default: ```cm'``.
.. option:: orientation, `landscape' | `portrait'
Paper orientation: Default: ```portrait'``.
.. option:: paper, `a4' | `letter'
Paper size. Default: ```a4'``.
.. option:: showOutput, BOOLEAN
Print report creation progress to screen. Shows you the page number as it is created and as it is written. This is useful to see where a potential error occurs in report creation. Default: ``true``.
.. option:: title, STRING
Report Title. Default: ``none``.
.. repmethod:: addPage
Adds a Page to the Report.
*Options*
.. option:: footnote, STRING
A footnote to be included at the bottom of this page. Default: ``none``.
.. option:: latex, STRING
The valid LaTeX code to be used for this page. Alows the user to create a page to be included in the report by passing LaTeX code directly. If this option is passed, the page itself will be saved in the :opt:`pageDirName <pageDirName, STRING>` directory in the form ``page_X.tex`` where X refers to the page number. Default: ``empty``.
.. option:: orientation, `landscape' | `portrait'
See :opt:`orientation <orientation, `landscape' | `portrait'>`.
.. option:: pageDirName, STRING
The name of the folder in which to store this page. Only used when the :opt:`latex <latex, STRING>` command is passed. Default: ``tmpRepDir``.
.. option:: paper, `a4' | `letter'
See :opt:`paper <paper, `a4' | `letter'>`.
.. option:: title, STRING | CELL_ARRAY_STRINGS
With one entry (a STRING), the title of the page. With more than one entry (a CELL_ARRAY_STRINGS), the title and subtitle(s) of the page. Values passed must be valid LaTeX code (e.g., ``%`` must be ``\%``). Default: ``none``.
.. option:: titleFormat, STRING | CELL_ARRAY_STRINGS
A string representing the valid LaTeX markup to use on ``title``. The number of cell array entries must be equal to that of the ``title`` option if you do not want to use the default value for the title (and subtitles). Default: ``\large\bfseries``.
.. option:: titleTruncate, INTEGER
Useful when automatically generating page titles that may become too long, ``titleTruncate`` can be used to truncate a title (and subsequent subtitles) when they pass the specified number of characters. Default: ``.off``.
.. repmethod:: addSection
Adds a ``Section`` to a ``Page``.
*Options*
.. option:: cols, INTEGER
The number of columns in the section. Default: ``1``.
.. option:: height, STRING
A string to be used with the ``\sectionheight`` LaTeX command. Default: ``'!'``
.. repmethod:: addGraph
Adds a ``Graph`` to a ``Section``.
*Options*
.. option:: data, dseries
The ``dseries`` that provides the data for the graph. Default: ``none``.
.. option:: axisShape, `box' | `L'
The shape the axis should have. ```box'`` means that there is an axis line to the left, right, bottom, and top of the graphed line(s). 'L'`` means that there is an axis to the left and bottom of the graphed line(s). Default: ```box'``.
.. option:: graphDirName, STRING
The name of the folder in which to store this figure. Default: ``tmpRepDir``.
.. option:: graphName, STRING
The name to use when saving this figure. Default: something of the form ``graph_pg1_sec2_row1_col3.tex``.
.. option:: height, DOUBLE
The height of the graph, in inches. Default: ``4.5``.
.. option:: showGrid, BOOLEAN
Whether or not to display the major grid on the graph. Default: ``true``.
.. option:: showLegend, BOOLEAN
Whether or not to display the legend.
NB: Unless you use the :opt:`graphLegendName <graphLegendName, STRING>` option, the name displayed in the legend is the tex name associated with the ``dseries``. You can modify this tex name by using :dsermeth:`tex_rename <B = tex_rename>`. Default: ``false``.
.. option:: legendAt, NUMERICAL_VECTOR
The coordinates for the legend location. If this option is passed, it overrides the :opt:`legendLocation <legendLocation, OPTION>` option. Must be of size ``2``. Default: ``empty``.
.. option:: showLegendBox, BOOLEAN
Whether or not to display a box around the legend. Default: ``false``.
.. option:: legendLocation, OPTION
Where to place the legend in the graph. Possible values for OPTION are::
`south west' | `south east' | `north west' | `north east' | `outer north east'
Default: ```south east'``.
.. option:: legendOrientation, `vertical' | `horizontal'
Orientation of the legend. Default: ```horizontal'``.
.. option:: legendFontSize, OPTION
The font size for legend entries. Possible values for OPTION are::
`tiny' | `scriptsize' | `footnotesize' | `small' | `normalsize' |
`large' | `Large' | `LARGE' | `huge' | `Huge'
Default: ``tiny``.
.. option:: miscTikzAxisOptions, STRING
If you are comfortable with ``PGFPLOTS/TikZ``, you can use this option to pass arguments directly to the ``PGFPLOTS/TikZ`` axis environment command. Specifically to be used for desired ``PGFPLOTS/TikZ`` options that have not been incorporated into Dynare Reporting. Default: ``empty``.
.. option:: miscTikzPictureOptions, STRING
If you are comfortable with ``PGFPLOTS/TikZ``, you can use this option to pass arguments directly to the ``PGFPLOTS/TikZ`` ``tikzpicture`` environment command. (e.g., to scale the graph in the x and y dimensions, you can pass following to this option: 'xscale=2.5, yscale=0.5'``). Specifically to be used for desired ``PGFPLOTS/TikZ`` options that have not been incorporated into Dynare Reporting. Default: ``empty``.
.. option:: seriesToUse, CELL_ARRAY_STRINGS
The names of the series contained in the ``dseries`` provided to the :opt:`data <data, dseries>` option. If empty, use all series provided to ``data`` option. Default: ``empty``.
.. option:: shade, dates
The date range showing the portion of the graph that should be shaded. Default: ``none``.
.. option:: shadeColor, STRING
The color to use in the shaded portion of the graph. All valid color strings defined for use by ``PGFPLOTS/TikZ`` are valid. A list of defined colors is::
'red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'black', 'gray',
'white','darkgray', 'lightgray', 'brown', 'lime', 'olive', 'orange',
'pink', 'purple', 'teal', 'violet'.
Furthermore, You can use combinations of these colors. For example, if you wanted a color that is 20\% green and 80\% purple, you could pass the string ``'green!20!purple'``. You can also use RGB colors, following the syntax: ```rgb,255:red,231;green,84;blue,121'`` which corresponds to the RGB color ``(231;84;121)``. More examples are available in the section 4.7.5 of the ``PGFPLOTS/TikZ`` manual, revision 1.10. Default: ```green'``
.. option:: shadeOpacity, DOUBLE
The opacity of the shaded area, must be in ``[0,100]``. Default: ``20``.
.. option:: tickFontSize, OPTION
The font size for x- and y-axis tick labels. Possible values for OPTION are::
`tiny' | `scriptsize' | `footnotesize' | `small' | `normalsize' |
`large' | `Large' | `LARGE' | `huge' | `Huge'
Default: ``normalsize``.
.. option:: title, STRING | CELL_ARRAY_STRINGS
Same as :opt:`title <title, STRING | CELL_ARRAY_STRINGS>`, just for graphs.
.. option:: titleFontSize, OPTION
The font size for title. Possible values for OPTION are::
`tiny' | `scriptsize' | `footnotesize' | `small' | `normalsize' |
`large' | `Large' | `LARGE' | `huge' | `Huge'
Default: ``normalsize``.
.. option:: titleFormat, STRING
The format to use for the graph title. Unlike :opt:`titleFormat <titleFormat, STRING | CELL_ARRAY_STRINGS>`, due to a constraint of ``TikZ``, this format applies to the title and subtitles. Default: ``TikZ`` default.
.. option:: width, DOUBLE
The width of the graph, in inches. Default: ``6.0``.
.. option:: writeCSV, BOOLEAN
Whether or not to write a CSV file with only the plotted data. The file will be saved in the directory specified by :opt:`graphDirName <graphDirName, STRING>` with the same base name as specified by :opt:`graphName <graphName, STRING>` with the ending ``.csv``. Default: ``false``.
.. option:: xlabel, STRING
The x-axis label. Default: ``none``.
.. option:: ylabel, STRING
The y-axis label. Default: ``none``.
.. option:: xAxisTight, BOOLEAN
Use a tight x axis. If false, uses ``PGFPLOTS/TikZ`` ``enlarge x limits`` to choose appropriate axis size. Default: ``true``.
.. option:: xrange, dates
The boundary on the x-axis to display in the graph. Default: ``all``.
.. option:: xTicks, NUMERICAL_VECTOR
Used only in conjunction with :opt:`xTickLabels <xTickLabels, CELL_ARRAY_STRINGS | `ALL'>`, this option denotes the numerical position of the label along the x-axis. The positions begin at ``1``. Default: the indices associated with the first and last dates of the ``dseries`` and, if passed, the index associated with the first date of the :opt:`shade <shade, dates>` option.
.. option:: xTickLabels, CELL_ARRAY_STRINGS | `ALL'
The labels to be mapped to the ticks provided by ``xTicks``. Default: the first and last dates of the ``dseries`` and, if passed, the date first date of the :opt:`shade <shade, dates>` option.
.. option:: xTickLabelAnchor, STRING
Where to anchor the x tick label. Default: ```south'``.
.. option:: xTickLabelRotation, DOUBLE
The amount to rotate the x tick labels by. Default: ``0``.
.. option:: yAxisTight, BOOLEAN
Use a tight y axis. If false, uses ``PGFPLOTS/TikZ`` ``enlarge y limits`` to choose appropriate axis size. Default: ``false``.
.. option:: yrange, NUMERICAL_VECTOR
The boundary on the y-axis to display in the graph, represented as a ``NUMERICAL_VECTOR`` of size ``2``, with the first entry less than the second entry. Default: ``all``.
.. option:: yTickLabelFixed, BOOLEAN
Round the y tick labels to a fixed number of decimal places, given by ``yTickLabelPrecision``. Default: ``.true``.
.. option:: yTickLabelPrecision, INTEGER
The precision with which to report the ``yTickLabel``. Default: ``1``.
.. option:: yTickLabelScaled, BOOLEAN
Determines whether or not there is a common scaling factor for the y axis. Default: ``true``.
.. option:: yTickLabelZeroFill, BOOLEAN
Whether or not to fill missing precision spots with zeros. Default: ``true``.
.. option:: showZeroline, BOOLEAN
Display a solid black line at :math:`y = 0`. Default: ``false``.
.. option:: zeroLineColor, STRING
The color to use for the zero line. Only used if :opt:`showZeroLine <showZeroline, BOOLEAN>` is true. See the explanation in :opt:`shadeColor <shadeColor, STRING>` for how to use colors with reports. Default: ```black'``.
.. repmethod:: addTable
Adds a ``Table`` to a ``Section``.
*Options*
.. option:: data, dseries
See :opt:`data <data, dseries>`.
.. option:: highlightRows, CELL_ARRAY_STRINGS
A cell array containing the colors to use for row highlighting. See :opt:`shadeColor <shadeColor, STRING>` for how to use colors with reports. Highlighting for a specific row can be overridden by using the :opt:`tableRowColor <tableRowColor, STRING>` option to :repmeth:`addSeries`. Default: ``empty``.
.. option:: showHlines, BOOLEAN
Whether or not to show horizontal lines separating the rows. Default: ``false``.
.. option:: precision, INTEGER
The number of decimal places to report in the table data. Default: ``1``.
.. option:: range, dates
The date range of the data to be displayed. Default: ``all``.
.. option:: seriesToUse, CELL_ARRAY_STRINGS
See :opt:`seriesToUse <seriesToUse, CELL_ARRAY_STRINGS>`.
.. option:: tableDirName, STRING
The name of the folder in which to store this table. Default: ``tmpRepDir``.
.. option:: tableName, STRING
The name to use when saving this table. Default: something of the form ``table_pg1_sec2_row1_col3.tex``.
.. option:: title, STRING
Same as :opt:`title <title, STRING>`, just for tables.
.. option:: titleFormat, STRING
Same as :opt:`titleFormat <titleFormat, STRING | CELL_ARRAY_STRINGS>`, just for tables. Default: ``\large``.
.. option:: vlineAfter, dates | CELL_ARRAY_DATES
Show a vertical line after the specified date (or dates if a cell array of dates is passed). Default: ``empty``.
.. option:: vlineAfterEndOfPeriod, BOOLEAN
Show a vertical line after the end of every period (i.e. after every year, after the fourth quarter, etc.). Default: ``false``.
.. option:: showVlines, BOOLEAN
Whether or not to show vertical lines separating the columns. Default: ``false``.
.. option:: writeCSV, BOOLEAN
Whether or not to write a CSV file containing the data displayed in the table. The file will be saved in the directory specified by :opt:`tableDirName <tableDirName, STRING>` with the same base name as specified by :opt:`tableName <tableName, STRING>` with the ending ``.csv``. Default: ``false``.
.. repmethod:: addSeries
Adds a ``Series`` to a ``Graph`` or a ``Table``.
NB: Options specific to graphs begin with ```graph'`` while options specific to tables begin with ```table'``.
*Options*
.. option:: data, dseries
See :opt:`data <data, dseries>`.
.. option:: graphBar, BOOLEAN
Whether or not to display this series as a bar graph as oppsed to the default of displaying it as a line graph. Default: ``false``.
.. option:: graphFanShadeColor, STRING
The shading color to use between a series and the previously-added series in a graph. Useful for making fan charts. Default: ``empty``.
.. option:: graphFanShadeOpacity, INTEGER
The opacity of the color passed in :opt:`graphFanShadeColor <graphFanShadeColor, STRING>`. Default: ``50``.
.. option:: graphBarColor, STRING
The outline color of each bar in the bar graph. Only active if :opt:`graphBar <graphBar, BOOLEAN>` is passed. Default: ```black'``.
.. option:: graphBarFillColor, STRING
The fill color of each bar in the bar graph. Only active if :opt:`graphBar <graphBar, BOOLEAN>` is passed. Default: ```black'``.
.. option:: graphBarWidth, DOUBLE
The width of each bar in the bar graph. Only active if :opt:`graphBar <graphBar, BOOLEAN>` is passed. Default: ``2``.
.. option:: graphHline, DOUBLE
Use this option to draw a horizontal line at the given value. Default: ``empty``.
.. option:: graphLegendName, STRING
The name to display in the legend for this series, passed as valid LaTeX (e.g., ``GDP_{US}, $\alpha$, \color{red}GDP\color{black}``). Will be displayed only if the ``data`` and :opt:`showLegend <showLegend, BOOLEAN>` options have been passed. Default: the tex name of the series.
.. option:: graphLineColor, STRING
Color to use for the series in a graph. See the explanation in :opt:`shadeColor <shadeColor, STRING>` for how to use colors with reports. Default: ```black'``
.. option:: graphLineStyle, OPTION
Line style for this series in a graph. Possible values for OPTION are::
`none' | `solid' | `dotted' | `densely dotted' | `loosely dotted' | `dashed' |
`densely dashed' | `loosely dashed' | `dashdotted' | `densely dashdotted' |
`loosely dashdotted' | `dashdotdotted' | `densely dashdotdotted' |
`loosely dashdotdotted'
Default: ```solid'``.
.. option:: graphLineWidth DOUBLE
Line width for this series in a graph. Default: ``0.5``.
.. option:: graphMarker, OPTION
The Marker to use on this series in a graph. Possible values for OPTION are::
`x' | `+' | `-' | `|' | `o' | `asterisk' | `star' | `10-pointed star' |
`oplus' | `oplus*' | `otimes' | `otimes*' | `square' | `square*' |
`triangle' | `triangle*' | `diamond' | `diamond*' | `halfdiamond*' |
`halfsquare*' | `halfsquare right*' | `halfsquare left*' | `Mercedes star' |
`Mercedes star flipped' | `halfcircle' | `halfcircle*' | `pentagon' |
`pentagon star'
Default: ``none``.
.. option:: graphMarkerEdgeColor, STRING
The edge color of the graph marker. See the explanation in :opt:`shadeColor <shadeColor, STRING>` for how to use colors with reports. Default: ``graphLineColor``.
.. option:: graphMarkerFaceColor, STRING
The face color of the graph marker. See the explanation in :opt:`shadeColor <shadeColor, STRING>` for how to use colors with reports. Default: ``graphLineColor``.
.. option:: graphMarkerSize, DOUBLE
The size of the graph marker. Default: ``1``.
.. option:: graphMiscTikzAddPlotOptions, STRING
If you are comfortable with ``PGFPLOTS/TikZ``, you can use this option to pass arguments directly to the ``PGFPLOTS/TikZ`` ``addPlots`` command. (e.g., Instead of passing the marker options above, you can pass a string such as the following to this option: ```mark=halfcircle*,mark options={rotate=90,scale=3}'``). Specifically to be used for desired ``PGFPLOTS/TikZ`` options that have not been incorporated into Dynare Reproting. Default: ``empty``.
.. option:: graphShowInLegend, BOOLEAN
Whether or not to show this series in the legend, given that the :opt:`showLegend <showLegend, BOOLEAN>` option was passed to :repmeth:`addGraph`. Default: ``true``.
.. option:: graphVline, dates
Use this option to draw a vertical line at a given date. Default: ``empty``.
.. option:: tableDataRhs, dseries
A series to be added to the right of the current series. Usefull for displaying aggregate data for a series. e.g if the series is quarterly ``tableDataRhs`` could point to the yearly averages of the quarterly series. This would cause quarterly data to be displayed followed by annual data. Default: ``empty``.
.. option:: tableRowColor, STRING
The color that you want the row to be. Predefined values include ``LightCyan`` and ``Gray``. Default: ``white``.
.. option:: tableRowIndent, INTEGER
The number of times to indent the name of the series in the table. Used to create subgroups of series. Default: ``0``.
.. option:: tableShowMarkers, BOOLEAN
In a Table, if ``true``, surround each cell with brackets and color it according to :opt:`tableNegColor <tableNegColor, LATEX_COLOR>` and :opt:`tablePosColor <tablePosColor, LATEX_COLOR>`. No effect for graphs. Default: ``false``.
.. option:: tableAlignRight, BOOLEAN
Whether or not to align the series name to the right of the cell. Default: ``false``.
.. option:: tableMarkerLimit, DOUBLE
For values less than :math:`-1*\texttt{tableMarkerLimit}`, mark the cell with the color denoted by tableNegColor. For those greater than ``tableMarkerLimit``, mark the cell with the color denoted by tablePosColor. Default: ``1e-4``.
.. option:: tableNaNSymb, STRING
Replace ``NaN`` values with the text in this option. Default: ``NaN``.
.. option:: tableNegColor, LATEX_COLOR
The color to use when marking Table data that is less than zero. Default: ```red'``
.. option:: tablePrecision, INTEGER
The number of decimal places to report in the table data. Default: the value set by :opt:`precision <precision, INTEGER>`.
.. option:: tablePosColor, LATEX_COLOR
The color to use when marking Table data that is greater than zero. Default: ```blue'``
.. option:: tableSubSectionHeader, STRING
A header for a subsection of the table. No data will be associated with it. It is equivalent to adding an empty series with a name. Default: ``''``
.. option:: zeroTol, DOUBLE
The zero tolerance. Anything smaller than ``zeroTol`` and larger than ``-zeroTol`` will be set to zero before being graphed or written to the table. Default: ``1e-6``.
.. repmethod:: addParagraph
Adds a ``Paragraph`` to a ``Section``.
NB: The ``Section`` can only be comprised of ``Paragraphs`` and must only have 1 column.
*Options*
.. option:: balancedCols, BOOLEAN
Determines whether the text is spread out evenly across the columns when the ``Paragraph`` has more than one column. Default: ``true``.
.. option:: cols, INTEGER
The number of columns for the ``Paragraph``. Default: ``1``.
.. option:: heading, STRING
The heading for the ``Paragraph`` (like a section heading). The string must be valid LaTeX code. Default: ``empty``.
.. option:: indent, BOOLEAN
Whether or not to indent the paragraph. Default: ``true``.
.. option:: text, STRING
The paragraph itself. The string must be valid LaTeX code. Default: ``empty``.
.. repmethod:: addVspace
Adds a ``Vspace`` (vertical space) to a ``Section``.
*Options*
.. option:: hline, INTEGER
The number of horizontal lines to be inserted. Default: ``0``.
.. option:: number, INTEGER
The number of new lines to be inserted. Default: ``1``.
.. repmethod:: write
Writes the LaTeX representation of this ``Report``, saving it to the file specified by :opt:`filename <fileName, FILENAME>`.
.. repmethod:: compile
Compiles the report written by ``write`` into a ``pdf`` file. If the report has not already been written (determined by the existence of the file specified by :opt:`filename <fileName, FILENAME>`, ``write`` is called.
*Options*
.. option:: compiler, FILENAME
Like :opt:`compiler <compiler, FILENAME>`, except will not overwrite the value of ``compiler`` contained in the report object. Hence, passing the value here is useful for using different LaTeX compilers or just for passing the value at the last minute.
.. option:: showOutput, BOOLEAN
Print the compiler output to the screen. Useful for debugging your code as the LaTeX compiler hangs if there is a problem. Default: the value of :opt:`showOutput <showOutput, BOOLEAN>`.
.. option:: showReport, BOOLEAN
Open the compiled report (works on Windows and macOS on Matlab). Default: ``true``.
*Example*
The following code creates a one page report. The first part of the page contains two graphs displayed across two columns and one row. The bottom of the page displays a centered table::
%% Create dseries
dsq = dseries(`quarterly.csv');
dsa = dseries(`annual.csv');
dsca = dseries(`annual_control.csv');
%% Report
rep = report();
%% Page 1
rep = rep.addPage(`title', {`My Page Title', `My Page Subtitle'}, ...
`titleFormat', {`\large\bfseries', `\large'});
% Section 1
rep = rep.addSection(`cols', 2);
rep = rep.addGraph(`title', `Graph (1,1)', `showLegend', true, ...
`xrange', dates(`2007q1'):dates(`2013q4'), ...
`shade', dates(`2012q2'):dates(`2013q4'));
rep = rep.addSeries(`data', dsq{`SERIES1'}, `graphLineColor', `blue', ...
`graphLineWidth', 1);
rep = rep.addSeries(`data', dsq{`SERIES2'}, `graphLineColor', `green', ...
`graphLineStyle', '--', `graphLineWidth', 1.5);
rep = rep.addGraph(`title', `Graph (1,2)', `showLegend', true, ...
`xrange', dates(`2007q1'):dates(`2013q4'), ...
`shade', dates(`2012q2'):dates(`2013q4'));
rep = rep.addSeries(`data', dsq{`SERIES3'}, `graphLineColor', `blue', ...
`graphLineWidth', 1);
rep = rep.addSeries(`data', dsq{`SERIES4'}, `graphLineColor', `green', ...
`graphLineStyle', '--', `graphLineWidth', 1.5);
% Section 2
rep = rep.addSection();
rep = rep.addTable(`title', `Table 1', ...
`range', dates(`2012Y'):dates(`2014Y'));
shortNames = {`US', `EU'};
longNames = {`United States', `Euro Area'};
for i=1:length(shortNames)
rep = rep.addSeries(`data', dsa{[`GDP_' shortNames{i}]});
delta = dsa{[`GDP_' shortNames{i}]}-dsca{[`GDP_' shortNames{i}]};
delta = delta.tex_rename(`$\Delta$');
rep = rep.addSeries(`data', delta, ...
`tableShowMarkers', true, ...
`tableAlignRight', true);
end
%% Write & Compile Report
rep.write();
rep.compile();

View File

@ -0,0 +1,246 @@
.. default-domain:: dynare
##############
Running Dynare
##############
In order to give instructions to Dynare, the user has to write a *model file* whose filename extension must be ``.mod``. This file contains the description of the model and the computing tasks required by the user. Its contents are described in :ref:`model-file`.
.. _dyn-invoc:
Dynare invocation
=================
Once the model file is written, Dynare is invoked using the ``dynare`` command at the MATLAB or Octave prompt (with the filename of the ``.mod`` given as argument).
In practice, the handling of the model file is done in two steps: in the first one, the model and the processing instructions written by the user in a *model file* are interpreted and the proper MATLAB or GNU Octave instructions are generated; in the second step, the program actually runs the computations. Both steps are triggered automatically by the ``dynare`` command.
.. matcomm :: dynare FILENAME[.mod] [OPTIONS…]
This command launches Dynare and executes the instructions included in ``FILENAME.mod``. This user-supplied file contains the model and the processing instructions, as described in :ref:`model-file`. The options, listed below, can be passed on the command line, following the name of the ``.mod`` file or in the first line of the ``.mod`` file itself (see below).
dynare begins by launching the preprocessor on the ``.mod file``. By default (unless ``use_dll`` option has been given to ``model``), the preprocessor creates three intermediary files:
``filename.m``
Contains variable declarations, and computing tasks.
``FILENAME_dynamic.m``
Contains the dynamic model equations. Note that Dynare might introduce auxiliary equations and variables (see :ref:`aux-variables`). Outputs are the residuals of the dynamic model equations in the order the equations were declared and the Jacobian of the dynamic model equations. For higher order approximations also the Hessian and the third-order derivatives are provided. When computing the Jacobian of the dynamic model, the order of the endogenous variables in the columns is stored in ``M_.lead_lag_incidence``. The rows of this matrix represent time periods: the first row denotes a lagged (time t-1) variable, the second row a contemporaneous (time t) variable, and the third row a leaded (time t+1) variable. The columns of the matrix represent the endogenous variables in their order of declaration. A zero in the matrix means that this endogenous does not appear in the model in this time period. The value in the ``M_.lead_lag_incidence`` matrix corresponds to the column of that variable in the Jacobian of the dynamic model. Example: Let the second declared variable be ``c`` and the ``(3,2)`` entry of ``M_.lead_lag_incidence`` be 15. Then the 15th column of the Jacobian is the derivative with respect to ``c(+1)``.
``FILENAME_static.m``
Contains the long run static model equations. Note that Dynare might introduce auxiliary equations and variables (see :ref:`aux-variables`). Outputs are the residuals of the static model equations in the order the equations were declared and the Jacobian of the static equations. Entry ``(i,j)`` of the Jacobian represents the derivative of the ith static model equation with respect to the jth model variable in declaration order.
These files may be looked at to understand errors reported at the simulation stage.
``dynare`` will then run the computing tasks by executing ``FILENAME.m``.
A few words of warning are warranted here: the filename of the ``.mod`` file should be chosen in such a way that the generated ``.m`` files described above do not conflict with ``.m`` files provided by MATLAB/Octave or by Dynare. Not respecting this rule could cause crashes or unexpected behaviour. In particular, it means that the ``.mod`` file cannot be given the name of a MATLAB/Octave or Dynare command. Under Octave, it also means that the ``.mod`` file cannot be named ``test.mod``.
*Options*
.. option:: noclearall
By default, ``dynare`` will issue a ``clear all`` command to MATLAB (<R2015b) or Octave, thereby deleting all workspace variables and functions; this option instructs ``dynare`` not to clear the workspace. Note that starting with Matlab 2015b ``dynare`` only deletes the global variables and the functions using persistent variables, in order to benefit from the JIT (Just In Time) compilation. In this case the option instructs ``dynare`` not to clear the globals and functions.
.. option:: onlyclearglobals
By default, ``dynare`` will issue a ``clear all`` command to MATLAB versions before 2015b and to Octave, thereby deleting all workspace variables; this option instructs ``dynare`` to clear only the global variables (i.e. ``M_, options_, oo_, estim_params_, bayestopt_``, and ``dataset_``), leaving the other variables in the workspace.
.. option:: debug
Instructs the preprocessor to write some debugging information about the scanning and parsing of the ``.mod`` file.
.. option:: notmpterms
Instructs the preprocessor to omit temporary terms in the static and dynamic files; this generally decreases performance, but is used for debugging purposes since it makes the static and dynamic files more readable.
.. option:: savemacro[=FILENAME]
Instructs ``dynare`` to save the intermediary file which is obtained after macro-processing (see :ref:`macro-proc-lang`); the saved output will go in the file specified, or if no file is specified in ``FILENAME-macroexp.mod``
.. option:: onlymacro
Instructs the preprocessor to only perform the macro-processing step, and stop just after. Mainly useful for debugging purposes or for using the macro-processor independently of the rest of Dynare toolbox.
.. option:: nolinemacro
Instructs the macro-preprocessor to omit line numbering information in the intermediary ``.mod`` file created after the macro-processing step. Useful in conjunction with ``savemacro`` when one wants that to reuse the intermediary ``.mod`` file, without having it cluttered by line numbering directives.
.. option:: nolog
Instructs Dynare to no create a logfile of this run in ``FILENAME.log.`` The default is to create the logfile.
.. option:: params_derivs_order=0|1|2
When :comm:`identification`, :comm:`dynare_sensitivity` (with identification), or :ref:`estimation_cmd <estim-comm>` are present, this option is used to limit the order of the derivatives with respect to the parameters that are calculated by the preprocessor. 0 means no derivatives, 1 means first derivatives, and 2 means second derivatives. Default: 2
.. option:: nowarn
Suppresses all warnings.
.. option:: json = parse|transform|compute
Causes the preprocessor to output a version of the ``.mod`` file in JSON format.
If ``parse`` is passed, the output will be written after the parsing of the ``.mod`` file to a file called ``FILENAME.json``.
If ``transform`` is passed, the JSON output of the transformed model (maximum lead of 1, minimum lag of -1, expectation operators substituted, etc.) will be written to a file called ``FILENAME.json`` and the original, untransformed model will be written in ``FILENAME_original.json``.
And if ``compute`` is passed, the output is written after the computing pass. In this case, the transformed model is written to ``FILENAME.json``, the original model is written to ``FILENAME_original.json``, and the dynamic and static files are written to ``FILENAME_dynamic.json`` and ``FILENAME_static.json``.
.. option:: jsonstdout
Instead of writing output requested by ``json`` to files, write to standard out.
.. option:: onlyjson
Quit processing once the output requested by ``json`` has been written.
.. option:: jsonderivsimple
Print a simplified version (excluding variable name(s) and lag information) of the static and dynamic files in ``FILENAME_static.json`` and ``FILENAME_dynamic.``.
.. option:: warn_uninit
Display a warning for each variable or parameter which is not initialized. See :ref:`param-init`, or :comm:`load_params_and_steady_state <load_params_and_steady_state>` for initialization of parameters. See :ref:`init-term-cond`, or :comm:`load_params_and_steady_state <load_params_and_steady_state>` for initialization of endogenous and exogenous variables.
.. option:: console
Activate console mode. In addition to the behavior of ``nodisplay``, Dynare will not use graphical waitbars for long computations.
.. option:: nograph
Activate the ``nograph`` option (see :opt:`nograph`), so that Dynare will not produce any graph.
.. option:: nointeractive
Instructs Dynare to not request user input.
.. option:: nopathchange
By default Dynare will change Matlab/Octaves path if ``dynare/matlab`` directory is not on top and if Dynares routines are overriden by routines provided in other toolboxes. If one wishes to override Dynares routines, the ``nopathchange`` options can be used. Alternatively, the path can be temporarly modified by the user at the top of the ``.mod`` file (using Matlab/Octaves ``addpath`` command).
.. option:: mingw
Tells Dynare that your MATLAB is configured for compiling MEX files with the MinGW compiler from TDM-GCC (see :ref:`compil-install`). This option is only available under Windows, and is used in conjunction with ``use_dll``.
.. option:: msvc
Tells Dynare that your MATLAB is configured for compiling MEX files with Microsoft Visual C++ (see :ref:`compil-install`). This option is only available under Windows, and is used in conjunction with ``use_dll``.
.. option:: cygwin
Tells Dynare that your MATLAB is configured for compiling MEX files with Cygwin (see :ref:`compil-install`). This option is only available under Windows, and is used in conjunction with ``use_dll``.
.. option:: parallel[=CLUSTER_NAME]
Tells Dynare to perform computations in parallel. If CLUSTER_NAME is passed, Dynare will use the specified cluster to perform parallel computations. Otherwise, Dynare will use the first cluster specified in the configuration file. See :ref:`conf-file`, for more information about the configuration file.
.. option:: conffile=FILENAME
Specifies the location of the configuration file if it differs from the default. See :ref:`conf-file`, for more information about the configuration file and its default location.
.. option:: parallel_slave_open_mode
Instructs Dynare to leave the connection to the slave node open after computation is complete, closing this connection only when Dynare finishes processing.
.. option:: parallel_test
Tests the parallel setup specified in the configuration file without executing the ``.mod`` file. See :ref:`conf-file`, for more information about the configuration file.
.. option:: -DMACRO_VARIABLE=MACRO_EXPRESSION
Defines a macro-variable from the command line (the same effect as using the Macro directive ``@#define`` in a model file, see :ref:`macro-proc-lang`).
.. option:: -I<<path>>
Defines a path to search for files to be included by the macroprocessor (using the ``@#include`` command). Multiple ``-I`` flags can be passed on the command line. The paths will be searched in the order that the ``-I`` flags are passed and the first matching file will be used. The flags passed here take priority over those passed to ``@#includepath``.
.. option:: nostrict
Allows Dynare to issue a warning and continue processing when
1. there are more endogenous variables than equations.
2. an undeclared symbol is assigned in ``initval`` or ``endval``.
3. exogenous variables were declared but not used in the ``model`` block.
.. option:: fast
Only useful with model option ``use_dll``. Dont recompile the MEX files when running again the same model file and the lists of variables and the equations havent changed. We use a 32 bit checksum, stored in ``<model filename>/checksum``. There is a very small probability that the preprocessor misses a change in the model. In case of doubt, re-run without the fast option.
.. option:: minimal_workspace
Instructs Dynare not to write parameter assignments to parameter names in the .m file produced by the preprocessor. This is potentially useful when running ``dynare`` on a large ``.mod`` file that runs into workspace size limitations imposed by MATLAB.
.. option:: compute_xrefs
Tells Dynare to compute the equation cross references, writing them to the output ``.m`` file.
These options can be passed to the preprocessor by listing them after the name of the ``.mod`` file. They can alternatively be defined in the first line of the ``.mod`` file, this avoids typing them on the command line each time a ``.mod`` file is to be run. This line must be a Dynare comment (ie must begin with //) and the options must be comma separated between ``--+`` options: and ``+--``. As in the command line, if an option admits a value the equal symbol must not be surrounded by spaces. For instance ``json = compute`` is not correct, and should be written ``json=compute``.
*Output*
Depending on the computing tasks requested in the ``.mod`` file, executing the ``dynare`` command will leave variables containing results in the workspace available for further processing. More details are given under the relevant computing tasks.
The ``M_, oo_``, and ``options_`` structures are saved in a file called ``FILENAME_results.mat``. If they exist, ``estim_params_, bayestopt_, dataset_, oo_recursive_`` and ``estimation_info`` are saved in the same file.
:ex:
::
dynare ramst;
dynare ramst.mod savemacro;
Alternatively the options can be specified in the first line of ``ramst.mod``::
// --+ options: savemacro, json=compute +--
The output of Dynare is left into three main variables in the MATLAB/Octave workspace:
.. matvar:: M_
Structure containing various information about the model.
.. matvar:: options_
Structure contains the values of the various options used by Dynare during the computation.
.. matvar:: oo_
Structure containing the various results of the computations.
.. matvar:: oo_recursive_
Cell array containing the ``oo_`` structures obtained when estimating the model for the different samples when performing recursive estimation and forecasting. The ``oo_`` structure obtained for the sample ranging to the `i` -th observation is saved in the `i` -th field. The fields for non-estimated endpoints are empty.
Dynare hooks
============
It is possible to call pre and post Dynare preprocessor hooks written as MATLAB scripts. The script ``MODFILENAME/hooks/priorprocessing.m`` is executed before the call to Dynares preprocessor, and can be used to programmatically transform the mod file that will be read by the preprocessor. The script ``MODFILENAME/hooks/postprocessing.m`` is executed just after the call to Dynares preprocessor, and can be used to programmatically transform the files generated by Dynares preprocessor before actual computations start. The pre and/or post dynare preprocessor hooks are executed if and only if the aforementioned scripts are detected in the same folder as the the model file, ``FILENAME.mod``.
Understanding Preprocessor Error Messages
=========================================
If the preprocessor runs into an error while processing your ``.mod`` file, it will issue an error. Due to the way that a parser works, sometimes these errors can be misleading. Here, we aim to demystify these error messages.
The preprocessor issues error messages of the form:
#. ``ERROR: <<file.mod>>: line A, col B: <<error message>>``
#. ``ERROR: <<file.mod>>: line A, cols B-C: <<error message>>``
#. ``ERROR: <<file.mod>>: line A, col B - line C, col D: <<error message>>``
The first two errors occur on a single line, with error two spanning multiple columns. Error three spans multiple rows.
Often, the line and column numbers are precise, leading you directly to the offending syntax. Infrequently however, because of the way the parser works, this is not the case. The most common example of misleading line and column numbers (and error message for that matter) is the case of a missing semicolon, as seen in the following example::
varexo a, b;
parameters c, ...;
In this case, the parser doesnt know a semicolon is missing at the end of the ``varexo`` command until it begins parsing the second line and bumps into the ``parameters`` command. This is because we allow commands to span multiple lines and, hence, the parser cannot know that the second line will not have a semicolon on it until it gets there. Once the parser begins parsing the second line, it realizes that it has encountered a keyword, ``parameters``, which it did not expect. Hence, it throws an error of the form: ``ERROR: <<file.mod>>: line 2, cols 0-9: syntax error, unexpected PARAMETERS``. In this case, you would simply place a semicolon at the end of line one and the parser would continue processing.

View File

@ -0,0 +1,281 @@
.. default-domain:: dynare
.. _conf-file:
######################
The configuration file
######################
The configuration file is used to provide Dynare with information not related to the model (and hence not placed in the model file). At the moment, it is only used when using Dynare to run parallel computations.
On Linux and macOS, the default location of the configuration file is ``$HOME/.dynare``, while on Windows it is ``%APPDATA%\dynare.ini`` (typically ``C:\Documents and Settings\USERNAME\Application Data\dynare.ini`` under Windows XP, or ``C:\Users\USERNAME\AppData\dynare.ini`` under Windows Vista/7/8). You can specify a non standard location using the ``conffile`` option of the ``dynare`` command (see :ref:`dyn-invoc`).
The parsing of the configuration file is case-sensitive and it should take the following form, with each option/choice pair placed on a newline::
[command0]
option0 = choice0
option1 = choice1
[command1]
option0 = choice0
option1 = choice1
The configuration file follows a few conventions (self-explanatory conventions such as ``USER_NAME`` have been excluded for concision):
``COMPUTER_NAME``
Indicates the valid name of a server (e.g. ``localhost``, ``server.cepremap.org``) or an IP address.
``DRIVE_NAME``
Indicates a valid drive name in Windows, without the trailing colon (e.g. ``C``).
``PATH``
Indicates a valid path in the underlying operating system (e.g. ``/home/user/dynare/matlab/``).
``PATH_AND_FILE``
Indicates a valid path to a file in the underlying operating system (e.g. ``/usr/local/MATLAB/R2010b/bin/matlab``).
``BOOLEAN``
Is ``true`` or ``false``.
Dynare Configuration
====================
This section explains how to configure Dynare for general processing. Currently, there is only one option available.
.. confblock:: [hooks]
This block can be used to specify configuration options that will be used when running Dynare.
*Options*
.. option:: GlobalInitFile = PATH_AND_FILE
The location of the global initialization file to be run at the end of ``global_initialization.m``.
:ex:
::
[hooks]
GlobalInitFile = /home/usern/dynare/myInitFile.m
.. confblock:: [paths]
This block can be used to specify paths that will be used when running dynare.
*Options*
.. option:: Include = PATH
A colon-separated path to use when searching for files to include via ``@#include``. Paths specified via :opt:`-I <-I\<\<path\>\>>` take priority over paths specified here, while these paths take priority over those specified by ``@#includepath``.
:ex:
::
[paths]
Include = /path/to/folder/containing/modfiles:/path/to/another/folder
.. _paral-conf:
Parallel Configuration
======================
This section explains how to configure Dynare for parallelizing some tasks which require very little inter-process communication.
The parallelization is done by running several MATLAB or Octave processes, either on local or on remote machines. Communication between master and slave processes are done through SMB on Windows and SSH on UNIX. Input and output data, and also some short status messages, are exchanged through network filesystems. Currently the system works only with homogenous grids: only Windows or only Unix machines.
The following routines are currently parallelized:
* the posterior sampling algorithms when using multiple chains;
* the Metropolis-Hastings diagnostics;
* the posterior IRFs;
* the prior and posterior statistics;
* some plotting routines.
Note that creating the configuration file is not enough in order to trigger parallelization of the computations: you also need to specify the ``parallel`` option to the ``dynare`` command. For more details, and for other options related to the parallelization engine, see :ref:`dyn-invoc`.
You also need to verify that the following requirements are met by your cluster (which is composed of a master and of one or more slaves):
For a Windows grid:
* a standard Windows network (SMB) must be in place;
* the `PsTools`_ suite must be installed in the path of the master Windows machine;
* the Windows user on the master machine has to be user of any other slave machine in the cluster, and that user will be used for the remote computations.
* detailed step-by-step setup instructions can be found in :ref:`win-ssg`.
For a UNIX grid:
* SSH must be installed on the master and on the slave machines;
* SSH keys must be installed so that the SSH connection from the master to the slaves can be done without passwords, or using an SSH agent.
We now turn to the description of the configuration directives. Note that comments in the configuration file can be provided by separate lines starting with a hashtag (#).
.. confblock:: [cluster]
When working in parallel, ``[cluster]`` is required to specify the group of computers that will be used. It is required even if you are only invoking multiple processes on one computer.
*Options*
.. option:: Name = CLUSTER_NAME
The reference name of this cluster.
.. option:: Members = NODE_NAME[(WEIGHT)] NODE_NAME[(WEIGHT)] ...
A list of nodes that comprise the cluster with an optional computing weight specified for that node. The computing weight indicates how much more powerful one node is with respect to the others (e.g. ``n1(2) n2(1) n3(3)`` means that ``n1`` is two times more powerful than ``n2`` whereas ``n3`` is three times more powerful than ``n2``). Each node is separated by at least one space and the weights are in parenthesis with no spaces separating them from their node.
:ex:
::
[cluster]
Name = c1
Members = n1 n2 n3
[cluster]
Name = c2
Members = n1(4) n2 n3
.. confblock:: [node]
When working in parallel, ``[node]`` is required for every computer that will be used. The options that are required differ, depending on the underlying operating system and whether you are working locally or remotely.
*Options*
.. option:: Name = NODE_NAME
The reference name of this node.
.. option:: CPUnbr = INTEGER | [INTEGER:INTEGER]
If just one integer is passed, the number of processors to use. If a range of integers is passed, the specific processors to use (processor counting is defined to begin at one as opposed to zero). Note that using specific processors is only possible under Windows; under Linux and macOS, if a range is passed the same number of processors will be used but the range will be adjusted to begin at one.
.. option:: ComputerName = COMPUTER_NAME
The name or IP address of the node. If you want to run locally, use ``localhost`` (case-sensitive).
.. option:: Port = INTEGER
The port number to connect to on the node. The default is empty, meaning that the connection will be made to the default SSH port (22).
.. option:: UserName = USER_NAME
The username used to log into a remote system. Required for remote runs on all platforms.
.. option:: Password = PASSWORD
The password used to log into the remote system. Required for remote runs originating from Windows.
.. option:: RemoteDrive = DRIVE_NAME
The drive to be used for remote computation. Required for remote runs originating from Windows.
.. option:: RemoteDirectory = PATH
The directory to be used for remote computation. Required for remote runs on all platforms.
.. option:: DynarePath = PATH
The path to the matlab subdirectory within the Dynare installation directory. The default is the empty string.
.. option:: MatlabOctavePath = PATH_AND_FILE
The path to the MATLAB or Octave executable. The default value is ``matlab``.
.. option:: NumberOfThreadsPerJob = INTEGER
For Windows nodes, sets the number of threads assigned to each remote MATLAB/Octave run. The default value is 1.
.. option:: SingleCompThread = BOOLEAN
Whether or not to disable MATLABs native multithreading. The default value is ``false``. Option meaningless under Octave.
.. option:: OperatingSystem = OPERATING_SYSTEM
The operating system associated with a node. Only necessary when creating a cluster with nodes from different operating systems. Possible values are ``unix`` or ``windows``. There is no default value.
:ex:
::
[node]
Name = n1
ComputerName = localhost
CPUnbr = 1
[node]
Name = n2
ComputerName = dynserv.cepremap.org
CPUnbr = 5
UserName = usern
RemoteDirectory = /home/usern/Remote
DynarePath = /home/usern/dynare/matlab
MatlabOctavePath = matlab
[node]
Name = n3
ComputerName = dynserv.dynare.org
Port = 3333
CPUnbr = [2:4]
UserName = usern
RemoteDirectory = /home/usern/Remote
DynarePath = /home/usern/dynare/matlab
MatlabOctavePath = matlab
.. _win-ssg:
Windows Step-by-Step Guide
==========================
This section outlines the steps necessary on most Windows systems to set up Dynare for parallel execution.
1. Write a configuration file containing the options you want. A mimimum working example setting up a cluster consisting of two local CPU cores that allows for e.g. running two Monte Carlo Markov Chains in parallel is shown below.
2. Save the configuration file somwhere. The name and file ending do not matter if you are providing it with the ``conffile`` command line option. The only restrictions are that the path must be a valid filename, not contain non-alpha-numeric characters, and not contain any whitespaces. For the configuration file to be accessible without providing an explicit path at the command line, you must save it under the name ``dynare.ini`` into your user accounts ``Application Data`` folder.
3. Install `PSTools`_ to your system, e.g. into ``C:\PSTools.``
4. Set the Windows System Path to the ``PSTools`` folder (e.g. using something along the line of pressing Windows Key+Pause to open the System Configuration, then go to Advanced -> Environment Variables -> Path).
5. Restart your computer to make the path change effective.
6. Open Matlab and type into the command window::
!psexec
This executes the ``psexec.exe`` from PSTools on your system and shows whether Dynare will be able to locate it. If Matlab complains at this stage, you did not correctly set your Windows system path for the ``PSTools`` folder.
7. If ``psexec.exe`` was located in the previous step, a popup will show up, asking for confirmation of the license agreement. Confirm this copyright notice of ``psexec`` (this needs to be done only once). After this, Dynare should be ready for parallel execution.
8. Call Dynare on your mod-file invoking the ``parallel`` option and providing the path to your configuration file with the ``conffile`` option (if you did not save it as ``%APPDATA%\dynare.ini`` in step 2 where it should be detected automatically)::
dynare ls2003 parallel conffile='C:\Users\Dynare~1\parallel\conf_file.ini'
Please keep in mind that no white spaces or names longer than 8 characters are allowed in the ``conffile`` path. The 8-character restriction can be circumvented by using the tilde Windows path notation as in the above example.
*Example*::
#cluster needs to always be defined first
[cluster]
#Provide a name for the cluster
Name=Local
#declare the nodes being member of the cluster
Members=n1
#declare nodes (they need not all be part of a cluster)
[node]
#name of the node
Name=n1
#name of the computer (localhost for the current machine)
ComputerName=localhost
#cores to be included from this node
CPUnbr=[1:2]
#path to matlab.exe; on Windows, theMatlab bin folder is in the system path
#so we only need to provide the name of the exe file
MatlabOctavePath=matlab
#Dynare path you are using
DynarePath=C:/dynare/2016-05-10/matlab
.. _PsTools: https://technet.microsoft.com/sysinternals/pstools.aspx

6696
src/source/themodelfile.rst Normal file

File diff suppressed because it is too large Load Diff

1782
src/source/timeseries.rst Normal file

File diff suppressed because it is too large Load Diff

4046
theme.css Normal file

File diff suppressed because it is too large Load Diff