Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
Loading items

Target

Select target project
  • normann/preprocessor
  • Dynare/preprocessor
  • FerhatMihoubi/preprocessor
  • MichelJuillard/preprocessor
  • sebastien/preprocessor
  • lnsongxf/preprocessor
  • albop/preprocessor
  • DoraK/preprocessor
  • amg/preprocessor
  • wmutschl/preprocessor
  • JohannesPfeifer/preprocessor
11 results
Select Git revision
  • 4.6
  • aux_vars_fix
  • master
  • occbin
  • pac_composite_target_mce
  • ramsey_k_order
  • rework_pac
  • uop
  • created_preprocessor_repo
9 results
Show changes
Commits on Source (254)
Showing
with 3925 additions and 2927 deletions
# This file should be kept in sync with the one in dynare.git (which also
# contains more explanations).
Language: Cpp
Standard: c++20
ColumnLimit: 100
BasedOnStyle: GNU
AllowShortFunctionsOnASingleLine: None
AlwaysBreakTemplateDeclarations: Yes
BreakConstructorInitializers: AfterColon
BreakInheritanceList: AfterColon
Cpp11BracedListStyle: true
DeriveLineEnding: false
IndentPPDirectives: AfterHash
InsertNewlineAtEOF: true
PackConstructorInitializers: NextLine
PPIndentWidth: 1
PointerAlignment: Left
# RemoveParentheses: ReturnStatement
# RemoveSemicolon: true
SpaceAfterTemplateKeyword: false
SpaceBeforeParens: ControlStatements
SpaceBeforeCpp11BracedList: true
# TODO: add the following check families:
# - bugprone-*
# - cppcoreguidelines-
# NB: as of clang-tidy 16, we get several false positives inside boost, notably this one:
# https://github.com/llvm/llvm-project/issues/40486
Checks: 'performance-*,modernize-*,-modernize-use-trailing-return-type,-clang-diagnostic-unqualified-std-cast-call'
variables:
TERM: linux
MINGW32_BOOST_VERSION: 1.81.0-7
MINGW64_BOOST_VERSION: 1.81.0-7
MINGW64_BOOST_VERSION: 1.88.0-2
WGET_OPTIONS: '--no-verbose --no-use-server-timestamps --retry-connrefused --retry-on-host-error'
# To ensure that "false && true" fails, see https://gitlab.com/gitlab-org/gitlab-runner/-/issues/25394#note_412609647
FF_ENABLE_BASH_EXIT_CODE_CHECK: 'true'
build_linux_x86_64:
stage: build
......@@ -16,7 +17,7 @@ build_linux_x86_64:
build_linux_arm64:
stage: build
script:
- meson setup -D buildtype=release --cross-file scripts/arm64-cross.ini build
- meson setup -D buildtype=release --cross-file scripts/linux-arm64-cross.ini build
- meson compile -C build -v
artifacts:
paths:
......@@ -46,8 +47,40 @@ build_macos_x86_64:
tags:
- macOS
script:
- arch -x86_64 meson setup -D buildtype=release --native-file scripts/homebrew-native.ini build
- arch -x86_64 meson setup -D buildtype=release --native-file scripts/homebrew-native-x86_64.ini build
- arch -x86_64 meson compile -C build -v
artifacts:
paths:
- build/src/dynare-preprocessor
build_macos_arm64:
stage: build
tags:
- macOS
script:
- export PATH="/opt/homebrew/bin:$PATH"
- arch -arm64 meson setup -D buildtype=release --native-file scripts/homebrew-native-arm64.ini build
- arch -arm64 meson compile -C build -v
artifacts:
paths:
- build/src/dynare-preprocessor
test_clang_format:
stage: test
script:
- meson setup build-clang-format
- ninja -C build-clang-format clang-format-check
needs: []
test_clang_tidy:
stage: test
script:
# Hack needed for meson < 1.6.0 which only looks for unversioned clang-tidy
- mkdir -p ~/.local/bin && ln -s /usr/bin/clang-tidy-19 ~/.local/bin/clang-tidy
- export PATH="$HOME/.local/bin:$PATH"
- meson setup build-clang-tidy
# Generate Flex and Bison files
- meson compile -C build-clang-tidy
- ninja -C build-clang-tidy clang-tidy
needs: []
when: manual
......@@ -15,7 +15,7 @@
\pgfdeclareimage[height=0.8cm]{logo}{dlogo}
\institute[Dynare Team]{\pgfuseimage{logo}}
\date{23 May 2023}
\date{31 May 2024}
\AtBeginSection[]
{
......@@ -156,9 +156,9 @@
\item comparison operators: \texttt{< > <= >= == !=}
\item logical operators: \verb+&& || !+
\item range with unit increment: \texttt{1:4} is equivalent to
real array \texttt{[1, 2, 3, 4]}. (NB: \texttt{[1:4]} is equivalent to an
real array \texttt{[1, 2, 3, 4]} \\ (NB: \texttt{[1:4]} is equivalent to an
array containing an array of reals, \textit{i.e.} \texttt{[[1, 2, 3, 4]]})
\item range with user-defined increment: \texttt{4:-1.1:-1} is equivalent to real array \texttt{[4, 2.9, 1.8, 0.7, -0.4]}.
\item range with user-defined increment: \\ \texttt{4:-1.1:-1} is equivalent to real array \texttt{[4, 2.9, 1.8, 0.7, -0.4]}
\end{itemize}
\end{block}
......@@ -314,7 +314,7 @@ Then \texttt{distance(3, 4)} will be equivalent to \texttt{5}.
\end{frame}
\begin{frame}[fragile=singleslide]
\frametitle{Defining macro-variables}
\frametitle{Defining macro-variables (1/2)}
The value of a macro-variable can be defined with the \verb+@#define+
directive.
......@@ -335,9 +335,31 @@ Then \texttt{distance(3, 4)} will be equivalent to \texttt{5}.
@#define t = ("US" in w) // Equals true
\end{verbatim}
\end{block}
NB: You can define macro variables on the Dynare command line by using the \texttt{-D} option
\end{frame}
\begin{frame}[fragile=singleslide]
\frametitle{Defining macro-variables (2/2)}
Macro variables can also be defined on the Dynare command line by using the
\texttt{-D} option, for easily switching between different flavours of a model.
\begin{block}{Example 1}
\begin{verbatim}
dynare myfile.mod -Dx=5
\end{verbatim}
The macro-variable \texttt{x} will be equal to \texttt{5} when running \texttt{myfile.mod}.
\end{block}
\begin{block}{Example 2}
Use single quotes around the \texttt{-D} option when there are spaces or
special characters in the variable definition.
\begin{verbatim}
dynare myfile.mod '-DA=[ i in [1,2,3] when i > 1 ]'
\end{verbatim}
The macro-variable \texttt{A} will be equal to \texttt{[2,3]} when running \texttt{myfile.mod}.
\end{block}
\end{frame}
\begin{frame}[fragile=singleslide]
\frametitle{Expression substitution}
\framesubtitle{Dummy example}
......@@ -611,7 +633,7 @@ end;
\begin{frame}
\frametitle{Macro-related command line options}
\begin{itemize}
\item \texttt{savemacro}: Useful for debugging or learning purposes, saves the output of the macro processor. If your \texttt{.mod} file is called \texttt{file.mod}, the output is saved to \texttt{file-macroexp.mod}.
\item \texttt{savemacro}: Useful for debugging or learning purposes, saves the output of the macro processor. If your \texttt{.mod} file is called \texttt{file.mod}, the output is saved to \texttt{file\_macroexp.mod}.
\item NB: \texttt{savemacro=filename} allows a user-defined file name
\item \texttt{linemacro}: In the output of \texttt{savemacro}, print line numbers where the macro directives were placed.
\item \texttt{onlymacro}: Stops processing after the macro processing step.
......@@ -866,7 +888,7 @@ rhos = [ 0.8, 0.9, 1];
\ccbysa
\column{0.71\textwidth}
\tiny
Copyright © 2008-2023 Dynare Team \\
Copyright © 2008-2024 Dynare Team \\
License: \href{http://creativecommons.org/licenses/by-sa/4.0/}{Creative
Commons Attribution-ShareAlike 4.0}
\end{columns}
......
\documentclass{beamer}
\documentclass[aspectratio=169]{beamer}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
......@@ -9,6 +9,8 @@
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\newenvironment{witemize}{\itemize\addtolength{\itemsep}{8pt}}{\enditemize}
\newenvironment{wenumerate}{\enumerate\addtolength{\itemsep}{8pt}}{\enditemize}
\graphicspath{{../logos}}
......@@ -69,7 +71,7 @@
\ccbysa
\column{0.71\textwidth}
\tiny
Copyright © 2007--2019 Dynare Team \\
Copyright © 2007--2023 Dynare Team \\
Licence: \href{http://creativecommons.org/licenses/by-sa/4.0/}{Creative
Commons Attribution-ShareAlike 4.0}
\end{columns}
......@@ -90,35 +92,106 @@
\begin{frame}
\frametitle{Calling Dynare}
\begin{itemize}
\begin{witemize}
\item Dynare is called from the host language platform with the syntax \texttt{dynare <<filename>>.mod}
\item This call can be followed by certain options:
\begin{itemize}
\item Some of these options impact host language platform functionality, \textit{e.g.} \texttt{nograph} prevents graphs from being displayed in MATLAB
\item Some cause differences in the output created by default, \textit{e.g.} \texttt{notmpterms} prevents temporary terms from being written to the static/dynamic files
\item While others impact the functionality of the macroprocessor or the preprocessor, \textit{e.g.} \texttt{nostrict} shuts off certain checks that the preprocessor does by defalut
\item Some of these options impact host language platform functionality\\
$\rightarrow$ \textit{e.g.} \texttt{nograph} prevents graphs from being displayed in MATLAB
\item Some cause differences in the output created by default\\
$\rightarrow$ \texttt{notmpterms} prevents temporary terms from being written to the static/dynamic files
\item While others impact the functionality of the macroprocessor or the preprocessor\\
$\rightarrow$ \textit{e.g.} \texttt{nostrict} shuts off certain checks that the preprocessor does by default
\end{itemize}
\item MATLAB command line supports syntax completion since Dynare 6.x
\end{witemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Command line options in the mod-file}
\begin{witemize}
\item Command line options can alternatively be defined in the first line of the .mod file
\item Avoids to always have to invoke an option at the command line\\
$\rightarrow$ particularly useful for the \texttt{nostrict} option during the development phase of a model
\item Definition must be
\begin{itemize}
\item a one-line Dynare comment, i.e. begin //
\item the options must be enclosed in \texttt{----+ options:} and \texttt{+----} and must be whitespace separated
\item As in the command line, if an option admits a value, the equal symbol must not be surrounded by spaces
\end{itemize}
\begin{block}{Example}
\begin{verbatim}
// --+ options: json=compute, stochastic, nostrict +--
\end{verbatim}
\end{block}
\end{witemize}
\end{frame}
\section{Macro processing}
\begin{frame}
\frametitle{Macro processing}
\begin{witemize}
\item The Dynare macro language provides a set of macro commands that can be used in \texttt{mod} files
\item The macro processor employs text expansions/inclusions to transform a \texttt{mod} file with macro commands into a \texttt{mod} file without macro commands\\
$\rightarrow$ result can be stored using \texttt{savemacro} option
\item The result is fed to the parser\\
$\rightarrow$ use \texttt{onlymacro} to stop after macro processing before parsing
\item Attention: the macro processor only does text substitution; objects computed in later steps are not available yet and cannot be conditioned on for that reason
\end{witemize}
\end{frame}
\section{Parsing}
\begin{frame}
\frametitle{Parsing overview}
\begin{itemize}
\begin{witemize}
\item Parsing is the action of transforming an input text (a \texttt{mod} file in our case) into a data structure suitable for computation
\item The parser consists of three components:
\begin{itemize}
\begin{wenumerate}
\item the \alert{lexical analyzer}, which recognizes the ``words'' of the \texttt{mod} file (analog to the \textit{vocabulary} of a language)
\item the \alert{syntax analyzer}, which recognizes the ``sentences'' of the \texttt{mod} file (analog to the \textit{grammar} of a language)
\item the \alert{parsing driver}, which coordinates the whole process and constructs the data structure using the results of the lexical and syntax analyses
\end{itemize}
\end{itemize}
\end{wenumerate}
\end{witemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Undesired Parsing}
\begin{witemize}
\item Dynare will try to parse all tokens it recognizes
\item Code not recognized by the parser is directly passed to the preprocessor output\\
$\rightarrow$ allows using MATLAB/Octave commands directly in the mod-file
\item Causes problems when one wants to invoke commands containing recognized tokens
\end{witemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Bypassing the parsing}
\begin{witemize}
\item The \texttt{verbatim} block instructs Dynare not to parse text contained in it
\item In the following example, \texttt{stoch\_simul} would otherwise be recognized as a Dynare command during parsing
\end{witemize}
\begin{block}{Verbatim example}
\begin{verbatim}
verbatim;
rhos = [ 0.8, 0.9, 1];
for iter = 1:length(rhos)
set_param_value('rho',rhos(iter));
[info, oo_, options_, M_] = stoch_simul(M_, options_, oo_, var_list_)
if info(1)~=0
error('Simulation failed for parameter draw')
end
end
end;
\end{verbatim}
\end{block}
\end{frame}
\begin{frame}
\frametitle{Lexical analysis}
\begin{itemize}
\frametitle{1.\ Lexical analysis}
\begin{witemize}
\item The lexical analyzer recognizes the ``words'' (or \alert{lexemes}) of the language
\item Defined in \texttt{DynareFlex.ll}, it is transformed into C++ source code by the program \texttt{flex}
\item This file details the list of known lexemes (described by regular expressions) and the associated \alert{token} for each of them
......@@ -126,7 +199,7 @@
\item For variable names or numbers, the token also contains the associated string for further processing
%\item \textit{Note:} the list of tokens can be found at the beginning of \texttt{DynareBison.yy}
\item When invoked, the lexical analyzer reads the next characters of the input, tries to recognize a lexeme, and either produces an error or returns the associated token
\end{itemize}
\end{witemize}
\end{frame}
\begin{frame}[fragile]
......@@ -161,7 +234,7 @@ SEMICOLON
\end{frame}
\begin{frame}
\frametitle{Syntax analysis}
\frametitle{2.\ Syntax analysis}
\framesubtitle{In Dynare}
\begin{itemize}
\item The \texttt{mod} file grammar is described in \texttt{DynareBison.yy}, which is transformed into C++ source code by the program \texttt{bison}
......@@ -203,13 +276,13 @@ expression := expression PLUS expression
\begin{frame}
\frametitle{Semantic actions}
\begin{itemize}
\item So far we have only described how to accept valid \texttt{mod} files and to reject others
\begin{witemize}
\item So far we have only described how to accept valid \texttt{mod} files and reject others
\item But validating is not enough: one needs to do something with the parsed \texttt{mod} file
\item Every grammar rule can have a \alert{semantic action} associated with it: C/C++ code enclosed by curly braces
\item Every rule can return a semantic value (referenced by \texttt{\$\$} in the action)
\item In the action, it is possible to refer to semantic values returned by components of the rule (using \texttt{\$1}, \texttt{\$2}, \ldots)
\end{itemize}
\end{witemize}
\end{frame}
\begin{frame}[fragile]
......@@ -240,15 +313,15 @@ expression := expression PLUS expression
\end{frame}
\begin{frame}
\frametitle{Parsing driver}
\frametitle{3.\ Parsing driver}
The class \texttt{ParsingDriver} has the following roles:
\begin{itemize}
\begin{witemize}
\item It opens the \texttt{mod} file and launches the lexical and syntaxic analyzers on it
\item It implements most of the semantic actions of the grammar
\item By doing so, it creates an object of type \texttt{ModFile}, which is the data structure representing the \texttt{mod} file
\item Or, if there is a parsing error (unknown keyword, undeclared symbol, syntax error), it displays the line and column numbers where the error occurred and exits
\end{itemize}
\end{witemize}
\end{frame}
\section{Data structure representing a \texttt{mod} file}
......@@ -272,7 +345,7 @@ The class \texttt{ParsingDriver} has the following roles:
\begin{frame}
\frametitle{The symbol table (1/3)}
\begin{itemize}
\begin{witemize}
\item A \alert{symbol} is simply the name of a variable (endogenous, exogenous, local, auxiliary, etc), parameter, external function, \ldots basically everything that is not recognized as a Dynare keyword
\item \alert{SymbolTable} is a simple class used to maintain the list of the symbols used in the \texttt{mod} file
\item For each symbol, it stores:
......@@ -281,7 +354,7 @@ The class \texttt{ParsingDriver} has the following roles:
\item its type (an enumerator defined in \texttt{CodeInterpreter.hh})
\item a unique integer identifier (also has a unique identifier by type)
\end{itemize}
\end{itemize}
\end{witemize}
\end{frame}
\begin{frame}
......@@ -303,20 +376,20 @@ The class \texttt{ParsingDriver} has the following roles:
\begin{frame}
\frametitle{The symbol table (3/3)}
\begin{itemize}
\begin{witemize}
\item Symbol table filled in:
\begin{itemize}
\begin{witemize}
\item using the \texttt{var}, \texttt{varexo}, \texttt{varexo\_det}, \texttt{parameter}, \texttt{external\_function}, \texttt{trend\_var}, and \texttt{log\_trend\_var} declarations
\item using pound sign (\#) constructions in the model block
\item using pound sign (\#) constructions (``model-local variables'') in the model block
\item on the fly during parsing: local variables outside models or unknown functions when an undeclared symbol is encountered
\item during the creation of auxiliary variables in the transform pass
\end{itemize}
\end{witemize}
\item Roles of the symbol table:
\begin{itemize}
\item permits parcimonious and more efficient representation of expressions (no need to duplicate or compare strings, only handle a pair of integers)
\begin{witemize}
\item permits parsimonious and more efficient representation of expressions (no need to duplicate or compare strings, only handle a pair of integers)
\item ensures that a given symbol is used with only one type
\end{itemize}
\end{itemize}
\end{witemize}
\end{witemize}
\end{frame}
\begin{frame}
......@@ -335,30 +408,30 @@ The class \texttt{ParsingDriver} has the following roles:
\begin{frame}
\frametitle{Expression trees (2/3)}
\begin{itemize}
\begin{witemize}
\item A tree node is represented by an instance of the abstract class \texttt{ExprNode}
\item This class has 5 sub-classes, corresponding to the 5 types of non-external-function nodes:
\begin{itemize}
\begin{wenumerate}
\item \texttt{NumConstNode} for constant nodes: contains the identifier of the numerical constants it represents
\item \texttt{VariableNode} for variable/parameters nodes: contains the identifier of the variable or parameter it represents
\item \texttt{UnaryOpNode} for unary operators (\textit{e.g.} unary minus, $\log$, $\sin$): contains an enumerator representing the operator, and a pointer to its child
\item \texttt{BinaryOpNode} for binary operators (\textit{e.g.} $+$, $*$, pow): contains an enumerator representing the operator, and pointers to its two children
\item \texttt{TrinaryOpNode} for trinary operators (\textit{e.g.} $normcdf$, $normpdf$): contains an enumerator representing the operator and pointers to its three children
\end{itemize}
\end{itemize}
\end{wenumerate}
\end{witemize}
\end{frame}
\begin{frame}
\frametitle{Expression trees (3/3)}
\begin{itemize}
\begin{witemize}
\item The abstract class \texttt{ExprNode} has an abstract sub-class called \texttt{AbstractExternalFunctionNode}
\item This abstract sub-class has 3 sub-classes, corresponding to the 3 types of external function nodes:
\begin{itemize}
\begin{wenumerate}
\item \texttt{ExternalFunctionNode} for external functions. Contains the identifier of the external function and a vector of its arguments
\item \texttt{FirstDerivExternalFunctionNode} for the first derivative of an external function. In addition to the information contained in \texttt{ExternalFunctionNode}, contains the index w.r.t. which this node is the derivative.
\item \texttt{SecondDerivExternalFunctionNode} for the second derivative of an external function. In addition to the information contained in \texttt{FirstDerivExternalFunctionNode}, contains the index w.r.t. which this node is the second derivative.
\end{itemize}
\end{itemize}
\end{wenumerate}
\end{witemize}
\end{frame}
......@@ -385,28 +458,28 @@ The class \texttt{ParsingDriver} has the following roles:
\begin{frame}
\frametitle{Constructing expression trees}
\begin{itemize}
\begin{witemize}
\item Class \texttt{DataTree} contains a set of methods for constructing expression trees
\item Construction is done bottom-up, node by node:
\begin{itemize}
\begin{witemize}
\item one method for adding a constant node (\texttt{AddPossiblyNegativeConstant(double)})
\item one method for a log node (\texttt{AddLog(arg)})
\item one method for a plus node (\texttt{AddPlus(arg1, arg2)})
\end{itemize}
\end{witemize}
\item These methods take pointers to \texttt{ExprNode}, allocate the memory for the node, construct it, and return its pointer
\item These methods are called:
\begin{itemize}
\begin{witemize}
\item from \texttt{ParsingDriver} in the semantic actions associated to the parsing of expressions
\item during symbolic derivation, to create derivatives expressions
\item during symbolic derivation to create derivatives expressions
\item when creating the static model from the dynamic model
\item \ldots
\end{itemize}
\end{itemize}
\end{witemize}
\end{witemize}
\end{frame}
\begin{frame}
\frametitle{Reduction of constants and symbolic simplifications}
\begin{itemize}
\begin{witemize}
\item The construction methods compute constants whenever possible
\begin{itemize}
\item Suppose you ask to construct the node $1+1$
......@@ -423,19 +496,20 @@ The class \texttt{ParsingDriver} has the following roles:
\item $x^0 = 1$
\end{itemize}
\item When a simplification rule applies, no new node is created
\end{itemize}
\item Attention: this may cause the program to detect issues not directly visible to users like a division by 0
\end{witemize}
\end{frame}
\begin{frame}
\frametitle{Sub-expression sharing (1/2)}
\begin{itemize}
\begin{witemize}
\item Consider the two following expressions: $(1+z)*\log(y)$ and $2^{(1+z)}$
\item Expressions share a common sub-expression: $1+z$
\item The internal representation of these expressions is:
\begin{center}
\includegraphics[width=7cm]{expr-sharing.png}
\end{center}
\end{itemize}
\end{witemize}
\end{frame}
\begin{frame}
......@@ -456,107 +530,107 @@ The class \texttt{ParsingDriver} has the following roles:
\begin{frame}
\frametitle{Final remarks about expressions}
\begin{itemize}
\begin{witemize}
\item Storage of negative constants
\begin{itemize}
\begin{witemize}
\item class \texttt{NumConstNode} only accepts positive constants
\item a negative constant is stored as a unary minus applied to a positive constant
\item this is a kind of identification constraint to avoid having two ways of representing negative constants: $(-2)$ and $-(2)$
\end{itemize}
\end{witemize}
\item Widely used constants
\begin{itemize}
\begin{witemize}
\item class \texttt{DataTree} has attributes containing pointers to constants: $0$, $1$, $2$, $-1$, \texttt{NaN}, $\infty$, $-\infty$, and $\pi$
\item these constants are used in many places (in simplification rules, in derivation algorithm\ldots)
\item sub-expression sharing algorithm ensures that these constants will never be duplicated
\end{itemize}
\end{itemize}
\end{witemize}
\end{witemize}
\end{frame}
\begin{frame}
\frametitle{List of statements}
\begin{itemize}
\begin{witemize}
\item A statement is represented by an instance of a subclass of the abstract class \texttt{Statement}
\item Three groups of statements:
\begin{itemize}
\item initialization statements (parameter initialization with $p = \ldots$, \texttt{initval}, \texttt{histval}, or \texttt{endval} block)
\item shocks blocks (\texttt{shocks}, \texttt{mshocks}, \ldots)
\item computing tasks (\texttt{steady}, \texttt{check}, \texttt{simul}, \ldots)
\item computing tasks (\texttt{steady}, \texttt{check}, \texttt{perfect\_foresight\_solver}, \ldots)
\end{itemize}
\item Each type of statement has its own class (\textit{e.g.} \texttt{InitValStatement}, \texttt{SimulStatement}, \ldots)
\item Each type of statement has its own class (\textit{e.g.} \texttt{InitValStatement}, \texttt{PerfectForesightSolverStatement}, \ldots)
\item The class \texttt{ModFile} stores a list of pointers of type \texttt{Statement*}, corresponding to the statements of the \texttt{mod} file, in their order of declaration
\item Heavy use of polymorphism in the check pass, computing pass, and when writing outputs: abstract class \texttt{Statement} provides a virtual method for these 3 actions
\end{itemize}
\end{witemize}
\end{frame}
\begin{frame}
\frametitle{Evaluation context}
\begin{itemize}
\begin{witemize}
\item The \texttt{ModFile} class contains an \alert{evaluation context}
\item It is a map associating a numerical value to some symbols
\item Filled in with \texttt{initval} block values and parameter initializations
\item Used during equation normalization (in the block decomposition), for finding non-zero entries in the jacobian
\item Used in testing that trends are compatible with a balanced growth path, for finding non-zero cross partials of equations with respect to trend variables and endogenous varibales
\end{itemize}
\item Used during equation normalization (in the block decomposition), for finding non-zero entries in the Jacobian
\item Used in testing that trends are compatible with a balanced growth path, for finding non-zero cross partials of equations with respect to trend variables and endogenous variables
\end{witemize}
\end{frame}
\section{Check pass}
\begin{frame}
\frametitle{Error checking during parsing}
\begin{itemize}
\begin{witemize}
\item Some errors in the \texttt{mod} file can be detected during parsing:
\begin{itemize}
\begin{witemize}
\item syntax errors
\item use of undeclared symbols in model block, initval block\ldots
\item use of a symbol incompatible with its type (\textit{e.g.} parameter in initval, local variable used both in model and outside model)
\item multiple shock declarations for the same variable
\end{itemize}
\end{witemize}
\item But some other checks can only be done when parsing is completed\ldots
\end{itemize}
\end{witemize}
\end{frame}
\begin{frame}
\frametitle{Check pass}
\begin{itemize}
\begin{witemize}
\item The check pass is implemented through the method \texttt{ModFile::checkPass()}
\item Performs many checks. Examples include:
\begin{itemize}
\begin{witemize}
\item check there is at least one equation in the model (except if doing a standalone BVAR estimation)
\item checks for coherence in statements (\textit{e.g.} options passed to statements do not conflict with each other, required options have been passed)
\item checks for coherence among statements (\textit{e.g.} if \texttt{osr} statement is present, ensure \texttt{osr\_params} and \texttt{optim\_weights} statements are present)
\item checks for coherence between statements and attributes of \texttt{mod} file (\textit{e.g.} \texttt{use\_dll} is not used with \texttt{block} or \texttt{bytecode})
\end{itemize}
\end{itemize}
\end{witemize}
\end{witemize}
\end{frame}
\section{Transform pass}
\begin{frame}
\frametitle{Transform pass (1/2)}
\begin{itemize}
\begin{witemize}
\item The transform pass is implemented through the method \texttt{ModFile::transformPass(bool nostrict)}
\item It makes necessary transformations (notably to the dynamic model, symbol table, and statements list) preparing the \texttt{ModFile} object for the computing pass. Examples of transformations include:
\begin{itemize}
\item It makes necessary transformations (notably to the dynamic model, symbol table, and statements list), preparing the \texttt{ModFile} object for the computing pass. Examples of transformations include:
\begin{witemize}
\item creation of auxiliary variables and equations for leads, lags, expectation operator, differentiated forward variables, etc.
\item detrending of model equations if nonstationary variables are present
\item decreasing leads/lags of predetermined variables by one period
\item addition of FOCs of Langrangian for Ramsey problem
\item addition of FOCs of Lagrangian for Ramsey problem
\item addition of \texttt{dsge\_prior\_weight} initialization before all other statements if estimating a DSGE-VAR where the weight of the DSGE prior of the VAR is calibrated
\end{itemize}
\end{itemize}
\end{witemize}
\end{witemize}
\end{frame}
\begin{frame}
\frametitle{Transform pass (2/2)}
\begin{itemize}
\begin{witemize}
\item It then freezes the symbol table, meaning that no more symbols can be created on the \texttt{ModFile} object
\item Finally checks are performed on the transformed model. Examples include:
\begin{itemize}
\item same number of endogenous varibables as equations (not done in certain situations, \textit{e.g.} Ramsey, discretionary policy, etc.)
\item correspondence among variables and statements, \textit{e.g.} Ramsey policy, identification, perfect foresight solver, and simul are incompatible with deterministic exogenous variables
\item correspondence among statements, \textit{e.g.} for DSGE-VAR without \texttt{bayesian\_irf} option, the number of shocks must be greater than or equal to the number of observed variables
\end{itemize}
\end{itemize}
\item Finally, checks are performed on the transformed model. Examples include:
\begin{witemize}
\item same number of endogenous variables as equations (not done in certain situations, \textit{e.g.} Ramsey, discretionary policy, where checks are done in MATLAB)
\item correspondence among variables and statements, \textit{e.g.} Ramsey policy, identification, perfect foresight solver, and perfect foresight solver are incompatible with deterministic exogenous variables
\item correspondence among statements, \textit{e.g.} for DSGE-VAR with \texttt{bayesian\_irf} option, the number of shocks must be equal to the number of observed variables
\end{witemize}
\end{witemize}
\end{frame}
......@@ -566,9 +640,9 @@ The class \texttt{ParsingDriver} has the following roles:
\frametitle{Overview of the computing pass}
\begin{itemize}
\item Computing pass implemented in \texttt{ModFile::computingPass()}
\item Creates Static model from Dynamic (by removing leads/lags)
\item Creates static model from dynamic one (by removing leads/lags)
\item Determines which derivatives to compute
\item Then calls \texttt{DynamicModel::computingPass()} which computes:
\item Then calls \texttt{DynamicModel::computingPass()}, which computes:
\begin{itemize}
\item leag/lag variable incidence matrix
\item symbolic derivatives w.r.t. endogenous, exogenous, and parameters, if needed
......@@ -576,34 +650,34 @@ The class \texttt{ParsingDriver} has the following roles:
\item temporary terms
\item computes equation cross references, if desired
\end{itemize}
\item NB: analagous operations for Static model are performed by \texttt{StaticModel::computingPass()}
\item Asserts that equations declared linear are indeed linear (by checking that Hessian == 0)
\item NB: analogous operations for static model are performed by \texttt{StaticModel::computingPass()}
\item Asserts that equations declared \texttt{linear} are indeed linear (by checking that Hessian == 0)
\item Finally, calls \texttt{Statement::computingPass()} on all statements
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Model Variables}
\begin{itemize}
\begin{witemize}
\item In the context of class \texttt{ModelTree}, a \alert{variable} is a pair (symbol, lag)
\item The symbol must correspond to a variable of type endogenous, exogenous, deterministic exogenous variable, or parameter
\item The \texttt{SymbolTable} class keeps track of valid symbols while the \texttt{variable\_node\_map} keeps track of model variables (symbol, lag pairs stored in \texttt{VariableNode} objects)
\item The \texttt{SymbolTable} class keeps track of valid symbols, while the \texttt{variable\_node\_map} keeps track of model variables (symbol, lag pairs stored in \texttt{VariableNode} objects)
\item After the computing pass, the \texttt{DynamicModel} class writes the leag/lag incidence matrix:
\begin{itemize}
\item three rows: the first row indicates $t-1$, the second row $t$, and the third row $t+1$
\begin{witemize}
\item \texttt{max\_lag + max\_lead + 1} rows (usually 3): the first row indicates $t-1$ (if applicable), the second row $t$, and the third row $t+1$ (if applicable)
\item one column for every endogenous symbol in order of declaration; NB: includes endogenous auxiliary variables created during the transform pass
\item elements of the matrix are either 0 (if the variable does not appear in the model) or correspond to the variable's column in the Jacobian of the dynamic model
\end{itemize}
\end{itemize}
\end{witemize}
\end{witemize}
\end{frame}
\begin{frame}
\frametitle{Static versus dynamic model}
\begin{itemize}
\begin{witemize}
\item The static model is simply the dynamic model without leads and lags
\item Static model used to characterize the steady state
\item The jacobian of the static model is used in the (MATLAB) solver for determining the steady state
\end{itemize}
\item The Jacobian of the static model is used in the (MATLAB) solver for determining the steady state
\end{witemize}
\begin{block}{Example}
\begin{itemize}
\item suppose dynamic model is $2x_t \cdot x_{t-1} = 0$
......@@ -616,41 +690,41 @@ The class \texttt{ParsingDriver} has the following roles:
\begin{frame}
\frametitle{Which derivatives to compute?}
\begin{itemize}
\begin{witemize}
\item In deterministic mode:
\begin{itemize}
\item static jacobian w.r.t. endogenous variables only
\item dynamic jacobian w.r.t. endogenous variables only
\item static Jacobian w.r.t. endogenous variables only
\item dynamic Jacobian w.r.t. endogenous variables only
\end{itemize}
\item In stochastic mode:
\begin{itemize}
\item static jacobian w.r.t. endogenous variables only
\item dynamic jacobian w.r.t. endogenous, exogenous, and deterministic exogenous variables
\item dynamic hessian w.r.t. endogenous, exogenous, and deterministic exogenous variables
\item static Jacobian w.r.t. endogenous variables only
\item dynamic Jacobian w.r.t. endogenous, exogenous, and deterministic exogenous variables
\item dynamic Hessian w.r.t. endogenous, exogenous, and deterministic exogenous variables
\item possibly dynamic 3rd derivatives (if \texttt{order} option $\geq 3$)
\item possibly dynamic jacobian and/or hessian w.r.t. parameters (if \texttt{identification} or analytic derivs needed for \texttt{estimation} and \texttt{params\_derivs\_order} $>0$)
\item possibly dynamic Jacobian and/or Hessian w.r.t. parameters (if \texttt{identification} or analytic derivs needed for \texttt{estimation} and \texttt{params\_derivs\_order} $>0$)
\end{itemize}
\item For Ramsey policy: the same as above, but with one further order of derivation than declared by the user with \texttt{order} option (the derivation order is determined in the check pass, see \texttt{RamseyPolicyStatement::checkPass()})
\end{itemize}
\end{witemize}
\end{frame}
\begin{frame}
\frametitle{Derivation algorithm (1/2)}
\begin{itemize}
\begin{witemize}
\item Derivation of the model implemented in \texttt{ModelTree::computeJacobian()}, \texttt{ModelTree::computeHessian()}, \texttt{ModelTree::computeThirdDerivatives()}, and \texttt{ModelTree::computeParamsDerivatives()}
\item Simply call \texttt{ExprNode::getDerivative(deriv\_id)} on each equation node
\item Use of polymorphism:
\begin{itemize}
\begin{witemize}
\item for a constant or variable node, derivative is straightforward ($0$ or $1$)
\item for a unary, binary, trinary op nodes and external function nodes, recursively calls method \texttt{computeDerivative()} on children to construct derivative
\end{itemize}
\end{itemize}
\end{witemize}
\end{witemize}
\end{frame}
\begin{frame}
\frametitle{Derivation algorithm (2/2)}
\framesubtitle{Optimizations}
\begin{itemize}
\begin{witemize}
\item Caching of derivation results
\begin{itemize}
\item method \texttt{ExprNode::getDerivative(deriv\_id)} memorizes its result in a member attribute (\texttt{derivatives}) the first time it is called
......@@ -660,12 +734,12 @@ The class \texttt{ParsingDriver} has the following roles:
\item Efficiently finds symbolic derivatives equal to $0$
\begin{itemize}
\item consider the expression $x+y^2$
\item without any computation, you know its derivative w.r.t. $z$ is zero
\item without any computation, you know its derivative w.r.t.\ $z$ is zero
\item each node stores in an attribute (\texttt{non\_null\_derivatives}) the set of variables which appear in the expression it represents ($\{x,y\}$ in the example)
\item this set is computed in \texttt{prepareForDerivation()}
\item when \texttt{getDerivative(deriv\_id)} is called, immediately returns zero if \texttt{deriv\_id} is not in that set
\end{itemize}
\end{itemize}
\end{witemize}
\end{frame}
\begin{frame}[fragile]
......@@ -674,7 +748,7 @@ The class \texttt{ParsingDriver} has the following roles:
\item When the preprocessor writes equations and derivatives in its outputs, it takes advantage of sub-expression sharing
\item In MATLAB static and dynamic output files, equations are preceded by a list of \alert{temporary terms}
\item These terms are variables containing expressions shared by several equations or derivatives
\item Using these terms greatly enhances the computing speed of the model residual, jacobian, hessian, or third derivative
\item Using these terms greatly enhances the computing speed of the model residual, Jacobian, Hessian, or third derivative
\end{itemize}
\begin{block}{Example}
\begin{columns}[t]
......@@ -699,26 +773,27 @@ residual(1)=3*T1+1;
\begin{frame}
\frametitle{Temporary terms (2/2)}
\begin{itemize}
\item Expression storage in the preprocessor implements maximal sharing but this is not optimal for the MATLAB output files, because creating a temporary variable also has a cost (in terms of CPU and of memory)
\begin{witemize}
\item Expression storage in the preprocessor implements maximal sharing, but this is not optimal for the MATLAB output files, because creating a temporary variable also has a cost (in terms of CPU and of memory)
\item Computation of temporary terms implements a trade-off between:
\begin{itemize}
\begin{witemize}
\item cost of duplicating sub-expressions
\item cost of creating new variables
\end{itemize}
\end{witemize}
\item Algorithm uses a recursive cost calculation, which marks some nodes as being ``temporary''
\item \textit{Problem}: redundant with optimizations done by the C/C++ compiler (when Dynare is in DLL mode) $\Rightarrow$ compilation very slow on big models
\end{itemize}
\item \textit{Problem}: redundant with optimizations done by the C/C++ compiler (when Dynare is in DLL mode)\\
$\Rightarrow$ compilation very slow on big models
\end{witemize}
\end{frame}
\begin{frame}
\frametitle{The special case of Ramsey policy}
\begin{itemize}
\frametitle{The special case of Ramsey model}
\begin{witemize}
\item For most statements, the method \texttt{computingPass()} is a no-op\ldots
\item \ldots except for \texttt{planner\_objective} statement, which serves to declare planner objective when doing optimal policy under commitment
\item Class \texttt{PlannerObjectiveStatement} contains an instance of \texttt{ModelTree}, which stores the objective function (\texttt{i.e.} only one equation in the tree)
\item Class \texttt{PlannerObjectiveStatement} contains an instance of \texttt{ModelTree} which stores the objective function (\texttt{i.e.} only one equation in the tree)
\item During the computing pass, triggers the computation of the first and second order (static) derivatives of the objective
\end{itemize}
\end{witemize}
\end{frame}
\section{Writing outputs}
......@@ -727,8 +802,8 @@ residual(1)=3*T1+1;
\frametitle{Output overview}
\begin{itemize}
\item Implemented in \texttt{ModFile::writeOutputFiles()}
\item If \texttt{mod} file is \texttt{model.mod}, all created filenames will begin with \texttt{model}
\item Main output file is \texttt{model.m}, containing:
\item If \texttt{mod} file is \texttt{mymodel.mod}, all created filenames will begin with \texttt{mymodel}
\item Main output file is \texttt{mymodel.driver}, containing:
\begin{itemize}
\item general initialization commands
\item symbol table output (from \texttt{SymbolTable::writeOutput()})
......@@ -737,11 +812,12 @@ residual(1)=3*T1+1;
\end{itemize}
\item Subsidiary output files:
\begin{itemize}
\item one for the static model
\item one for the dynamic model
\item one for the auxiliary variables
\item for the static model (residuals, temporary terms, derivatives)
\item for the dynamic model (residuals, temporary terms, derivatives)
\item one for the auxiliary variables in the dynamic model (if relevant)
\item one for the steady state file (if relevant)
\item one for the planner objective (if relevant)
\item for the planner objective and Lagrange multipliers (static residuals and derivatives, if relevant)
\item one each for the static and dynamic parameter derivatives (if required)
\end{itemize}
\end{itemize}
\end{frame}
......@@ -831,7 +907,7 @@ residual(1)=3*T1+1;
\item No divergence of codebase: don't need to repeat code (checks, transformations, etc.) across platforms
\item Creates \texttt{mod} files that can be used on other host language platforms
\item Adds one more HLP library to distribute
\item Need to design/implement classes that will store processed dynare \texttt{mod} file in various HLPs
\item Need to design/implement classes that will store processed Dynare \texttt{mod} file in various HLPs
\end{itemize}
\end{frame}
......
......@@ -2,7 +2,8 @@
# It is not used when building Dynare as a whole.
project('dynare-preprocessor', 'cpp',
version : '6-unstable',
version : '7-unstable',
# NB: update C++ standard in .clang-format whenever the following is modified
default_options : [ 'cpp_std=gnu++20', 'warning_level=2' ],
meson_version : '>=0.64.0')
......
# Meson native file for compiling under Homebrew / arm64
[binaries]
cpp = '/opt/homebrew/bin/g++-15'
flex = '/opt/homebrew/opt/flex/bin/flex'
bison = '/opt/homebrew/opt/bison/bin/bison'
[built-in options]
# XCode 15 (on Ventura and Sonoma) has a linker issue, see https://github.com/mesonbuild/meson/issues/12282, workaround is to use ld_classic
cpp_link_args = [ '-Wl,-ld_classic' ]
\ No newline at end of file
# Meson native file for compiling under Homebrew / x86-64
[binaries]
cpp = '/usr/local/bin/g++-15'
flex = '/usr/local/opt/flex/bin/flex'
bison = '/usr/local/opt/bison/bin/bison'
[built-in options]
# XCode 15 (on Ventura and Sonoma) has a linker issue, see https://github.com/mesonbuild/meson/issues/12282, workaround is to use ld_classic
cpp_link_args = [ '-Wl,-ld_classic' ]
\ No newline at end of file
# Meson native file for compiling under Homebrew
[binaries]
cpp = 'g++-13'
flex = '/usr/local/opt/flex/bin/flex'
bison = '/usr/local/opt/bison/bin/bison'
File moved
# Meson cross file for creating a WebAssembly version of the preprocessor.
#
# Requires emscripten to be installed.
# Was successfully tested with emscripten 3.1.69 installed through emsdk
# tool, as described on: https://emscripten.org/docs/getting_started/downloads.html
# Don’t forget to source script snippet in current shell before running meson.
#
# Compilation creates a .wasm and .js wrapper under <builddir>/src/
#
# Can be run locally with node.js using:
# node dynare-preprocessor.js file.mod
# NB: a version of node.js is shipped with emscripten (under the node/
# subdirectory), but another version should also work.
[binaries]
cpp = 'em++'
[host_machine]
system = 'emscripten'
# Could be changed to wasm64 if 4GB memory constraint is hit
# Some background: https://v8.dev/blog/4gb-wasm-memory
cpu_family = 'wasm32'
cpu = 'wasm32'
endian = 'little'
[built-in options]
# Never do a debug build, because otherwise the lack of optimisations can
# overflow the memory capacities.
buildtype = 'release'
# The -fexceptions flag (for both compilation and linking) is needed for an
# unknown reason (C++ compilers are supposed to always add exception support).
# The -Wno-unqualified-std-cast-call flag removes many warnings about “move”
# not being qualified with “std::” namespace.
# The -fexperimental-library flag is needed to get std::jthread support (it was
# supposed to no longer be necessary for LLVM 20, but for some reason we still
# need it).
cpp_args = [ '-fexceptions', '-Wno-unqualified-std-cast-call', '-fexperimental-library' ]
# NODERAWFS=1 is needed for accessing the local filesystem
cpp_link_args = [ '-s', 'NODERAWFS=1', '-fexceptions' ]
[properties]
# It’s necessary to use a different copy of Boost than the one under
# /usr/include, because otherwise GCC headers confuse Clang
boost_root = '/tmp/boost_1_86_0'
/*
* Copyright © 2022-2023 Dynare Team
* Copyright © 2022-2024 Dynare Team
*
* This file is part of Dynare.
*
......@@ -17,14 +17,17 @@
* along with Dynare. If not, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <ios>
#include <cstdlib>
#include <algorithm>
#include <cstdlib>
#include <ios>
#include <iostream>
#include "Bytecode.hh"
BytecodeWriter::BytecodeWriter(const filesystem::path &filename)
namespace Bytecode
{
Writer::Writer(const filesystem::path& filename)
{
open(filename, ios::out | ios::binary);
if (!is_open())
......@@ -35,17 +38,16 @@ BytecodeWriter::BytecodeWriter(const filesystem::path &filename)
}
template<>
BytecodeWriter &
operator<<(BytecodeWriter &code_file, const FCALL_ &instr)
Writer&
operator<<(Writer& code_file, const FCALL& instr)
{
code_file.instructions_positions.push_back(code_file.tellp());
auto write_member = [&code_file](const auto &member)
{
auto write_member = [&code_file](const auto& member) {
code_file.write(reinterpret_cast<const char*>(&member), sizeof member);
};
write_member(instr.op_code);
write_member(instr.tag);
write_member(instr.nb_output_arguments);
write_member(instr.nb_input_arguments);
write_member(instr.indx);
......@@ -66,23 +68,22 @@ operator<<(BytecodeWriter &code_file, const FCALL_ &instr)
}
template<>
BytecodeWriter &
operator<<(BytecodeWriter &code_file, const FBEGINBLOCK_ &instr)
Writer&
operator<<(Writer& code_file, const FBEGINBLOCK& instr)
{
code_file.instructions_positions.push_back(code_file.tellp());
auto write_member = [&code_file](const auto &member)
{
auto write_member = [&code_file](const auto& member) {
code_file.write(reinterpret_cast<const char*>(&member), sizeof member);
};
write_member(instr.op_code);
write_member(instr.tag);
write_member(instr.size);
write_member(instr.type);
for (int i = 0; i < instr.size; i++)
{
write_member(instr.variable[i]);
write_member(instr.equation[i]);
write_member(instr.variables[i]);
write_member(instr.equations[i]);
}
if (instr.type == BlockSimulationType::solveTwoBoundariesSimple
|| instr.type == BlockSimulationType::solveTwoBoundariesComplete
......@@ -96,8 +97,10 @@ operator<<(BytecodeWriter &code_file, const FBEGINBLOCK_ &instr)
write_member(instr.det_exo_size);
write_member(instr.exo_size);
for_each_n(instr.det_exogenous.begin(), instr.det_exo_size, write_member);
for_each_n(instr.exogenous.begin(), instr.exo_size, write_member);
ranges::for_each_n(instr.det_exogenous.begin(), instr.det_exo_size, write_member);
ranges::for_each_n(instr.exogenous.begin(), instr.exo_size, write_member);
return code_file;
}
}
/*
* Copyright © 2007-2023 Dynare Team
* Copyright © 2007-2024 Dynare Team
*
* This file is part of Dynare.
*
......@@ -17,50 +17,66 @@
* along with Dynare. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef _BYTECODE_HH
#define _BYTECODE_HH
#ifndef BYTECODE_HH
#define BYTECODE_HH
#include <concepts>
#include <filesystem>
#include <fstream>
#include <vector>
#include <utility>
#include <ios>
#include <filesystem>
#include <type_traits>
#include <utility>
#include <vector>
#include "CommonEnums.hh"
using namespace std;
// The different opcodes of bytecode
enum class Tags
namespace Bytecode
{
// The different tags encoding a bytecode instruction
enum class Tag
{
FLDZ, // Loads a zero onto the stack
FLDC, // Loads a constant term onto the stack
FDIMT, // Defines the number of temporary terms - dynamic context (the period has to be indicated)
FDIMST, // Defines the number of temporary terms - static context (the period hasn’t to be indicated)
FDIMST, // Defines the number of temporary terms - static context (the period hasn’t to be
// indicated)
FLDT, // Loads a temporary term onto the stack - dynamic context (the period has to be indicated)
FLDST, // Loads a temporary term onto the stack - static context (the period hasn’t to be indicated)
FSTPT, // Stores a temporary term from the stack - dynamic context (the period has to be indicated)
FSTPST, // Stores a temporary term from the stack - static context (the period hasn’t to be indicated)
FLDU, // Loads an element of the vector U onto the stack - dynamic context (the period has to be indicated)
FLDSU, // Loads an element of the vector U onto the stack - static context (the period hasn’t to be indicated)
FSTPU, // Stores an element of the vector U from the stack - dynamic context (the period has to be indicated)
FSTPSU, // Stores an element of the vector U from the stack - static context (the period hasn’t to be indicated)
FLDV, // Loads a variable (described in SymbolType) onto the stack - dynamic context (the period has to be indicated)
FLDSV, // Loads a variable (described in SymbolType) onto the stack - static context (the period hasn’t to be indicated)
FLDVS, // Loads a variable (described in SymbolType) onto the stack - dynamic context but inside the STEADY_STATE operator (the period hasn’t to be indicated)
FSTPV, // Stores a variable (described in SymbolType) from the stack - dynamic context (the period has to be indicated)
FSTPSV, // Stores a variable (described in SymbolType) from the stack - static context (the period hasn’t to be indicated)
FLDST, // Loads a temporary term onto the stack - static context (the period hasn’t to be
// indicated)
FSTPT, // Stores a temporary term from the stack - dynamic context (the period has to be
// indicated)
FSTPST, // Stores a temporary term from the stack - static context (the period hasn’t to be
// indicated)
FLDU, // Loads an element of the vector U onto the stack - dynamic context (the period has to be
// indicated)
FLDSU, // Loads an element of the vector U onto the stack - static context (the period hasn’t to
// be indicated)
FSTPU, // Stores an element of the vector U from the stack - dynamic context (the period has to be
// indicated)
FSTPSU, // Stores an element of the vector U from the stack - static context (the period hasn’t to
// be indicated)
FLDV, // Loads a variable (described in SymbolType) onto the stack - dynamic context (the period
// has to be indicated)
FLDSV, // Loads a variable (described in SymbolType) onto the stack - static context (the period
// hasn’t to be indicated)
FLDVS, // Loads a variable (described in SymbolType) onto the stack - dynamic context but inside
// the STEADY_STATE operator (the period hasn’t to be indicated)
FSTPV, // Stores a variable (described in SymbolType) from the stack - dynamic context (the period
// has to be indicated)
FSTPSV, // Stores a variable (described in SymbolType) from the stack - static context (the period
// hasn’t to be indicated)
FLDR, // Loads a residual onto the stack
FSTPR, // Stores a residual from the stack
FSTPG, // Stores a derivative from the stack
FSTPG2, // Stores a derivative matrix for a static model from the stack
FSTPG3, // Stores a derivative matrix for a dynamic model from the stack
FSTPG, // Stores the derivative of a simple (single-equation) block in simulate mode
FSTPG2, // Stores the derivative matrix of a block in evaluate mode
FUNARY, // A unary operator
FBINARY, // A binary operator
......@@ -71,7 +87,8 @@ enum class Tags
FBEGINBLOCK, // Marks the beginning of a model block
FENDBLOCK, // Marks the end of a model block
FENDEQU, // Marks the last equation of the block; for a block that has to be solved, the derivatives appear just after this flag
FENDEQU, // Marks the last equation of the block; for a block that has to be solved, the
// derivatives appear just after this flag
FEND, // Marks the end of the model code
FNUMEXPR, // Stores the expression type and references
......@@ -105,660 +122,342 @@ enum class ExternalFunctionCallType
numericalSecondDerivative
};
struct Block_contain_type
{
int Equation, Variable, Own_Derivative;
};
class BytecodeWriter;
class Writer;
struct BytecodeInstruction
struct Instruction
{
const Tags op_code;
explicit BytecodeInstruction(Tags op_code_arg) :
op_code {op_code_arg}
const Tag tag;
explicit Instruction(Tag tag_arg) : tag {tag_arg}
{
}
protected:
/* This is a base class, so the destructor should be either public+virtual or
protected+non-virtual. We opt for the latter, because otherwise this class
would no longer be POD; its memory representation would also include
runtime type information, and our crude serialization technique (copying the
whole object from memory) would thus not work. */
~BytecodeInstruction() = default;
~Instruction() = default;
};
template<typename T1>
class TagWithOneArgument : public BytecodeInstruction
{
protected:
T1 arg1;
public:
TagWithOneArgument(Tags op_code_arg, T1 arg_arg1) : BytecodeInstruction{op_code_arg},
arg1{arg_arg1}
{
};
protected:
// See BytecodeInstruction destructor for the rationale
~TagWithOneArgument() = default;
};
template<typename T>
concept IsInstruction = derived_from<T, Instruction>;
template<typename T1, typename T2>
class TagWithTwoArguments : public BytecodeInstruction
struct FLDZ final : public Instruction
{
protected:
T1 arg1;
T2 arg2;
public:
TagWithTwoArguments(Tags op_code_arg, T1 arg_arg1, T2 arg_arg2) :
BytecodeInstruction{op_code_arg}, arg1{arg_arg1}, arg2{arg_arg2}
FLDZ() : Instruction {Tag::FLDZ}
{
};
protected:
// See BytecodeInstruction destructor for the rationale
~TagWithTwoArguments() = default;
};
template<typename T1, typename T2, typename T3>
class TagWithThreeArguments : public BytecodeInstruction
{
protected:
T1 arg1;
T2 arg2;
T3 arg3;
public:
TagWithThreeArguments(Tags op_code_arg, T1 arg_arg1, T2 arg_arg2, T3 arg_arg3) :
BytecodeInstruction{op_code_arg}, arg1{arg_arg1}, arg2{arg_arg2}, arg3{arg_arg3}
{
};
protected:
// See BytecodeInstruction destructor for the rationale
~TagWithThreeArguments() = default;
};
template<typename T1, typename T2, typename T3, typename T4>
class TagWithFourArguments : public BytecodeInstruction
{
protected:
T1 arg1;
T2 arg2;
T3 arg3;
T4 arg4;
public:
TagWithFourArguments(Tags op_code_arg, T1 arg_arg1, T2 arg_arg2, T3 arg_arg3, T4 arg_arg4) :
BytecodeInstruction{op_code_arg}, arg1{arg_arg1}, arg2{arg_arg2},
arg3{move(arg_arg3)}, arg4{arg_arg4}
{
};
protected:
// See BytecodeInstruction destructor for the rationale
~TagWithFourArguments() = default;
};
class FLDZ_ final : public BytecodeInstruction
{
public:
FLDZ_() : BytecodeInstruction{Tags::FLDZ}
{
};
}
};
class FEND_ final : public BytecodeInstruction
struct FEND final : public Instruction
{
public:
FEND_() : BytecodeInstruction{Tags::FEND}
FEND() : Instruction {Tag::FEND}
{
};
}
};
class FENDBLOCK_ final : public BytecodeInstruction
struct FENDBLOCK final : public Instruction
{
public:
FENDBLOCK_() : BytecodeInstruction{Tags::FENDBLOCK}
FENDBLOCK() : Instruction {Tag::FENDBLOCK}
{
};
}
};
class FENDEQU_ final : public BytecodeInstruction
struct FENDEQU final : public Instruction
{
public:
FENDEQU_() : BytecodeInstruction{Tags::FENDEQU}
FENDEQU() : Instruction {Tag::FENDEQU}
{
};
}
};
class FDIMT_ final : public TagWithOneArgument<int>
struct FDIMT final : public Instruction
{
public:
explicit FDIMT_(int size_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FDIMT, size_arg}
const int size;
explicit FDIMT(int size_arg) : Instruction {Tag::FDIMT}, size {size_arg}
{
};
int
get_size()
{
return arg1;
};
}
};
class FDIMST_ final : public TagWithOneArgument<int>
struct FDIMST final : public Instruction
{
public:
explicit FDIMST_(int size_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FDIMST, size_arg}
const int size;
explicit FDIMST(int size_arg) : Instruction {Tag::FDIMST}, size {size_arg}
{
};
int
get_size()
{
return arg1;
};
}
};
class FLDC_ final : public TagWithOneArgument<double>
{
public:
explicit FLDC_(double value_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FLDC, value_arg}
struct FLDC final : public Instruction
{
};
double
get_value()
const double value;
explicit FLDC(double value_arg) : Instruction {Tag::FLDC}, value {value_arg}
{
return arg1;
};
}
};
class FLDU_ final : public TagWithOneArgument<int>
struct FLDU final : public Instruction
{
public:
explicit FLDU_(int pos_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FLDU, pos_arg}
{
};
int
get_pos()
const int pos;
explicit FLDU(int pos_arg) : Instruction {Tag::FLDU}, pos {pos_arg}
{
return arg1;
};
}
};
class FLDSU_ final : public TagWithOneArgument<int>
struct FLDSU final : public Instruction
{
public:
explicit FLDSU_(int pos_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FLDSU, pos_arg}
{
};
int
get_pos()
const int pos;
explicit FLDSU(int pos_arg) : Instruction {Tag::FLDSU}, pos {pos_arg}
{
return arg1;
};
}
};
class FLDR_ final : public TagWithOneArgument<int>
struct FLDR final : public Instruction
{
public:
explicit FLDR_(int pos_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FLDR, pos_arg}
const int pos;
explicit FLDR(int pos_arg) : Instruction {Tag::FLDR}, pos {pos_arg}
{
};
int
get_pos()
{
return arg1;
};
}
};
class FLDT_ final : public TagWithOneArgument<int>
{
public:
explicit FLDT_(int pos_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FLDT, pos_arg}
struct FLDT final : public Instruction
{
};
int
get_pos()
const int pos;
explicit FLDT(int pos_arg) : Instruction {Tag::FLDT}, pos {pos_arg}
{
return arg1;
};
}
};
class FLDST_ final : public TagWithOneArgument<int>
{
public:
explicit FLDST_(int pos_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FLDST, pos_arg}
struct FLDST final : public Instruction
{
};
int
get_pos()
const int pos;
explicit FLDST(int pos_arg) : Instruction {Tag::FLDST}, pos {pos_arg}
{
return arg1;
};
}
};
class FSTPT_ final : public TagWithOneArgument<int>
{
public:
explicit FSTPT_(int pos_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FSTPT, pos_arg}
struct FSTPT final : public Instruction
{
};
int
get_pos()
const int pos;
explicit FSTPT(int pos_arg) : Instruction {Tag::FSTPT}, pos {pos_arg}
{
return arg1;
};
}
};
class FSTPST_ final : public TagWithOneArgument<int>
{
public:
explicit FSTPST_(int pos_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FSTPST, pos_arg}
struct FSTPST final : public Instruction
{
};
int
get_pos()
const int pos;
explicit FSTPST(int pos_arg) : Instruction {Tag::FSTPST}, pos {pos_arg}
{
return arg1;
};
}
};
class FSTPR_ final : public TagWithOneArgument<int>
{
public:
explicit FSTPR_(int pos_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FSTPR, pos_arg}
struct FSTPR final : public Instruction
{
};
int
get_pos()
const int pos;
explicit FSTPR(int pos_arg) : Instruction {Tag::FSTPR}, pos {pos_arg}
{
return arg1;
};
}
};
class FSTPU_ final : public TagWithOneArgument<int>
{
public:
explicit FSTPU_(int pos_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FSTPU, pos_arg}
struct FSTPU final : public Instruction
{
};
int
get_pos()
const int pos;
explicit FSTPU(int pos_arg) : Instruction {Tag::FSTPU}, pos {pos_arg}
{
return arg1;
};
}
};
class FSTPSU_ final : public TagWithOneArgument<int>
{
public:
explicit FSTPSU_(int pos_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FSTPSU, pos_arg}
struct FSTPSU final : public Instruction
{
};
int
get_pos()
const int pos;
explicit FSTPSU(int pos_arg) : Instruction {Tag::FSTPSU}, pos {pos_arg}
{
return arg1;
};
}
};
class FSTPG_ final : public TagWithOneArgument<int>
{
public:
explicit FSTPG_(int pos_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FSTPG, pos_arg}
struct FSTPG final : public Instruction
{
};
int
get_pos()
explicit FSTPG() : Instruction {Tag::FSTPG}
{
return arg1;
};
}
};
class FSTPG2_ final : public TagWithTwoArguments<int, int>
{
public:
FSTPG2_(int row_arg, int col_arg) : TagWithTwoArguments::TagWithTwoArguments{Tags::FSTPG2, row_arg, col_arg}
{
};
int
get_row()
struct FSTPG2 final : public Instruction
{
return arg1;
};
int
get_col()
const int row, col;
FSTPG2(int row_arg, int col_arg) : Instruction {Tag::FSTPG2}, row {row_arg}, col {col_arg}
{
return arg2;
};
}
};
class FSTPG3_ final : public TagWithFourArguments<int, int, int, int>
{
public:
FSTPG3_(int row_arg, int col_arg, int lag_arg, int col_pos_arg) : TagWithFourArguments::TagWithFourArguments{Tags::FSTPG3, row_arg, col_arg, lag_arg, col_pos_arg}
{
};
int
get_row()
{
return arg1;
};
int
get_col()
struct FUNARY final : public Instruction
{
return arg2;
};
int
get_lag()
{
return arg2;
};
int
get_col_pos()
const UnaryOpcode op_code;
explicit FUNARY(UnaryOpcode op_code_arg) : Instruction {Tag::FUNARY}, op_code {op_code_arg}
{
return arg4;
};
}
};
class FUNARY_ final : public TagWithOneArgument<UnaryOpcode>
{
public:
explicit FUNARY_(UnaryOpcode op_type_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FUNARY, op_type_arg}
struct FBINARY final : public Instruction
{
};
UnaryOpcode
get_op_type()
const BinaryOpcode op_code;
explicit FBINARY(BinaryOpcode op_code_arg) : Instruction {Tag::FBINARY}, op_code {op_code_arg}
{
return arg1;
};
}
};
class FBINARY_ final : public TagWithOneArgument<BinaryOpcode>
struct FTRINARY final : public Instruction
{
public:
explicit FBINARY_(BinaryOpcode op_type_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FBINARY, op_type_arg}
{
};
BinaryOpcode
get_op_type()
const TrinaryOpcode op_code;
explicit FTRINARY(TrinaryOpcode op_code_arg) : Instruction {Tag::FTRINARY}, op_code {op_code_arg}
{
return arg1;
};
}
};
class FTRINARY_ final : public TagWithOneArgument<TrinaryOpcode>
struct FJMPIFEVAL final : public Instruction
{
public:
explicit FTRINARY_(TrinaryOpcode op_type_arg) : TagWithOneArgument::TagWithOneArgument{Tags::FTRINARY, op_type_arg}
const int pos;
explicit FJMPIFEVAL(int pos_arg) : Instruction {Tag::FJMPIFEVAL}, pos {pos_arg}
{
};
TrinaryOpcode
get_op_type()
{
return arg1;
};
}
};
class FJMPIFEVAL_ final : public TagWithOneArgument<int>
{
public:
explicit FJMPIFEVAL_(int arg_pos) : TagWithOneArgument::TagWithOneArgument{Tags::FJMPIFEVAL, arg_pos}
struct FJMP final : public Instruction
{
};
int
get_pos()
const int pos;
explicit FJMP(int pos_arg) : Instruction {Tag::FJMP}, pos {pos_arg}
{
return arg1;
}
};
class FJMP_ final : public TagWithOneArgument<int>
struct FLDTEF final : public Instruction
{
public:
explicit FJMP_(int arg_pos) : TagWithOneArgument::TagWithOneArgument{Tags::FJMP, arg_pos}
{
};
int
get_pos()
const int number;
explicit FLDTEF(int number_arg) : Instruction {Tag::FLDTEF}, number {number_arg}
{
return arg1;
}
};
class FLDTEF_ final : public TagWithOneArgument<int>
{
public:
explicit FLDTEF_(int number) : TagWithOneArgument::TagWithOneArgument{Tags::FLDTEF, number}
struct FSTPTEF final : public Instruction
{
};
int
get_number()
const int number;
explicit FSTPTEF(int number_arg) : Instruction {Tag::FSTPTEF}, number {number_arg}
{
return arg1;
}
};
class FSTPTEF_ final : public TagWithOneArgument<int>
{
public:
explicit FSTPTEF_(int number) : TagWithOneArgument::TagWithOneArgument{Tags::FSTPTEF, number}
struct FLDTEFD final : public Instruction
{
};
int
get_number()
const int indx, row;
FLDTEFD(int indx_arg, int row_arg) : Instruction {Tag::FLDTEFD}, indx {indx_arg}, row {row_arg}
{
return arg1;
}
};
class FLDTEFD_ final : public TagWithTwoArguments<int, int>
{
public:
FLDTEFD_(int indx, int row) : TagWithTwoArguments::TagWithTwoArguments{Tags::FLDTEFD, indx, row}
{
};
int
get_indx()
struct FSTPTEFD final : public Instruction
{
return arg1;
};
int
get_row()
const int indx, row;
FSTPTEFD(int indx_arg, int row_arg) : Instruction {Tag::FSTPTEFD}, indx {indx_arg}, row {row_arg}
{
return arg2;
};
}
};
class FSTPTEFD_ final : public TagWithTwoArguments<int, int>
{
public:
FSTPTEFD_(int indx, int row) : TagWithTwoArguments::TagWithTwoArguments{Tags::FSTPTEFD, indx, row}
{
};
int
get_indx()
struct FLDTEFDD final : public Instruction
{
return arg1;
};
int
get_row()
const int indx, row, col;
FLDTEFDD(int indx_arg, int row_arg, int col_arg) :
Instruction {Tag::FLDTEFDD}, indx {indx_arg}, row {row_arg}, col {col_arg}
{
return arg2;
};
}
};
class FLDTEFDD_ final : public TagWithThreeArguments<int, int, int>
{
public:
FLDTEFDD_(int indx, int row, int col) : TagWithThreeArguments::TagWithThreeArguments{Tags::FLDTEFDD, indx, row, col}
struct FSTPTEFDD final : public Instruction
{
};
int
get_indx()
const int indx, row, col;
FSTPTEFDD(int indx_arg, int row_arg, int col_arg) :
Instruction {Tag::FSTPTEF}, indx {indx_arg}, row {row_arg}, col {col_arg}
{
return arg1;
};
int
get_row()
{
return arg2;
};
int
get_col()
{
return arg3;
};
}
};
class FSTPTEFDD_ final : public TagWithThreeArguments<int, int, int>
{
public:
FSTPTEFDD_(int indx, int row, int col) : TagWithThreeArguments::TagWithThreeArguments{Tags::FSTPTEF, indx, row, col}
struct FLDVS final : public Instruction
{
};
int
get_indx()
const SymbolType type;
const int pos;
FLDVS(SymbolType type_arg, int pos_arg) : Instruction {Tag::FLDVS}, type {type_arg}, pos {pos_arg}
{
return arg1;
};
int
get_row()
{
return arg2;
};
int
get_col()
{
return arg3;
};
}
};
class FLDVS_ final : public TagWithTwoArguments<SymbolType, int>
{
public:
FLDVS_(SymbolType type_arg, int pos_arg) : TagWithTwoArguments::TagWithTwoArguments{Tags::FLDVS, type_arg, pos_arg}
{
};
SymbolType
get_type()
struct FLDSV final : public Instruction
{
return arg1;
};
int
get_pos()
const SymbolType type;
const int pos;
FLDSV(SymbolType type_arg, int pos_arg) : Instruction {Tag::FLDSV}, type {type_arg}, pos {pos_arg}
{
return arg2;
};
}
};
class FLDSV_ final : public TagWithTwoArguments<SymbolType, int>
struct FSTPSV final : public Instruction
{
public:
FLDSV_(SymbolType type_arg, int pos_arg) : TagWithTwoArguments::TagWithTwoArguments{Tags::FLDSV, type_arg, pos_arg}
{
};
SymbolType
get_type()
const SymbolType type;
const int pos;
FSTPSV(SymbolType type_arg, int pos_arg) :
Instruction {Tag::FSTPSV}, type {type_arg}, pos {pos_arg}
{
return arg1;
};
int
get_pos()
{
return arg2;
};
}
};
class FSTPSV_ final : public TagWithTwoArguments<SymbolType, int>
struct FLDV final : public Instruction
{
public:
FSTPSV_(SymbolType type_arg, int pos_arg) : TagWithTwoArguments::TagWithTwoArguments{Tags::FSTPSV, type_arg, pos_arg}
const SymbolType type;
const int pos, lead_lag;
FLDV(SymbolType type_arg, int pos_arg, int lead_lag_arg) :
Instruction {Tag::FLDV}, type {type_arg}, pos {pos_arg}, lead_lag {lead_lag_arg}
{
};
SymbolType
get_type()
{
return arg1;
};
int
get_pos()
{
return arg2;
};
}
};
class FLDV_ final : public TagWithThreeArguments<SymbolType, int, int>
{
public:
FLDV_(SymbolType type_arg, int pos_arg, int lead_lag_arg) :
TagWithThreeArguments::TagWithThreeArguments{Tags::FLDV, type_arg, pos_arg, lead_lag_arg}
{
};
SymbolType
get_type()
struct FSTPV final : public Instruction
{
return arg1;
};
int
get_pos()
{
return arg2;
};
int
get_lead_lag()
const SymbolType type;
const int pos, lead_lag;
FSTPV(SymbolType type_arg, int pos_arg, int lead_lag_arg) :
Instruction {Tag::FSTPV}, type {type_arg}, pos {pos_arg}, lead_lag {lead_lag_arg}
{
return arg3;
};
}
};
class FSTPV_ final : public TagWithThreeArguments<SymbolType, int, int>
{
public:
FSTPV_(SymbolType type_arg, int pos_arg, int lead_lag_arg) :
TagWithThreeArguments::TagWithThreeArguments{Tags::FSTPV, type_arg, pos_arg, lead_lag_arg}
{
};
SymbolType
get_type()
{
return arg1;
};
int
get_pos()
{
return arg2;
};
int
get_lead_lag()
class FCALL final : public Instruction
{
return arg3;
};
};
template<IsInstruction B>
friend Writer& operator<<(Writer& code_file, const B& instr);
class FCALL_ final : public BytecodeInstruction
{
template<typename B>
friend BytecodeWriter &operator<<(BytecodeWriter &code_file, const B &instr);
private:
int nb_output_arguments, nb_input_arguments, indx;
string func_name;
string arg_func_name;
int add_input_arguments {0}, row {0}, col {0};
ExternalFunctionCallType call_type;
public:
FCALL_(int nb_output_arguments_arg, int nb_input_arguments_arg, string func_name_arg, int indx_arg, ExternalFunctionCallType call_type_arg) :
BytecodeInstruction{Tags::FCALL},
FCALL(int nb_output_arguments_arg, int nb_input_arguments_arg, string func_name_arg, int indx_arg,
ExternalFunctionCallType call_type_arg) :
Instruction {Tag::FCALL},
nb_output_arguments {nb_output_arguments_arg},
nb_input_arguments {nb_input_arguments_arg},
indx {indx_arg},
func_name {move(func_name_arg)},
call_type {call_type_arg}
{
};
}
/* Deserializing constructor.
Updates the code pointer to point beyond the bytes read. */
FCALL_(char *&code) :
BytecodeInstruction{Tags::FCALL}
FCALL(char*& code) : Instruction {Tag::FCALL}
{
code += sizeof(op_code);
code += sizeof(tag);
auto read_member = [&code](auto &member)
{
auto read_member = [&code](auto& member) {
member = *reinterpret_cast<add_pointer_t<decltype(member)>>(code);
code += sizeof member;
};
......@@ -786,47 +485,47 @@ public:
{
// printf("get_function_name => func_name=%s\n",func_name.c_str());fflush(stdout);
return func_name;
};
}
int
get_nb_output_arguments()
{
return nb_output_arguments;
};
}
int
get_nb_input_arguments()
{
return nb_input_arguments;
};
}
int
get_indx()
{
return indx;
};
}
void
set_arg_func_name(string arg_arg_func_name)
{
arg_func_name = arg_arg_func_name;
};
arg_func_name = move(arg_arg_func_name);
}
string
get_arg_func_name()
{
return arg_func_name;
};
}
void
set_nb_add_input_arguments(int arg_add_input_arguments)
{
add_input_arguments = arg_add_input_arguments;
};
}
int
get_nb_add_input_arguments()
{
return add_input_arguments;
};
}
void
set_row(int arg_row)
{
row = arg_row;
};
}
int
get_row()
{
......@@ -836,12 +535,12 @@ public:
set_col(int arg_col)
{
col = arg_col;
};
}
int
get_col()
{
return col;
};
}
ExternalFunctionCallType
get_call_type()
{
......@@ -849,38 +548,40 @@ public:
}
};
class FNUMEXPR_ final : public BytecodeInstruction
class FNUMEXPR final : public Instruction
{
private:
ExpressionType expression_type;
int equation; // Equation number (non-block-specific) (or temporary term number for ExpressionType::TemporaryTerm)
int equation; // Equation number (non-block-specific) (or temporary term number for
// ExpressionType::TemporaryTerm)
int dvariable1; // For derivatives, type-specific ID of the derivation variable
int lag1; // For derivatives, lead/lag of the derivation variable
public:
FNUMEXPR_(const ExpressionType expression_type_arg, int equation_arg) :
BytecodeInstruction{Tags::FNUMEXPR},
FNUMEXPR(const ExpressionType expression_type_arg, int equation_arg) :
Instruction {Tag::FNUMEXPR},
expression_type {expression_type_arg},
equation {equation_arg},
dvariable1 {0},
lag1 {0}
{
};
FNUMEXPR_(const ExpressionType expression_type_arg, int equation_arg, int dvariable1_arg) :
BytecodeInstruction{Tags::FNUMEXPR},
}
FNUMEXPR(const ExpressionType expression_type_arg, int equation_arg, int dvariable1_arg) :
Instruction {Tag::FNUMEXPR},
expression_type {expression_type_arg},
equation {equation_arg},
dvariable1 {dvariable1_arg},
lag1 {0}
{
};
FNUMEXPR_(const ExpressionType expression_type_arg, int equation_arg, int dvariable1_arg, int lag1_arg) :
BytecodeInstruction{Tags::FNUMEXPR},
}
FNUMEXPR(const ExpressionType expression_type_arg, int equation_arg, int dvariable1_arg,
int lag1_arg) :
Instruction {Tag::FNUMEXPR},
expression_type {expression_type_arg},
equation {equation_arg},
dvariable1 {dvariable1_arg},
lag1 {lag1_arg}
{
};
}
ExpressionType
get_expression_type()
{
......@@ -890,49 +591,51 @@ public:
get_equation()
{
return equation;
};
}
int
get_dvariable1()
{
return dvariable1;
};
}
int
get_lag1()
{
return lag1;
};
}
};
class FBEGINBLOCK_ final : public BytecodeInstruction
class FBEGINBLOCK final : public Instruction
{
template<typename B>
friend BytecodeWriter &operator<<(BytecodeWriter &code_file, const B &instr);
template<IsInstruction B>
friend Writer& operator<<(Writer& code_file, const B& instr);
private:
int size {0};
BlockSimulationType type;
vector<int> variable;
vector<int> equation;
vector<int> variables;
vector<int> equations;
vector<int> exogenous;
vector<int> det_exogenous;
bool is_linear {false};
vector<Block_contain_type> Block_Contain_;
int u_count_int {0};
int nb_col_jacob {0};
int det_exo_size, exo_size;
public:
/* Constructor when derivatives w.r.t. exogenous are present (only makes
sense when there is no block-decomposition, since there is no provision for
derivatives w.r.t. endogenous not belonging to the block) */
FBEGINBLOCK_(int size_arg, BlockSimulationType type_arg, int first_element, int block_size,
const vector<int> &variable_arg, const vector<int> &equation_arg,
bool is_linear_arg, int u_count_int_arg, int nb_col_jacob_arg,
int det_exo_size_arg, int exo_size_arg,
vector<int> det_exogenous_arg, vector<int> exogenous_arg) :
BytecodeInstruction{Tags::FBEGINBLOCK},
FBEGINBLOCK(int size_arg, BlockSimulationType type_arg, int first_element, int block_size,
const vector<int>& variables_arg, const vector<int>& equations_arg,
bool is_linear_arg, int u_count_int_arg, int nb_col_jacob_arg, int det_exo_size_arg,
int exo_size_arg, vector<int> det_exogenous_arg, vector<int> exogenous_arg) :
Instruction {Tag::FBEGINBLOCK},
size {size_arg},
type {type_arg},
variable{variable_arg.begin()+first_element, variable_arg.begin()+(first_element+block_size)},
equation{equation_arg.begin()+first_element, equation_arg.begin()+(first_element+block_size)},
variables {variables_arg.begin() + first_element,
variables_arg.begin() + (first_element + block_size)},
equations {equations_arg.begin() + first_element,
equations_arg.begin() + (first_element + block_size)},
exogenous {move(exogenous_arg)},
det_exogenous {move(det_exogenous_arg)},
is_linear {is_linear_arg},
......@@ -943,14 +646,16 @@ public:
{
}
// Constructor when derivatives w.r.t. exogenous are absent
FBEGINBLOCK_(int size_arg, BlockSimulationType type_arg, int first_element, int block_size,
const vector<int> &variable_arg, const vector<int> &equation_arg,
FBEGINBLOCK(int size_arg, BlockSimulationType type_arg, int first_element, int block_size,
const vector<int>& variables_arg, const vector<int>& equations_arg,
bool is_linear_arg, int u_count_int_arg, int nb_col_jacob_arg) :
BytecodeInstruction{Tags::FBEGINBLOCK},
Instruction {Tag::FBEGINBLOCK},
size {size_arg},
type {type_arg},
variable{variable_arg.begin()+first_element, variable_arg.begin()+(first_element+block_size)},
equation{equation_arg.begin()+first_element, equation_arg.begin()+(first_element+block_size)},
variables {variables_arg.begin() + first_element,
variables_arg.begin() + (first_element + block_size)},
equations {equations_arg.begin() + first_element,
equations_arg.begin() + (first_element + block_size)},
is_linear {is_linear_arg},
u_count_int {u_count_int_arg},
nb_col_jacob {nb_col_jacob_arg},
......@@ -960,25 +665,23 @@ public:
}
/* Deserializing constructor.
Updates the code pointer to point beyond the bytes read. */
FBEGINBLOCK_(char *&code) :
BytecodeInstruction{Tags::FBEGINBLOCK}
FBEGINBLOCK(char*& code) : Instruction {Tag::FBEGINBLOCK}
{
code += sizeof(op_code);
code += sizeof(tag);
auto read_member = [&code](auto &member)
{
auto read_member = [&code](auto& member) {
member = *reinterpret_cast<add_pointer_t<decltype(member)>>(code);
code += sizeof member;
};
read_member(size);
read_member(type);
variables.resize(size);
equations.resize(size);
for (int i {0}; i < size; i++)
{
Block_contain_type bc;
read_member(bc.Variable);
read_member(bc.Equation);
Block_Contain_.push_back(move(bc));
read_member(variables[i]);
read_member(equations[i]);
}
if (type == BlockSimulationType::solveTwoBoundariesSimple
|| type == BlockSimulationType::solveTwoBoundariesComplete
......@@ -1010,46 +713,46 @@ public:
get_size()
{
return size;
};
}
BlockSimulationType
get_type()
{
return type;
};
}
bool
get_is_linear()
{
return is_linear;
};
}
int
get_u_count_int()
{
return u_count_int;
};
vector<Block_contain_type>
get_Block_Contain()
}
vector<int>
get_variables()
{
return Block_Contain_;
};
return variables;
}
vector<int>
get_equations()
{
return equations;
}
int
get_nb_col_jacob()
{
return nb_col_jacob;
};
}
int
get_exo_size()
{
return exo_size;
};
}
int
get_det_exo_size()
{
return det_exo_size;
};
vector<int>
get_endogenous()
{
return variable;
}
vector<int>
get_exogenous()
......@@ -1059,15 +762,17 @@ public:
};
// Superclass of std::ofstream for writing a sequence of bytecode instructions
class BytecodeWriter : private ofstream
class Writer : private ofstream
{
template<typename B>
friend BytecodeWriter &operator<<(BytecodeWriter &code_file, const B &instr);
template<IsInstruction B>
friend Writer& operator<<(Writer& code_file, const B& instr);
private:
// Stores the positions of all instructions in the byte stream
vector<pos_type> instructions_positions;
public:
BytecodeWriter(const filesystem::path &filename);
Writer(const filesystem::path& filename);
// Returns the number of the next instruction to be written
int
getInstructionCounter() const
......@@ -1077,9 +782,8 @@ public:
/* Overwrites an existing instruction, given its number.
It is the responsibility of the caller to ensure that the new instruction
occupies exactly as many bytes as the former one. */
template<typename B>
void
overwriteInstruction(int instruction_number, const B &new_instruction)
overwriteInstruction(int instruction_number, const IsInstruction auto& new_instruction)
{
seekp(instructions_positions.at(instruction_number));
*this << new_instruction;
......@@ -1090,9 +794,9 @@ public:
// Overloads of operator<< for writing bytecode instructions
template<typename B>
BytecodeWriter &
operator<<(BytecodeWriter &code_file, const B &instr)
template<IsInstruction B>
Writer&
operator<<(Writer& code_file, const B& instr)
{
code_file.instructions_positions.push_back(code_file.tellp());
code_file.write(reinterpret_cast<const char*>(&instr), sizeof(B));
......@@ -1100,9 +804,11 @@ operator<<(BytecodeWriter &code_file, const B &instr)
}
template<>
BytecodeWriter &operator<<(BytecodeWriter &code_file, const FCALL_ &instr);
Writer& operator<<(Writer& code_file, const FCALL& instr);
template<>
BytecodeWriter &operator<<(BytecodeWriter &code_file, const FBEGINBLOCK_ &instr);
Writer& operator<<(Writer& code_file, const FBEGINBLOCK& instr);
}
#endif // _BYTECODE_HH
#endif
/*
* Copyright © 2007-2022 Dynare Team
* Copyright © 2007-2024 Dynare Team
*
* This file is part of Dynare.
*
......@@ -17,24 +17,30 @@
* along with Dynare. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef _COMMON_ENUMS_HH
#define _COMMON_ENUMS_HH
#ifndef COMMON_ENUMS_HH
#define COMMON_ENUMS_HH
//! Enumeration of possible symbol types
/*! Warning: do not to change existing values for 0 to 4: the values matter for homotopy_setup command */
/*! Warning: do not to change existing values for 0 to 4: the values matter for homotopy_setup
* command */
enum class SymbolType
{
endogenous = 0, //!< Endogenous
exogenous = 1, //!< Exogenous
exogenousDet = 2, //!< Exogenous deterministic
parameter = 4, //!< Parameter
modelLocalVariable = 10, //!< Local variable whose scope is model (pound expression)
modFileLocalVariable = 11, //!< Local variable whose scope is mod file (model excluded)
externalFunction = 12, //!< External (user-defined) function
trend = 13, //!< Trend variable
statementDeclaredVariable = 14, //!< Local variable assigned within a Statement (see subsample statement for example)
endogenous = 0, // Endogenous (non-heterogeneous)
exogenous = 1, // Exogenous (non-heterogeneous)
exogenousDet = 2, // Exogenous deterministic (non-heterogeneous)
parameter = 4, // Parameter (non-heterogeneous)
heterogeneousEndogenous = 5, // Endogenous that is heterogeneous across some dimension
heterogeneousExogenous = 6, // Exogenous that is heterogeneous across some dimension
heterogeneousParameter = 7, // Parameter that is heterogeneous across some dimension
modelLocalVariable = 10, // Local variable whose scope is model (pound expression)
modFileLocalVariable = 11, // Local variable whose scope is mod file (model excluded)
externalFunction = 12, // External (user-defined) function
trend = 13, // Trend variable
statementDeclaredVariable
= 14, //!< Local variable assigned within a Statement (see subsample statement for example)
logTrend = 15, //!< Log-trend variable
unusedEndogenous = 16, //!< Type to mark unused endogenous variables when `nostrict` option is passed
unusedEndogenous
= 16, //!< Type to mark unused endogenous variables when `nostrict` option is passed
// Value 17 is unused for the time being (but could be reused)
......@@ -42,6 +48,13 @@ enum class SymbolType
excludedVariable = 19 //!< Variable excluded via model_remove/var_remove/include_eqs/exclude_eqs
};
constexpr bool
isHeterogeneous(SymbolType type)
{
return type == SymbolType::heterogeneousEndogenous || type == SymbolType::heterogeneousExogenous
|| type == SymbolType::heterogeneousParameter;
}
enum class UnaryOpcode
{
uminus,
......@@ -66,12 +79,14 @@ enum class UnaryOpcode
sign,
steadyState,
steadyStateParamDeriv, // for the derivative of the STEADY_STATE operator w.r.t. to a parameter
steadyStateParam2ndDeriv, // for the 2nd derivative of the STEADY_STATE operator w.r.t. to a parameter
steadyStateParam2ndDeriv, // for the 2nd derivative of the STEADY_STATE operator w.r.t. to a
// parameter
expectation,
erf,
erfc,
diff,
adl
adl,
sum
};
enum class BinaryOpcode
......@@ -119,23 +134,24 @@ enum class PriorDistributions
enum class EquationType
{
unknown, //!< Unknown equation type
evaluate, //!< Simple evaluation, normalized variable on left-hand side (written as such by the user)
evaluateRenormalized, //!< Simple evaluation, normalized variable on left-hand side (normalization computed by the preprocessor)
evaluate, //!< Simple evaluation, normalized variable on left-hand side (written as such by the
//!< user)
evaluateRenormalized, //!< Simple evaluation, normalized variable on left-hand side (normalization
//!< computed by the preprocessor)
solve //!< No simple evaluation of the equation, it has to be solved
};
enum class BlockSimulationType
{
unknown, //!< Unknown simulation type
evaluateForward, //!< Simple evaluation, normalized variable on left-hand side, forward
evaluateForward = 1, //!< Simple evaluation, normalized variable on left-hand side, forward
evaluateBackward, //!< Simple evaluation, normalized variable on left-hand side, backward
solveForwardSimple, //!< Block of one equation, newton solver needed, forward
solveBackwardSimple, //!< Block of one equation, newton solver needed, backward
solveTwoBoundariesSimple, //!< Block of one equation, Newton solver needed, forward and backward
solveForwardComplete, //!< Block of several equations, Newton solver needed, forward
solveBackwardComplete, //!< Block of several equations, Newton solver needed, backward
solveTwoBoundariesComplete //!< Block of several equations, Newton solver needed, forward and backwar
solveTwoBoundariesComplete //!< Block of several equations, Newton solver needed, forward and
//!< backwar
};
enum class PacTargetKind
......@@ -146,4 +162,4 @@ enum class PacTargetKind
dd
};
#endif // _COMMON_ENUMS_HH
#endif
/*
* Copyright © 2003-2023 Dynare Team
* Copyright © 2003-2024 Dynare Team
*
* This file is part of Dynare.
*
......@@ -17,27 +17,27 @@
* along with Dynare. If not, see <https://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <cassert>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <sstream>
using namespace std;
#include "ComputingTasks.hh"
#include "Statement.hh"
#include "ParsingDriver.hh"
#include "Statement.hh"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/tokenizer.hpp>
#pragma GCC diagnostic pop
#include <utility>
#include <algorithm>
#include <utility>
SteadyStatement::SteadyStatement(OptionsList options_list_arg) :
options_list {move(options_list_arg)}
......@@ -71,8 +71,7 @@ SteadyStatement::writeJsonOutput(ostream &output) const
output << "}";
}
CheckStatement::CheckStatement(OptionsList options_list_arg) :
options_list{move(options_list_arg)}
CheckStatement::CheckStatement(OptionsList options_list_arg) : options_list {move(options_list_arg)}
{
}
......@@ -128,8 +127,7 @@ ModelInfoStatement::writeJsonOutput(ostream &output) const
output << "}";
}
SimulStatement::SimulStatement(OptionsList options_list_arg) :
options_list{move(options_list_arg)}
SimulStatement::SimulStatement(OptionsList options_list_arg) : options_list {move(options_list_arg)}
{
}
......@@ -155,8 +153,8 @@ SimulStatement::writeOutput(ostream &output, [[maybe_unused]] const string &base
options_list_new.erase("datafile");
}
options_list_new.writeOutput(output);
output << "perfect_foresight_setup;" << endl
<< "perfect_foresight_solver;" << endl;
output << "oo_ = perfect_foresight_setup(M_, options_, oo_);" << endl
<< "[oo_, Simulated_time_series] = perfect_foresight_solver(M_, options_, oo_);" << endl;
}
void
......@@ -177,7 +175,8 @@ PerfectForesightSetupStatement::PerfectForesightSetupStatement(OptionsList optio
}
void
PerfectForesightSetupStatement::writeOutput(ostream &output, [[maybe_unused]] const string &basename,
PerfectForesightSetupStatement::writeOutput(ostream& output,
[[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
auto options_list_new = options_list; // Need a copy, because of const
......@@ -190,7 +189,7 @@ PerfectForesightSetupStatement::writeOutput(ostream &output, [[maybe_unused]] co
options_list_new.erase("datafile");
}
options_list_new.writeOutput(output);
output << "perfect_foresight_setup;" << endl;
output << "oo_ = perfect_foresight_setup(M_, options_, oo_);" << endl;
}
void
......@@ -218,11 +217,12 @@ PerfectForesightSolverStatement::checkPass(ModFileStructure &mod_file_struct,
}
void
PerfectForesightSolverStatement::writeOutput(ostream &output, [[maybe_unused]] const string &basename,
PerfectForesightSolverStatement::writeOutput(ostream& output,
[[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
options_list.writeOutput(output);
output << "perfect_foresight_solver;" << endl;
output << "[oo_, Simulated_time_series] = perfect_foresight_solver(M_, options_, oo_);" << endl;
}
void
......@@ -237,18 +237,19 @@ PerfectForesightSolverStatement::writeJsonOutput(ostream &output) const
output << "}";
}
PerfectForesightWithExpectationErrorsSetupStatement::PerfectForesightWithExpectationErrorsSetupStatement(OptionsList options_list_arg) :
PerfectForesightWithExpectationErrorsSetupStatement::
PerfectForesightWithExpectationErrorsSetupStatement(OptionsList options_list_arg) :
options_list {move(options_list_arg)}
{
}
void
PerfectForesightWithExpectationErrorsSetupStatement::writeOutput(ostream &output,
[[maybe_unused]] const string &basename,
PerfectForesightWithExpectationErrorsSetupStatement::writeOutput(
ostream& output, [[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
options_list.writeOutput(output);
output << "perfect_foresight_with_expectation_errors_setup;" << endl;
output << "oo_ = perfect_foresight_with_expectation_errors_setup(M_, options_, oo_);" << endl;
}
void
......@@ -263,25 +264,28 @@ PerfectForesightWithExpectationErrorsSetupStatement::writeJsonOutput(ostream &ou
output << "}";
}
PerfectForesightWithExpectationErrorsSolverStatement::PerfectForesightWithExpectationErrorsSolverStatement(OptionsList options_list_arg) :
PerfectForesightWithExpectationErrorsSolverStatement::
PerfectForesightWithExpectationErrorsSolverStatement(OptionsList options_list_arg) :
options_list(move(options_list_arg))
{
}
void
PerfectForesightWithExpectationErrorsSolverStatement::checkPass(ModFileStructure &mod_file_struct,
[[maybe_unused]] WarningConsolidation &warnings)
PerfectForesightWithExpectationErrorsSolverStatement::checkPass(
ModFileStructure& mod_file_struct, [[maybe_unused]] WarningConsolidation& warnings)
{
mod_file_struct.perfect_foresight_with_expectation_errors_solver_present = true;
}
void
PerfectForesightWithExpectationErrorsSolverStatement::writeOutput(ostream &output,
[[maybe_unused]] const string &basename,
PerfectForesightWithExpectationErrorsSolverStatement::writeOutput(
ostream& output, [[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
options_list.writeOutput(output);
output << "perfect_foresight_with_expectation_errors_solver;" << endl;
output << "[oo_, Simulated_time_series] = perfect_foresight_with_expectation_errors_solver(M_, "
"options_, oo_);"
<< endl;
}
void
......@@ -298,8 +302,7 @@ PerfectForesightWithExpectationErrorsSolverStatement::writeJsonOutput(ostream &o
PriorPosteriorFunctionStatement::PriorPosteriorFunctionStatement(const bool prior_func_arg,
OptionsList options_list_arg) :
prior_func{prior_func_arg},
options_list{move(options_list_arg)}
prior_func {prior_func_arg}, options_list {move(options_list_arg)}
{
}
......@@ -307,17 +310,18 @@ void
PriorPosteriorFunctionStatement::checkPass([[maybe_unused]] ModFileStructure& mod_file_struct,
[[maybe_unused]] WarningConsolidation& warnings)
{
if (auto opt = options_list.get_if<OptionsList::StringVal>("function");
!opt || opt->empty())
if (auto opt = options_list.get_if<OptionsList::StringVal>("function"); !opt || opt->empty())
{
cerr << "ERROR: both the 'prior_function' and 'posterior_function' commands require the 'function' option"
cerr << "ERROR: both the 'prior_function' and 'posterior_function' commands require the "
"'function' option"
<< endl;
exit(EXIT_FAILURE);
}
}
void
PriorPosteriorFunctionStatement::writeOutput(ostream &output, [[maybe_unused]] const string &basename,
PriorPosteriorFunctionStatement::writeOutput(ostream& output,
[[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
options_list.writeOutput(output);
......@@ -506,92 +510,6 @@ RamseyModelStatement::writeJsonOutput(ostream &output) const
output << "}";
}
RamseyConstraintsStatement::RamseyConstraintsStatement(const SymbolTable &symbol_table_arg, constraints_t constraints_arg) :
symbol_table{symbol_table_arg},
constraints{move(constraints_arg)}
{
}
void
RamseyConstraintsStatement::checkPass(ModFileStructure &mod_file_struct,
[[maybe_unused]] WarningConsolidation &warnings)
{
mod_file_struct.ramsey_constraints_present = true;
}
void
RamseyConstraintsStatement::writeOutput(ostream &output, [[maybe_unused]] const string &basename,
[[maybe_unused]] bool minimal_workspace) const
{
output << "M_.ramsey_model_constraints = {" << endl;
for (bool printed_something{false};
const auto &it : constraints)
{
if (exchange(printed_something, true))
output << ", ";
output << "{" << it.endo + 1 << ", '";
switch (it.code)
{
case BinaryOpcode::less:
output << '<';
break;
case BinaryOpcode::greater:
output << '>';
break;
case BinaryOpcode::lessEqual:
output << "<=";
break;
case BinaryOpcode::greaterEqual:
output << ">=";
break;
default:
cerr << "Ramsey constraints: this shouldn't happen." << endl;
exit(EXIT_FAILURE);
}
output << "', '";
it.expression->writeOutput(output);
output << "'}" << endl;
}
output << "};" << endl;
}
void
RamseyConstraintsStatement::writeJsonOutput(ostream &output) const
{
output << R"({"statementName": "ramsey_constraints")"
<< R"(, "ramsey_model_constraints": [)" << endl;
for (bool printed_something{false};
const auto &it : constraints)
{
if (exchange(printed_something, true))
output << ", ";
output << R"({"constraint": ")" << symbol_table.getName(it.endo) << " ";
switch (it.code)
{
case BinaryOpcode::less:
output << '<';
break;
case BinaryOpcode::greater:
output << '>';
break;
case BinaryOpcode::lessEqual:
output << "<=";
break;
case BinaryOpcode::greaterEqual:
output << ">=";
break;
default:
cerr << "Ramsey constraints: this shouldn't happen." << endl;
exit(EXIT_FAILURE);
}
output << " ";
it.expression->writeJsonOutput(output, {}, {});
output << R"("})" << endl;
}
output << "]" << endl;
output << "}";
}
RamseyPolicyStatement::RamseyPolicyStatement(SymbolList symbol_list_arg,
OptionsList options_list_arg,
const SymbolTable& symbol_table_arg) :
......@@ -714,7 +632,8 @@ DiscretionaryPolicyStatement::DiscretionaryPolicyStatement(SymbolList symbol_lis
}
void
DiscretionaryPolicyStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
DiscretionaryPolicyStatement::checkPass(ModFileStructure& mod_file_struct,
WarningConsolidation& warnings)
{
mod_file_struct.discretionary_policy_present = true;
......@@ -775,7 +694,8 @@ DiscretionaryPolicyStatement::writeOutput(ostream &output, [[maybe_unused]] cons
options_list.writeOutput(output);
symbol_list.writeOutput("var_list_", output);
output << "[info, oo_, options_, M_] = discretionary_policy(M_, options_, oo_, var_list_);" << endl;
output << "[info, oo_, options_, M_] = discretionary_policy(M_, options_, oo_, var_list_);"
<< endl;
}
void
......@@ -830,7 +750,9 @@ OccbinSolverStatement::writeOutput(ostream &output, [[maybe_unused]] const strin
[[maybe_unused]] bool minimal_workspace) const
{
options_list.writeOutput(output, "options_.occbin");
output << "[oo_.dr, oo_.occbin.simul]= occbin.solver(M_, options_, oo_.dr , oo_.steady_state, oo_.exo_steady_state, oo_.exo_det_steady_state);" << endl;
output << "[oo_.dr, oo_.occbin.simul]= occbin.solver(M_, options_, oo_.dr , oo_.steady_state, "
"oo_.exo_steady_state, oo_.exo_det_steady_state);"
<< endl;
}
void
......@@ -872,8 +794,7 @@ OccbinWriteRegimesStatement::writeJsonOutput(ostream &output) const
OccbinGraphStatement::OccbinGraphStatement(SymbolList symbol_list_arg,
OptionsList options_list_arg) :
symbol_list{move(symbol_list_arg)},
options_list{move(options_list_arg)}
symbol_list {move(symbol_list_arg)}, options_list {move(options_list_arg)}
{
}
......@@ -904,8 +825,7 @@ OccbinGraphStatement::writeJsonOutput(ostream &output) const
}
EstimationStatement::EstimationStatement(const SymbolTable& symbol_table_arg,
SymbolList symbol_list_arg,
OptionsList options_list_arg) :
SymbolList symbol_list_arg, OptionsList options_list_arg) :
symbol_table {symbol_table_arg},
symbol_list {move(symbol_list_arg)},
options_list {move(options_list_arg)}
......@@ -939,8 +859,7 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
mod_file_struct.estimation_analytic_derivation = true;
if (options_list.contains("dsge_var"))
options_list.visit("dsge_var", [&]<class T>(const T &v)
{
options_list.visit("dsge_var", [&]<class T>(const T& v) {
if constexpr (is_same_v<T, OptionsList::StringVal>)
mod_file_struct.dsge_var_estimated = true;
else if constexpr (is_same_v<T, OptionsList::NumVal>)
......@@ -948,37 +867,36 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
});
// Fill in mod_file_struct.bayesian_irf_present
if (auto opt = options_list.get_if<OptionsList::NumVal>("bayesian_irf");
opt && *opt == "true")
if (auto opt = options_list.get_if<OptionsList::NumVal>("bayesian_irf"); opt && *opt == "true")
mod_file_struct.bayesian_irf_present = true;
if (options_list.contains("dsge_varlag"))
if (mod_file_struct.dsge_var_calibrated.empty()
&& !mod_file_struct.dsge_var_estimated)
if (mod_file_struct.dsge_var_calibrated.empty() && !mod_file_struct.dsge_var_estimated)
{
cerr << "ERROR: The estimation statement requires a dsge_var option to be passed "
<< "if the dsge_varlag option is passed." << endl;
exit(EXIT_FAILURE);
}
if (!mod_file_struct.dsge_var_calibrated.empty()
&& mod_file_struct.dsge_var_estimated)
if (!mod_file_struct.dsge_var_calibrated.empty() && mod_file_struct.dsge_var_estimated)
{
cerr << "ERROR: An estimation statement cannot take more than one dsge_var option." << endl;
exit(EXIT_FAILURE);
}
if (!options_list.contains("datafile")
&& !mod_file_struct.estimation_data_statement_present)
if (!options_list.contains("datafile") && !mod_file_struct.estimation_data_statement_present)
{
cerr << "ERROR: The estimation statement requires a data file to be supplied via the datafile option." << endl;
cerr << "ERROR: The estimation statement requires a data file to be supplied via the "
"datafile option."
<< endl;
exit(EXIT_FAILURE);
}
if (options_list.contains("mode_file")
&& mod_file_struct.estim_params_use_calib)
if (options_list.contains("mode_file") && mod_file_struct.estim_params_use_calib)
{
cerr << "ERROR: The mode_file option of the estimation statement is incompatible with the use_calibration option of the estimated_params_init block." << endl;
cerr << "ERROR: The mode_file option of the estimation statement is incompatible with the "
"use_calibration option of the estimated_params_init block."
<< endl;
exit(EXIT_FAILURE);
}
......@@ -987,30 +905,33 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
{
if (options_list.contains("mh_jscale"))
{
cerr << "ERROR: The mh_tune_jscale and mh_jscale options of the estimation statement are incompatible." << endl;
cerr << "ERROR: The mh_tune_jscale and mh_jscale options of the estimation statement are "
"incompatible."
<< endl;
exit(EXIT_FAILURE);
}
}
else if (options_list.contains("mh_tune_jscale.guess"))
{
cerr << "ERROR: The option mh_tune_guess in estimation statement cannot be used without option mh_tune_jscale." << endl;
cerr << "ERROR: The option mh_tune_guess in estimation statement cannot be used without "
"option mh_tune_jscale."
<< endl;
exit(EXIT_FAILURE);
}
/* Check that we are not trying to estimate a parameter appearing in the
planner discount factor (see dynare#1173) */
vector<int> estimated_params_in_planner_discount;
set_intersection(mod_file_struct.estimated_parameters.begin(),
mod_file_struct.estimated_parameters.end(),
mod_file_struct.parameters_in_planner_discount.begin(),
mod_file_struct.parameters_in_planner_discount.end(),
ranges::set_intersection(mod_file_struct.estimated_parameters,
mod_file_struct.parameters_in_planner_discount,
back_inserter(estimated_params_in_planner_discount));
if (!estimated_params_in_planner_discount.empty())
{
cerr << "ERROR: It is not possible to estimate a parameter ("
<< symbol_table.getName(estimated_params_in_planner_discount[0])
<< ") that appears in the discount factor of the planner (i.e. in the 'planner_discount' option)." << endl;
<< ") that appears in the discount factor of the planner (i.e. in the "
"'planner_discount' option)."
<< endl;
exit(EXIT_FAILURE);
}
......@@ -1032,11 +953,9 @@ EstimationStatement::writeOutput(ostream &output, [[maybe_unused]] const string
options_list.writeOutput(output);
// Special treatment for order option and particle filter
if (auto opt = options_list.get_if<OptionsList::NumVal>("order");
!opt)
if (auto opt = options_list.get_if<OptionsList::NumVal>("order"); !opt)
output << "options_.order = 1;" << endl;
else if (int order {stoi(*opt)};
order >= 2)
else if (int order {stoi(*opt)}; order >= 2)
{
output << "options_.particle.status = true;" << endl;
if (order > 2)
......@@ -1044,8 +963,7 @@ EstimationStatement::writeOutput(ostream &output, [[maybe_unused]] const string
}
// Do not check for the steady state in diffuse filter mode (#400)
if (auto opt = options_list.get_if<OptionsList::NumVal>("diffuse_filter");
opt && *opt == "true")
if (auto opt = options_list.get_if<OptionsList::NumVal>("diffuse_filter"); opt && *opt == "true")
output << "options_.steadystate.nocheck = true;" << endl;
symbol_list.writeOutput("var_list_", output);
......@@ -1069,17 +987,16 @@ EstimationStatement::writeJsonOutput(ostream &output) const
output << "}";
}
DynareSensitivityStatement::DynareSensitivityStatement(OptionsList options_list_arg) :
SensitivityStatement::SensitivityStatement(OptionsList options_list_arg) :
options_list {move(options_list_arg)}
{
}
void
DynareSensitivityStatement::checkPass(ModFileStructure &mod_file_struct,
SensitivityStatement::checkPass(ModFileStructure& mod_file_struct,
[[maybe_unused]] WarningConsolidation& warnings)
{
if (auto opt = options_list.get_if<OptionsList::NumVal>("identification");
opt && *opt == "1")
if (auto opt = options_list.get_if<OptionsList::NumVal>("identification"); opt && *opt == "1")
{
mod_file_struct.identification_present = true;
// The following triggers 3rd order derivatives, see preprocessor#40
......@@ -1089,7 +1006,7 @@ DynareSensitivityStatement::checkPass(ModFileStructure &mod_file_struct,
}
void
DynareSensitivityStatement::writeOutput(ostream &output, [[maybe_unused]] const string &basename,
SensitivityStatement::writeOutput(ostream& output, [[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
options_list.writeOutput(output, "options_gsa");
......@@ -1106,13 +1023,13 @@ DynareSensitivityStatement::writeOutput(ostream &output, [[maybe_unused]] const
if (auto opt = options_list.get_if<OptionsList::SymbolListVal>("graph_format"))
opt->writeOutput("options_.graph_format", output);
output << "dynare_sensitivity(options_gsa);" << endl;
output << "gsa.run(M_,oo_,options_,bayestopt_,estim_params_,options_gsa);" << endl;
}
void
DynareSensitivityStatement::writeJsonOutput(ostream &output) const
SensitivityStatement::writeJsonOutput(ostream& output) const
{
output << R"({"statementName": "dynare_sensitivity")";
output << R"({"statementName": "sensitivity")";
if (!options_list.empty())
{
output << ", ";
......@@ -1121,10 +1038,8 @@ DynareSensitivityStatement::writeJsonOutput(ostream &output) const
output << "}";
}
RplotStatement::RplotStatement(SymbolList symbol_list_arg,
const SymbolTable &symbol_table_arg) :
symbol_list{move(symbol_list_arg)},
symbol_table{symbol_table_arg}
RplotStatement::RplotStatement(SymbolList symbol_list_arg, const SymbolTable& symbol_table_arg) :
symbol_list {move(symbol_list_arg)}, symbol_table {symbol_table_arg}
{
}
......@@ -1134,7 +1049,8 @@ RplotStatement::checkPass([[maybe_unused]] ModFileStructure &mod_file_struct,
{
try
{
symbol_list.checkPass(warnings, { SymbolType::endogenous, SymbolType::exogenous}, symbol_table);
symbol_list.checkPass(warnings, {SymbolType::endogenous, SymbolType::exogenous},
symbol_table);
}
catch (SymbolList::SymbolListException& e)
{
......@@ -1167,8 +1083,7 @@ void
UnitRootVarsStatement::writeOutput(ostream& output, [[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
output << "options_.diffuse_filter = 1;" << endl
<< "options_.steadystate.nocheck = 1;" << endl;
output << "options_.diffuse_filter = 1;" << endl << "options_.steadystate.nocheck = 1;" << endl;
}
void
......@@ -1205,10 +1120,9 @@ DsampleStatement::writeJsonOutput(ostream &output) const
<< R"("value2": )" << val2 << "}";
}
AbstractEstimatedParamsStatement::AbstractEstimatedParamsStatement(vector<EstimationParams> estim_params_list_arg,
const SymbolTable &symbol_table_arg) :
estim_params_list{move(estim_params_list_arg)},
symbol_table{symbol_table_arg}
AbstractEstimatedParamsStatement::AbstractEstimatedParamsStatement(
vector<EstimationParams> estim_params_list_arg, const SymbolTable& symbol_table_arg) :
estim_params_list {move(estim_params_list_arg)}, symbol_table {symbol_table_arg}
{
}
......@@ -1229,7 +1143,8 @@ AbstractEstimatedParamsStatement::commonCheckPass() const
if (already_declared_corr.contains(x))
{
cerr << "ERROR: in `" << blockName() << "' block, the correlation between " << it.name << " and " << it.name2 << " is declared twice." << endl;
cerr << "ERROR: in `" << blockName() << "' block, the correlation between " << it.name
<< " and " << it.name2 << " is declared twice." << endl;
exit(EXIT_FAILURE);
}
else
......@@ -1239,7 +1154,8 @@ AbstractEstimatedParamsStatement::commonCheckPass() const
{
if (already_declared.contains(it.name))
{
cerr << "ERROR: in `" << blockName() << "' block, the symbol " << it.name << " is declared twice." << endl;
cerr << "ERROR: in `" << blockName() << "' block, the symbol " << it.name
<< " is declared twice." << endl;
exit(EXIT_FAILURE);
}
else
......@@ -1267,10 +1183,8 @@ AbstractEstimatedParamsStatement::commonCheckPass() const
it.p4->collectVariables(SymbolType::parameter, used_params);
it.jscale->collectVariables(SymbolType::parameter, used_params);
vector<int> intersect;
set_intersection(declared_params.begin(), declared_params.end(),
used_params.begin(), used_params.end(),
back_inserter(intersect));
if (intersect.size() > 0)
ranges::set_intersection(declared_params, used_params, back_inserter(intersect));
if (!intersect.empty())
{
cerr << "ERROR: in `" << blockName() << "' block, the value of estimated parameter "
<< symbol_table.getName(intersect[0]) << " is used in the declaration for ";
......@@ -1307,10 +1221,11 @@ EstimatedParamsStatement::checkPass(ModFileStructure &mod_file_struct,
if (it.prior == PriorDistributions::beta)
try
{
if (it.mean->eval(eval_context_t()) == 0.5
&& it.std->eval(eval_context_t()) == 0.5)
if (it.mean->eval(eval_context_t()) == 0.5 && it.std->eval(eval_context_t()) == 0.5)
{
cerr << "ERROR: The prior density is not defined for the beta distribution when the mean = standard deviation = 0.5." << endl;
cerr << "ERROR: The prior density is not defined for the beta distribution when "
"the mean = standard deviation = 0.5."
<< endl;
exit(EXIT_FAILURE);
}
}
......@@ -1352,7 +1267,9 @@ EstimatedParamsStatement::writeOutput(ostream &output, [[maybe_unused]] const st
int tsid = symbol_table.getTypeSpecificID(it.name) + 1;
int tsid2;
SymbolType symb_type = symbol_table.getType(it.name);
string errmsg = " has been specified twice in two concatenated ''estimated_params'' blocks. Depending on your intention, you may want to use the ''overwrite'' option or an ''estimated_params_remove'' block.";
string errmsg = " has been specified twice in two concatenated ''estimated_params'' blocks. "
"Depending on your intention, you may want to use the ''overwrite'' option "
"or an ''estimated_params_remove'' block.";
switch (it.type)
{
......@@ -1364,7 +1281,8 @@ EstimatedParamsStatement::writeOutput(ostream &output, [[maybe_unused]] const st
<< "estim_params_.var_exo = [estim_params_.var_exo; ";
else if (symb_type == SymbolType::endogenous)
output << "if ~isempty(find(estim_params_.var_endo(:,1)==" << tsid << "))" << endl
<< " error('The standard deviation of the measurement error for " << it.name << errmsg << "')" << endl
<< " error('The standard deviation of the measurement error for " << it.name
<< errmsg << "')" << endl
<< "end" << endl
<< "estim_params_.var_endo = [estim_params_.var_endo; ";
output << tsid;
......@@ -1373,21 +1291,26 @@ EstimatedParamsStatement::writeOutput(ostream &output, [[maybe_unused]] const st
output << "if ~isempty(find(estim_params_.param_vals(:,1)==" << tsid << "))" << endl
<< " error('Parameter " << it.name << errmsg << "')" << endl
<< "end" << endl
<< "estim_params_.param_vals = [estim_params_.param_vals; "
<< tsid;
<< "estim_params_.param_vals = [estim_params_.param_vals; " << tsid;
break;
case 3:
tsid2 = symbol_table.getTypeSpecificID(it.name2) + 1;
if (symb_type == SymbolType::exogenous)
output << "if ~isempty(find((estim_params_.corrx(:,1)==" << tsid << " & estim_params_.corrx(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrx(:,2)==" << tsid << " & estim_params_.corrx(:,1)==" << tsid2 << ")))" << endl
<< " error('The correlation between " << it.name << " and " << it.name2 << errmsg << "')" << endl
output << "if ~isempty(find((estim_params_.corrx(:,1)==" << tsid
<< " & estim_params_.corrx(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrx(:,2)==" << tsid
<< " & estim_params_.corrx(:,1)==" << tsid2 << ")))" << endl
<< " error('The correlation between " << it.name << " and " << it.name2
<< errmsg << "')" << endl
<< "end" << endl
<< "estim_params_.corrx = [estim_params_.corrx; ";
else if (symb_type == SymbolType::endogenous)
output << "if ~isempty(find((estim_params_.corrn(:,1)==" << tsid << " & estim_params_.corrn(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrn(:,2)==" << tsid << " & estim_params_.corrn(:,1)==" << tsid2 << ")))" << endl
<< " error('The correlation between measurement errors on " << it.name << " and " << it.name2 << errmsg << "')" << endl
output << "if ~isempty(find((estim_params_.corrn(:,1)==" << tsid
<< " & estim_params_.corrn(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrn(:,2)==" << tsid
<< " & estim_params_.corrn(:,1)==" << tsid2 << ")))" << endl
<< " error('The correlation between measurement errors on " << it.name
<< " and " << it.name2 << errmsg << "')" << endl
<< "end" << endl
<< "estim_params_.corrn = [estim_params_.corrn; ";
output << tsid << ", " << symbol_table.getTypeSpecificID(it.name2) + 1;
......@@ -1399,8 +1322,7 @@ EstimatedParamsStatement::writeOutput(ostream &output, [[maybe_unused]] const st
it.low_bound->writeOutput(output);
output << ", ";
it.up_bound->writeOutput(output);
output << ", "
<< static_cast<int>(it.prior) << ", ";
output << ", " << static_cast<int>(it.prior) << ", ";
it.mean->writeOutput(output);
output << ", ";
it.std->writeOutput(output);
......@@ -1419,8 +1341,7 @@ EstimatedParamsStatement::writeJsonOutput(ostream &output) const
{
output << R"({"statementName": "estimated_params", )"
<< R"("params": [)";
for (bool printed_something{false};
const auto &it : estim_params_list)
for (bool printed_something {false}; const auto& it : estim_params_list)
{
if (exchange(printed_something, true))
output << ", ";
......@@ -1445,9 +1366,7 @@ EstimatedParamsStatement::writeJsonOutput(ostream &output) const
it.low_bound->writeJsonOutput(output, {}, {});
output << R"(", "upper_bound": ")";
it.up_bound->writeJsonOutput(output, {}, {});
output << R"(", "prior_distribution": )"
<< static_cast<int>(it.prior)
<< R"(, "mean": ")";
output << R"(", "prior_distribution": )" << static_cast<int>(it.prior) << R"(, "mean": ")";
it.mean->writeJsonOutput(output, {}, {});
output << R"(", "std": ")";
it.std->writeJsonOutput(output, {}, {});
......@@ -1463,8 +1382,8 @@ EstimatedParamsStatement::writeJsonOutput(ostream &output) const
<< "}";
}
EstimatedParamsInitStatement::EstimatedParamsInitStatement(vector<EstimationParams> estim_params_list_arg,
const SymbolTable &symbol_table_arg,
EstimatedParamsInitStatement::EstimatedParamsInitStatement(
vector<EstimationParams> estim_params_list_arg, const SymbolTable& symbol_table_arg,
const bool use_calibration_arg) :
AbstractEstimatedParamsStatement(move(estim_params_list_arg), symbol_table_arg),
use_calibration {use_calibration_arg}
......@@ -1501,37 +1420,38 @@ EstimatedParamsInitStatement::writeOutput(ostream &output, [[maybe_unused]] cons
{
output << "tmp1 = find(estim_params_.var_exo(:,1)==" << tsid << ");" << endl
<< "if isempty(tmp1)" << endl
<< " disp(sprintf('The standard deviation of %s is not estimated (the value provided in estimated_params_init is not used).', M_.exo_names{" << tsid << "}))" << endl;
<< " disp(sprintf('The standard deviation of %s is not estimated (the "
"value provided in estimated_params_init is not used).', M_.exo_names{"
<< tsid << "}))" << endl;
skipline = true;
output << "else" << endl
<< " estim_params_.var_exo(tmp1,2) = ";
output << "else" << endl << " estim_params_.var_exo(tmp1,2) = ";
it.init_val->writeOutput(output);
output << ";" << endl
<< "end" << endl;
output << ";" << endl << "end" << endl;
}
else if (symb_type == SymbolType::endogenous)
{
output << "tmp1 = find(estim_params_.var_endo(:,1)==" << tsid << ");" << endl
<< "if isempty(tmp1)" << endl
<< " disp(sprintf('The standard deviation of the measurement error on %s is not estimated (the value provided in estimated_params_init is not used).', M_.endo_names{" << tsid << "}))" << endl;
<< " disp(sprintf('The standard deviation of the measurement error on %s "
"is not estimated (the value provided in estimated_params_init is not "
"used).', M_.endo_names{"
<< tsid << "}))" << endl;
skipline = true;
output << "else" << endl
<< " estim_params_.var_endo(tmp1,2) = ";
output << "else" << endl << " estim_params_.var_endo(tmp1,2) = ";
it.init_val->writeOutput(output);
output << ";" << endl
<< "end" << endl;
output << ";" << endl << "end" << endl;
}
else if (symb_type == SymbolType::parameter)
{
output << "tmp1 = find(estim_params_.param_vals(:,1)==" << tsid << ");" << endl
<< "if isempty(tmp1)" << endl
<< " disp(sprintf('Parameter %s is not estimated (the value provided in estimated_params_init is not used).', M_.param_names{" << tsid << "}))" << endl;
<< " disp(sprintf('Parameter %s is not estimated (the value provided in "
"estimated_params_init is not used).', M_.param_names{"
<< tsid << "}))" << endl;
skipline = true;
output << "else" << endl
<< " estim_params_.param_vals(tmp1,2) = ";
output << "else" << endl << " estim_params_.param_vals(tmp1,2) = ";
it.init_val->writeOutput(output);
output << ";" << endl
<< "end" << endl;
output << ";" << endl << "end" << endl;
}
}
else
......@@ -1539,31 +1459,34 @@ EstimatedParamsInitStatement::writeOutput(ostream &output, [[maybe_unused]] cons
int tsid2 = symbol_table.getTypeSpecificID(it.name2) + 1;
if (symb_type == SymbolType::exogenous)
{
output << "tmp1 = find((estim_params_.corrx(:,1)==" << tsid << " & estim_params_.corrx(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrx(:,2)==" << tsid << " & estim_params_.corrx(:,1)==" << tsid2 << "));" << endl
output << "tmp1 = find((estim_params_.corrx(:,1)==" << tsid
<< " & estim_params_.corrx(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrx(:,2)==" << tsid
<< " & estim_params_.corrx(:,1)==" << tsid2 << "));" << endl
<< "if isempty(tmp1)" << endl
<< " disp(sprintf('The correlation between %s and %s is not estimated (the value provided in estimated_params_init is not used).', M_.exo_names{"
<< " disp(sprintf('The correlation between %s and %s is not estimated (the "
"value provided in estimated_params_init is not used).', M_.exo_names{"
<< tsid << "}, M_.exo_names{" << tsid2 << "}))" << endl;
skipline = true;
output << "else" << endl
<< " estim_params_.corrx(tmp1,3) = ";
output << "else" << endl << " estim_params_.corrx(tmp1,3) = ";
it.init_val->writeOutput(output);
output << ";" << endl
<< "end" << endl;
output << ";" << endl << "end" << endl;
}
else if (symb_type == SymbolType::endogenous)
{
output << "tmp1 = find((estim_params_.corrn(:,1)==" << tsid << " & estim_params_.corrn(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrn(:,2)==" << tsid << " & estim_params_.corrn(:,1)==" << tsid2 << "));" << endl
output << "tmp1 = find((estim_params_.corrn(:,1)==" << tsid
<< " & estim_params_.corrn(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrn(:,2)==" << tsid
<< " & estim_params_.corrn(:,1)==" << tsid2 << "));" << endl
<< "if isempty(tmp1)" << endl
<< " disp(sprintf('The correlation between measurement errors on %s and %s is not estimated (the value provided in estimated_params_init is not used).', M_.endo_names{"
<< " disp(sprintf('The correlation between measurement errors on %s and %s "
"is not estimated (the value provided in estimated_params_init is not "
"used).', M_.endo_names{"
<< tsid << "}, M_.endo_names{" << tsid2 << "}))" << endl;
skipline = true;
output << "else" << endl
<< " estim_params_.corrn(tmp1,3) = ";
output << "else" << endl << " estim_params_.corrn(tmp1,3) = ";
it.init_val->writeOutput(output);
output << ";" << endl
<< "end" << endl;
output << ";" << endl << "end" << endl;
}
}
}
......@@ -1580,8 +1503,7 @@ EstimatedParamsInitStatement::writeJsonOutput(ostream &output) const
output << R"(, "use_calibration_initialization": 1)";
output << R"(, "params": [)";
for (bool printed_something{false};
const auto &it : estim_params_list)
for (bool printed_something {false}; const auto& it : estim_params_list)
{
if (exchange(printed_something, true))
output << ", ";
......@@ -1607,8 +1529,8 @@ EstimatedParamsInitStatement::writeJsonOutput(ostream &output) const
<< "}";
}
EstimatedParamsBoundsStatement::EstimatedParamsBoundsStatement(vector<EstimationParams> estim_params_list_arg,
const SymbolTable &symbol_table_arg) :
EstimatedParamsBoundsStatement::EstimatedParamsBoundsStatement(
vector<EstimationParams> estim_params_list_arg, const SymbolTable& symbol_table_arg) :
AbstractEstimatedParamsStatement(move(estim_params_list_arg), symbol_table_arg)
{
}
......@@ -1621,7 +1543,8 @@ EstimatedParamsBoundsStatement::checkPass([[maybe_unused]] ModFileStructure &mod
}
void
EstimatedParamsBoundsStatement::writeOutput(ostream &output, [[maybe_unused]] const string &basename,
EstimatedParamsBoundsStatement::writeOutput(ostream& output,
[[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
for (const auto& it : estim_params_list)
......@@ -1636,8 +1559,7 @@ EstimatedParamsBoundsStatement::writeOutput(ostream &output, [[maybe_unused]] co
output << "tmp1 = find(estim_params_.var_exo(:,1)==" << tsid << ");" << endl
<< "estim_params_.var_exo(tmp1,3) = ";
it.low_bound->writeOutput(output);
output << ";" << endl
<< "estim_params_.var_exo(tmp1,4) = ";
output << ";" << endl << "estim_params_.var_exo(tmp1,4) = ";
it.up_bound->writeOutput(output);
output << ";" << endl;
}
......@@ -1646,8 +1568,7 @@ EstimatedParamsBoundsStatement::writeOutput(ostream &output, [[maybe_unused]] co
output << "tmp1 = find(estim_params_.var_endo(:,1)==" << tsid << ");" << endl
<< "estim_params_.var_endo(tmp1,3) = ";
it.low_bound->writeOutput(output);
output << ";" << endl
<< "estim_params_.var_endo(tmp1,4) = ";
output << ";" << endl << "estim_params_.var_endo(tmp1,4) = ";
it.up_bound->writeOutput(output);
output << ";" << endl;
}
......@@ -1656,8 +1577,7 @@ EstimatedParamsBoundsStatement::writeOutput(ostream &output, [[maybe_unused]] co
output << "tmp1 = find(estim_params_.param_vals(:,1)==" << tsid << ");" << endl
<< "estim_params_.param_vals(tmp1,3) = ";
it.low_bound->writeOutput(output);
output << ";" << endl
<< "estim_params_.param_vals(tmp1,4) = ";
output << ";" << endl << "estim_params_.param_vals(tmp1,4) = ";
it.up_bound->writeOutput(output);
output << ";" << endl;
}
......@@ -1667,23 +1587,25 @@ EstimatedParamsBoundsStatement::writeOutput(ostream &output, [[maybe_unused]] co
int tsid2 = symbol_table.getTypeSpecificID(it.name2) + 1;
if (symb_type == SymbolType::exogenous)
{
output << "tmp1 = find((estim_params_.corrx(:,1)==" << tsid << " & estim_params_.corrx(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrx(:,2)==" << tsid << " & estim_params_.corrx(:,1)==" << tsid2 << "));" << endl
output << "tmp1 = find((estim_params_.corrx(:,1)==" << tsid
<< " & estim_params_.corrx(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrx(:,2)==" << tsid
<< " & estim_params_.corrx(:,1)==" << tsid2 << "));" << endl
<< "estim_params_.corrx(tmp1,4) = ";
it.low_bound->writeOutput(output);
output << ";" << endl
<< "estim_params_.corrx(tmp1,5) = ";
output << ";" << endl << "estim_params_.corrx(tmp1,5) = ";
it.up_bound->writeOutput(output);
output << ";" << endl;
}
else if (symb_type == SymbolType::endogenous)
{
output << "tmp1 = find((estim_params_.corrn(:,1)==" << tsid << " & estim_params_.corrn(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrn(:,2)==" << tsid << " & estim_params_.corrn(:,1)==" << tsid2 << "));" << endl
output << "tmp1 = find((estim_params_.corrn(:,1)==" << tsid
<< " & estim_params_.corrn(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrn(:,2)==" << tsid
<< " & estim_params_.corrn(:,1)==" << tsid2 << "));" << endl
<< "estim_params_.corrn(tmp1,4) = ";
it.low_bound->writeOutput(output);
output << ";" << endl
<< "estim_params_.corrn(tmp1,5) = ";
output << ";" << endl << "estim_params_.corrn(tmp1,5) = ";
it.up_bound->writeOutput(output);
output << ";" << endl;
}
......@@ -1697,8 +1619,7 @@ EstimatedParamsBoundsStatement::writeJsonOutput(ostream &output) const
output << R"({"statementName": "estimated_params_bounds", )"
<< R"("params": [)";
for (bool printed_something{false};
const auto &it : estim_params_list)
for (bool printed_something {false}; const auto& it : estim_params_list)
{
if (exchange(printed_something, true))
output << ", ";
......@@ -1726,15 +1647,15 @@ EstimatedParamsBoundsStatement::writeJsonOutput(ostream &output) const
<< "}";
}
EstimatedParamsRemoveStatement::EstimatedParamsRemoveStatement(vector<EstimationParams> estim_params_list_arg,
const SymbolTable &symbol_table_arg) :
estim_params_list{move(estim_params_list_arg)},
symbol_table{symbol_table_arg}
EstimatedParamsRemoveStatement::EstimatedParamsRemoveStatement(
vector<EstimationParams> estim_params_list_arg, const SymbolTable& symbol_table_arg) :
estim_params_list {move(estim_params_list_arg)}, symbol_table {symbol_table_arg}
{
}
void
EstimatedParamsRemoveStatement::writeOutput(ostream &output, [[maybe_unused]] const string &basename,
EstimatedParamsRemoveStatement::writeOutput(ostream& output,
[[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
for (const auto& it : estim_params_list)
......@@ -1747,21 +1668,27 @@ EstimatedParamsRemoveStatement::writeOutput(ostream &output, [[maybe_unused]] co
if (symb_type == SymbolType::exogenous)
output << "tmp1 = find(estim_params_.var_exo(:,1)==" << tsid << ");" << endl
<< "if isempty(tmp1)" << endl
<< " error(sprintf('estimated_params_remove: the standard deviation of %s is not estimated.', M_.exo_names{" << tsid << "}))" << endl
<< " error(sprintf('estimated_params_remove: the standard deviation of %s is "
"not estimated.', M_.exo_names{"
<< tsid << "}))" << endl
<< "else" << endl
<< " estim_params_.var_exo(tmp1,:) = [];"
<< "end" << endl;
else if (symb_type == SymbolType::endogenous)
output << "tmp1 = find(estim_params_.var_endo(:,1)==" << tsid << ");" << endl
<< "if isempty(tmp1)" << endl
<< " error(sprintf('estimated_params_remove: the standard deviation of the measurement error on %s is not estimated.', M_.endo_names{" << tsid << "}))" << endl
<< " error(sprintf('estimated_params_remove: the standard deviation of the "
"measurement error on %s is not estimated.', M_.endo_names{"
<< tsid << "}))" << endl
<< "else" << endl
<< " estim_params_.var_endo(tmp1,:) = [];"
<< "end" << endl;
else if (symb_type == SymbolType::parameter)
output << "tmp1 = find(estim_params_.param_vals(:,1)==" << tsid << ");" << endl
<< "if isempty(tmp1)" << endl
<< " error(sprintf('estimated_params_remove: parameter %s is not estimated.', M_.param_names{" << tsid << "}))" << endl
<< " error(sprintf('estimated_params_remove: parameter %s is not "
"estimated.', M_.param_names{"
<< tsid << "}))" << endl
<< "else" << endl
<< " estim_params_.param_vals(tmp1,:) = [];"
<< "end" << endl;
......@@ -1770,19 +1697,25 @@ EstimatedParamsRemoveStatement::writeOutput(ostream &output, [[maybe_unused]] co
{
int tsid2 = symbol_table.getTypeSpecificID(it.name2) + 1;
if (symb_type == SymbolType::exogenous)
output << "tmp1 = find((estim_params_.corrx(:,1)==" << tsid << " & estim_params_.corrx(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrx(:,2)==" << tsid << " & estim_params_.corrx(:,1)==" << tsid2 << "));" << endl
output << "tmp1 = find((estim_params_.corrx(:,1)==" << tsid
<< " & estim_params_.corrx(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrx(:,2)==" << tsid
<< " & estim_params_.corrx(:,1)==" << tsid2 << "));" << endl
<< "if isempty(tmp1)" << endl
<< " error(sprintf('estimated_params_remove: the correlation between %s and %s is not estimated.', M_.exo_names{"
<< " error(sprintf('estimated_params_remove: the correlation between %s and "
"%s is not estimated.', M_.exo_names{"
<< tsid << "}, M_.exo_names{" << tsid2 << "}))" << endl
<< "else" << endl
<< " estim_params_.corrx(tmp1,:) = [];"
<< "end" << endl;
else if (symb_type == SymbolType::endogenous)
output << "tmp1 = find((estim_params_.corrn(:,1)==" << tsid << " & estim_params_.corrn(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrn(:,2)==" << tsid << " & estim_params_.corrn(:,1)==" << tsid2 << "));" << endl
output << "tmp1 = find((estim_params_.corrn(:,1)==" << tsid
<< " & estim_params_.corrn(:,2)==" << tsid2 << ") | "
<< "(estim_params_.corrn(:,2)==" << tsid
<< " & estim_params_.corrn(:,1)==" << tsid2 << "));" << endl
<< "if isempty(tmp1)" << endl
<< " error(sprintf('estimated_params_remove: the correlation between measurement errors on %s and %s is not estimated.', M_.endo_names{"
<< " error(sprintf('estimated_params_remove: the correlation between "
"measurement errors on %s and %s is not estimated.', M_.endo_names{"
<< tsid << "}, M_.endo_names{" << tsid2 << "}))" << endl
<< "else" << endl
<< " estim_params_.corrn(tmp1,:) = [];"
......@@ -1797,8 +1730,7 @@ EstimatedParamsRemoveStatement::writeJsonOutput(ostream &output) const
output << R"({"statementName": "estimated_params_remove", )"
<< R"("params": [)";
for (bool printed_something{false};
const auto &it : estim_params_list)
for (bool printed_something {false}; const auto& it : estim_params_list)
{
if (exchange(printed_something, true))
output << ", ";
......@@ -1824,8 +1756,7 @@ EstimatedParamsRemoveStatement::writeJsonOutput(ostream &output) const
DeterministicTrendsStatement::DeterministicTrendsStatement(trend_elements_t trend_elements_arg,
const SymbolTable& symbol_table_arg) :
trend_elements{move(trend_elements_arg)},
symbol_table{symbol_table_arg}
trend_elements {move(trend_elements_arg)}, symbol_table {symbol_table_arg}
{
}
......@@ -1834,19 +1765,16 @@ DeterministicTrendsStatement::writeOutput(ostream &output, [[maybe_unused]] cons
[[maybe_unused]] bool minimal_workspace) const
{
output << "options_.trend_coeff = {};" << endl;
for (const auto &trend_element : trend_elements)
for (const auto& [name, val] : trend_elements)
if (symbol_table.getType(name) == SymbolType::endogenous)
{
SymbolType type = symbol_table.getType(trend_element.first);
if (type == SymbolType::endogenous)
{
output << "tmp1 = strmatch('" << trend_element.first << "',M_.endogenous_names,'exact');" << endl;
output << "options_.deterministic_trend_coeffs{tmp1} = '";
trend_element.second->writeOutput(output);
output << "tmp1 = strmatch('" << name << "',M_.endogenous_names,'exact');" << endl
<< "options_.deterministic_trend_coeffs{tmp1} = '";
val->writeOutput(output);
output << "';" << endl;
}
else
cerr << "Warning : Non-variable symbol used in deterministic_trends: " << trend_element.first << endl;
}
cerr << "Warning: Non-variable symbol used in deterministic_trends: " << name << endl;
}
void
......@@ -1854,28 +1782,24 @@ DeterministicTrendsStatement::writeJsonOutput(ostream &output) const
{
output << R"({"statementName": "deterministic_trends", )"
<< R"("trends" : {)";
for (bool printed_something{false};
const auto &trend_element : trend_elements)
{
if (symbol_table.getType(trend_element.first) == SymbolType::endogenous)
for (bool printed_something {false}; const auto& [name, val] : trend_elements)
if (symbol_table.getType(name) == SymbolType::endogenous)
{
if (exchange(printed_something, true))
output << ", ";
output << R"(")" << trend_element.first << R"(": ")";
trend_element.second->writeJsonOutput(output, {}, {});
output << R"(")" << name << R"(": ")";
val->writeJsonOutput(output, {}, {});
output << R"(")" << endl;
}
else
cerr << "Warning : Non-variable symbol used in deterministic_trends: " << trend_element.first << endl;
}
cerr << "Warning: Non-variable symbol used in deterministic_trends: " << name << endl;
output << "}"
<< "}";
}
ObservationTrendsStatement::ObservationTrendsStatement(trend_elements_t trend_elements_arg,
const SymbolTable& symbol_table_arg) :
trend_elements{move(trend_elements_arg)},
symbol_table{symbol_table_arg}
trend_elements {move(trend_elements_arg)}, symbol_table {symbol_table_arg}
{
}
......@@ -1884,19 +1808,16 @@ ObservationTrendsStatement::writeOutput(ostream &output, [[maybe_unused]] const
[[maybe_unused]] bool minimal_workspace) const
{
output << "options_.trend_coeff = {};" << endl;
for (const auto &trend_element : trend_elements)
{
SymbolType type = symbol_table.getType(trend_element.first);
if (type == SymbolType::endogenous)
for (const auto& [name, val] : trend_elements)
if (symbol_table.getType(name) == SymbolType::endogenous)
{
output << "tmp1 = strmatch('" << trend_element.first << "',options_.varobs,'exact');" << endl;
output << "options_.trend_coeffs{tmp1} = '";
trend_element.second->writeOutput(output);
output << "tmp1 = strmatch('" << name << "',options_.varobs,'exact');" << endl
<< "options_.trend_coeffs{tmp1} = '";
val->writeOutput(output);
output << "';" << endl;
}
else
cerr << "Warning : Non-variable symbol used in observation_trends: " << trend_element.first << endl;
}
cerr << "Warning: Non-variable symbol used in observation_trends: " << name << endl;
}
void
......@@ -1904,25 +1825,23 @@ ObservationTrendsStatement::writeJsonOutput(ostream &output) const
{
output << R"({"statementName": "observation_trends", )"
<< R"("trends" : {)";
for (bool printed_something{false};
const auto &trend_element : trend_elements)
{
if (symbol_table.getType(trend_element.first) == SymbolType::endogenous)
for (bool printed_something {false}; const auto& [name, val] : trend_elements)
if (symbol_table.getType(name) == SymbolType::endogenous)
{
if (exchange(printed_something, true))
output << ", ";
output << R"(")" << trend_element.first << R"(": ")";
trend_element.second->writeJsonOutput(output, {}, {});
output << R"(")" << name << R"(": ")";
val->writeJsonOutput(output, {}, {});
output << R"(")" << endl;
}
else
cerr << "Warning : Non-variable symbol used in observation_trends: " << trend_element.first << endl;
}
cerr << "Warning: Non-variable symbol used in observation_trends: " << name << endl;
output << "}"
<< "}";
}
FilterInitialStateStatement::FilterInitialStateStatement(filter_initial_state_elements_t filter_initial_state_elements_arg,
FilterInitialStateStatement::FilterInitialStateStatement(
filter_initial_state_elements_t filter_initial_state_elements_arg,
const SymbolTable& symbol_table_arg) :
filter_initial_state_elements {move(filter_initial_state_elements_arg)},
symbol_table {symbol_table_arg}
......@@ -1958,8 +1877,7 @@ FilterInitialStateStatement::writeOutput(ostream &output, [[maybe_unused]] const
}
}
output << "M_.filter_initial_state("
<< symbol_table.getTypeSpecificID(symb_id) + 1
output << "M_.filter_initial_state(" << symbol_table.getTypeSpecificID(symb_id) + 1
<< ",:) = {'" << symbol_table.getName(symb_id) << "', '";
val->writeOutput(output);
output << ";'};" << endl;
......@@ -1972,14 +1890,12 @@ FilterInitialStateStatement::writeJsonOutput(ostream &output) const
output << R"({"statementName": "filter_initial_state", )"
<< R"("states": [)";
for (bool printed_something{false};
const auto &[key, val] : filter_initial_state_elements)
for (bool printed_something {false}; const auto& [key, val] : filter_initial_state_elements)
{
if (exchange(printed_something, true))
output << ", ";
auto& [symb_id, lag] = key;
output << R"({ "var": ")" << symbol_table.getName(symb_id)
<< R"(", "lag": )" << lag
output << R"({ "var": ")" << symbol_table.getName(symb_id) << R"(", "lag": )" << lag
<< R"(, "value": ")";
val->writeJsonOutput(output, {}, {});
output << R"(" })";
......@@ -1987,9 +1903,9 @@ FilterInitialStateStatement::writeJsonOutput(ostream &output) const
output << "] }";
}
OsrParamsStatement::OsrParamsStatement(SymbolList symbol_list_arg, const SymbolTable &symbol_table_arg) :
symbol_list{move(symbol_list_arg)},
symbol_table{symbol_table_arg}
OsrParamsStatement::OsrParamsStatement(SymbolList symbol_list_arg,
const SymbolTable& symbol_table_arg) :
symbol_list {move(symbol_list_arg)}, symbol_table {symbol_table_arg}
{
}
......@@ -1997,7 +1913,7 @@ void
OsrParamsStatement::checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings)
{
if (mod_file_struct.osr_params_present)
cerr << "WARNING: You have more than one osr_params statement in the .mod file." << endl;
warnings << "WARNING: You have more than one osr_params statement in the .mod file." << endl;
mod_file_struct.osr_params_present = true;
try
......@@ -2018,9 +1934,9 @@ OsrParamsStatement::writeOutput(ostream &output, [[maybe_unused]] const string &
symbol_list.writeOutput("M_.osr.param_names", output);
output << "M_.osr.param_names = cellstr(M_.osr.param_names);" << endl
<< "M_.osr.param_indices = zeros(length(M_.osr.param_names), 1);" << endl;
for (int i{0};
auto &symbol : symbol_list.getSymbols())
output << "M_.osr.param_indices(" << ++i <<") = " << symbol_table.getTypeSpecificID(symbol) + 1 << ";" << endl;
for (int i {0}; auto& symbol : symbol_list.getSymbols())
output << "M_.osr.param_indices(" << ++i << ") = " << symbol_table.getTypeSpecificID(symbol) + 1
<< ";" << endl;
}
void
......@@ -2046,7 +1962,8 @@ OsrParamsBoundsStatement::checkPass(ModFileStructure &mod_file_struct,
{
if (!mod_file_struct.osr_params_present)
{
cerr << "ERROR: you must have an osr_params statement before the osr_params_bounds block." << endl;
cerr << "ERROR: you must have an osr_params statement before the osr_params_bounds block."
<< endl;
exit(EXIT_FAILURE);
}
}
......@@ -2056,7 +1973,9 @@ OsrParamsBoundsStatement::writeOutput(ostream &output, [[maybe_unused]] const st
[[maybe_unused]] bool minimal_workspace) const
{
output << "M_.osr.param_bounds = [-inf(length(M_.osr.param_names), 1), inf(length(M_.osr.param_names), 1)];" << endl;
output << "M_.osr.param_bounds = [-inf(length(M_.osr.param_names), 1), "
"inf(length(M_.osr.param_names), 1)];"
<< endl;
for (const auto& it : osr_params_list)
{
......@@ -2073,8 +1992,7 @@ OsrParamsBoundsStatement::writeJsonOutput(ostream &output) const
{
output << R"({"statementName": "osr_params_bounds")"
<< R"(, "bounds": [)";
for (bool printed_something{false};
const auto &it : osr_params_list)
for (bool printed_something {false}; const auto& it : osr_params_list)
{
if (exchange(printed_something, true))
output << ", ";
......@@ -2117,7 +2035,6 @@ OsrStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation
opt && *opt == "1")
mod_file_struct.osr_analytic_derivation = true;
// Option k_order_solver (implicit when order >= 3)
if (auto opt = options_list.get_if<OptionsList::NumVal>("k_order_solver");
(opt && *opt == "true") || mod_file_struct.order_option >= 3)
......@@ -2146,7 +2063,9 @@ OsrStatement::writeOutput(ostream &output, [[maybe_unused]] const string &basena
options_list.writeOutput(output);
symbol_list.writeOutput("var_list_", output);
output << "[info, oo_, options_, M_] = osr.run(M_, options_, oo_, var_list_,M_.osr.param_names,M_.osr.variable_indices,M_.osr.variable_weights);" << endl;
output << "[info, oo_, options_, M_] = osr.run(M_, options_, oo_, "
"var_list_,M_.osr.param_names,M_.osr.variable_indices,M_.osr.variable_weights);"
<< endl;
}
void
......@@ -2190,7 +2109,8 @@ OptimWeightsStatement::writeOutput(ostream &output, [[maybe_unused]] const strin
<< "% OPTIM_WEIGHTS" << endl
<< "%" << endl
<< "M_.osr.variable_weights = sparse(M_.endo_nbr,M_.endo_nbr);" << endl
<< "M_.osr.variable_indices = [];" << endl << endl;
<< "M_.osr.variable_indices = [];" << endl
<< endl;
for (const auto& [name, value] : var_weights)
{
......@@ -2208,7 +2128,8 @@ OptimWeightsStatement::writeOutput(ostream &output, [[maybe_unused]] const strin
output << "M_.osr.variable_weights(" << id1 << "," << id2 << ") = ";
value->writeOutput(output);
output << ";" << endl;
output << "M_.osr.variable_indices = [M_.osr.variable_indices; " << id1 << "; " << id2 << "];" << endl;
output << "M_.osr.variable_indices = [M_.osr.variable_indices; " << id1 << "; " << id2 << "];"
<< endl;
}
}
......@@ -2255,7 +2176,8 @@ DynaSaveStatement::checkPass([[maybe_unused]] ModFileStructure &mod_file_struct,
{
try
{
symbol_list.checkPass(warnings, { SymbolType::endogenous, SymbolType::exogenous }, symbol_table);
symbol_list.checkPass(warnings, {SymbolType::endogenous, SymbolType::exogenous},
symbol_table);
}
catch (SymbolList::SymbolListException& e)
{
......@@ -2269,8 +2191,7 @@ DynaSaveStatement::writeOutput(ostream &output, [[maybe_unused]] const string &b
[[maybe_unused]] bool minimal_workspace) const
{
symbol_list.writeOutput("var_list_", output);
output << "dynasave('" << filename
<< "',var_list_);" << endl;
output << "dynasave('" << filename << "',var_list_);" << endl;
}
void
......@@ -2300,7 +2221,8 @@ DynaTypeStatement::checkPass([[maybe_unused]] ModFileStructure &mod_file_struct,
{
try
{
symbol_list.checkPass(warnings, { SymbolType::endogenous, SymbolType::exogenous }, symbol_table);
symbol_list.checkPass(warnings, {SymbolType::endogenous, SymbolType::exogenous},
symbol_table);
}
catch (SymbolList::SymbolListException& e)
{
......@@ -2314,8 +2236,7 @@ DynaTypeStatement::writeOutput(ostream &output, [[maybe_unused]] const string &b
[[maybe_unused]] bool minimal_workspace) const
{
symbol_list.writeOutput("var_list_", output);
output << "dynatype('" << filename
<< "',var_list_);" << endl;
output << "dynatype('" << filename << "',var_list_);" << endl;
}
void
......@@ -2333,8 +2254,7 @@ DynaTypeStatement::writeJsonOutput(ostream &output) const
ModelComparisonStatement::ModelComparisonStatement(filename_list_t filename_list_arg,
OptionsList options_list_arg) :
filename_list{move(filename_list_arg)},
options_list{move(options_list_arg)}
filename_list {move(filename_list_arg)}, options_list {move(options_list_arg)}
{
}
......@@ -2344,8 +2264,7 @@ ModelComparisonStatement::writeOutput(ostream &output, [[maybe_unused]] const st
{
options_list.writeOutput(output);
output << "ModelNames_ = {};" << endl
<< "ModelPriors_ = [];" << endl;
output << "ModelNames_ = {};" << endl << "ModelPriors_ = [];" << endl;
for (const auto& [name, prior] : filename_list)
output << "ModelNames_ = { ModelNames_{:} '" << name << "'};" << endl
......@@ -2361,8 +2280,7 @@ ModelComparisonStatement::writeJsonOutput(ostream &output) const
if (!filename_list.empty())
output << R"(, "filename_list": {)";
for (bool printed_something{false};
const auto &[name, prior] : filename_list)
for (bool printed_something {false}; const auto& [name, prior] : filename_list)
{
if (exchange(printed_something, true))
output << ", ";
......@@ -2382,8 +2300,8 @@ ModelComparisonStatement::writeJsonOutput(ostream &output) const
output << "}";
}
PlannerObjectiveStatement::PlannerObjectiveStatement(const PlannerObjective &model_tree_arg) :
model_tree{model_tree_arg}
PlannerObjectiveStatement::PlannerObjectiveStatement(unique_ptr<PlannerObjective> model_tree_arg) :
model_tree {move(model_tree_arg)}
{
}
......@@ -2391,10 +2309,11 @@ void
PlannerObjectiveStatement::checkPass(ModFileStructure& mod_file_struct,
[[maybe_unused]] WarningConsolidation& warnings)
{
assert(model_tree.equation_number() == 1);
if (model_tree.exoPresentInEqs())
assert(model_tree->equation_number() == 1);
if (model_tree->exoPresentInEqs())
{
cerr << "ERROR: You cannot include exogenous variables (or variables of undeclared type) in the planner objective. Please "
cerr << "ERROR: You cannot include exogenous variables (or variables of undeclared type) in "
"the planner objective. Please "
<< "define an auxiliary endogenous variable like eps_aux=epsilon and use it instead "
<< "of the varexo." << endl;
exit(EXIT_FAILURE);
......@@ -2405,13 +2324,13 @@ PlannerObjectiveStatement::checkPass(ModFileStructure &mod_file_struct,
const PlannerObjective&
PlannerObjectiveStatement::getPlannerObjective() const
{
return model_tree;
return *model_tree;
}
void
PlannerObjectiveStatement::computingPass(const ModFileStructure& mod_file_struct)
{
model_tree.computingPass(max(3, mod_file_struct.order_option), 0, {}, false, false, false);
model_tree->computingPass(max(3, mod_file_struct.order_option), 0, {}, false, false, false);
computing_pass_called = true;
}
......@@ -2419,15 +2338,8 @@ void
PlannerObjectiveStatement::writeOutput(ostream& output, const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
output << "M_.NNZDerivatives_objective = [";
for (int i=1; i < static_cast<int>(model_tree.getNNZDerivatives().size()); i++)
output << (i > model_tree.getComputedDerivsOrder() ? -1 : model_tree.getNNZDerivatives()[i]) << ";";
output << "];" << endl
<< "M_.objective_tmp_nbr = [";
for (const auto &temporary_terms_derivative : model_tree.getTemporaryTermsDerivatives())
output << temporary_terms_derivative.size() << "; ";
output << "];" << endl;
model_tree.writeStaticFile(basename + ".objective", false, "", {}, false);
model_tree->writeDriverOutput(output);
model_tree->writeStaticFile(basename + ".objective", false, "", {}, false);
}
void
......@@ -2436,16 +2348,15 @@ PlannerObjectiveStatement::writeJsonOutput(ostream &output) const
output << R"({"statementName": "planner_objective")"
<< ", ";
if (computing_pass_called)
model_tree.writeJsonComputingPassOutput(output, false);
model_tree->writeJsonComputingPassOutput(output, false);
else
model_tree.writeJsonOutput(output);
model_tree->writeJsonOutput(output);
output << "}";
}
BVARDensityStatement::BVARDensityStatement(int maxnlags_arg, OptionsList options_list_arg) :
maxnlags{maxnlags_arg},
options_list{move(options_list_arg)}
maxnlags {maxnlags_arg}, options_list {move(options_list_arg)}
{
}
......@@ -2477,8 +2388,7 @@ BVARDensityStatement::writeJsonOutput(ostream &output) const
}
BVARForecastStatement::BVARForecastStatement(int nlags_arg, OptionsList options_list_arg) :
nlags{nlags_arg},
options_list{move(options_list_arg)}
nlags {nlags_arg}, options_list {move(options_list_arg)}
{
}
......@@ -2510,8 +2420,7 @@ BVARForecastStatement::writeJsonOutput(ostream &output) const
}
BVARIRFStatement::BVARIRFStatement(int nirf_arg, string identificationname_arg) :
nirf{nirf_arg},
identificationname{move(identificationname_arg)}
nirf {nirf_arg}, identificationname {move(identificationname_arg)}
{
}
......@@ -2536,8 +2445,7 @@ BVARIRFStatement::writeJsonOutput(ostream &output) const
output << "}";
}
SBVARStatement::SBVARStatement(OptionsList options_list_arg) :
options_list{move(options_list_arg)}
SBVARStatement::SBVARStatement(OptionsList options_list_arg) : options_list {move(options_list_arg)}
{
}
......@@ -2580,8 +2488,7 @@ MSSBVAREstimationStatement::checkPass(ModFileStructure &mod_file_struct,
mod_file_struct.bvar_present = true;
if (!options_list.contains("ms.create_init")
&& (!options_list.contains("datafile")
|| !options_list.contains("ms.initial_year")))
&& (!options_list.contains("datafile") || !options_list.contains("ms.initial_year")))
{
cerr << "ERROR: If you do not pass no_create_init to ms_estimation, "
<< "you must pass the datafile and initial_year options." << endl;
......@@ -2631,8 +2538,7 @@ MSSBVARSimulationStatement::writeOutput(ostream &output, [[maybe_unused]] const
options_list.writeOutput(output);
// Redeclare drop option if necessary
if ((options_list.contains("ms.mh_replic")
|| options_list.contains("ms.thinning_factor"))
if ((options_list.contains("ms.mh_replic") || options_list.contains("ms.thinning_factor"))
&& !options_list.contains("ms.drop"))
output << "options_.ms.drop = 0.1*options_.ms.mh_replic*options_.ms.thinning_factor;" << endl;
......@@ -2684,7 +2590,8 @@ MSSBVARComputeMDDStatement::writeJsonOutput(ostream &output) const
output << "}";
}
MSSBVARComputeProbabilitiesStatement::MSSBVARComputeProbabilitiesStatement(OptionsList options_list_arg) :
MSSBVARComputeProbabilitiesStatement::MSSBVARComputeProbabilitiesStatement(
OptionsList options_list_arg) :
options_list {move(options_list_arg)}
{
}
......@@ -2743,8 +2650,7 @@ MSSBVARIrfStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
regimes_present = options_list.contains("ms.regimes"),
filtered_probabilities_present = options_list.contains("ms.filtered_probabilities");
(filtered_probabilities_present && regime_present)
|| (filtered_probabilities_present && regimes_present)
|| (regimes_present && regime_present))
|| (filtered_probabilities_present && regimes_present) || (regimes_present && regime_present))
{
cerr << "ERROR: You may only pass one of regime, regimes and "
<< "filtered_probabilities to ms_irf" << endl;
......@@ -2800,8 +2706,7 @@ MSSBVARForecastStatement::checkPass(ModFileStructure &mod_file_struct,
{
mod_file_struct.bvar_present = true;
if (options_list.contains("ms.regimes")
&& options_list.contains("ms.regime"))
if (options_list.contains("ms.regimes") && options_list.contains("ms.regime"))
{
cerr << "ERROR: You may only pass one of regime and regimes to ms_forecast" << endl;
exit(EXIT_FAILURE);
......@@ -2829,7 +2734,8 @@ MSSBVARForecastStatement::writeJsonOutput(ostream &output) const
output << "}";
}
MSSBVARVarianceDecompositionStatement::MSSBVARVarianceDecompositionStatement(OptionsList options_list_arg) :
MSSBVARVarianceDecompositionStatement::MSSBVARVarianceDecompositionStatement(
OptionsList options_list_arg) :
options_list {move(options_list_arg)}
{
}
......@@ -2844,8 +2750,7 @@ MSSBVARVarianceDecompositionStatement::checkPass(ModFileStructure &mod_file_stru
regimes_present = options_list.contains("ms.regimes"),
filtered_probabilities_present = options_list.contains("ms.filtered_probabilities");
(filtered_probabilities_present && regime_present)
|| (filtered_probabilities_present && regimes_present)
|| (regimes_present && regime_present))
|| (filtered_probabilities_present && regimes_present) || (regimes_present && regime_present))
{
cerr << "ERROR: You may only pass one of regime, regimes and "
<< "filtered_probabilities to ms_variance_decomposition" << endl;
......@@ -2875,13 +2780,14 @@ MSSBVARVarianceDecompositionStatement::writeJsonOutput(ostream &output) const
output << "}";
}
IdentificationStatement::IdentificationStatement(OptionsList options_list_arg)
: options_list{move(options_list_arg)}
IdentificationStatement::IdentificationStatement(OptionsList options_list_arg) :
options_list {move(options_list_arg)}
{
if (auto opt = options_list.get_if<OptionsList::NumVal>("max_dim_cova_group");
opt && stoi(*opt) == 0)
{
cerr << "ERROR: The max_dim_cova_group option to identification only accepts integers > 0." << endl;
cerr << "ERROR: The max_dim_cova_group option to identification only accepts integers > 0."
<< endl;
exit(EXIT_FAILURE);
}
}
......@@ -2897,14 +2803,16 @@ IdentificationStatement::checkPass(ModFileStructure &mod_file_struct,
int order = stoi(*opt);
if (order < 1 || order > 3)
{
cerr << "ERROR: the order option of identification command must be between 1 and 3" << endl;
cerr << "ERROR: the order option of identification command must be between 1 and 3"
<< endl;
exit(EXIT_FAILURE);
}
mod_file_struct.identification_order = max(mod_file_struct.identification_order, order);
}
else
// The default value for order is 1 (which triggers 2nd order dynamic derivatives, see preprocessor#40)
// The default value for order is 1 (which triggers 2nd order dynamic derivatives, see
// preprocessor#40)
mod_file_struct.identification_order = max(mod_file_struct.identification_order, 1);
}
......@@ -2926,7 +2834,8 @@ IdentificationStatement::writeOutput(ostream &output, [[maybe_unused]] const str
if (auto opt = options_list.get_if<OptionsList::SymbolListVal>("graph_format"))
opt->writeOutput("options_.graph_format", output);
output << "dynare_identification(options_ident);" << endl;
output << "identification.run(M_,oo_,options_,bayestopt_,estim_params_,"
<< "options_ident);" << endl;
}
void
......@@ -2941,14 +2850,15 @@ IdentificationStatement::writeJsonOutput(ostream &output) const
output << "}";
}
WriteLatexDynamicModelStatement::WriteLatexDynamicModelStatement(const DynamicModel &dynamic_model_arg, bool write_equation_tags_arg) :
dynamic_model{dynamic_model_arg},
write_equation_tags{write_equation_tags_arg}
WriteLatexDynamicModelStatement::WriteLatexDynamicModelStatement(
const DynamicModel& dynamic_model_arg, bool write_equation_tags_arg) :
dynamic_model {dynamic_model_arg}, write_equation_tags {write_equation_tags_arg}
{
}
void
WriteLatexDynamicModelStatement::writeOutput([[maybe_unused]] ostream &output, const string &basename,
WriteLatexDynamicModelStatement::writeOutput([[maybe_unused]] ostream& output,
const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
dynamic_model.writeLatexFile(basename, write_equation_tags);
......@@ -2960,14 +2870,15 @@ WriteLatexDynamicModelStatement::writeJsonOutput(ostream &output) const
output << R"({"statementName": "write_latex_dynamic_model"})";
}
WriteLatexStaticModelStatement::WriteLatexStaticModelStatement(const StaticModel &static_model_arg, bool write_equation_tags_arg) :
static_model(static_model_arg),
write_equation_tags(write_equation_tags_arg)
WriteLatexStaticModelStatement::WriteLatexStaticModelStatement(const StaticModel& static_model_arg,
bool write_equation_tags_arg) :
static_model(static_model_arg), write_equation_tags(write_equation_tags_arg)
{
}
void
WriteLatexStaticModelStatement::writeOutput([[maybe_unused]] ostream &output, const string &basename,
WriteLatexStaticModelStatement::writeOutput([[maybe_unused]] ostream& output,
const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
static_model.writeLatexFile(basename, write_equation_tags);
......@@ -2979,14 +2890,15 @@ WriteLatexStaticModelStatement::writeJsonOutput(ostream &output) const
output << R"({"statementName": "write_latex_static_model"})";
}
WriteLatexOriginalModelStatement::WriteLatexOriginalModelStatement(const DynamicModel &original_model_arg, bool write_equation_tags_arg) :
original_model{original_model_arg},
write_equation_tags{write_equation_tags_arg}
WriteLatexOriginalModelStatement::WriteLatexOriginalModelStatement(
const DynamicModel& original_model_arg, bool write_equation_tags_arg) :
original_model {original_model_arg}, write_equation_tags {write_equation_tags_arg}
{
}
void
WriteLatexOriginalModelStatement::writeOutput([[maybe_unused]] ostream &output, const string &basename,
WriteLatexOriginalModelStatement::writeOutput([[maybe_unused]] ostream& output,
const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
original_model.writeLatexOriginalFile(basename, write_equation_tags);
......@@ -2998,7 +2910,8 @@ WriteLatexOriginalModelStatement::writeJsonOutput(ostream &output) const
output << R"({"statementName": "write_latex_original_model"})";
}
WriteLatexSteadyStateModelStatement::WriteLatexSteadyStateModelStatement(const SteadyStateModel &steady_state_model_arg) :
WriteLatexSteadyStateModelStatement::WriteLatexSteadyStateModelStatement(
const SteadyStateModel& steady_state_model_arg) :
steady_state_model {steady_state_model_arg}
{
}
......@@ -3034,7 +2947,8 @@ ShockDecompositionStatement::ShockDecompositionStatement(SymbolList symbol_list_
}
void
ShockDecompositionStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
ShockDecompositionStatement::checkPass(ModFileStructure& mod_file_struct,
WarningConsolidation& warnings)
{
if (auto opt = options_list.get_if<OptionsList::NumVal>("shock_decomp.with_epilogue");
opt && *opt == "true")
......@@ -3057,7 +2971,8 @@ ShockDecompositionStatement::writeOutput(ostream &output, [[maybe_unused]] const
{
options_list.writeOutput(output);
symbol_list.writeOutput("var_list_", output);
output << "oo_ = shock_decomposition(M_,oo_,options_,var_list_,bayestopt_,estim_params_);" << endl;
output << "oo_ = shock_decomposition(M_,oo_,options_,var_list_,bayestopt_,estim_params_);"
<< endl;
}
void
......@@ -3077,9 +2992,8 @@ ShockDecompositionStatement::writeJsonOutput(ostream &output) const
output << "}";
}
RealtimeShockDecompositionStatement::RealtimeShockDecompositionStatement(SymbolList symbol_list_arg,
OptionsList options_list_arg,
const SymbolTable &symbol_table_arg) :
RealtimeShockDecompositionStatement::RealtimeShockDecompositionStatement(
SymbolList symbol_list_arg, OptionsList options_list_arg, const SymbolTable& symbol_table_arg) :
symbol_list {move(symbol_list_arg)},
options_list {move(options_list_arg)},
symbol_table {symbol_table_arg}
......@@ -3087,7 +3001,8 @@ RealtimeShockDecompositionStatement::RealtimeShockDecompositionStatement(SymbolL
}
void
RealtimeShockDecompositionStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
RealtimeShockDecompositionStatement::checkPass(ModFileStructure& mod_file_struct,
WarningConsolidation& warnings)
{
if (auto opt = options_list.get_if<OptionsList::NumVal>("shock_decomp.with_epilogue");
opt && *opt == "true")
......@@ -3111,7 +3026,9 @@ RealtimeShockDecompositionStatement::writeOutput(ostream &output,
{
options_list.writeOutput(output);
symbol_list.writeOutput("var_list_", output);
output << "oo_ = realtime_shock_decomposition(M_,oo_,options_,var_list_,bayestopt_,estim_params_);" << endl;
output
<< "oo_ = realtime_shock_decomposition(M_,oo_,options_,var_list_,bayestopt_,estim_params_);"
<< endl;
}
void
......@@ -3131,9 +3048,8 @@ RealtimeShockDecompositionStatement::writeJsonOutput(ostream &output) const
output << "}";
}
PlotShockDecompositionStatement::PlotShockDecompositionStatement(SymbolList symbol_list_arg,
OptionsList options_list_arg,
const SymbolTable &symbol_table_arg) :
PlotShockDecompositionStatement::PlotShockDecompositionStatement(
SymbolList symbol_list_arg, OptionsList options_list_arg, const SymbolTable& symbol_table_arg) :
symbol_list {move(symbol_list_arg)},
options_list {move(options_list_arg)},
symbol_table {symbol_table_arg}
......@@ -3156,7 +3072,8 @@ PlotShockDecompositionStatement::checkPass([[maybe_unused]] ModFileStructure &mo
}
void
PlotShockDecompositionStatement::writeOutput(ostream &output, [[maybe_unused]] const string &basename,
PlotShockDecompositionStatement::writeOutput(ostream& output,
[[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
output << "options_ = set_default_plot_shock_decomposition_options(options_);" << endl;
......@@ -3182,9 +3099,8 @@ PlotShockDecompositionStatement::writeJsonOutput(ostream &output) const
output << "}";
}
InitialConditionDecompositionStatement::InitialConditionDecompositionStatement(SymbolList symbol_list_arg,
OptionsList options_list_arg,
const SymbolTable &symbol_table_arg) :
InitialConditionDecompositionStatement::InitialConditionDecompositionStatement(
SymbolList symbol_list_arg, OptionsList options_list_arg, const SymbolTable& symbol_table_arg) :
symbol_list {move(symbol_list_arg)},
options_list {move(options_list_arg)},
symbol_table {symbol_table_arg}
......@@ -3192,7 +3108,8 @@ InitialConditionDecompositionStatement::InitialConditionDecompositionStatement(S
}
void
InitialConditionDecompositionStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
InitialConditionDecompositionStatement::checkPass(ModFileStructure& mod_file_struct,
WarningConsolidation& warnings)
{
if (auto opt = options_list.get_if<OptionsList::NumVal>("initial_condition_decomp.with_epilogue");
opt && *opt == "true")
......@@ -3217,7 +3134,9 @@ InitialConditionDecompositionStatement::writeOutput(ostream &output,
output << "options_ = set_default_initial_condition_decomposition_options(options_);" << endl;
options_list.writeOutput(output);
symbol_list.writeOutput("var_list_", output);
output << "oo_ = initial_condition_decomposition(M_, oo_, options_, var_list_, bayestopt_, estim_params_);" << endl;
output << "oo_ = initial_condition_decomposition(M_, oo_, options_, var_list_, bayestopt_, "
"estim_params_);"
<< endl;
}
void
......@@ -3237,10 +3156,9 @@ InitialConditionDecompositionStatement::writeJsonOutput(ostream &output) const
output << "}";
}
SqueezeShockDecompositionStatement::SqueezeShockDecompositionStatement(SymbolList symbol_list_arg,
const SymbolTable &symbol_table_arg) :
symbol_list{move(symbol_list_arg)},
symbol_table{symbol_table_arg}
SqueezeShockDecompositionStatement::SqueezeShockDecompositionStatement(
SymbolList symbol_list_arg, const SymbolTable& symbol_table_arg) :
symbol_list {move(symbol_list_arg)}, symbol_table {symbol_table_arg}
{
}
......@@ -3306,7 +3224,9 @@ ConditionalForecastStatement::writeOutput(ostream &output, [[maybe_unused]] cons
[[maybe_unused]] bool minimal_workspace) const
{
options_list.writeOutput(output, "options_cond_fcst_");
output << "imcforecast(constrained_paths_, constrained_vars_, options_cond_fcst_);" << endl;
output << "oo_.conditional_forecast=conditional_forecasts.run(M_,options_,"
<< "oo_,bayestopt_,estim_params_,constrained_paths_, constrained_vars_,"
<< "options_cond_fcst_);" << endl;
}
void
......@@ -3321,12 +3241,10 @@ ConditionalForecastStatement::writeJsonOutput(ostream &output) const
output << "}";
}
PlotConditionalForecastStatement::PlotConditionalForecastStatement(optional<int> periods_arg,
SymbolList symbol_list_arg,
PlotConditionalForecastStatement::PlotConditionalForecastStatement(
const optional<int>& periods_arg, SymbolList symbol_list_arg,
const SymbolTable& symbol_table_arg) :
periods{move(periods_arg)},
symbol_list{move(symbol_list_arg)},
symbol_table{symbol_table_arg}
periods {periods_arg}, symbol_list {move(symbol_list_arg)}, symbol_table {symbol_table_arg}
{
}
......@@ -3346,14 +3264,15 @@ PlotConditionalForecastStatement::checkPass([[maybe_unused]] ModFileStructure &m
}
void
PlotConditionalForecastStatement::writeOutput(ostream &output, [[maybe_unused]] const string &basename,
PlotConditionalForecastStatement::writeOutput(ostream& output,
[[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
symbol_list.writeOutput("var_list_", output);
if (periods)
output << "plot_icforecast(var_list_, " << *periods << ",options_,oo_);" << endl;
output << "conditional_forecasts.plot(var_list_, " << *periods << ",options_,oo_);" << endl;
else
output << "plot_icforecast(var_list_,[],options_,oo_);" << endl;
output << "conditional_forecasts.plot(var_list_,[],options_,oo_);" << endl;
}
void
......@@ -3370,10 +3289,9 @@ PlotConditionalForecastStatement::writeJsonOutput(ostream &output) const
output << "}";
}
SvarIdentificationStatement::SvarIdentificationStatement(svar_identification_restrictions_t restrictions_arg,
bool upper_cholesky_present_arg,
bool lower_cholesky_present_arg,
bool constants_exclusion_present_arg,
SvarIdentificationStatement::SvarIdentificationStatement(
svar_identification_restrictions_t restrictions_arg, bool upper_cholesky_present_arg,
bool lower_cholesky_present_arg, bool constants_exclusion_present_arg,
const SymbolTable& symbol_table_arg) :
restrictions {move(restrictions_arg)},
upper_cholesky_present {upper_cholesky_present_arg},
......@@ -3420,9 +3338,7 @@ SvarIdentificationStatement::writeOutput(ostream &output, [[maybe_unused]] const
[[maybe_unused]] bool minimal_workspace) const
{
assert(!(upper_cholesky_present && lower_cholesky_present));
output << "%" << endl
<< "% SVAR IDENTIFICATION" << endl
<< "%" << endl;
output << "%" << endl << "% SVAR IDENTIFICATION" << endl << "%" << endl;
if (upper_cholesky_present)
output << "options_.ms.upper_cholesky=1;" << endl;
......@@ -3442,8 +3358,7 @@ SvarIdentificationStatement::writeOutput(ostream &output, [[maybe_unused]] const
if (k < 1)
{
cerr << "ERROR: lag = " << r
<< ", number of endogenous variables = " << n
cerr << "ERROR: lag = " << r << ", number of endogenous variables = " << n
<< ", number of exogenous variables = " << m
<< ". If this is not a logical error in the specification"
<< " of the .mod file, please report it to the Dynare Team." << endl;
......@@ -3451,8 +3366,10 @@ SvarIdentificationStatement::writeOutput(ostream &output, [[maybe_unused]] const
}
if (n < 1)
{
cerr << "ERROR: Number of endogenous variables = " << n << "< 1. If this is not a logical "
<< "error in the specification of the .mod file, please report it to the Dynare Team." << endl;
cerr
<< "ERROR: Number of endogenous variables = " << n << "< 1. If this is not a logical "
<< "error in the specification of the .mod file, please report it to the Dynare Team."
<< endl;
exit(EXIT_FAILURE);
}
output << "options_.ms.Qi = cell(" << n << ",1);" << endl
......@@ -3462,17 +3379,22 @@ SvarIdentificationStatement::writeOutput(ostream &output, [[maybe_unused]] const
{
assert(it.lag >= 0);
if (it.lag == 0)
output << "options_.ms.Qi{" << it.equation << "}(" << it.restriction_nbr << ", " << it.variable + 1 << ") = ";
output << "options_.ms.Qi{" << it.equation << "}(" << it.restriction_nbr << ", "
<< it.variable + 1 << ") = ";
else
{
int col = (it.lag - 1) * n + it.variable + 1;
if (col > k)
{
cerr << "ERROR: lag =" << it.lag << ", num endog vars = " << n << "current endog var index = " << it.variable << ". Index "
<< "out of bounds. If the above does not represent a logical error, please report this to the Dynare Team." << endl;
cerr << "ERROR: lag =" << it.lag << ", num endog vars = " << n
<< "current endog var index = " << it.variable << ". Index "
<< "out of bounds. If the above does not represent a logical error, please "
"report this to the Dynare Team."
<< endl;
exit(EXIT_FAILURE);
}
output << "options_.ms.Ri{" << it.equation << "}(" << it.restriction_nbr << ", " << col << ") = ";
output << "options_.ms.Ri{" << it.equation << "}(" << it.restriction_nbr << ", "
<< col << ") = ";
}
it.value->writeOutput(output);
output << ";" << endl;
......@@ -3497,11 +3419,9 @@ SvarIdentificationStatement::writeJsonOutput(ostream &output) const
if (!upper_cholesky_present && !lower_cholesky_present)
{
output << R"(, "nlags": )" << getMaxLag()
<< R"(, "restrictions": [)";
output << R"(, "nlags": )" << getMaxLag() << R"(, "restrictions": [)";
for (bool printed_something{false};
const auto &it : restrictions)
for (bool printed_something {false}; const auto& it : restrictions)
{
if (exchange(printed_something, true))
output << ", ";
......@@ -3529,7 +3449,8 @@ MarkovSwitchingStatement::MarkovSwitchingStatement(OptionsList options_list_arg)
{
if (restriction.size() != 3)
{
cerr << "ERROR: restrictions in the subsample statement must be specified in the form "
cerr
<< "ERROR: restrictions in the subsample statement must be specified in the form "
<< "[current_period_regime, next_period_regime, transition_probability]" << endl;
exit(EXIT_FAILURE);
}
......@@ -3541,7 +3462,8 @@ MarkovSwitchingStatement::MarkovSwitchingStatement(OptionsList options_list_arg)
if (from_regime > num_regimes || to_regime > num_regimes)
{
cerr << "ERROR: the regimes specified in the restrictions option must be "
<< "<= the number of regimes specified in the number_of_regimes option" << endl;
<< "<= the number of regimes specified in the number_of_regimes option"
<< endl;
exit(EXIT_FAILURE);
}
......@@ -3653,14 +3575,11 @@ MarkovSwitchingStatement::writeOutput(ostream &output, [[maybe_unused]] const st
assert(options_list.contains("ms.duration"));
output << "options_.ms.duration = ";
bool isDurationAVec { options_list.visit("ms.duration",
[&]<class T>(const T &v) -> bool
{
bool isDurationAVec {options_list.visit("ms.duration", [&]<class T>(const T& v) -> bool {
if constexpr (is_same_v<T, OptionsList::VecValueVal>)
{
output << "[";
for (bool printed_something{false};
const auto &it : v)
for (bool printed_something {false}; const auto& it : v)
{
if (exchange(printed_something, true))
output << ", ";
......@@ -3676,7 +3595,9 @@ MarkovSwitchingStatement::writeOutput(ostream &output, [[maybe_unused]] const st
}
else
{
cerr << "MarkovSwitchingStatement::writeOutput: incorrect value type for 'ms.duration' option" << endl;
cerr << "MarkovSwitchingStatement::writeOutput: incorrect value type for 'ms.duration' "
"option"
<< endl;
exit(EXIT_FAILURE);
}
})};
......@@ -3685,18 +3606,16 @@ MarkovSwitchingStatement::writeOutput(ostream &output, [[maybe_unused]] const st
int NOR {stoi(options_list.get<OptionsList::NumVal>("ms.number_of_regimes"))};
for (int i {0}; i < NOR; i++)
{
output << "options_.ms.ms_chain(" << chainNumber << ").regime("
<< i+1 << ").duration = options_.ms.duration";
output << "options_.ms.ms_chain(" << chainNumber << ").regime(" << i + 1
<< ").duration = options_.ms.duration";
if (isDurationAVec)
output << "(" << i + 1 << ")";
output << ";" << endl;
}
for (int restrictions_index{0};
const auto &[regimes, prob] : restriction_map)
output << "options_.ms.ms_chain(" << chainNumber << ").restrictions("
<< ++restrictions_index << ") = {[" << regimes.first << ", "
<< regimes.second << ", " << prob << "]};" << endl;
for (int restrictions_index {0}; const auto& [regimes, prob] : restriction_map)
output << "options_.ms.ms_chain(" << chainNumber << ").restrictions(" << ++restrictions_index
<< ") = {[" << regimes.first << ", " << regimes.second << ", " << prob << "]};" << endl;
}
void
......@@ -3711,23 +3630,19 @@ MarkovSwitchingStatement::writeJsonOutput(ostream &output) const
if (!restriction_map.empty())
output << ", {";
for (bool printed_something{false};
const auto &[regimes, prob] : restriction_map)
for (bool printed_something {false}; const auto& [regimes, prob] : restriction_map)
{
if (exchange(printed_something, true))
output << ", ";
output << R"({"current_period_regime": )" << regimes.first
<< R"(, "next_period_regime": )" << regimes.second
<< R"(, "transition_probability": )"<< prob
<< "}";
output << R"({"current_period_regime": )" << regimes.first << R"(, "next_period_regime": )"
<< regimes.second << R"(, "transition_probability": )" << prob << "}";
}
if (!restriction_map.empty())
output << "}";
output << "}";
}
SvarStatement::SvarStatement(OptionsList options_list_arg) :
options_list{move(options_list_arg)}
SvarStatement::SvarStatement(OptionsList options_list_arg) : options_list {move(options_list_arg)}
{
}
......@@ -3800,8 +3715,7 @@ SvarGlobalIdentificationCheckStatement::writeJsonOutput(ostream &output) const
output << R"({"statementName": "svar_global_identification"})";
}
SetTimeStatement::SetTimeStatement(OptionsList options_list_arg) :
options_list{move(options_list_arg)}
SetTimeStatement::SetTimeStatement(string period_arg) : period {move(period_arg)}
{
}
......@@ -3809,19 +3723,13 @@ void
SetTimeStatement::writeOutput(ostream& output, [[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
options_list.writeOutput(output);
output << "options_.initial_period = " << period << endl;
}
void
SetTimeStatement::writeJsonOutput(ostream& output) const
{
output << R"({"statementName": "set_time")";
if (!options_list.empty())
{
output << ", ";
options_list.writeJsonOutput(output);
}
output << "}";
output << R"({"statementName": "set_time", "period": ")" << period << R"("})";
}
EstimationDataStatement::EstimationDataStatement(OptionsList options_list_arg) :
......@@ -3838,12 +3746,12 @@ EstimationDataStatement::checkPass(ModFileStructure &mod_file_struct,
if (auto opt = options_list.get_if<OptionsList::NumVal>("nobs"))
if (stoi(*opt) <= 0)
{
cerr << "ERROR: The nobs option of the data statement only accepts positive integers." << endl;
cerr << "ERROR: The nobs option of the data statement only accepts positive integers."
<< endl;
exit(EXIT_FAILURE);
}
bool has_file = options_list.contains("file"),
has_series = options_list.contains("series");
bool has_file = options_list.contains("file"), has_series = options_list.contains("series");
if (!has_file && !has_series)
{
cerr << "ERROR: The file or series option must be passed to the data statement." << endl;
......@@ -3851,7 +3759,9 @@ EstimationDataStatement::checkPass(ModFileStructure &mod_file_struct,
}
if (has_file && has_series)
{
cerr << "ERROR: The file and series options cannot be used simultaneously in the data statement." << endl;
cerr << "ERROR: The file and series options cannot be used simultaneously in the data "
"statement."
<< endl;
exit(EXIT_FAILURE);
}
}
......@@ -3875,8 +3785,7 @@ EstimationDataStatement::writeJsonOutput(ostream &output) const
output << "}";
}
SubsamplesStatement::SubsamplesStatement(string name1_arg,
string name2_arg,
SubsamplesStatement::SubsamplesStatement(string name1_arg, string name2_arg,
subsample_declaration_map_t subsample_declaration_map_arg,
const SymbolTable& symbol_table_arg) :
name1 {move(name1_arg)},
......@@ -3887,12 +3796,11 @@ SubsamplesStatement::SubsamplesStatement(string name1_arg,
}
void
SubsamplesStatement::writeOutput(ostream &output,
[[maybe_unused]] const string &basename,
SubsamplesStatement::writeOutput(ostream& output, [[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
output << "subsamples_indx = get_new_or_existing_ei_index('subsamples_index', '"
<< name1 << "','" << name2 << "');" << endl
output << "subsamples_indx = get_new_or_existing_ei_index('subsamples_index', '" << name1 << "','"
<< name2 << "');" << endl
<< "estimation_info.subsamples_index(subsamples_indx) = {'" << name1;
if (!name2.empty())
output << ":" << name2;
......@@ -3900,15 +3808,14 @@ SubsamplesStatement::writeOutput(ostream &output,
<< "estimation_info.subsamples(subsamples_indx).range = {};" << endl
<< "estimation_info.subsamples(subsamples_indx).range_index = {};" << endl;
for (int map_indx{1};
const auto &[range, dates] : subsample_declaration_map)
for (int map_indx {1}; const auto& [range, dates] : subsample_declaration_map)
{
output << "estimation_info.subsamples(subsamples_indx).range_index(" << map_indx << ") = {'"
<< range << "'};" << endl
<< "estimation_info.subsamples(subsamples_indx).range(" << map_indx << ").date1 = "
<< dates.first << ";" << endl
<< "estimation_info.subsamples(subsamples_indx).range(" << map_indx << ").date2 = "
<< dates.second << ";" << endl;
<< "estimation_info.subsamples(subsamples_indx).range(" << map_indx
<< ").date1 = " << dates.first << ";" << endl
<< "estimation_info.subsamples(subsamples_indx).range(" << map_indx
<< ").date2 = " << dates.second << ";" << endl;
map_indx++;
}
......@@ -3935,8 +3842,7 @@ SubsamplesStatement::writeOutput(ostream &output,
if (!name2.empty())
output << "_corr";
output << "_prior_index', '"
<< name1 << "', '";
output << "_prior_index', '" << name1 << "', '";
if (!name2.empty())
output << name2;
output << "');" << endl;
......@@ -3952,7 +3858,8 @@ SubsamplesStatement::writeOutput(ostream &output,
output << lhs_field << "(eifind).subsample_prior = estimation_info.empty_prior;" << endl
<< lhs_field << "(eifind).subsample_prior(1:" << subsample_declaration_map.size()
<< ") = estimation_info.empty_prior;" << endl
<< lhs_field << "(eifind).range_index = estimation_info.subsamples(subsamples_indx).range_index;"
<< lhs_field
<< "(eifind).range_index = estimation_info.subsamples(subsamples_indx).range_index;"
<< endl;
}
......@@ -3965,8 +3872,7 @@ SubsamplesStatement::writeJsonOutput(ostream &output) const
output << R"(, "name2": ")" << name2 << R"(")";
output << R"(, "declarations": {)";
for (bool printed_something{false};
const auto &[range, dates] : subsample_declaration_map)
for (bool printed_something {false}; const auto& [range, dates] : subsample_declaration_map)
{
if (exchange(printed_something, true))
output << ",";
......@@ -3980,10 +3886,8 @@ SubsamplesStatement::writeJsonOutput(ostream &output) const
<< "}";
}
SubsamplesEqualStatement::SubsamplesEqualStatement(string to_name1_arg,
string to_name2_arg,
string from_name1_arg,
string from_name2_arg,
SubsamplesEqualStatement::SubsamplesEqualStatement(string to_name1_arg, string to_name2_arg,
string from_name1_arg, string from_name2_arg,
const SymbolTable& symbol_table_arg) :
to_name1 {move(to_name1_arg)},
to_name2 {move(to_name2_arg)},
......@@ -3997,15 +3901,16 @@ void
SubsamplesEqualStatement::writeOutput(ostream& output, [[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
output << "subsamples_to_indx = get_new_or_existing_ei_index('subsamples_index', '"
<< to_name1 << "','" << to_name2 << "');" << endl
output << "subsamples_to_indx = get_new_or_existing_ei_index('subsamples_index', '" << to_name1
<< "','" << to_name2 << "');" << endl
<< "estimation_info.subsamples_index(subsamples_to_indx) = {'" << to_name1;
if (!to_name2.empty())
output << ":" << to_name2;
output << "'};" << endl
<< "subsamples_from_indx = get_existing_subsamples_indx('" << from_name1 << "','" << from_name2 << "');"
<< endl
<< "estimation_info.subsamples(subsamples_to_indx) = estimation_info.subsamples(subsamples_from_indx);"
<< "subsamples_from_indx = get_existing_subsamples_indx('" << from_name1 << "','"
<< from_name2 << "');" << endl
<< "estimation_info.subsamples(subsamples_to_indx) = "
"estimation_info.subsamples(subsamples_from_indx);"
<< endl;
// Initialize associated subsample substructures in estimation_info
......@@ -4031,8 +3936,7 @@ SubsamplesEqualStatement::writeOutput(ostream &output, [[maybe_unused]] const st
if (!to_name2.empty())
output << "_corr";
output << "_prior_index', '"
<< to_name1 << "', '";
output << "_prior_index', '" << to_name1 << "', '";
if (!to_name2.empty())
output << to_name2;
output << "');" << endl;
......@@ -4046,9 +3950,12 @@ SubsamplesEqualStatement::writeOutput(ostream &output, [[maybe_unused]] const st
output << "'};" << endl;
output << lhs_field << "(eifind).subsample_prior = estimation_info.empty_prior;" << endl
<< lhs_field << "(eifind).subsample_prior(1:size(estimation_info.subsamples(subsamples_to_indx).range_index,2)) = estimation_info.empty_prior;"
<< lhs_field
<< "(eifind).subsample_prior(1:size(estimation_info.subsamples(subsamples_to_indx).range_"
"index,2)) = estimation_info.empty_prior;"
<< endl
<< lhs_field << "(eifind).range_index = estimation_info.subsamples(subsamples_to_indx).range_index;"
<< lhs_field
<< "(eifind).range_index = estimation_info.subsamples(subsamples_to_indx).range_index;"
<< endl;
}
......@@ -4096,8 +4003,7 @@ JointPriorStatement::checkPass([[maybe_unused]] ModFileStructure &mod_file_struc
exit(EXIT_FAILURE);
}
if (auto opt = options_list.get_if<OptionsList::VecValueVal>("domain");
opt && opt->size() != 4)
if (auto opt = options_list.get_if<OptionsList::VecValueVal>("domain"); opt && opt->size() != 4)
{
cerr << "ERROR: You must pass exactly four values to the domain option." << endl;
exit(EXIT_FAILURE);
......@@ -4111,12 +4017,14 @@ JointPriorStatement::writeOutput(ostream &output, [[maybe_unused]] const string
for (const auto& joint_parameter : joint_parameters)
output << "eifind = get_new_or_existing_ei_index('joint_parameter_prior_index', '"
<< joint_parameter << "', '');" << endl
<< "estimation_info.joint_parameter_prior_index(eifind) = {'" << joint_parameter << "'};" << endl;
<< "estimation_info.joint_parameter_prior_index(eifind) = {'" << joint_parameter << "'};"
<< endl;
output << "key = {[";
for (const auto& joint_parameter : joint_parameters)
output << "get_new_or_existing_ei_index('joint_parameter_prior_index', '" << joint_parameter << "', '') ..."
<< endl << " ";
output << "get_new_or_existing_ei_index('joint_parameter_prior_index', '" << joint_parameter
<< "', '') ..." << endl
<< " ";
output << "]};" << endl;
string lhs_field("estimation_info.joint_parameter_tmp");
......@@ -4146,24 +4054,25 @@ JointPriorStatement::writeOutput(ostream &output, [[maybe_unused]] const string
<< " " << lhs_field << ".stdev , ..." << endl
<< " " << lhs_field << ".truncate , ..." << endl
<< " " << lhs_field << ".variance];" << endl
<< "estimation_info.joint_parameter = [estimation_info.joint_parameter; estimation_info.joint_parameter_tmp];" << endl
<< "estimation_info.joint_parameter = [estimation_info.joint_parameter; "
"estimation_info.joint_parameter_tmp];"
<< endl
<< "estimation_info=rmfield(estimation_info, 'joint_parameter_tmp');" << endl;
}
void
JointPriorStatement::writeOutputHelper(ostream &output, const string &field, const string &lhs_field) const
JointPriorStatement::writeOutputHelper(ostream& output, const string& field,
const string& lhs_field) const
{
output << lhs_field << "." << field << " = {";
if (options_list.contains(field))
options_list.visit(field, [&]<class T>(const T &v)
{
options_list.visit(field, [&]<class T>(const T& v) {
if constexpr (is_same_v<T, OptionsList::NumVal>)
output << v;
else if constexpr (is_same_v<T, OptionsList::VecValueVal>)
{
output << "[";
for (bool printed_something{false};
const auto &it2 : v)
for (bool printed_something {false}; const auto& it2 : v)
{
if (exchange(printed_something, true))
output << ", ";
......@@ -4174,14 +4083,12 @@ JointPriorStatement::writeOutputHelper(ostream &output, const string &field, con
else if constexpr (is_same_v<T, vector<vector<string>>>)
{
output << "{";
for (bool printed_something{false};
const auto &it2 : v)
for (bool printed_something {false}; const auto& it2 : v)
{
if (exchange(printed_something, true))
output << ", ";
output << "[";
for (bool printed_something2{false};
const auto &it3 : it2)
for (bool printed_something2 {false}; const auto& it3 : it2)
{
if (exchange(printed_something2, true))
output << ", ";
......@@ -4207,8 +4114,7 @@ JointPriorStatement::writeJsonOutput(ostream &output) const
{
output << R"({"statementName": "joint_prior")"
<< R"(, "key": [)";
for (bool printed_something{false};
const auto &it : joint_parameters)
for (bool printed_something {false}; const auto& it : joint_parameters)
{
if (exchange(printed_something, true))
output << ", ";
......@@ -4256,10 +4162,8 @@ JointPriorStatement::writeJsonOutput(ostream &output) const
output << "}";
}
BasicPriorStatement::BasicPriorStatement(string name_arg,
string subsample_name_arg,
PriorDistributions prior_shape_arg,
expr_t variance_arg,
BasicPriorStatement::BasicPriorStatement(string name_arg, string subsample_name_arg,
PriorDistributions prior_shape_arg, expr_t variance_arg,
OptionsList options_list_arg) :
name {move(name_arg)},
subsample_name {move(subsample_name_arg)},
......@@ -4288,12 +4192,12 @@ BasicPriorStatement::checkPass([[maybe_unused]] ModFileStructure &mod_file_struc
if (bool has_stdev = options_list.contains("stdev");
(!has_stdev && !variance) || (has_stdev && variance))
{
cerr << "ERROR: You must pass exactly one of stdev and variance to the prior statement." << endl;
cerr << "ERROR: You must pass exactly one of stdev and variance to the prior statement."
<< endl;
exit(EXIT_FAILURE);
}
if (auto opt = options_list.get_if<OptionsList::VecValueVal>("domain");
opt && opt->size() != 2)
if (auto opt = options_list.get_if<OptionsList::VecValueVal>("domain"); opt && opt->size() != 2)
{
cerr << "ERROR: You must pass exactly two values to the domain option." << endl;
exit(EXIT_FAILURE);
......@@ -4303,18 +4207,13 @@ BasicPriorStatement::checkPass([[maybe_unused]] ModFileStructure &mod_file_struc
bool
BasicPriorStatement::is_structural_innovation(const SymbolType symb_type) const
{
if (symb_type == SymbolType::exogenous)
return true;
return false;
return symb_type == SymbolType::exogenous;
}
void
BasicPriorStatement::get_base_name(const SymbolType symb_type, string& lhs_field) const
{
if (symb_type == SymbolType::exogenous)
lhs_field = "structural_innovation";
else
lhs_field = "measurement_error";
lhs_field = (symb_type == SymbolType::exogenous ? "structural_innovation" : "measurement_error");
}
void
......@@ -4344,11 +4243,11 @@ BasicPriorStatement::writeCommonOutput(ostream &output, const string &lhs_field)
}
void
BasicPriorStatement::writeCommonOutputHelper(ostream &output, const string &field, const string &lhs_field) const
BasicPriorStatement::writeCommonOutputHelper(ostream& output, const string& field,
const string& lhs_field) const
{
if (options_list.contains(field))
options_list.visit(field, [&]<class T>(const T &v)
{
options_list.visit(field, [&]<class T>(const T& v) {
if constexpr (is_same_v<T, OptionsList::NumVal>)
output << lhs_field << "." << field << " = " << v << ";" << endl;
// TODO: handle other variant types
......@@ -4362,8 +4261,10 @@ BasicPriorStatement::writePriorOutput(ostream &output, string &lhs_field, const
lhs_field += ".prior(1)";
else
{
output << "subsamples_indx = get_existing_subsamples_indx('" << name << "','" << name2 << "');" << endl
<< "eisind = get_subsamples_range_indx(subsamples_indx, '" << subsample_name << "');" << endl;
output << "subsamples_indx = get_existing_subsamples_indx('" << name << "','" << name2
<< "');" << endl
<< "eisind = get_subsamples_range_indx(subsamples_indx, '" << subsample_name << "');"
<< endl;
lhs_field += ".subsample_prior(eisind)";
}
writeCommonOutput(output, lhs_field);
......@@ -4424,12 +4325,11 @@ BasicPriorStatement::writeJsonShape(ostream &output) const
}
}
PriorStatement::PriorStatement(string name_arg,
string subsample_name_arg,
PriorDistributions prior_shape_arg,
expr_t variance_arg,
PriorStatement::PriorStatement(string name_arg, string subsample_name_arg,
PriorDistributions prior_shape_arg, expr_t variance_arg,
OptionsList options_list_arg) :
BasicPriorStatement{move(name_arg), move(subsample_name_arg), prior_shape_arg, variance_arg, move(options_list_arg)}
BasicPriorStatement {move(name_arg), move(subsample_name_arg), prior_shape_arg, variance_arg,
move(options_list_arg)}
{
}
......@@ -4438,8 +4338,8 @@ PriorStatement::writeOutput(ostream &output, [[maybe_unused]] const string &base
[[maybe_unused]] bool minimal_workspace) const
{
string lhs_field = "estimation_info.parameter(eifind)";
output << "eifind = get_new_or_existing_ei_index('parameter_prior_index', '"
<< name << "', '');" << endl
output << "eifind = get_new_or_existing_ei_index('parameter_prior_index', '" << name << "', '');"
<< endl
<< "estimation_info.parameter_prior_index(eifind) = {'" << name << "'};" << endl;
writePriorOutput(output, lhs_field, "");
}
......@@ -4452,13 +4352,12 @@ PriorStatement::writeJsonOutput(ostream &output) const
output << "}";
}
StdPriorStatement::StdPriorStatement(string name_arg,
string subsample_name_arg,
PriorDistributions prior_shape_arg,
expr_t variance_arg,
StdPriorStatement::StdPriorStatement(string name_arg, string subsample_name_arg,
PriorDistributions prior_shape_arg, expr_t variance_arg,
OptionsList options_list_arg,
const SymbolTable& symbol_table_arg) :
BasicPriorStatement{move(name_arg), move(subsample_name_arg), prior_shape_arg, variance_arg, move(options_list_arg)},
BasicPriorStatement {move(name_arg), move(subsample_name_arg), prior_shape_arg, variance_arg,
move(options_list_arg)},
symbol_table {symbol_table_arg}
{
}
......@@ -4469,8 +4368,8 @@ StdPriorStatement::writeOutput(ostream &output, [[maybe_unused]] const string &b
{
string lhs_field;
get_base_name(symbol_table.getType(name), lhs_field);
output << "eifind = get_new_or_existing_ei_index('" << lhs_field << "_prior_index', '"
<< name << "', '');" << endl
output << "eifind = get_new_or_existing_ei_index('" << lhs_field << "_prior_index', '" << name
<< "', '');" << endl
<< "estimation_info." << lhs_field << "_prior_index(eifind) = {'" << name << "'};" << endl;
lhs_field = "estimation_info." + lhs_field + "(eifind)";
......@@ -4487,11 +4386,11 @@ StdPriorStatement::writeJsonOutput(ostream &output) const
CorrPriorStatement::CorrPriorStatement(string name_arg1, string name_arg2,
string subsample_name_arg,
PriorDistributions prior_shape_arg,
expr_t variance_arg,
PriorDistributions prior_shape_arg, expr_t variance_arg,
OptionsList options_list_arg,
const SymbolTable& symbol_table_arg) :
BasicPriorStatement{move(name_arg1), move(subsample_name_arg), prior_shape_arg, variance_arg, move(options_list_arg)},
BasicPriorStatement {move(name_arg1), move(subsample_name_arg), prior_shape_arg, variance_arg,
move(options_list_arg)},
name1 {move(name_arg2)},
symbol_table {symbol_table_arg}
{
......@@ -4519,8 +4418,8 @@ CorrPriorStatement::writeOutput(ostream &output, [[maybe_unused]] const string &
output << "eifind = get_new_or_existing_ei_index('" << lhs_field << "_corr_prior_index', '"
<< name << "', '" << name1 << "');" << endl
<< "estimation_info." << lhs_field << "_corr_prior_index(eifind) = {'"
<< name << ":" << name1 << "'};" << endl;
<< "estimation_info." << lhs_field << "_corr_prior_index(eifind) = {'" << name << ":"
<< name1 << "'};" << endl;
lhs_field = "estimation_info." + lhs_field + "_corr(eifind)";
writePriorOutput(output, lhs_field, name1);
......@@ -4535,14 +4434,10 @@ CorrPriorStatement::writeJsonOutput(ostream &output) const
output << "}";
}
PriorEqualStatement::PriorEqualStatement(string to_declaration_type_arg,
string to_name1_arg,
string to_name2_arg,
string to_subsample_name_arg,
string from_declaration_type_arg,
string from_name1_arg,
string from_name2_arg,
string from_subsample_name_arg,
PriorEqualStatement::PriorEqualStatement(string to_declaration_type_arg, string to_name1_arg,
string to_name2_arg, string to_subsample_name_arg,
string from_declaration_type_arg, string from_name1_arg,
string from_name2_arg, string from_subsample_name_arg,
const SymbolTable& symbol_table_arg) :
to_declaration_type {move(to_declaration_type_arg)},
to_name1 {move(to_name1_arg)},
......@@ -4560,8 +4455,10 @@ void
PriorEqualStatement::checkPass([[maybe_unused]] ModFileStructure& mod_file_struct,
[[maybe_unused]] WarningConsolidation& warnings)
{
if ((to_declaration_type != "par" && to_declaration_type != "std" && to_declaration_type != "corr")
|| (from_declaration_type != "par" && from_declaration_type != "std" && from_declaration_type != "corr"))
if ((to_declaration_type != "par" && to_declaration_type != "std"
&& to_declaration_type != "corr")
|| (from_declaration_type != "par" && from_declaration_type != "std"
&& from_declaration_type != "corr"))
{
cerr << "Internal Dynare Error" << endl;
exit(EXIT_FAILURE);
......@@ -4622,8 +4519,10 @@ PriorEqualStatement::writeOutput(ostream &output, [[maybe_unused]] const string
lhs_field += ".prior";
else
{
output << "subsamples_to_indx = get_existing_subsamples_indx('" << to_name1 << "','" << to_name2 << "');" << endl
<< "ei_to_ss_ind = get_subsamples_range_indx(subsamples_to_indx, '" << to_subsample_name << "');" << endl;
output << "subsamples_to_indx = get_existing_subsamples_indx('" << to_name1 << "','"
<< to_name2 << "');" << endl
<< "ei_to_ss_ind = get_subsamples_range_indx(subsamples_to_indx, '"
<< to_subsample_name << "');" << endl;
lhs_field += ".subsample_prior(ei_to_ss_ind)";
}
......@@ -4631,8 +4530,10 @@ PriorEqualStatement::writeOutput(ostream &output, [[maybe_unused]] const string
rhs_field += ".prior";
else
{
output << "subsamples_from_indx = get_existing_subsamples_indx('" << from_name1 << "','" << from_name2 << "');" << endl
<< "ei_from_ss_ind = get_subsamples_range_indx(subsamples_from_indx, '" << from_subsample_name << "');" << endl;
output << "subsamples_from_indx = get_existing_subsamples_indx('" << from_name1 << "','"
<< from_name2 << "');" << endl
<< "ei_from_ss_ind = get_subsamples_range_indx(subsamples_from_indx, '"
<< from_subsample_name << "');" << endl;
rhs_field += ".subsample_prior(ei_from_ss_ind)";
}
......@@ -4654,8 +4555,7 @@ PriorEqualStatement::writeJsonOutput(ostream &output) const
<< "}";
}
BasicOptionsStatement::BasicOptionsStatement(string name_arg,
string subsample_name_arg,
BasicOptionsStatement::BasicOptionsStatement(string name_arg, string subsample_name_arg,
OptionsList options_list_arg) :
name {move(name_arg)},
subsample_name {move(subsample_name_arg)},
......@@ -4672,10 +4572,7 @@ BasicOptionsStatement::is_structural_innovation(const SymbolType symb_type) cons
void
BasicOptionsStatement::get_base_name(const SymbolType symb_type, string& lhs_field) const
{
if (symb_type == SymbolType::exogenous)
lhs_field = "structural_innovation";
else
lhs_field = "measurement_error";
lhs_field = (symb_type == SymbolType::exogenous ? "structural_innovation" : "measurement_error");
}
void
......@@ -4689,11 +4586,11 @@ BasicOptionsStatement::writeCommonOutput(ostream &output, const string &lhs_fiel
}
void
BasicOptionsStatement::writeCommonOutputHelper(ostream &output, const string &field, const string &lhs_field) const
BasicOptionsStatement::writeCommonOutputHelper(ostream& output, const string& field,
const string& lhs_field) const
{
if (options_list.contains(field))
options_list.visit(field, [&]<class T>(const T &v)
{
options_list.visit(field, [&]<class T>(const T& v) {
if constexpr (is_same_v<T, OptionsList::NumVal>)
output << lhs_field << "." << field << " = " << v << ";" << endl;
// TODO: handle other variant types
......@@ -4701,14 +4598,17 @@ BasicOptionsStatement::writeCommonOutputHelper(ostream &output, const string &fi
}
void
BasicOptionsStatement::writeOptionsOutput(ostream &output, string &lhs_field, const string &name2) const
BasicOptionsStatement::writeOptionsOutput(ostream& output, string& lhs_field,
const string& name2) const
{
if (subsample_name.empty())
lhs_field += ".options(1)";
else
{
output << "subsamples_indx = get_existing_subsamples_indx('" << name << "','" << name2 << "');" << endl
<< "eisind = get_subsamples_range_indx(subsamples_indx, '" << subsample_name << "');" << endl;
output << "subsamples_indx = get_existing_subsamples_indx('" << name << "','" << name2
<< "');" << endl
<< "eisind = get_subsamples_range_indx(subsamples_indx, '" << subsample_name << "');"
<< endl;
lhs_field += ".subsample_options(eisind)";
}
writeCommonOutput(output, lhs_field);
......@@ -4727,8 +4627,7 @@ BasicOptionsStatement::writeJsonOptionsOutput(ostream &output) const
}
}
OptionsStatement::OptionsStatement(string name_arg,
string subsample_name_arg,
OptionsStatement::OptionsStatement(string name_arg, string subsample_name_arg,
OptionsList options_list_arg) :
BasicOptionsStatement {move(name_arg), move(subsample_name_arg), move(options_list_arg)}
{
......@@ -4739,8 +4638,8 @@ OptionsStatement::writeOutput(ostream &output, [[maybe_unused]] const string &ba
[[maybe_unused]] bool minimal_workspace) const
{
string lhs_field = "estimation_info.parameter(eifind)";
output << "eifind = get_new_or_existing_ei_index('parameter_options_index', '"
<< name << "', '');" << endl
output << "eifind = get_new_or_existing_ei_index('parameter_options_index', '" << name
<< "', '');" << endl
<< "estimation_info.parameter_options_index(eifind) = {'" << name << "'};" << endl;
writeOptionsOutput(output, lhs_field, "");
}
......@@ -4753,8 +4652,7 @@ OptionsStatement::writeJsonOutput(ostream &output) const
output << "}";
}
StdOptionsStatement::StdOptionsStatement(string name_arg,
string subsample_name_arg,
StdOptionsStatement::StdOptionsStatement(string name_arg, string subsample_name_arg,
OptionsList options_list_arg,
const SymbolTable& symbol_table_arg) :
BasicOptionsStatement {move(name_arg), move(subsample_name_arg), move(options_list_arg)},
......@@ -4768,9 +4666,10 @@ StdOptionsStatement::writeOutput(ostream &output, [[maybe_unused]] const string
{
string lhs_field;
get_base_name(symbol_table.getType(name), lhs_field);
output << "eifind = get_new_or_existing_ei_index('" << lhs_field << "_options_index', '"
<< name << "', '');" << endl
<< "estimation_info." << lhs_field << "_options_index(eifind) = {'" << name << "'};" << endl;
output << "eifind = get_new_or_existing_ei_index('" << lhs_field << "_options_index', '" << name
<< "', '');" << endl
<< "estimation_info." << lhs_field << "_options_index(eifind) = {'" << name << "'};"
<< endl;
lhs_field = "estimation_info." + lhs_field + "(eifind)";
writeOptionsOutput(output, lhs_field, "");
......@@ -4785,8 +4684,7 @@ StdOptionsStatement::writeJsonOutput(ostream &output) const
}
CorrOptionsStatement::CorrOptionsStatement(string name_arg1, string name_arg2,
string subsample_name_arg,
OptionsList options_list_arg,
string subsample_name_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg) :
BasicOptionsStatement {move(name_arg1), move(subsample_name_arg), move(options_list_arg)},
name1 {move(name_arg2)},
......@@ -4816,8 +4714,8 @@ CorrOptionsStatement::writeOutput(ostream &output, [[maybe_unused]] const string
output << "eifind = get_new_or_existing_ei_index('" << lhs_field << "_corr_options_index', '"
<< name << "', '" << name1 << "');" << endl
<< "estimation_info." << lhs_field << "_corr_options_index(eifind) = {'"
<< name << ":" << name1 << "'};" << endl;
<< "estimation_info." << lhs_field << "_corr_options_index(eifind) = {'" << name << ":"
<< name1 << "'};" << endl;
lhs_field = "estimation_info." + lhs_field + "_corr(eifind)";
writeOptionsOutput(output, lhs_field, name1);
......@@ -4832,13 +4730,10 @@ CorrOptionsStatement::writeJsonOutput(ostream &output) const
output << "}";
}
OptionsEqualStatement::OptionsEqualStatement(string to_declaration_type_arg,
string to_name1_arg,
string to_name2_arg,
string to_subsample_name_arg,
OptionsEqualStatement::OptionsEqualStatement(string to_declaration_type_arg, string to_name1_arg,
string to_name2_arg, string to_subsample_name_arg,
string from_declaration_type_arg,
string from_name1_arg,
string from_name2_arg,
string from_name1_arg, string from_name2_arg,
string from_subsample_name_arg,
const SymbolTable& symbol_table_arg) :
to_declaration_type {move(to_declaration_type_arg)},
......@@ -4857,8 +4752,10 @@ void
OptionsEqualStatement::checkPass([[maybe_unused]] ModFileStructure& mod_file_struct,
[[maybe_unused]] WarningConsolidation& warnings)
{
if ((to_declaration_type != "par" && to_declaration_type != "std" && to_declaration_type != "corr")
|| (from_declaration_type != "par" && from_declaration_type != "std" && from_declaration_type != "corr"))
if ((to_declaration_type != "par" && to_declaration_type != "std"
&& to_declaration_type != "corr")
|| (from_declaration_type != "par" && from_declaration_type != "std"
&& from_declaration_type != "corr"))
{
cerr << "Internal Dynare Error" << endl;
exit(EXIT_FAILURE);
......@@ -4883,10 +4780,7 @@ OptionsEqualStatement::writeJsonOutput(ostream &output) const
void
OptionsEqualStatement::get_base_name(const SymbolType symb_type, string& lhs_field) const
{
if (symb_type == SymbolType::exogenous)
lhs_field = "structural_innovation";
else
lhs_field = "measurement_error";
lhs_field = (symb_type == SymbolType::exogenous ? "structural_innovation" : "measurement_error");
}
void
......@@ -4934,8 +4828,10 @@ OptionsEqualStatement::writeOutput(ostream &output, [[maybe_unused]] const strin
lhs_field += ".options";
else
{
output << "subsamples_to_indx = get_existing_subsamples_indx('" << to_name1 << "','" << to_name2 << "');" << endl
<< "ei_to_ss_ind = get_subsamples_range_indx(subsamples_to_indx, '" << to_subsample_name << "');" << endl;
output << "subsamples_to_indx = get_existing_subsamples_indx('" << to_name1 << "','"
<< to_name2 << "');" << endl
<< "ei_to_ss_ind = get_subsamples_range_indx(subsamples_to_indx, '"
<< to_subsample_name << "');" << endl;
lhs_field += ".subsample_options(ei_to_ss_ind)";
}
......@@ -4943,8 +4839,10 @@ OptionsEqualStatement::writeOutput(ostream &output, [[maybe_unused]] const strin
rhs_field += ".options";
else
{
output << "subsamples_from_indx = get_existing_subsamples_indx('" << from_name1 << "','" << from_name2 << "');" << endl
<< "ei_from_ss_ind = get_subsamples_range_indx(subsamples_from_indx, '" << from_subsample_name << "');" << endl;
output << "subsamples_from_indx = get_existing_subsamples_indx('" << from_name1 << "','"
<< from_name2 << "');" << endl
<< "ei_from_ss_ind = get_subsamples_range_indx(subsamples_from_indx, '"
<< from_subsample_name << "');" << endl;
rhs_field += ".subsample_options(ei_from_ss_ind)";
}
......@@ -4985,7 +4883,9 @@ CalibSmootherStatement::writeOutput(ostream &output, [[maybe_unused]] const stri
symbol_list.writeOutput("var_list_", output);
output << "options_.smoother = true;" << endl
<< "options_.order = 1;" << endl
<< "[oo_, M_, options_, bayestopt_] = evaluate_smoother(options_.parameter_set, var_list_, M_, oo_, options_, bayestopt_, estim_params_);" << endl;
<< "[oo_, M_, options_, bayestopt_] = evaluate_smoother(options_.parameter_set, "
"var_list_, M_, oo_, options_, bayestopt_, estim_params_);"
<< endl;
}
void
......@@ -5005,8 +4905,8 @@ CalibSmootherStatement::writeJsonOutput(ostream &output) const
output << "}";
}
ExtendedPathStatement::ExtendedPathStatement(OptionsList options_list_arg)
: options_list{move(options_list_arg)}
ExtendedPathStatement::ExtendedPathStatement(OptionsList options_list_arg) :
options_list {move(options_list_arg)}
{
}
......@@ -5034,7 +4934,8 @@ ExtendedPathStatement::writeOutput(ostream &output, [[maybe_unused]] const strin
options_list_new.erase("periods");
options_list_new.writeOutput(output);
output << "extended_path([], " << periods << ", [], options_, M_, oo_);" << endl;
output << "[Simulated_time_series, oo_] = extended_path([], " << periods
<< ", [], options_, M_, oo_);" << endl;
}
void
......@@ -5109,15 +5010,21 @@ MethodOfMomentsStatement::checkPass(ModFileStructure &mod_file_struct,
mod_file_struct.order_option = max(mod_file_struct.order_option, order);
}
if (!options_list.contains("datafile"))
if (!options_list.contains("mom.mom_method"))
{
cerr << "ERROR: The method_of_moments statement requires a data file to be supplied via the datafile option." << endl;
cerr << "ERROR: The 'method_of_moments' statement requires a method to be supplied via the "
"'mom_method' option. Possible values are 'GMM', 'SMM', or 'IRF_MATCHING'."
<< endl;
exit(EXIT_FAILURE);
}
if (!options_list.contains("mom.mom_method"))
auto mom_method_value = options_list.get_if<OptionsList::StringVal>("mom.mom_method");
if ((mom_method_value == "GMM" || mom_method_value == "SMM")
&& !options_list.contains("datafile"))
{
cerr << "ERROR: The method_of_moments statement requires a method to be supplied via the mom_method option. Possible values are GMM or SMM." << endl;
cerr << "ERROR: The 'method_of_moments' statement requires a data file to be supplied via "
"the 'datafile' option."
<< endl;
exit(EXIT_FAILURE);
}
......@@ -5152,7 +5059,9 @@ MethodOfMomentsStatement::writeOutput(ostream &output, [[maybe_unused]] const st
{
options_list.writeOutput(output, "options_mom_");
output << "[oo_, options_mom_, M_] = mom.run(bayestopt_, options_, oo_, estim_params_, M_, options_mom_);" << endl;
output << "[oo_, options_mom_, M_] = mom.run(bayestopt_, options_, oo_, estim_params_, M_, "
"options_mom_);"
<< endl;
}
void
......@@ -5167,9 +5076,8 @@ MethodOfMomentsStatement::writeJsonOutput(ostream &output) const
output << "}";
}
GenerateIRFsStatement::GenerateIRFsStatement(OptionsList options_list_arg,
vector<string> generate_irf_names_arg,
GenerateIRFsStatement::GenerateIRFsStatement(
OptionsList options_list_arg, vector<string> generate_irf_names_arg,
vector<map<string, double>> generate_irf_elements_arg) :
options_list {move(options_list_arg)},
generate_irf_names {move(generate_irf_names_arg)},
......@@ -5191,14 +5099,13 @@ GenerateIRFsStatement::writeOutput(ostream &output, [[maybe_unused]] const strin
output << "'" << generate_irf_name << "'; ";
output << "};" << endl;
output << "options_.irf_opt.irf_shocks = zeros(M_.exo_nbr, "
<< generate_irf_names.size() << ");" << endl;
output << "options_.irf_opt.irf_shocks = zeros(M_.exo_nbr, " << generate_irf_names.size() << ");"
<< endl;
for (size_t i = 0; i < generate_irf_names.size(); i++)
for (auto& [exo_name, exo_value] : generate_irf_elements[i])
output << "options_.irf_opt.irf_shocks(M_.exo_names == '"
<< exo_name << "', " << i + 1 << ") = "
<< exo_value << ";" << endl;
output << "options_.irf_opt.irf_shocks(M_.exo_names == '" << exo_name << "', " << i + 1
<< ") = " << exo_value << ";" << endl;
}
void
......@@ -5234,7 +5141,8 @@ GenerateIRFsStatement::writeJsonOutput(ostream &output) const
output << "}";
}
MatchedMomentsStatement::MatchedMomentsStatement(const SymbolTable &symbol_table_arg,
MatchedMomentsStatement::MatchedMomentsStatement(
const SymbolTable& symbol_table_arg,
vector<tuple<vector<int>, vector<int>, vector<int>>> moments_arg) :
symbol_table {symbol_table_arg}, moments {move(moments_arg)}
{
......@@ -5265,30 +5173,26 @@ void
MatchedMomentsStatement::writeJsonOutput(ostream& output) const
{
output << R"({"statementName": "matched_moments", "moments": [)" << endl;
for (bool printed_something{false};
const auto &[symb_ids, lags, powers] : moments)
for (bool printed_something {false}; const auto& [symb_ids, lags, powers] : moments)
{
if (exchange(printed_something, true))
output << ',';
output << R"( { "endos": [)";
for (bool printed_something2{false};
int s : symb_ids)
for (bool printed_something2 {false}; int s : symb_ids)
{
if (exchange(printed_something2, true))
output << ',';
output << symbol_table.getTypeSpecificID(s) + 1;
}
output << R"(], "lags": [)";
for (bool printed_something2{false};
int l : lags)
for (bool printed_something2 {false}; int l : lags)
{
if (exchange(printed_something2, true))
output << ',';
output << l;
}
output << R"(], "powers": [)";
for (bool printed_something2{false};
int p : powers)
for (bool printed_something2 {false}; int p : powers)
{
if (exchange(printed_something2, true))
output << ',';
......@@ -5299,9 +5203,10 @@ MatchedMomentsStatement::writeJsonOutput(ostream &output) const
output << "]}" << endl;
}
OccbinConstraintsStatement::OccbinConstraintsStatement(const DataTree &data_tree_arg,
vector<tuple<string, BinaryOpNode *, BinaryOpNode *, expr_t, expr_t>> constraints_arg)
: data_tree{data_tree_arg}, constraints{move(constraints_arg)}
OccbinConstraintsStatement::OccbinConstraintsStatement(
const DataTree& data_tree_arg,
vector<tuple<string, BinaryOpNode*, BinaryOpNode*, expr_t, expr_t>> constraints_arg) :
data_tree {data_tree_arg}, constraints {move(constraints_arg)}
{
}
......@@ -5316,7 +5221,8 @@ OccbinConstraintsStatement::checkPass(ModFileStructure &mod_file_struct,
}
if (constraints.size() > 2)
{
cerr << "ERROR: only up to two constraints are supported in 'occbin_constraints' block" << endl;
cerr << "ERROR: only up to two constraints are supported in 'occbin_constraints' block"
<< endl;
exit(EXIT_FAILURE);
}
mod_file_struct.occbin_constraints_present = true;
......@@ -5329,11 +5235,14 @@ OccbinConstraintsStatement::writeOutput(ostream &output, const string &basename,
output << "M_.occbin.constraint_nbr = " << constraints.size() << ';' << endl
<< "M_.occbin.pswitch = [" << endl;
for (const auto& [name, bind, relax, error_bind, error_relax] : constraints)
output << data_tree.symbol_table.getTypeSpecificID(ParsingDriver::buildOccbinBindParamName(name)) + 1 << ' ';
output << data_tree.symbol_table.getTypeSpecificID(
ParsingDriver::buildOccbinBindParamName(name))
+ 1
<< ' ';
output << "];" << endl
<< "options_.occbin = struct();" << endl
<< "options_.occbin = occbin.set_default_options(options_.occbin, M_);" << endl
<< "oo_.dr=set_state_space(oo_.dr,M_,options_);" << endl;
<< "oo_.dr=set_state_space(oo_.dr,M_);" << endl;
filesystem::path filename {"+" + basename + "/occbin_difference.m"};
ofstream diff_output {filename, ios::out | ios::binary};
......@@ -5342,20 +5251,21 @@ OccbinConstraintsStatement::writeOutput(ostream &output, const string &basename,
cerr << "Error: Can't open file " << filename.string() << " for writing" << endl;
exit(EXIT_FAILURE);
}
diff_output << "function [binding, relax, err] = occbin_difference(zdatalinear, params, steady_state)" << endl;
for (int idx{1};
const auto &[name, bind, relax, error_bind, error_relax] : constraints)
diff_output
<< "function [binding, relax, err] = occbin_difference(zdatalinear, params, steady_state)"
<< endl;
for (int idx {1}; const auto& [name, bind, relax, error_bind, error_relax] : constraints)
{
diff_output << "binding.constraint_" << idx << " = ";
dynamic_cast<ExprNode *>(bind)->writeOutput(diff_output, ExprNodeOutputType::occbinDifferenceFile);
diff_output << ';' << endl
<< "relax.constraint_" << idx << " = ";
dynamic_cast<ExprNode*>(bind)->writeOutput(diff_output,
ExprNodeOutputType::occbinDifferenceFile);
diff_output << ';' << endl << "relax.constraint_" << idx << " = ";
if (relax)
dynamic_cast<ExprNode *>(relax)->writeOutput(diff_output, ExprNodeOutputType::occbinDifferenceFile);
dynamic_cast<ExprNode*>(relax)->writeOutput(diff_output,
ExprNodeOutputType::occbinDifferenceFile);
else
diff_output << "~binding.constraint_" << idx;
diff_output << ';' << endl
<< "err.binding_constraint_" << idx << " = ";
diff_output << ';' << endl << "err.binding_constraint_" << idx << " = ";
if (error_bind)
error_bind->writeOutput(diff_output, ExprNodeOutputType::occbinDifferenceFile);
else
......@@ -5366,8 +5276,7 @@ OccbinConstraintsStatement::writeOutput(ostream &output, const string &basename,
bind->arg2->writeOutput(diff_output, ExprNodeOutputType::occbinDifferenceFile);
diff_output << "))";
}
diff_output << ';' << endl
<< "err.relax_constraint_" << idx << " = ";
diff_output << ';' << endl << "err.relax_constraint_" << idx << " = ";
if (error_relax)
error_relax->writeOutput(diff_output, ExprNodeOutputType::occbinDifferenceFile);
else if (relax)
......@@ -5425,8 +5334,7 @@ OccbinConstraintsStatement::writeJsonOutput(ostream &output) const
output << "]}" << endl;
}
ResidStatement::ResidStatement(OptionsList options_list_arg) :
options_list{move(options_list_arg)}
ResidStatement::ResidStatement(OptionsList options_list_arg) : options_list {move(options_list_arg)}
{
}
......@@ -5434,8 +5342,8 @@ void
ResidStatement::writeOutput(ostream& output, [[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
options_list.writeOutput(output, "options_resid_");
output << "display_static_residuals(M_, options_, oo_, options_resid_);" << endl;
options_list.writeOutput(output);
output << "display_static_residuals(M_, options_, oo_);" << endl;
}
void
......@@ -5449,3 +5357,103 @@ ResidStatement::writeJsonOutput(ostream &output) const
}
output << "}";
}
MatchedIrfsStatement::MatchedIrfsStatement(matched_irfs_t values_weights_arg, bool overwrite_arg) :
values_weights {move(values_weights_arg)}, overwrite {overwrite_arg}
{
}
void
MatchedIrfsStatement::writeOutput(ostream& output, [[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
if (overwrite)
output << "M_.matched_irfs = {};" << endl;
for (const auto& [key, vec] : values_weights)
{
const auto& [endo, exo] = key;
output << "M_.matched_irfs = [M_.matched_irfs; {'" << endo << "', '" << exo << "', {";
for (const auto& [p1, p2, value, weight] : vec)
{
output << p1 << ":" << p2 << ", ";
value->writeOutput(output);
output << ", ";
weight->writeOutput(output);
output << "; ";
}
output << "}}];" << endl;
}
}
void
MatchedIrfsStatement::writeJsonOutput(ostream& output) const
{
output << R"({"statementName": "matched_irfs")"
<< R"(, "overwrite": )" << boolalpha << overwrite << R"(, "contents": [)";
for (bool printed_something {false}; const auto& [key, vec] : values_weights)
{
if (exchange(printed_something, true))
output << ", ";
const auto& [endo, exo] = key;
output << R"({"var": ")" << endo << R"(", "varexo": ")" << exo
<< R"(", "periods_values_weights": [)";
for (bool printed_something2 {false}; const auto& [p1, p2, value, weight] : vec)
{
if (exchange(printed_something2, true))
output << ", ";
output << R"({"period1": )" << p1 << ", "
<< R"("period2": })" << p2 << ", "
<< R"("value": ")";
value->writeJsonOutput(output, {}, {});
output << R"(", "weight": ")";
weight->writeJsonOutput(output, {}, {});
output << R"("})";
}
output << "]}";
}
output << "]}";
}
MatchedIrfsWeightsStatement::MatchedIrfsWeightsStatement(matched_irfs_weights_t weights_arg,
bool overwrite_arg) :
weights {move(weights_arg)}, overwrite {overwrite_arg}
{
}
void
MatchedIrfsWeightsStatement::writeOutput(ostream& output, [[maybe_unused]] const string& basename,
[[maybe_unused]] bool minimal_workspace) const
{
if (overwrite)
output << "M_.matched_irfs_weights = {};" << endl;
for (const auto& [key, val] : weights)
{
const auto& [endo1, periods1, exo1, endo2, periods2, exo2] = key;
output << "M_.matched_irfs_weights = [M_.matched_irfs_weights; {'" << endo1 << "', "
<< periods1 << ", '" << exo1 << "', '" << endo2 << "', " << periods2 << ", '" << exo2
<< "', ";
val->writeOutput(output);
output << "}];" << endl;
}
}
void
MatchedIrfsWeightsStatement::writeJsonOutput(ostream& output) const
{
output << R"({"statementName": "matched_irfs_weights")"
<< R"(, "overwrite": )" << boolalpha << overwrite << R"(, "contents": [)";
for (bool printed_something {false}; const auto& [key, val] : weights)
{
const auto& [endo1, periods1, exo1, endo2, periods2, exo2] = key;
if (exchange(printed_something, true))
output << ", ";
output << R"({"endo1": ")" << endo1 << R"(", "periods1": ")" << periods1 << R"(", "exo1": )"
<< exo1 << R"(", "endo2": ")" << endo2 << R"(", "periods2": ")" << periods2
<< R"(", "exo2": )" << exo2 << R"(", "weight": ")";
val->writeJsonOutput(output, {}, {});
output << R"("})";
}
output << "]}";
}
/*
* Copyright © 2003-2023 Dynare Team
* Copyright © 2003-2024 Dynare Team
*
* This file is part of Dynare.
*
......@@ -17,23 +17,25 @@
* along with Dynare. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef _COMPUTINGTASKS_HH
#define _COMPUTINGTASKS_HH
#ifndef COMPUTING_TASKS_HH
#define COMPUTING_TASKS_HH
#include <ostream>
#include <memory>
#include <optional>
#include <ostream>
#include "SymbolList.hh"
#include "SymbolTable.hh"
#include "Statement.hh"
#include "StaticModel.hh"
#include "DynamicModel.hh"
#include "ModelEquationBlock.hh"
#include "Statement.hh"
#include "StaticModel.hh"
#include "SymbolList.hh"
#include "SymbolTable.hh"
class SteadyStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit SteadyStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -45,6 +47,7 @@ class CheckStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit CheckStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -56,6 +59,7 @@ class SimulStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit SimulStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -67,6 +71,7 @@ class PerfectForesightSetupStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit PerfectForesightSetupStatement(OptionsList options_list_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -77,6 +82,7 @@ class PerfectForesightSolverStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit PerfectForesightSolverStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -88,6 +94,7 @@ class PerfectForesightWithExpectationErrorsSetupStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit PerfectForesightWithExpectationErrorsSetupStatement(OptionsList options_list_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -98,6 +105,7 @@ class PerfectForesightWithExpectationErrorsSolverStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit PerfectForesightWithExpectationErrorsSolverStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -110,6 +118,7 @@ class PriorPosteriorFunctionStatement : public Statement
private:
const bool prior_func;
const OptionsList options_list;
public:
PriorPosteriorFunctionStatement(const bool prior_func_arg, OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -121,6 +130,7 @@ class ModelInfoStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit ModelInfoStatement(OptionsList options_list_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -133,6 +143,7 @@ private:
const SymbolList symbol_list;
const OptionsList options_list;
const SymbolTable& symbol_table;
public:
StochSimulStatement(SymbolList symbol_list_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
......@@ -147,6 +158,7 @@ private:
const SymbolList symbol_list;
const OptionsList options_list;
const SymbolTable& symbol_table;
public:
ForecastStatement(SymbolList symbol_list_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
......@@ -159,28 +171,9 @@ class RamseyModelStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit RamseyModelStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) override;
void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream &output) const override;
};
class RamseyConstraintsStatement : public Statement
{
public:
struct Constraint
{
int endo;
BinaryOpcode code;
expr_t expression;
};
using constraints_t = vector<Constraint>;
private:
const SymbolTable &symbol_table;
const constraints_t constraints;
public:
RamseyConstraintsStatement(const SymbolTable &symbol_table_arg, constraints_t constraints_arg);
explicit RamseyModelStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
......@@ -192,6 +185,7 @@ private:
const SymbolList symbol_list;
const OptionsList options_list;
const SymbolTable& symbol_table;
public:
RamseyPolicyStatement(SymbolList symbol_list_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
......@@ -204,6 +198,7 @@ class EvaluatePlannerObjectiveStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit EvaluatePlannerObjectiveStatement(OptionsList options_list_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -214,6 +209,7 @@ class OccbinSetupStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit OccbinSetupStatement(OptionsList options_list_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -224,6 +220,7 @@ class OccbinSolverStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit OccbinSolverStatement(OptionsList options_list_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -234,6 +231,7 @@ class OccbinWriteRegimesStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit OccbinWriteRegimesStatement(OptionsList options_list_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -245,9 +243,9 @@ class OccbinGraphStatement : public Statement
private:
const SymbolList symbol_list;
const OptionsList options_list;
public:
OccbinGraphStatement(SymbolList symbol_list_arg,
OptionsList options_list_arg);
OccbinGraphStatement(SymbolList symbol_list_arg, OptionsList options_list_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
};
......@@ -258,6 +256,7 @@ private:
const SymbolList symbol_list;
const OptionsList options_list;
const SymbolTable& symbol_table;
public:
DiscretionaryPolicyStatement(SymbolList symbol_list_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
......@@ -271,6 +270,7 @@ class RplotStatement : public Statement
private:
const SymbolList symbol_list;
const SymbolTable& symbol_table;
public:
RplotStatement(SymbolList symbol_list_arg, const SymbolTable& symbol_table_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -289,6 +289,7 @@ class DsampleStatement : public Statement
{
private:
const int val1, val2;
public:
explicit DsampleStatement(int val1_arg);
DsampleStatement(int val1_arg, int val2_arg);
......@@ -302,21 +303,22 @@ private:
const SymbolTable& symbol_table;
const SymbolList symbol_list;
const OptionsList options_list;
public:
EstimationStatement(const SymbolTable &symbol_table_arg,
SymbolList symbol_list_arg,
EstimationStatement(const SymbolTable& symbol_table_arg, SymbolList symbol_list_arg,
OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
};
class DynareSensitivityStatement : public Statement
class SensitivityStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit DynareSensitivityStatement(OptionsList options_list_arg);
explicit SensitivityStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
......@@ -326,9 +328,11 @@ class ObservationTrendsStatement : public Statement
{
public:
using trend_elements_t = map<string, expr_t>;
private:
const trend_elements_t trend_elements;
const SymbolTable& symbol_table;
public:
ObservationTrendsStatement(trend_elements_t trend_elements_arg,
const SymbolTable& symbol_table_arg);
......@@ -340,9 +344,11 @@ class DeterministicTrendsStatement : public Statement
{
public:
using trend_elements_t = map<string, expr_t>;
private:
const trend_elements_t trend_elements;
const SymbolTable& symbol_table;
public:
DeterministicTrendsStatement(trend_elements_t trend_elements_arg,
const SymbolTable& symbol_table_arg);
......@@ -354,9 +360,11 @@ class FilterInitialStateStatement : public Statement
{
public:
using filter_initial_state_elements_t = map<pair<int, int>, expr_t>;
private:
const filter_initial_state_elements_t filter_initial_state_elements;
const SymbolTable& symbol_table;
public:
FilterInitialStateStatement(filter_initial_state_elements_t filter_initial_state_elements_arg,
const SymbolTable& symbol_table_arg);
......@@ -369,6 +377,7 @@ class OsrParamsStatement : public Statement
private:
const SymbolList symbol_list;
const SymbolTable& symbol_table;
public:
OsrParamsStatement(SymbolList symbol_list_arg, const SymbolTable& symbol_table_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -382,6 +391,7 @@ private:
const SymbolList symbol_list;
const OptionsList options_list;
const SymbolTable& symbol_table;
public:
OsrStatement(SymbolList symbol_list_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
......@@ -410,6 +420,7 @@ class OsrParamsBoundsStatement : public Statement
{
private:
const vector<OsrParams> osr_params_list;
public:
explicit OsrParamsBoundsStatement(vector<OsrParams> osr_params_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -423,6 +434,7 @@ private:
const SymbolList symbol_list;
const string filename;
const SymbolTable& symbol_table;
public:
DynaTypeStatement(SymbolList symbol_list_arg, string filename_arg,
const SymbolTable& symbol_table_arg);
......@@ -437,6 +449,7 @@ private:
const SymbolList symbol_list;
const string filename;
const SymbolTable& symbol_table;
public:
DynaSaveStatement(SymbolList symbol_list_arg, string filename_arg,
const SymbolTable& symbol_table_arg);
......@@ -449,12 +462,13 @@ class ModelComparisonStatement : public Statement
{
public:
using filename_list_t = vector<pair<string, string>>;
private:
filename_list_t filename_list;
OptionsList options_list;
public:
ModelComparisonStatement(filename_list_t filename_list_arg,
OptionsList options_list_arg);
ModelComparisonStatement(filename_list_t filename_list_arg, OptionsList options_list_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
};
......@@ -493,7 +507,7 @@ protected:
const SymbolTable& symbol_table;
AbstractEstimatedParamsStatement(vector<EstimationParams> estim_params_list_arg,
const SymbolTable& symbol_table_arg);
virtual string blockName() const = 0;
[[nodiscard]] virtual string blockName() const = 0;
// Part of the check pass that is common to the three estimated_params{,_init,bounds} blocks
void commonCheckPass() const;
};
......@@ -502,11 +516,15 @@ class EstimatedParamsStatement : public AbstractEstimatedParamsStatement
{
private:
const bool overwrite;
public:
EstimatedParamsStatement(vector<EstimationParams> estim_params_list_arg,
const SymbolTable &symbol_table_arg,
bool overwrite_arg);
string blockName() const override { return "estimated_params"; };
const SymbolTable& symbol_table_arg, bool overwrite_arg);
[[nodiscard]] string
blockName() const override
{
return "estimated_params";
}
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
......@@ -516,11 +534,15 @@ class EstimatedParamsInitStatement : public AbstractEstimatedParamsStatement
{
private:
const bool use_calibration;
public:
EstimatedParamsInitStatement(vector<EstimationParams> estim_params_list_arg,
const SymbolTable &symbol_table_arg,
const bool use_calibration_arg);
string blockName() const override { return "estimated_params_init"; };
const SymbolTable& symbol_table_arg, const bool use_calibration_arg);
[[nodiscard]] string
blockName() const override
{
return "estimated_params_init";
}
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
......@@ -531,7 +553,11 @@ class EstimatedParamsBoundsStatement : public AbstractEstimatedParamsStatement
public:
EstimatedParamsBoundsStatement(vector<EstimationParams> estim_params_list_arg,
const SymbolTable& symbol_table_arg);
string blockName() const override { return "estimated_params_bounds"; };
[[nodiscard]] string
blockName() const override
{
return "estimated_params_bounds";
}
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
......@@ -554,13 +580,14 @@ class OptimWeightsStatement : public Statement
public:
using var_weights_t = map<string, expr_t>;
using covar_weights_t = map<pair<string, string>, expr_t>;
private:
const var_weights_t var_weights;
const covar_weights_t covar_weights;
const SymbolTable& symbol_table;
public:
OptimWeightsStatement(var_weights_t var_weights_arg,
covar_weights_t covar_weights_arg,
OptimWeightsStatement(var_weights_t var_weights_arg, covar_weights_t covar_weights_arg,
const SymbolTable& symbol_table_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -570,10 +597,11 @@ public:
class PlannerObjectiveStatement : public Statement
{
private:
PlannerObjective model_tree;
unique_ptr<PlannerObjective> model_tree;
bool computing_pass_called {false};
public:
explicit PlannerObjectiveStatement(const PlannerObjective &model_tree_arg);
explicit PlannerObjectiveStatement(unique_ptr<PlannerObjective> model_tree_arg);
/*! \todo check there are only endogenous variables at the current period in the objective
(no exogenous, no lead/lag) */
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -582,7 +610,7 @@ public:
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
//! Return a reference the Planner Objective model tree
const PlannerObjective &getPlannerObjective() const;
[[nodiscard]] const PlannerObjective& getPlannerObjective() const;
};
class BVARDensityStatement : public Statement
......@@ -590,6 +618,7 @@ class BVARDensityStatement : public Statement
private:
const int maxnlags;
const OptionsList options_list;
public:
BVARDensityStatement(int maxnlags_arg, OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -602,6 +631,7 @@ class BVARForecastStatement : public Statement
private:
const int nlags;
const OptionsList options_list;
public:
BVARForecastStatement(int nlags_arg, OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -614,6 +644,7 @@ class BVARIRFStatement : public Statement
private:
const int nirf;
const string identificationname;
public:
BVARIRFStatement(int nirf_arg, string identificationname_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -625,6 +656,7 @@ class SBVARStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit SBVARStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -636,6 +668,7 @@ class MSSBVAREstimationStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit MSSBVAREstimationStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -647,6 +680,7 @@ class MSSBVARSimulationStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit MSSBVARSimulationStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -658,6 +692,7 @@ class MSSBVARComputeMDDStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit MSSBVARComputeMDDStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -669,6 +704,7 @@ class MSSBVARComputeProbabilitiesStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit MSSBVARComputeProbabilitiesStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -682,6 +718,7 @@ private:
const SymbolList symbol_list;
const OptionsList options_list;
const SymbolTable& symbol_table;
public:
MSSBVARIrfStatement(SymbolList symbol_list_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
......@@ -694,6 +731,7 @@ class MSSBVARForecastStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit MSSBVARForecastStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -705,6 +743,7 @@ class MSSBVARVarianceDecompositionStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit MSSBVARVarianceDecompositionStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -716,6 +755,7 @@ class IdentificationStatement : public Statement
{
private:
OptionsList options_list;
public:
explicit IdentificationStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -728,8 +768,10 @@ class WriteLatexDynamicModelStatement : public Statement
private:
const DynamicModel& dynamic_model;
const bool write_equation_tags;
public:
WriteLatexDynamicModelStatement(const DynamicModel &dynamic_model_arg, bool write_equation_tags_arg);
WriteLatexDynamicModelStatement(const DynamicModel& dynamic_model_arg,
bool write_equation_tags_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
};
......@@ -739,6 +781,7 @@ class WriteLatexStaticModelStatement : public Statement
private:
const StaticModel& static_model;
const bool write_equation_tags;
public:
WriteLatexStaticModelStatement(const StaticModel& static_model_arg, bool write_equation_tags_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -750,8 +793,10 @@ class WriteLatexOriginalModelStatement : public Statement
private:
const DynamicModel& original_model;
const bool write_equation_tags;
public:
WriteLatexOriginalModelStatement(const DynamicModel &original_model_arg, bool write_equation_tags_arg);
WriteLatexOriginalModelStatement(const DynamicModel& original_model_arg,
bool write_equation_tags_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
};
......@@ -760,6 +805,7 @@ class WriteLatexSteadyStateModelStatement : public Statement
{
private:
const SteadyStateModel& steady_state_model;
public:
explicit WriteLatexSteadyStateModelStatement(const SteadyStateModel& steady_state_model_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -773,6 +819,7 @@ private:
const SymbolList symbol_list;
const OptionsList options_list;
const SymbolTable& symbol_table;
public:
ShockDecompositionStatement(SymbolList symbol_list_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
......@@ -787,6 +834,7 @@ private:
const SymbolList symbol_list;
const OptionsList options_list;
const SymbolTable& symbol_table;
public:
RealtimeShockDecompositionStatement(SymbolList symbol_list_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
......@@ -801,6 +849,7 @@ private:
const SymbolList symbol_list;
const OptionsList options_list;
const SymbolTable& symbol_table;
public:
PlotShockDecompositionStatement(SymbolList symbol_list_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
......@@ -815,6 +864,7 @@ private:
const SymbolList symbol_list;
const OptionsList options_list;
const SymbolTable& symbol_table;
public:
InitialConditionDecompositionStatement(SymbolList symbol_list_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
......@@ -828,6 +878,7 @@ class SqueezeShockDecompositionStatement : public Statement
private:
const SymbolList symbol_list;
const SymbolTable& symbol_table;
public:
SqueezeShockDecompositionStatement(SymbolList symbol_list_arg,
const SymbolTable& symbol_table_arg);
......@@ -840,6 +891,7 @@ class ConditionalForecastStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit ConditionalForecastStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -853,8 +905,9 @@ private:
const optional<int> periods; // The user is allowed not to declare periods
const SymbolList symbol_list;
const SymbolTable& symbol_table;
public:
PlotConditionalForecastStatement(optional<int> periods_arg, SymbolList symbol_list_arg,
PlotConditionalForecastStatement(const optional<int>& periods_arg, SymbolList symbol_list_arg,
const SymbolTable& symbol_table_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -867,6 +920,7 @@ private:
const SymbolList symbol_list;
const OptionsList options_list;
const SymbolTable& symbol_table;
public:
CalibSmootherStatement(SymbolList symbol_list_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
......@@ -879,6 +933,7 @@ class ExtendedPathStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit ExtendedPathStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -900,15 +955,16 @@ public:
};
using svar_identification_restrictions_t = vector<svar_identification_restriction>;
private:
const svar_identification_restrictions_t restrictions;
const bool upper_cholesky_present, lower_cholesky_present, constants_exclusion_present;
const SymbolTable& symbol_table;
int getMaxLag() const;
[[nodiscard]] int getMaxLag() const;
public:
SvarIdentificationStatement(svar_identification_restrictions_t restrictions_arg,
bool upper_cholesky_present_arg,
bool lower_cholesky_present_arg,
bool upper_cholesky_present_arg, bool lower_cholesky_present_arg,
bool constants_exclusion_present_arg,
const SymbolTable& symbol_table_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -921,6 +977,7 @@ class MarkovSwitchingStatement : public Statement
private:
const OptionsList options_list;
map<pair<int, int>, double> restriction_map;
public:
explicit MarkovSwitchingStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -932,6 +989,7 @@ class SvarStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit SvarStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -949,9 +1007,10 @@ public:
class SetTimeStatement : public Statement
{
private:
const OptionsList options_list;
const string period;
public:
explicit SetTimeStatement(OptionsList options_list_arg);
explicit SetTimeStatement(string period_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
};
......@@ -960,6 +1019,7 @@ class EstimationDataStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit EstimationDataStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -972,13 +1032,14 @@ class SubsamplesStatement : public Statement
public:
//! Storage for declaring subsamples: map<subsample_name, <date1, date2 >
using subsample_declaration_map_t = map<string, pair<string, string>>;
private:
const string name1, name2;
const subsample_declaration_map_t subsample_declaration_map;
const SymbolTable& symbol_table;
public:
SubsamplesStatement(string name1_arg,
string name2_arg,
SubsamplesStatement(string name1_arg, string name2_arg,
subsample_declaration_map_t subsample_declaration_map_arg,
const SymbolTable& symbol_table_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -990,12 +1051,10 @@ class SubsamplesEqualStatement : public Statement
private:
const string to_name1, to_name2, from_name1, from_name2;
const SymbolTable& symbol_table;
public:
SubsamplesEqualStatement(string to_name1_arg,
string to_name2_arg,
string from_name1_arg,
string from_name2_arg,
const SymbolTable &symbol_table_arg);
SubsamplesEqualStatement(string to_name1_arg, string to_name2_arg, string from_name1_arg,
string from_name2_arg, const SymbolTable& symbol_table_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
};
......@@ -1007,9 +1066,9 @@ private:
const PriorDistributions prior_shape;
const OptionsList options_list;
void writeOutputHelper(ostream& output, const string& field, const string& lhs_field) const;
public:
JointPriorStatement(vector<string> joint_parameters_arg,
PriorDistributions prior_shape_arg,
JointPriorStatement(vector<string> joint_parameters_arg, PriorDistributions prior_shape_arg,
OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -1023,17 +1082,15 @@ protected:
const PriorDistributions prior_shape;
const expr_t variance;
const OptionsList options_list;
BasicPriorStatement(string name_arg,
string subsample_name_arg,
PriorDistributions prior_shape_arg,
expr_t variance_arg,
BasicPriorStatement(string name_arg, string subsample_name_arg,
PriorDistributions prior_shape_arg, expr_t variance_arg,
OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void get_base_name(const SymbolType symb_type, string& lhs_field) const;
void writeCommonOutput(ostream& output, const string& lhs_field) const;
void writeCommonOutputHelper(ostream& output, const string& field, const string& lhs_field) const;
void writePriorOutput(ostream& output, string& lhs_field, const string& name2) const;
bool is_structural_innovation(const SymbolType symb_type) const;
[[nodiscard]] bool is_structural_innovation(const SymbolType symb_type) const;
void writePriorIndex(ostream& output, const string& lhs_field) const;
void writeVarianceOption(ostream& output, const string& lhs_field) const;
void writeOutputHelper(ostream& output, const string& field, const string& lhs_field) const;
......@@ -1045,11 +1102,8 @@ protected:
class PriorStatement : public BasicPriorStatement
{
public:
PriorStatement(string name_arg,
string subsample_name_arg,
PriorDistributions prior_shape_arg,
expr_t variance_arg,
OptionsList options_list_arg);
PriorStatement(string name_arg, string subsample_name_arg, PriorDistributions prior_shape_arg,
expr_t variance_arg, OptionsList options_list_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
};
......@@ -1058,12 +1112,10 @@ class StdPriorStatement : public BasicPriorStatement
{
private:
const SymbolTable& symbol_table;
public:
StdPriorStatement(string name_arg,
string subsample_name_arg,
PriorDistributions prior_shape_arg,
expr_t variance_arg,
OptionsList options_list_arg,
StdPriorStatement(string name_arg, string subsample_name_arg, PriorDistributions prior_shape_arg,
expr_t variance_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
......@@ -1074,14 +1126,11 @@ class CorrPriorStatement : public BasicPriorStatement
private:
const string name1;
const SymbolTable& symbol_table;
public:
CorrPriorStatement(string name_arg1,
string name_arg2,
string subsample_name_arg,
PriorDistributions prior_shape_arg,
expr_t variance_arg,
OptionsList options_list_arg,
const SymbolTable &symbol_table_arg);
CorrPriorStatement(string name_arg1, string name_arg2, string subsample_name_arg,
PriorDistributions prior_shape_arg, expr_t variance_arg,
OptionsList options_list_arg, const SymbolTable& symbol_table_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
......@@ -1093,15 +1142,11 @@ private:
const string to_declaration_type, to_name1, to_name2, to_subsample_name;
const string from_declaration_type, from_name1, from_name2, from_subsample_name;
const SymbolTable& symbol_table;
public:
PriorEqualStatement(string to_declaration_type_arg,
string to_name1_arg,
string to_name2_arg,
string to_subsample_name_arg,
string from_declaration_type_arg,
string from_name1_arg,
string from_name2_arg,
string from_subsample_name_arg,
PriorEqualStatement(string to_declaration_type_arg, string to_name1_arg, string to_name2_arg,
string to_subsample_name_arg, string from_declaration_type_arg,
string from_name1_arg, string from_name2_arg, string from_subsample_name_arg,
const SymbolTable& symbol_table_arg);
void get_base_name(const SymbolType symb_type, string& lhs_field) const;
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -1114,14 +1159,12 @@ class BasicOptionsStatement : public Statement
protected:
const string name, subsample_name;
const OptionsList options_list;
BasicOptionsStatement(string name_arg,
string subsample_name_arg,
OptionsList options_list_arg);
BasicOptionsStatement(string name_arg, string subsample_name_arg, OptionsList options_list_arg);
void get_base_name(const SymbolType symb_type, string& lhs_field) const;
void writeOptionsOutput(ostream& output, string& lhs_field, const string& name2) const;
void writeCommonOutput(ostream& output, const string& lhs_field) const;
void writeCommonOutputHelper(ostream& output, const string& field, const string& lhs_field) const;
bool is_structural_innovation(const SymbolType symb_type) const;
[[nodiscard]] bool is_structural_innovation(const SymbolType symb_type) const;
void writeOptionsIndex(ostream& output, const string& lhs_field) const;
void writeOutputHelper(ostream& output, const string& field, const string& lhs_field) const;
void writeJsonOptionsOutput(ostream& output) const;
......@@ -1139,10 +1182,9 @@ class StdOptionsStatement : public BasicOptionsStatement
{
private:
const SymbolTable& symbol_table;
public:
StdOptionsStatement(string name_arg,
string subsample_name_arg,
OptionsList options_list_arg,
StdOptionsStatement(string name_arg, string subsample_name_arg, OptionsList options_list_arg,
const SymbolTable& symbol_table_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
......@@ -1153,11 +1195,10 @@ class CorrOptionsStatement : public BasicOptionsStatement
private:
const string name1;
const SymbolTable& symbol_table;
public:
CorrOptionsStatement(string name_arg1, string name_arg2,
string subsample_name_arg,
OptionsList options_list_arg,
const SymbolTable &symbol_table_arg);
CorrOptionsStatement(string name_arg1, string name_arg2, string subsample_name_arg,
OptionsList options_list_arg, const SymbolTable& symbol_table_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
......@@ -1169,16 +1210,12 @@ private:
const string to_declaration_type, to_name1, to_name2, to_subsample_name;
const string from_declaration_type, from_name1, from_name2, from_subsample_name;
const SymbolTable& symbol_table;
public:
OptionsEqualStatement(string to_declaration_type_arg,
string to_name1_arg,
string to_name2_arg,
string to_subsample_name_arg,
string from_declaration_type_arg,
string from_name1_arg,
string from_name2_arg,
string from_subsample_name_arg,
const SymbolTable &symbol_table_arg);
OptionsEqualStatement(string to_declaration_type_arg, string to_name1_arg, string to_name2_arg,
string to_subsample_name_arg, string from_declaration_type_arg,
string from_name1_arg, string from_name2_arg,
string from_subsample_name_arg, const SymbolTable& symbol_table_arg);
void get_base_name(const SymbolType symb_type, string& lhs_field) const;
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -1196,6 +1233,7 @@ class Smoother2histvalStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit Smoother2histvalStatement(OptionsList options_list_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -1206,6 +1244,7 @@ class MethodOfMomentsStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit MethodOfMomentsStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
......@@ -1220,9 +1259,9 @@ private:
const OptionsList options_list;
const vector<string> generate_irf_names;
const vector<map<string, double>> generate_irf_elements;
public:
GenerateIRFsStatement(OptionsList options_list_arg,
vector<string> generate_irf_names_arg,
GenerateIRFsStatement(OptionsList options_list_arg, vector<string> generate_irf_names_arg,
vector<map<string, double>> generate_irf_elements_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
......@@ -1232,6 +1271,7 @@ class MatchedMomentsStatement : public Statement
{
private:
const SymbolTable& symbol_table;
public:
/* Each moment is represented by a three vectors: symb_ids, lags, powers.
See the definition of ExprNode::matchMatchedMoment() for more details */
......@@ -1246,10 +1286,13 @@ class OccbinConstraintsStatement : public Statement
{
private:
DataTree data_tree;
public:
// The tuple is (name, bind, relax, error_bind, error_relax) (where relax and error_{bind,relax} can be nullptr)
// The tuple is (name, bind, relax, error_bind, error_relax) (where relax and error_{bind,relax}
// can be nullptr)
const vector<tuple<string, BinaryOpNode*, BinaryOpNode*, expr_t, expr_t>> constraints;
OccbinConstraintsStatement(const DataTree &data_tree_arg,
OccbinConstraintsStatement(
const DataTree& data_tree_arg,
vector<tuple<string, BinaryOpNode*, BinaryOpNode*, expr_t, expr_t>> constraints_arg);
void checkPass(ModFileStructure& mod_file_struct, WarningConsolidation& warnings) override;
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
......@@ -1260,10 +1303,40 @@ class ResidStatement : public Statement
{
private:
const OptionsList options_list;
public:
explicit ResidStatement(OptionsList options_list_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
};
class MatchedIrfsStatement : public Statement
{
public:
// (endo name, exo name) → vector of (period start, period end, value, weight)
using matched_irfs_t = map<pair<string, string>, vector<tuple<int, int, expr_t, expr_t>>>;
MatchedIrfsStatement(matched_irfs_t values_weights_arg, bool overwrite_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
private:
const matched_irfs_t values_weights;
const bool overwrite;
};
class MatchedIrfsWeightsStatement : public Statement
{
public:
/* (endo1 name, period index or range for endo1, exo1 name, endo2 name, period index or range for
endo2, exo2 name) → weight */
using matched_irfs_weights_t = map<tuple<string, string, string, string, string, string>, expr_t>;
MatchedIrfsWeightsStatement(matched_irfs_weights_t weights_arg, bool overwrite_arg);
void writeOutput(ostream& output, const string& basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream& output) const override;
private:
const matched_irfs_weights_t weights;
const bool overwrite;
};
#endif
/*
* Copyright © 2010-2023 Dynare Team
* Copyright © 2010-2024 Dynare Team
*
* This file is part of Dynare.
*
......@@ -17,33 +17,25 @@
* along with Dynare. If not, see <https://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <fstream>
#include <iostream>
#include <utility>
#include <vector>
#include "ConfigFile.hh"
#ifdef _WIN32
# include <shlobj.h>
#endif
#include "Configuration.hh"
#include "DataTree.hh" // For strsplit()
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/tokenizer.hpp>
#pragma GCC diagnostic pop
using namespace std;
Hook::Hook(string global_init_file_arg)
{
if (global_init_file_arg.empty())
{
cerr << "ERROR: The Hook must have a Global Initialization File argument." << endl;
exit(EXIT_FAILURE);
}
hooks["global_init_file"] = move(global_init_file_arg);
}
Path::Path(vector<string> includepath_arg)
Configuration::Path::Path(vector<string> includepath_arg)
{
if (includepath_arg.empty())
{
......@@ -53,10 +45,13 @@ Path::Path(vector<string> includepath_arg)
paths["include"] = move(includepath_arg);
}
FollowerNode::FollowerNode(string computerName_arg, string port_arg, int minCpuNbr_arg, int maxCpuNbr_arg, string userName_arg,
string password_arg, string remoteDrive_arg, string remoteDirectory_arg,
string programPath_arg, string programConfig_arg, string matlabOctavePath_arg, bool singleCompThread_arg,
int numberOfThreadsPerJob_arg, string operatingSystem_arg) :
Configuration::FollowerNode::FollowerNode(string computerName_arg, string port_arg,
int minCpuNbr_arg, int maxCpuNbr_arg, string userName_arg,
string password_arg, string remoteDrive_arg,
string remoteDirectory_arg, string programPath_arg,
string programConfig_arg, string matlabOctavePath_arg,
bool singleCompThread_arg, int numberOfThreadsPerJob_arg,
string operatingSystem_arg) :
computerName {move(computerName_arg)},
port {move(port_arg)},
minCpuNbr {minCpuNbr_arg},
......@@ -81,12 +76,13 @@ FollowerNode::FollowerNode(string computerName_arg, string port_arg, int minCpuN
if (!operatingSystem.empty())
if (operatingSystem != "windows" && operatingSystem != "unix")
{
cerr << "ERROR: The OperatingSystem must be either 'unix' or 'windows' (Case Sensitive)." << endl;
cerr << "ERROR: The OperatingSystem must be either 'unix' or 'windows' (Case Sensitive)."
<< endl;
exit(EXIT_FAILURE);
}
}
Cluster::Cluster(member_nodes_t member_nodes_arg) :
Configuration::Cluster::Cluster(member_nodes_t member_nodes_arg) :
member_nodes {move(member_nodes_arg)}
{
if (member_nodes.empty())
......@@ -96,10 +92,11 @@ Cluster::Cluster(member_nodes_t member_nodes_arg) :
}
}
ConfigFile::ConfigFile(bool parallel_arg, bool parallel_test_arg,
Configuration::Configuration(bool parallel_arg, bool parallel_test_arg,
bool parallel_follower_open_mode_arg, bool parallel_use_psexec_arg,
string cluster_name_arg) :
parallel{parallel_arg}, parallel_test{parallel_test_arg},
parallel {parallel_arg},
parallel_test {parallel_test_arg},
parallel_follower_open_mode {parallel_follower_open_mode_arg},
parallel_use_psexec {parallel_use_psexec_arg},
cluster_name {move(cluster_name_arg)}
......@@ -107,70 +104,63 @@ ConfigFile::ConfigFile(bool parallel_arg, bool parallel_test_arg,
}
void
ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
Configuration::getConfigFileInfo(const filesystem::path& conffile_option,
WarningConsolidation& warnings)
{
using namespace boost;
ifstream configFile;
filesystem::path config_file {conffile_option};
if (config_file.empty())
{
filesystem::path defaultConfigFile;
// Test OS and try to open default file
#if defined(_WIN32) || defined(__CYGWIN32__)
if (auto appdata = getenv("APPDATA");
appdata)
defaultConfigFile = filesystem::path{appdata} / "dynare.ini";
else
{
if (parallel || parallel_test)
cerr << "ERROR: ";
else
cerr << "WARNING: ";
cerr << "APPDATA environment variable not found." << endl;
config_file = findConfigFile("dynare.ini");
if (parallel || parallel_test)
exit(EXIT_FAILURE);
}
if (config_file.empty()) // Try old default location (Dynare ⩽ 5) for backward compatibility
{
filesystem::path old_default_config_file;
#ifdef _WIN32
array<wchar_t, MAX_PATH + 1> appdata;
if (SHGetFolderPathW(nullptr, CSIDL_APPDATA | CSIDL_FLAG_DONT_VERIFY, nullptr,
SHGFP_TYPE_CURRENT, appdata.data())
== S_OK)
old_default_config_file = filesystem::path {appdata.data()} / "dynare.ini";
#else
if (auto home = getenv("HOME");
home)
defaultConfigFile = filesystem::path{home} / ".dynare";
else
if (auto home = getenv("HOME"); home)
old_default_config_file = filesystem::path {home} / ".dynare";
#endif
if (!old_default_config_file.empty() && exists(old_default_config_file))
{
if (parallel || parallel_test)
cerr << "ERROR: ";
else
cerr << "WARNING: ";
cerr << "HOME environment variable not found." << endl;
if (parallel || parallel_test)
exit(EXIT_FAILURE);
warnings << "WARNING: the location " << old_default_config_file.string()
<< " for the configuration file is obsolete; please see the reference"
<< " manual for the new location." << endl;
config_file = old_default_config_file;
}
#endif
configFile.open(defaultConfigFile, fstream::in);
if (!configFile.is_open())
}
}
if (config_file.empty())
{
if (parallel || parallel_test)
{
cerr << "ERROR: Could not open the default config file (" << defaultConfigFile.string() << ")" << endl;
cerr << "ERROR: the parallel or parallel_test option was passed but no configuration "
<< "file was found" << endl;
exit(EXIT_FAILURE);
}
else
return;
}
}
else
{
ifstream configFile;
configFile.open(config_file, fstream::in);
if (!configFile.is_open())
{
cerr << "ERROR: Couldn't open file " << config_file.string() << endl;;
cerr << "ERROR: Couldn't open configuration file " << config_file.string() << endl;
exit(EXIT_FAILURE);
}
}
string name, computerName, port, userName, password, remoteDrive,
remoteDirectory, programPath, programConfig, matlabOctavePath,
operatingSystem, global_init_file;
string name, computerName, port, userName, password, remoteDrive, remoteDirectory, programPath,
programConfig, matlabOctavePath, operatingSystem;
vector<string> includepath;
int minCpuNbr {0}, maxCpuNbr {0};
int numberOfThreadsPerJob {1};
......@@ -187,24 +177,17 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
if (line.empty() || !line.compare(0, 1, "#"))
continue;
if (line == "[node]"
|| line == "[cluster]"
|| line == "[hooks]"
|| line == "[paths]")
if (line == "[node]" || line == "[cluster]" || line == "[hooks]" || line == "[paths]")
{
if (!global_init_file.empty())
// we were just in [hooks]
addHooksConfFileElement(global_init_file);
else if (!includepath.empty())
if (!includepath.empty())
// we were just in [paths]
addPathsConfFileElement(includepath);
else
// we were just in [node] or [cluster]
addParallelConfFileElement(inNode, inCluster, member_nodes, name,
computerName, port, minCpuNbr, maxCpuNbr, userName,
password, remoteDrive, remoteDirectory,
programPath, programConfig, matlabOctavePath, singleCompThread,
numberOfThreadsPerJob, operatingSystem);
addParallelConfFileElement(
inNode, inCluster, member_nodes, name, computerName, port, minCpuNbr, maxCpuNbr,
userName, password, remoteDrive, remoteDirectory, programPath, programConfig,
matlabOctavePath, singleCompThread, numberOfThreadsPerJob, operatingSystem);
//! Reset communication vars / option defaults
if (line == "[hooks]")
......@@ -236,9 +219,8 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
inPaths = false;
}
name = userName = computerName = port = password = remoteDrive
= remoteDirectory = programPath = programConfig = matlabOctavePath
= operatingSystem = global_init_file = "";
name = userName = computerName = port = password = remoteDrive = remoteDirectory
= programPath = programConfig = matlabOctavePath = operatingSystem = "";
includepath.clear();
minCpuNbr = maxCpuNbr = 0;
numberOfThreadsPerJob = 1;
......@@ -251,7 +233,8 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
split(tokenizedLine, line, is_any_of("="));
if (tokenizedLine.size() != 2)
{
cerr << "ERROR (in config file): Options should be formatted as 'option = value'." << endl;
cerr << "ERROR (in config file): Options should be formatted as 'option = value'."
<< endl;
exit(EXIT_FAILURE);
}
trim(tokenizedLine.front());
......@@ -263,12 +246,15 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
global_init_file = tokenizedLine.back();
else
{
cerr << "ERROR: May not have more than one GlobalInitFile option in [hooks] block." << endl;
cerr
<< "ERROR: May not have more than one GlobalInitFile option in [hooks] block."
<< endl;
exit(EXIT_FAILURE);
}
else
{
cerr << "ERROR: Unrecognized option " << tokenizedLine.front() << " in [hooks] block." << endl;
cerr << "ERROR: Unrecognized option " << tokenizedLine.front()
<< " in [hooks] block." << endl;
exit(EXIT_FAILURE);
}
else if (inPaths)
......@@ -286,16 +272,17 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
}
else
{
cerr << "ERROR: May not have more than one Include option in [paths] block." << endl;
cerr << "ERROR: May not have more than one Include option in [paths] block."
<< endl;
exit(EXIT_FAILURE);
}
else
{
cerr << "ERROR: Unrecognized option " << tokenizedLine.front() << " in [paths] block." << endl;
cerr << "ERROR: Unrecognized option " << tokenizedLine.front()
<< " in [paths] block." << endl;
exit(EXIT_FAILURE);
}
else
if (tokenizedLine.front() == "Name")
else if (tokenizedLine.front() == "Name")
name = tokenizedLine.back();
else if (tokenizedLine.front() == "CPUnbr")
{
......@@ -308,8 +295,7 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
minCpuNbr = 1;
maxCpuNbr = stoi(tokenizedCpuNbr.front());
}
else if (tokenizedCpuNbr.size() == 2
&& tokenizedCpuNbr[0].at(0) == '['
else if (tokenizedCpuNbr.size() == 2 && tokenizedCpuNbr[0].at(0) == '['
&& tokenizedCpuNbr[1].at(tokenizedCpuNbr[1].size() - 1) == ']')
{
tokenizedCpuNbr[0].erase(0, 1);
......@@ -354,8 +340,7 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
remoteDrive = tokenizedLine.back();
else if (tokenizedLine.front() == "RemoteDirectory")
remoteDirectory = tokenizedLine.back();
else if (tokenizedLine.front() == "DynarePath"
|| tokenizedLine.front() == "ProgramPath")
else if (tokenizedLine.front() == "DynarePath" || tokenizedLine.front() == "ProgramPath")
programPath = tokenizedLine.back();
else if (tokenizedLine.front() == "ProgramConfig")
programConfig = tokenizedLine.back();
......@@ -370,7 +355,9 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
singleCompThread = false;
else
{
cerr << "ERROR (in config file): The value passed to SingleCompThread may only be 'true' or 'false'." << endl;
cerr << "ERROR (in config file): The value passed to SingleCompThread may only be "
"'true' or 'false'."
<< endl;
exit(EXIT_FAILURE);
}
else if (tokenizedLine.front() == "OperatingSystem")
......@@ -380,8 +367,7 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
char_separator sep(" ,;", "()", drop_empty_tokens);
tokenizer tokens(tokenizedLine.back(), sep);
string node_name;
for (bool begin_weight{false};
const auto &token : tokens)
for (bool begin_weight {false}; const auto& token : tokens)
{
if (token == "(")
{
......@@ -401,7 +387,9 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
{
if (member_nodes.contains(node_name))
{
cerr << "ERROR (in config file): Node entered twice in specification of cluster." << endl;
cerr << "ERROR (in config file): Node entered twice in specification "
"of cluster."
<< endl;
exit(EXIT_FAILURE);
}
else
......@@ -415,14 +403,18 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
auto weight = stod(token);
if (weight <= 0)
{
cerr << "ERROR (in config file): Misspecification of weights passed to Members option." << endl;
cerr << "ERROR (in config file): Misspecification of weights passed to "
"Members option."
<< endl;
exit(EXIT_FAILURE);
}
member_nodes[node_name] = weight;
}
catch (const invalid_argument&)
{
cerr << "ERROR (in config file): Misspecification of weights passed to Members option." << endl;
cerr << "ERROR (in config file): Misspecification of weights passed to "
"Members option."
<< endl;
exit(EXIT_FAILURE);
}
}
......@@ -432,27 +424,27 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
member_nodes[node_name] = 1.0;
else
{
cerr << "ERROR (in config file): Node entered twice in specification of cluster." << endl;
cerr << "ERROR (in config file): Node entered twice in specification of "
"cluster."
<< endl;
exit(EXIT_FAILURE);
}
}
}
else
{
cerr << "ERROR (in config file): Option " << tokenizedLine.front() << " is invalid." << endl;
cerr << "ERROR (in config file): Option " << tokenizedLine.front() << " is invalid."
<< endl;
exit(EXIT_FAILURE);
}
}
}
if (!global_init_file.empty())
addHooksConfFileElement(global_init_file);
else if (!includepath.empty())
if (!includepath.empty())
addPathsConfFileElement(includepath);
else
addParallelConfFileElement(inNode, inCluster, member_nodes, name,
computerName, port, minCpuNbr, maxCpuNbr, userName,
password, remoteDrive, remoteDirectory,
addParallelConfFileElement(inNode, inCluster, member_nodes, name, computerName, port, minCpuNbr,
maxCpuNbr, userName, password, remoteDrive, remoteDirectory,
programPath, programConfig, matlabOctavePath, singleCompThread,
numberOfThreadsPerJob, operatingSystem);
......@@ -460,19 +452,7 @@ ConfigFile::getConfigFileInfo(const filesystem::path &config_file)
}
void
ConfigFile::addHooksConfFileElement(string global_init_file)
{
if (global_init_file.empty())
{
cerr << "ERROR: The global initialization file must be passed to the GlobalInitFile option." << endl;
exit(EXIT_FAILURE);
}
else
hooks.emplace_back(move(global_init_file));
}
void
ConfigFile::addPathsConfFileElement(vector<string> includepath)
Configuration::addPathsConfFileElement(vector<string> includepath)
{
if (includepath.empty())
{
......@@ -484,12 +464,15 @@ ConfigFile::addPathsConfFileElement(vector<string> includepath)
}
void
ConfigFile::addParallelConfFileElement(bool inNode, bool inCluster, const member_nodes_t &member_nodes, const string &name,
const string &computerName, const string &port, int minCpuNbr, int maxCpuNbr,
const string &userName, const string &password, const string &remoteDrive,
const string &remoteDirectory, const string &programPath, const string &programConfig,
const string &matlabOctavePath, bool singleCompThread, int numberOfThreadsPerJob,
const string &operatingSystem)
Configuration::addParallelConfFileElement(bool inNode, bool inCluster,
const member_nodes_t& member_nodes, const string& name,
const string& computerName, const string& port,
int minCpuNbr, int maxCpuNbr, const string& userName,
const string& password, const string& remoteDrive,
const string& remoteDirectory, const string& programPath,
const string& programConfig,
const string& matlabOctavePath, bool singleCompThread,
int numberOfThreadsPerJob, const string& operatingSystem)
{
//! ADD NODE
if (inNode)
......@@ -498,24 +481,22 @@ ConfigFile::addParallelConfFileElement(bool inNode, bool inCluster, const member
cerr << "Invalid option passed to [node]." << endl;
exit(EXIT_FAILURE);
}
else
if (name.empty() || follower_nodes.contains(name))
else if (name.empty() || follower_nodes.contains(name))
{
cerr << "ERROR: Every node must be assigned a unique name." << endl;
exit(EXIT_FAILURE);
}
else
follower_nodes.try_emplace(name, computerName, port, minCpuNbr, maxCpuNbr, userName,
password, remoteDrive, remoteDirectory, programPath, programConfig,
follower_nodes.try_emplace(name, computerName, port, minCpuNbr, maxCpuNbr, userName, password,
remoteDrive, remoteDirectory, programPath, programConfig,
matlabOctavePath, singleCompThread, numberOfThreadsPerJob,
operatingSystem);
//! ADD CLUSTER
else if (inCluster)
{
if (minCpuNbr > 0 || maxCpuNbr > 0 || !userName.empty()
|| !password.empty() || !remoteDrive.empty() || !remoteDirectory.empty()
|| !programPath.empty() || !programConfig.empty()
|| !matlabOctavePath.empty() || !operatingSystem.empty())
if (minCpuNbr > 0 || maxCpuNbr > 0 || !userName.empty() || !password.empty()
|| !remoteDrive.empty() || !remoteDirectory.empty() || !programPath.empty()
|| !programConfig.empty() || !matlabOctavePath.empty() || !operatingSystem.empty())
{
cerr << "Invalid option passed to [cluster]." << endl;
exit(EXIT_FAILURE);
......@@ -535,18 +516,8 @@ ConfigFile::addParallelConfFileElement(bool inNode, bool inCluster, const member
}
void
ConfigFile::checkPass([[maybe_unused]] WarningConsolidation &warnings) const
{
for (bool global_init_file_declared{false};
const auto &hook : hooks)
for (const auto &mapit : hook.get_hooks())
if (mapit.first == "global_init_file")
if (exchange(global_init_file_declared, true))
Configuration::checkPass([[maybe_unused]] WarningConsolidation& warnings) const
{
cerr << "ERROR: Only one global initialization file may be provided." << endl;
exit(EXIT_FAILURE);
}
if (!parallel && !parallel_test)
return;
......@@ -573,19 +544,22 @@ ConfigFile::checkPass([[maybe_unused]] WarningConsolidation &warnings) const
}
catch (const invalid_argument&)
{
cerr << "ERROR (node " << follower_node.first << "): the port must be an integer." << endl;
cerr << "ERROR (node " << follower_node.first << "): the port must be an integer."
<< endl;
exit(EXIT_FAILURE);
}
if (follower_node.second.computerName == "localhost") // We are working locally
{
if (!follower_node.second.remoteDrive.empty())
{
cerr << "ERROR (node " << follower_node.first << "): the RemoteDrive option may not be passed for a local node." << endl;
cerr << "ERROR (node " << follower_node.first
<< "): the RemoteDrive option may not be passed for a local node." << endl;
exit(EXIT_FAILURE);
}
if (!follower_node.second.remoteDirectory.empty())
{
cerr << "ERROR (node " << follower_node.first << "): the RemoteDirectory option may not be passed for a local node." << endl;
cerr << "ERROR (node " << follower_node.first
<< "): the RemoteDirectory option may not be passed for a local node." << endl;
exit(EXIT_FAILURE);
}
}
......@@ -593,19 +567,26 @@ ConfigFile::checkPass([[maybe_unused]] WarningConsolidation &warnings) const
{
if (follower_node.second.userName.empty())
{
cerr << "ERROR (node " << follower_node.first << "): the UserName option must be passed for every remote node." << endl;
cerr << "ERROR (node " << follower_node.first
<< "): the UserName option must be passed for every remote node." << endl;
exit(EXIT_FAILURE);
}
if (follower_node.second.operatingSystem == "windows")
{
if (follower_node.second.password.empty())
{
cerr << "ERROR (node " << follower_node.first << "): the Password option must be passed under Windows for every remote node." << endl;
cerr << "ERROR (node " << follower_node.first
<< "): the Password option must be passed under Windows for every remote "
"node."
<< endl;
exit(EXIT_FAILURE);
}
if (follower_node.second.remoteDrive.empty())
{
cerr << "ERROR (node " << follower_node.first << "): the RemoteDrive option must be passed under Windows for every remote node." << endl;
cerr << "ERROR (node " << follower_node.first
<< "): the RemoteDrive option must be passed under Windows for every remote "
"node."
<< endl;
exit(EXIT_FAILURE);
}
}
......@@ -614,19 +595,26 @@ ConfigFile::checkPass([[maybe_unused]] WarningConsolidation &warnings) const
{
if (follower_node.second.password.empty())
{
cerr << "ERROR (node " << follower_node.first << "): the Password option must be passed under Windows for every remote node." << endl;
cerr << "ERROR (node " << follower_node.first
<< "): the Password option must be passed under Windows for every remote "
"node."
<< endl;
exit(EXIT_FAILURE);
}
if (follower_node.second.remoteDrive.empty())
{
cerr << "ERROR (node " << follower_node.first << "): the RemoteDrive option must be passed under Windows for every remote node." << endl;
cerr << "ERROR (node " << follower_node.first
<< "): the RemoteDrive option must be passed under Windows for every remote "
"node."
<< endl;
exit(EXIT_FAILURE);
}
}
#endif
if (follower_node.second.remoteDirectory.empty())
{
cerr << "ERROR (node " << follower_node.first << "): the RemoteDirectory must be specified for every remote node." << endl;
cerr << "ERROR (node " << follower_node.first
<< "): the RemoteDirectory must be specified for every remote node." << endl;
exit(EXIT_FAILURE);
}
}
......@@ -641,7 +629,8 @@ ConfigFile::checkPass([[maybe_unused]] WarningConsolidation &warnings) const
if (!cluster_name.empty() && !clusters.contains(cluster_name))
{
cerr << "ERROR: Cluster Name " << cluster_name << " was not found in the config file." << endl;
cerr << "ERROR: Cluster Name " << cluster_name << " was not found in the config file."
<< endl;
exit(EXIT_FAILURE);
}
......@@ -649,14 +638,21 @@ ConfigFile::checkPass([[maybe_unused]] WarningConsolidation &warnings) const
for (const auto& itmn : cluster.second.member_nodes)
if (!follower_nodes.contains(itmn.first))
{
cerr << "Error: node " << itmn.first << " specified in cluster " << cluster.first << " was not found" << endl;
cerr << "Error: node " << itmn.first << " specified in cluster " << cluster.first
<< " was not found" << endl;
exit(EXIT_FAILURE);
}
}
void
ConfigFile::transformPass()
Configuration::transformPass()
{
/* If the user did not specify the GlobalInitFile option, use global_init.m in configuration
directory if it exists */
if (auto default_global_init_file = findConfigFile("global_init.m");
global_init_file.empty() && !default_global_init_file.empty())
global_init_file = default_global_init_file.string();
if (!parallel && !parallel_test)
return;
......@@ -670,21 +666,21 @@ ConfigFile::transformPass()
}
#endif
auto cluster_it = cluster_name.empty() ? clusters.find(firstClusterName) : clusters.find(cluster_name);
auto& cluster = cluster_name.empty() ? clusters.at(firstClusterName) : clusters.at(cluster_name);
double weight_denominator {0.0};
for (const auto &it : cluster_it->second.member_nodes)
weight_denominator += it.second;
for (const auto& [name, weight] : cluster.member_nodes)
weight_denominator += weight;
for (auto &member_node : cluster_it->second.member_nodes)
member_node.second /= weight_denominator;
for (auto& [name, weight] : cluster.member_nodes)
weight /= weight_denominator;
}
vector<filesystem::path>
ConfigFile::getIncludePaths() const
Configuration::getIncludePaths() const
{
vector<filesystem::path> include_paths;
for (auto path : paths)
for (const auto& path : paths)
for (const auto& mapit : path.get_paths())
for (const auto& vecit : mapit.second)
include_paths.emplace_back(vecit);
......@@ -692,64 +688,51 @@ ConfigFile::getIncludePaths() const
}
void
ConfigFile::writeHooks(ostream &output) const
Configuration::writeHooks(ostream& output) const
{
for (auto hook : hooks)
for (const auto &mapit : hook.get_hooks())
output << "options_." << mapit.first << " = '" << mapit.second << "';" << endl;
if (!global_init_file.empty())
output << "options_.global_init_file = '" << global_init_file << "';" << endl;
}
void
ConfigFile::writeCluster(ostream &output) const
Configuration::writeCluster(ostream& output) const
{
if (!parallel && !parallel_test)
return;
auto cluster_it = cluster_name.empty() ? clusters.find(firstClusterName) : clusters.find(cluster_name);
const auto& cluster
= cluster_name.empty() ? clusters.at(firstClusterName) : clusters.at(cluster_name);
for (int i{1};
const auto &follower_node : follower_nodes)
for (int i {1}; const auto& [name, node] : follower_nodes)
{
bool follower_node_in_member_nodes = false;
for (const auto &itmn : cluster_it->second.member_nodes)
if (follower_node.first == itmn.first)
follower_node_in_member_nodes = true;
if (!follower_node_in_member_nodes)
continue;
if (!cluster.member_nodes.contains(name))
continue; // Skip nodes not in the selected cluster
output << "options_.parallel";
if (i > 1)
output << "(" << i << ")";
i++;
output << " = struct('Local', ";
if (follower_node.second.computerName == "localhost")
output << "1, ";
else
output << "0, ";
output << "'ComputerName', '" << follower_node.second.computerName << "', "
<< "'Port', '" << follower_node.second.port << "', "
<< "'CPUnbr', [" << follower_node.second.minCpuNbr << ":" << follower_node.second.maxCpuNbr << "], "
<< "'UserName', '" << follower_node.second.userName << "', "
<< "'Password', '" << follower_node.second.password << "', "
<< "'RemoteDrive', '" << follower_node.second.remoteDrive << "', "
<< "'RemoteDirectory', '" << follower_node.second.remoteDirectory << "', "
output << " = struct('Local', " << noboolalpha << (node.computerName == "localhost") << ", "
<< "'ComputerName', '" << node.computerName << "', "
<< "'Port', '" << node.port << "', "
<< "'CPUnbr', [" << node.minCpuNbr << ":" << node.maxCpuNbr << "], "
<< "'UserName', '" << node.userName << "', "
<< "'Password', '" << node.password << "', "
<< "'RemoteDrive', '" << node.remoteDrive << "', "
<< "'RemoteDirectory', '" << node.remoteDirectory
<< "', "
// The following should be switched back to “ProgramPath” once we move to Dragonfly
<< "'DynarePath', '" << follower_node.second.programPath << "', "
<< "'ProgramConfig', '" << follower_node.second.programConfig << "', "
<< "'MatlabOctavePath', '" << follower_node.second.matlabOctavePath << "', "
<< "'OperatingSystem', '" << follower_node.second.operatingSystem << "', "
<< "'NodeWeight', '" << cluster_it->second.member_nodes.at(follower_node.first) << "', "
<< "'NumberOfThreadsPerJob', " << follower_node.second.numberOfThreadsPerJob << ", ";
if (follower_node.second.singleCompThread)
output << "'SingleCompThread', 'true');" << endl;
else
output << "'SingleCompThread', 'false');" << endl;
<< "'DynarePath', '" << node.programPath << "', "
<< "'ProgramConfig', '" << node.programConfig << "', "
<< "'MatlabOctavePath', '" << node.matlabOctavePath << "', "
<< "'OperatingSystem', '" << node.operatingSystem << "', "
<< "'NodeWeight', '" << cluster.member_nodes.at(name) << "', "
<< "'NumberOfThreadsPerJob', " << node.numberOfThreadsPerJob << ", "
<< "'SingleCompThread', '" << boolalpha << node.singleCompThread << "');" << endl;
}
// Default values for the following two are both in DynareMain.cc and matlab/default_option_values.m
// Default values for the following two are both in DynareMain.cc and
// matlab/default_option_values.m
if (parallel_follower_open_mode)
output << "options_.parallel_info.leaveSlaveOpen = 1;" << endl;
if (!parallel_use_psexec)
......@@ -759,14 +742,18 @@ ConfigFile::writeCluster(ostream &output) const
output << "InitializeComputationalEnvironment();" << endl;
if (parallel_test)
output << "ErrorCode = AnalyseComputationalEnvironment(options_.parallel, options_.parallel_info);" << endl
<< "disp(['AnalyseComputationalEnvironment returned with Error Code: ' num2str(ErrorCode)]);" << endl
output
<< "ErrorCode = AnalyseComputationalEnvironment(options_.parallel, options_.parallel_info);"
<< endl
<< "disp(['AnalyseComputationalEnvironment returned with Error Code: ' "
"num2str(ErrorCode)]);"
<< endl
<< "diary off;" << endl
<< "return;" << endl;
}
void
ConfigFile::writeEndParallel(ostream &output) const
Configuration::writeEndParallel(ostream& output) const
{
if ((!parallel && !parallel_test) || !parallel_follower_open_mode)
return;
......@@ -775,3 +762,46 @@ ConfigFile::writeEndParallel(ostream &output) const
<< " closeSlave(options_.parallel,options_.parallel_info.RemoteTmpFolder);" << endl
<< "end" << endl;
}
filesystem::path
Configuration::findConfigFile(const string& filename)
{
#ifdef _WIN32
array<wchar_t, MAX_PATH + 1> appdata;
if (SHGetFolderPathW(nullptr, CSIDL_APPDATA | CSIDL_FLAG_DONT_VERIFY, nullptr, SHGFP_TYPE_CURRENT,
appdata.data())
== S_OK)
{
filesystem::path candidate {filesystem::path {appdata.data()} / "dynare" / filename};
if (exists(candidate))
return candidate;
}
#else
filesystem::path xdg_config_home;
if (auto xdg_config_home_env = getenv("XDG_CONFIG_HOME"); xdg_config_home_env)
xdg_config_home = xdg_config_home_env;
if (auto home = getenv("HOME"); xdg_config_home.empty() && home)
xdg_config_home = filesystem::path {home} / ".config";
if (!xdg_config_home.empty())
{
filesystem::path candidate {xdg_config_home / "dynare" / filename};
if (exists(candidate))
return candidate;
}
string xdg_config_dirs;
if (auto xdg_config_dirs_env = getenv("XDG_CONFIG_DIRS"); xdg_config_dirs_env)
xdg_config_dirs = xdg_config_dirs_env;
if (xdg_config_dirs.empty())
xdg_config_dirs = "/etc/xdg";
for (const auto& dir : DataTree::strsplit(xdg_config_dirs, ':'))
{
filesystem::path candidate {filesystem::path {dir} / "dynare" / filename};
if (exists(candidate))
return candidate;
}
#endif
return {};
}
......@@ -17,57 +17,49 @@
* along with Dynare. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef _CONFIG_FILE_HH
#define _CONFIG_FILE_HH
#ifndef CONFIGURATION_HH
#define CONFIGURATION_HH
#include <filesystem>
#include <map>
#include <vector>
#include <filesystem>
#include "WarningConsolidation.hh"
using namespace std;
using member_nodes_t = map<string, double>;
class Hook
/* The abstract representation of the configuration.
Merges information from the command-line and from the configuration file. */
class Configuration
{
public:
explicit Hook(string global_init_file_arg);
Configuration(bool parallel_arg, bool parallel_test_arg, bool parallel_follower_open_mode_arg,
bool parallel_use_psexec_arg, string cluster_name);
private:
map<string, string> hooks;
public:
map<string, string>
get_hooks() const
{
return hooks;
};
};
using member_nodes_t = map<string, double>;
class Path
{
public:
explicit Path(vector<string> includepath_arg);
private:
map<string, vector<string>> paths;
public:
map<string, vector<string>>
[[nodiscard]] map<string, vector<string>>
get_paths() const
{
return paths;
};
}
private:
map<string, vector<string>> paths;
};
class FollowerNode
struct FollowerNode
{
friend class ConfigFile;
public:
FollowerNode(string computerName_arg, string port_arg, int minCpuNbr_arg, int maxCpuNbr_arg, string userName_arg,
string password_arg, string remoteDrive_arg, string remoteDirectory_arg,
string programPath_arg, string programConfig_arg, string matlabOctavePath_arg, bool singleCompThread_arg,
FollowerNode(string computerName_arg, string port_arg, int minCpuNbr_arg, int maxCpuNbr_arg,
string userName_arg, string password_arg, string remoteDrive_arg,
string remoteDirectory_arg, string programPath_arg, string programConfig_arg,
string matlabOctavePath_arg, bool singleCompThread_arg,
int numberOfThreadsPerJob_arg, string operatingSystem_arg);
protected:
const string computerName, port;
int minCpuNbr, maxCpuNbr;
const string userName, password;
......@@ -78,55 +70,51 @@ protected:
const string operatingSystem;
};
class Cluster
struct Cluster
{
friend class ConfigFile;
public:
explicit Cluster(member_nodes_t member_nodes_arg);
protected:
member_nodes_t member_nodes;
};
//! The abstract representation of a "config" file
class ConfigFile
{
public:
ConfigFile(bool parallel_arg, bool parallel_test_arg, bool parallel_follower_open_mode_arg,
bool parallel_use_psexec_arg, string cluster_name);
private:
const bool parallel, parallel_test, parallel_follower_open_mode, parallel_use_psexec;
const string cluster_name;
string firstClusterName;
//! Hooks
vector<Hook> hooks;
string global_init_file;
//! Paths
vector<Path> paths;
//! Cluster Table
map<string, Cluster> clusters;
//! Node Map
map<string, FollowerNode> follower_nodes;
//! Add Hooks
void addHooksConfFileElement(string global_init_file);
//! Add Paths
void addPathsConfFileElement(vector<string> includepath);
//! Add a FollowerNode or a Cluster object
void addParallelConfFileElement(bool inNode, bool inCluster, const member_nodes_t &member_nodes, const string &name,
const string &computerName, const string &port, int minCpuNbr, int maxCpuNbr,
const string &userName, const string &password, const string &remoteDrive,
const string &remoteDirectory, const string &programPath, const string &programConfig,
const string &matlabOctavePath, bool singleCompThread, int numberOfThreadsPerJob,
const string &operatingSystem);
void addParallelConfFileElement(bool inNode, bool inCluster, const member_nodes_t& member_nodes,
const string& name, const string& computerName,
const string& port, int minCpuNbr, int maxCpuNbr,
const string& userName, const string& password,
const string& remoteDrive, const string& remoteDirectory,
const string& programPath, const string& programConfig,
const string& matlabOctavePath, bool singleCompThread,
int numberOfThreadsPerJob, const string& operatingSystem);
/* Given a filename (e.g. dynare.ini), looks for it in the configuration directory:
– if under Linux or macOS, look into the “dynare” subdirectory of the XDG
configuration directories (following the default values and the precedence order specified in
the XDG specification)
– if under Windows, look into %APPDATA%\dynare\
The returned path will be empty if the file is not found. */
[[nodiscard]] static filesystem::path findConfigFile(const string& filename);
public:
//! Parse config file
void getConfigFileInfo(const filesystem::path &parallel_config_file);
void getConfigFileInfo(const filesystem::path& conffile_option, WarningConsolidation& warnings);
//! Check Pass
void checkPass(WarningConsolidation& warnings) const;
//! Check Pass
void transformPass();
//! Get Path Info
vector<filesystem::path> getIncludePaths() const;
[[nodiscard]] vector<filesystem::path> getIncludePaths() const;
//! Write any hooks
void writeHooks(ostream& output) const;
//! Create options_.parallel structure, write options
......@@ -135,4 +123,4 @@ public:
void writeEndParallel(ostream& output) const;
};
#endif // ! CONFIG_FILE_HH
#endif
/*
* Copyright © 2003-2023 Dynare Team
* Copyright © 2003-2025 Dynare Team
*
* This file is part of Dynare.
*
......@@ -17,13 +17,14 @@
* along with Dynare. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <cassert>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <cassert>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <iterator>
#include <ranges>
#include "DataTree.hh"
......@@ -46,13 +47,13 @@ DataTree::initConstants()
Pi = AddNonNegativeConstant("3.141592653589793");
}
DataTree::DataTree(SymbolTable &symbol_table_arg,
NumericalConstants &num_constants_arg,
DataTree::DataTree(SymbolTable& symbol_table_arg, NumericalConstants& num_constants_arg,
ExternalFunctionsTable& external_functions_table_arg,
bool is_dynamic_arg) :
HeterogeneityTable& heterogeneity_table_arg, bool is_dynamic_arg) :
symbol_table {symbol_table_arg},
num_constants {num_constants_arg},
external_functions_table {external_functions_table_arg},
heterogeneity_table {heterogeneity_table_arg},
is_dynamic {is_dynamic_arg}
{
initConstants();
......@@ -62,19 +63,21 @@ DataTree::DataTree(const DataTree &d) :
symbol_table {d.symbol_table},
num_constants {d.num_constants},
external_functions_table {d.external_functions_table},
heterogeneity_table {d.heterogeneity_table},
is_dynamic {d.is_dynamic},
local_variables_vector {d.local_variables_vector}
{
// Constants must be initialized first because they are used in some Add* methods
initConstants();
// See commment in DataTree::operator=() for the rationale
for (int symb_id : d.local_variables_vector)
local_variables_table[symb_id] = d.local_variables_table.at(symb_id)->clone(*this);
for (const auto& it : d.node_list)
it->clone(*this);
assert(node_list.size() == d.node_list.size());
for (const auto &[symb_id, value] : d.local_variables_table)
local_variables_table[symb_id] = value->clone(*this);
}
DataTree&
......@@ -83,6 +86,7 @@ DataTree::operator=(const DataTree &d)
assert(&symbol_table == &d.symbol_table);
assert(&num_constants == &d.num_constants);
assert(&external_functions_table == &d.external_functions_table);
assert(&heterogeneity_table == &d.heterogeneity_table);
assert(is_dynamic == d.is_dynamic);
num_const_node_map.clear();
......@@ -125,8 +129,7 @@ DataTree::AddNonNegativeConstant(const string &value)
{
int id = num_constants.AddNonNegativeConstant(value);
if (auto it = num_const_node_map.find(id);
it != num_const_node_map.end())
if (auto it = num_const_node_map.find(id); it != num_const_node_map.end())
return it->second;
auto sp = make_unique<NumConstNode>(*this, node_list.size(), id);
......@@ -145,8 +148,7 @@ DataTree::AddVariable(int symb_id, int lag)
exit(EXIT_FAILURE);
}
if (auto it = variable_node_map.find({ symb_id, lag });
it != variable_node_map.end())
if (auto it = variable_node_map.find({symb_id, lag}); it != variable_node_map.end())
return it->second;
auto sp = make_unique<VariableNode>(*this, node_list.size(), symb_id, lag);
......@@ -162,7 +164,8 @@ DataTree::getVariable(int symb_id, int lag) const
auto it = variable_node_map.find({symb_id, lag});
if (it == variable_node_map.end())
{
cerr << "DataTree::getVariable: unknown variable node for symb_id=" << symb_id << " and lag=" << lag << endl;
cerr << "DataTree::getVariable: unknown variable node for symb_id=" << symb_id
<< " and lag=" << lag << endl;
exit(EXIT_FAILURE);
}
return it->second;
......@@ -208,7 +211,7 @@ DataTree::AddPlus(expr_t iArg1, expr_t iArg2)
// To treat commutativity of "+"
// Nodes iArg1 and iArg2 are sorted by index
if (iArg1->idx > iArg2->idx && !no_commutativity)
if (iArg1->idx > iArg2->idx && !no_commutativity) // NOLINT(clang-analyzer-core.NullDereference)
swap(iArg1, iArg2);
return AddBinaryOp(iArg1, BinaryOpcode::plus, iArg2);
}
......@@ -250,8 +253,7 @@ DataTree::AddUMinus(expr_t iArg1)
return Zero;
// Simplify -(-x) in x
if (auto uarg = dynamic_cast<UnaryOpNode *>(iArg1);
uarg && uarg->op_code == UnaryOpcode::uminus)
if (auto uarg = dynamic_cast<UnaryOpNode*>(iArg1); uarg && uarg->op_code == UnaryOpcode::uminus)
return uarg->arg;
return AddUnaryOp(UnaryOpcode::uminus, iArg1);
......@@ -287,7 +289,7 @@ DataTree::AddTimes(expr_t iArg1, expr_t iArg2)
// To treat commutativity of "*"
// Nodes iArg1 and iArg2 are sorted by index
if (iArg1->idx > iArg2->idx && !no_commutativity)
if (iArg1->idx > iArg2->idx && !no_commutativity) // NOLINT(clang-analyzer-core.NullDereference)
swap(iArg1, iArg2);
return AddBinaryOp(iArg1, BinaryOpcode::times, iArg2);
}
......@@ -668,7 +670,8 @@ DataTree::AddSteadyStateParamDeriv(expr_t iArg1, int param_symb_id)
expr_t
DataTree::AddSteadyStateParam2ndDeriv(expr_t iArg1, int param1_symb_id, int param2_symb_id)
{
return AddUnaryOp(UnaryOpcode::steadyStateParam2ndDeriv, iArg1, 0, param1_symb_id, param2_symb_id);
return AddUnaryOp(UnaryOpcode::steadyStateParam2ndDeriv, iArg1, 0, param1_symb_id,
param2_symb_id);
}
expr_t
......@@ -680,8 +683,7 @@ DataTree::AddExpectation(int iArg1, expr_t iArg2)
expr_t
DataTree::AddVarExpectation(const string& model_name)
{
if (auto it = var_expectation_node_map.find(model_name);
it != var_expectation_node_map.end())
if (auto it = var_expectation_node_map.find(model_name); it != var_expectation_node_map.end())
return it->second;
auto sp = make_unique<VarExpectationNode>(*this, node_list.size(), model_name);
......@@ -694,8 +696,7 @@ DataTree::AddVarExpectation(const string &model_name)
expr_t
DataTree::AddPacExpectation(const string& model_name)
{
if (auto it = pac_expectation_node_map.find(model_name);
it != pac_expectation_node_map.end())
if (auto it = pac_expectation_node_map.find(model_name); it != pac_expectation_node_map.end())
return it->second;
auto sp = make_unique<PacExpectationNode>(*this, node_list.size(), model_name);
......@@ -757,43 +758,56 @@ DataTree::AddExternalFunction(int symb_id, const vector<expr_t> &arguments)
}
expr_t
DataTree::AddFirstDerivExternalFunction(int top_level_symb_id, const vector<expr_t> &arguments, int input_index)
DataTree::AddFirstDerivExternalFunction(int top_level_symb_id, const vector<expr_t>& arguments,
int input_index)
{
assert(symbol_table.getType(top_level_symb_id) == SymbolType::externalFunction);
if (auto it = first_deriv_external_function_node_map.find({ arguments, input_index, top_level_symb_id });
if (auto it
= first_deriv_external_function_node_map.find({arguments, input_index, top_level_symb_id});
it != first_deriv_external_function_node_map.end())
return it->second;
auto sp = make_unique<FirstDerivExternalFunctionNode>(*this, node_list.size(), top_level_symb_id, arguments, input_index);
auto sp = make_unique<FirstDerivExternalFunctionNode>(*this, node_list.size(), top_level_symb_id,
arguments, input_index);
auto p = sp.get();
node_list.push_back(move(sp));
first_deriv_external_function_node_map.try_emplace({ arguments, input_index, top_level_symb_id }, p);
first_deriv_external_function_node_map.try_emplace({arguments, input_index, top_level_symb_id},
p);
return p;
}
expr_t
DataTree::AddSecondDerivExternalFunction(int top_level_symb_id, const vector<expr_t> &arguments, int input_index1, int input_index2)
DataTree::AddSecondDerivExternalFunction(int top_level_symb_id, const vector<expr_t>& arguments,
int input_index1, int input_index2)
{
assert(symbol_table.getType(top_level_symb_id) == SymbolType::externalFunction);
if (auto it = second_deriv_external_function_node_map.find({ arguments, input_index1, input_index2,
top_level_symb_id });
if (auto it = second_deriv_external_function_node_map.find(
{arguments, input_index1, input_index2, top_level_symb_id});
it != second_deriv_external_function_node_map.end())
return it->second;
auto sp = make_unique<SecondDerivExternalFunctionNode>(*this, node_list.size(), top_level_symb_id, arguments, input_index1, input_index2);
auto sp = make_unique<SecondDerivExternalFunctionNode>(*this, node_list.size(), top_level_symb_id,
arguments, input_index1, input_index2);
auto p = sp.get();
node_list.push_back(move(sp));
second_deriv_external_function_node_map.try_emplace({ arguments, input_index1, input_index2, top_level_symb_id }, p);
second_deriv_external_function_node_map.try_emplace(
{arguments, input_index1, input_index2, top_level_symb_id}, p);
return p;
}
expr_t
DataTree::AddSum(expr_t arg)
{
return AddUnaryOp(UnaryOpcode::sum, arg);
}
bool
DataTree::isSymbolUsed(int symb_id) const
{
for (const auto &[symb_lag, expr] : variable_node_map)
if (symb_lag.first == symb_id)
if (ranges::any_of(views::keys(variable_node_map),
[=](const auto& symb_lag) { return symb_lag.first == symb_id; }))
return true;
if (local_variables_table.contains(symb_id))
......@@ -840,18 +854,18 @@ DataTree::addAllParamDerivId([[maybe_unused]] set<int> &deriv_id_set)
bool
DataTree::isUnaryOpUsed(UnaryOpcode opcode) const
{
return any_of(unary_op_node_map.begin(), unary_op_node_map.end(),
[=](const auto &it) { return get<1>(it.first) == opcode; });
return ranges::any_of(views::keys(unary_op_node_map),
[=](const auto& key) { return get<1>(key) == opcode; });
}
bool
DataTree::isUnaryOpUsedOnType(SymbolType type, UnaryOpcode opcode) const
{
set<int> var;
for (const auto &it : unary_op_node_map)
if (get<1>(it.first) == opcode)
for (const auto& [key, value] : unary_op_node_map)
if (get<1>(key) == opcode)
{
it.second->collectVariables(type, var);
value->collectVariables(type, var);
if (!var.empty())
return true;
}
......@@ -861,18 +875,18 @@ DataTree::isUnaryOpUsedOnType(SymbolType type, UnaryOpcode opcode) const
bool
DataTree::isBinaryOpUsed(BinaryOpcode opcode) const
{
return any_of(binary_op_node_map.begin(), binary_op_node_map.end(),
[=](const auto &it) { return get<2>(it.first) == opcode; });
return ranges::any_of(views::keys(binary_op_node_map),
[=](const auto& key) { return get<2>(key) == opcode; });
}
bool
DataTree::isBinaryOpUsedOnType(SymbolType type, BinaryOpcode opcode) const
{
set<int> var;
for (const auto &it : binary_op_node_map)
if (get<2>(it.first) == opcode)
for (const auto& [key, value] : binary_op_node_map)
if (get<2>(key) == opcode)
{
it.second->collectVariables(type, var);
value->collectVariables(type, var);
if (!var.empty())
return true;
}
......@@ -897,7 +911,9 @@ DataTree::writeCHelpersDefinition(ostream &output) const
<< "inline double" << endl
<< "getPowerDeriv(double x, double p, int k)" << endl
<< "{" << endl
<< " if (fabs(x) < " << power_deriv_near_zero << " && p > 0 && k > p && fabs(p-nearbyint(p)) < " << power_deriv_near_zero << ')' << endl
<< " if (fabs(x) < " << power_deriv_near_zero
<< " && p >= 0 && k > p && fabs(p-nearbyint(p)) < " << power_deriv_near_zero << ')'
<< endl
<< " return 0.0;" << endl
<< " else" << endl
<< " {" << endl
......@@ -932,8 +948,7 @@ DataTree::strsplit(string_view str, char delim)
while (true)
{
size_t idx {str.find(delim)};
if (auto sub {str.substr(0, idx)};
!sub.empty())
if (auto sub {str.substr(0, idx)}; !sub.empty())
result.emplace_back(sub);
if (idx == string_view::npos)
break;
......@@ -943,10 +958,10 @@ DataTree::strsplit(string_view str, char delim)
}
filesystem::path
DataTree::packageDir(string_view package)
DataTree::packageDir(const string_view& package)
{
filesystem::path d;
for (const auto &it : strsplit(move(package), '.'))
for (const auto& it : strsplit(package, '.'))
d /= "+" + it;
return d;
}
......@@ -956,7 +971,7 @@ DataTree::writeToFileIfModified(stringstream &new_contents, const filesystem::pa
{
ifstream old_file {filename, ios::in | ios::binary};
if (old_file.is_open()
&& equal(istreambuf_iterator<char>{old_file}, istreambuf_iterator<char>{},
&& ranges::equal(istreambuf_iterator<char> {old_file}, istreambuf_iterator<char> {},
istreambuf_iterator<char> {new_contents}, istreambuf_iterator<char> {}))
return;
old_file.close();
......@@ -969,7 +984,7 @@ DataTree::writeToFileIfModified(stringstream &new_contents, const filesystem::pa
cerr << "ERROR: Can't open file " << filename.string() << " for writing" << endl;
exit(EXIT_FAILURE);
}
copy(istreambuf_iterator<char>{new_contents}, istreambuf_iterator<char>{},
ranges::copy(istreambuf_iterator<char> {new_contents}, istreambuf_iterator<char> {},
ostreambuf_iterator<char> {new_file});
new_file.close();
}
/*
* Copyright © 2003-2023 Dynare Team
* Copyright © 2003-2024 Dynare Team
*
* This file is part of Dynare.
*
......@@ -17,25 +17,26 @@
* along with Dynare. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef _DATATREE_HH
#define _DATATREE_HH
#ifndef DATA_TREE_HH
#define DATA_TREE_HH
#include <string>
#include <map>
#include <vector>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <utility>
#include <memory>
#include <filesystem>
#include <iomanip>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "SymbolTable.hh"
#include "NumericalConstants.hh"
#include "ExternalFunctionsTable.hh"
#include "ExprNode.hh"
#include "ExternalFunctionsTable.hh"
#include "HeterogeneityTable.hh"
#include "NumericalConstants.hh"
#include "SubModel.hh"
#include "SymbolTable.hh"
using namespace std;
......@@ -48,7 +49,11 @@ public:
NumericalConstants& num_constants;
//! A reference to the external functions table
ExternalFunctionsTable& external_functions_table;
// A reference to the heterogeneity table
HeterogeneityTable& heterogeneity_table;
//! Is it possible to use leads/lags on variable nodes?
/* NB: This data member cannot be replaced by a virtual method, because this information is needed
in AddVariable(), which itself can be called from the copy constructor. */
const bool is_dynamic;
private:
......@@ -60,8 +65,10 @@ private:
using variable_node_map_t = map<pair<int, int>, VariableNode*>;
variable_node_map_t variable_node_map;
//! (arg, op_code, arg_exp_info_set, param1_symb_id, param2_symb_id, adl_param_name, adl_lags) -> UnaryOpNode
using unary_op_node_map_t = map<tuple<expr_t, UnaryOpcode, int, int, int, string, vector<int>>, UnaryOpNode *>;
//! (arg, op_code, arg_exp_info_set, param1_symb_id, param2_symb_id, adl_param_name, adl_lags) ->
//! UnaryOpNode
using unary_op_node_map_t
= map<tuple<expr_t, UnaryOpcode, int, int, int, string, vector<int>>, UnaryOpNode*>;
unary_op_node_map_t unary_op_node_map;
//! ( arg1, arg2, opCode, order of Power Derivative) -> BinaryOpNode
......@@ -89,11 +96,13 @@ private:
pac_target_nonstationary_node_map_t pac_target_nonstationary_node_map;
// (arguments, deriv_idx, symb_id) -> FirstDerivExternalFunctionNode
using first_deriv_external_function_node_map_t = map<tuple<vector<expr_t>, int, int>, FirstDerivExternalFunctionNode *>;
using first_deriv_external_function_node_map_t
= map<tuple<vector<expr_t>, int, int>, FirstDerivExternalFunctionNode*>;
first_deriv_external_function_node_map_t first_deriv_external_function_node_map;
// (arguments, deriv_idx1, deriv_idx2, symb_id) -> SecondDerivExternalFunctionNode
using second_deriv_external_function_node_map_t = map<tuple<vector<expr_t>, int, int, int>, SecondDerivExternalFunctionNode *>;
using second_deriv_external_function_node_map_t
= map<tuple<vector<expr_t>, int, int, int>, SecondDerivExternalFunctionNode*>;
second_deriv_external_function_node_map_t second_deriv_external_function_node_map;
// Flag to disable simplifications related to commutativity of addition and multiplication
......@@ -102,11 +111,12 @@ private:
protected:
//! Stores local variables value (maps symbol ID to corresponding node)
map<int, expr_t> local_variables_table;
//! Stores the order of appearance of local variables in the model block. Needed following change in #563
//! Stores the order of appearance of local variables in the model block. Needed following change
//! in #563
vector<int> local_variables_vector;
//! Internal implementation of ParamUsedWithLeadLag()
bool ParamUsedWithLeadLagInternal() const;
[[nodiscard]] bool ParamUsedWithLeadLagInternal() const;
/* Writes the contents of “new_contents” to the file “filename”. However, if
the file already exists and would not be modified by this operation, then do
......@@ -119,18 +129,21 @@ private:
//! The list of nodes
vector<unique_ptr<ExprNode>> node_list;
inline expr_t AddUnaryOp(UnaryOpcode op_code, expr_t arg, int arg_exp_info_set = 0, int param1_symb_id = 0, int param2_symb_id = 0, const string &adl_param_name = "", const vector<int> &adl_lags = vector<int>());
inline expr_t AddBinaryOp(expr_t arg1, BinaryOpcode op_code, expr_t arg2, int powerDerivOrder = 0);
inline expr_t AddUnaryOp(UnaryOpcode op_code, expr_t arg, int arg_exp_info_set = 0,
int param1_symb_id = 0, int param2_symb_id = 0,
const string& adl_param_name = "",
const vector<int>& adl_lags = vector<int>());
inline expr_t AddBinaryOp(expr_t arg1, BinaryOpcode op_code, expr_t arg2,
int powerDerivOrder = 0);
inline expr_t AddTrinaryOp(expr_t arg1, TrinaryOpcode op_code, expr_t arg2, expr_t arg3);
//! Initializes the predefined constants, used only from the constructors
void initConstants();
public:
DataTree(SymbolTable &symbol_table_arg,
NumericalConstants &num_constants_arg,
DataTree(SymbolTable& symbol_table_arg, NumericalConstants& num_constants_arg,
ExternalFunctionsTable& external_functions_table_arg,
bool is_static_args = false);
HeterogeneityTable& heterogeneity_table_arg, bool is_dynamic_arg = false);
virtual ~DataTree() = default;
......@@ -159,7 +172,7 @@ public:
//! Gets a variable
/*! Same as AddVariable, except that it fails if the variable node has not
already been created */
VariableNode *getVariable(int symb_id, int lag = 0) const;
[[nodiscard]] VariableNode* getVariable(int symb_id, int lag = 0) const;
//! Adds "arg1+arg2" to model tree
expr_t AddPlus(expr_t iArg1, expr_t iArg2);
//! Adds "arg1-arg2" to model tree
......@@ -261,22 +274,28 @@ public:
//! Adds an external function node
expr_t AddExternalFunction(int symb_id, const vector<expr_t>& arguments);
//! Adds an external function node for the first derivative of an external function
expr_t AddFirstDerivExternalFunction(int top_level_symb_id, const vector<expr_t> &arguments, int input_index);
expr_t AddFirstDerivExternalFunction(int top_level_symb_id, const vector<expr_t>& arguments,
int input_index);
//! Adds an external function node for the second derivative of an external function
expr_t AddSecondDerivExternalFunction(int top_level_symb_id, const vector<expr_t> &arguments, int input_index1, int input_index2);
expr_t AddSecondDerivExternalFunction(int top_level_symb_id, const vector<expr_t>& arguments,
int input_index1, int input_index2);
// Adds "SUM(arg)" to model tree
expr_t AddSum(expr_t arg);
//! Checks if a given symbol is used somewhere in the data tree
bool isSymbolUsed(int symb_id) const;
[[nodiscard]] bool isSymbolUsed(int symb_id) const;
//! Checks if a given unary op is used somewhere in the data tree
bool isUnaryOpUsed(UnaryOpcode opcode) const;
[[nodiscard]] bool isUnaryOpUsed(UnaryOpcode opcode) const;
//! Checks if a given unary op is used somewhere in the data tree on an endogenous variable
bool isUnaryOpUsedOnType(SymbolType type, UnaryOpcode opcode) const;
[[nodiscard]] bool isUnaryOpUsedOnType(SymbolType type, UnaryOpcode opcode) const;
//! Checks if a given binary op is used somewhere in the data tree
bool isBinaryOpUsed(BinaryOpcode opcode) const;
[[nodiscard]] bool isBinaryOpUsed(BinaryOpcode opcode) const;
//! Checks if a given binary op is used somewhere in the data tree on an endogenous variable
bool isBinaryOpUsedOnType(SymbolType type, BinaryOpcode opcode) const;
//! Returns the minimum lag (as a negative number) of the given symbol in the whole data tree (and not only in the equations !!)
[[nodiscard]] bool isBinaryOpUsedOnType(SymbolType type, BinaryOpcode opcode) const;
//! Returns the minimum lag (as a negative number) of the given symbol in the whole data tree (and
//! not only in the equations !!)
/*! Returns 0 if the symbol is not used */
int minLagForSymbol(int symb_id) const;
[[nodiscard]] int minLagForSymbol(int symb_id) const;
/* Writes definitions of C function helpers (getPowerDeriv(), sign()) as
inline functions */
void writeCHelpersDefinition(ostream& output) const;
......@@ -298,17 +317,17 @@ public:
};
// Returns the derivation ID, or throws an exception if the derivation ID does not exist
virtual int getDerivID(int symb_id, int lag) const noexcept(false);
[[nodiscard]] virtual int getDerivID(int symb_id, int lag) const noexcept(false);
// Get the type corresponding to a derivation ID
virtual SymbolType getTypeByDerivID(int deriv_id) const noexcept(false);
[[nodiscard]] virtual SymbolType getTypeByDerivID(int deriv_id) const noexcept(false);
// Get the lag corresponding to a derivation ID
virtual int getLagByDerivID(int deriv_id) const noexcept(false);
[[nodiscard]] virtual int getLagByDerivID(int deriv_id) const noexcept(false);
// Get the symbol ID corresponding to a derivation ID
virtual int getSymbIDByDerivID(int deriv_id) const noexcept(false);
[[nodiscard]] virtual int getSymbIDByDerivID(int deriv_id) const noexcept(false);
// Get the type-specific ID corresponding to a derivation ID
virtual int getTypeSpecificIDByDerivID(int deriv_id) const;
[[nodiscard]] virtual int getTypeSpecificIDByDerivID(int deriv_id) const;
// Get the symbol name corresponding to a derivation ID
string
[[nodiscard]] string
getNameByDerivID(int deriv_id) const
{
return symbol_table.getName(getSymbIDByDerivID(deriv_id));
......@@ -317,7 +336,7 @@ public:
/* Returns the column of the Jacobian associated to a derivation ID.
The “sparse” argument selects between the legacy representation and the
sparse representation. */
virtual int
[[nodiscard]] virtual int
getJacobianCol([[maybe_unused]] int deriv_id, [[maybe_unused]] bool sparse) const
{
throw UnknownDerivIDException();
......@@ -326,7 +345,7 @@ public:
/* Returns the number of columns of the Jacobian
The “sparse” argument selects between the legacy representation and the
sparse representation. */
virtual int
[[nodiscard]] virtual int
getJacobianColsNbr([[maybe_unused]] bool sparse) const
{
throw UnknownDerivIDException();
......@@ -335,27 +354,26 @@ public:
//! Adds to the set all the deriv IDs corresponding to parameters
virtual void addAllParamDerivId(set<int>& deriv_id_set);
//! Returns bool indicating whether DataTree represents a Dynamic Model (returns true in DynamicModel.hh)
virtual bool
isDynamic() const
{
return false;
};
struct UnknownLocalVariableException
{
//! Symbol ID
int id;
};
expr_t
getLocalVariable(int symb_id) const
[[nodiscard]] expr_t
getLocalVariable(int symb_id, int lead_lag) const
{
auto it = local_variables_table.find(symb_id);
if (it == local_variables_table.end())
throw UnknownLocalVariableException {symb_id};
/* In the following, the case without lead/lag is optimized. It makes a difference on models
with many nested model-local variables, see e.g.
https://forum.dynare.org/t/pre-processing-takes-very-long/26865 */
if (lead_lag == 0)
return it->second;
else
return it->second->decreaseLeadsLags(-lead_lag);
}
static void
......@@ -373,7 +391,7 @@ public:
and returns the path to the corresponding filesystem directory.
In practice the package nesting is used for the planner_objective (stored
inside +objective subdir). */
static filesystem::path packageDir(string_view package);
static filesystem::path packageDir(const string_view& package);
};
inline expr_t
......@@ -384,7 +402,7 @@ DataTree::AddPossiblyNegativeConstant(double v)
if (isnan(v))
return NaN;
if (isinf(v))
return (v < 0 ? MinusInfinity : Infinity);
return v < 0 ? MinusInfinity : Infinity;
bool neg = false;
if (v < 0)
......@@ -404,21 +422,23 @@ DataTree::AddPossiblyNegativeConstant(double v)
}
inline expr_t
DataTree::AddUnaryOp(UnaryOpcode op_code, expr_t arg, int arg_exp_info_set, int param1_symb_id, int param2_symb_id, const string &adl_param_name, const vector<int> &adl_lags)
DataTree::AddUnaryOp(UnaryOpcode op_code, expr_t arg, int arg_exp_info_set, int param1_symb_id,
int param2_symb_id, const string& adl_param_name, const vector<int>& adl_lags)
{
// If the node already exists in tree, share it
if (auto it = unary_op_node_map.find({ arg, op_code, arg_exp_info_set, param1_symb_id, param2_symb_id, adl_param_name, adl_lags });
if (auto it = unary_op_node_map.find({arg, op_code, arg_exp_info_set, param1_symb_id,
param2_symb_id, adl_param_name, adl_lags});
it != unary_op_node_map.end())
return it->second;
// Try to reduce to a constant
// Case where arg is a constant and op_code == UnaryOpcode::uminus (i.e. we're adding a negative constant) is skipped
if (auto carg = dynamic_cast<NumConstNode *>(arg);
op_code != UnaryOpcode::uminus || !carg)
// Case where arg is a constant and op_code == UnaryOpcode::uminus (i.e. we're adding a negative
// constant) is skipped
if (auto carg = dynamic_cast<NumConstNode*>(arg); op_code != UnaryOpcode::uminus || !carg)
{
try
{
double argval = arg->eval({});
double argval = arg->eval({}); // NOLINT(clang-analyzer-core.CallAndMessage)
double val = UnaryOpNode::eval_opcode(op_code, argval);
return AddPossiblyNegativeConstant(val);
}
......@@ -427,10 +447,13 @@ DataTree::AddUnaryOp(UnaryOpcode op_code, expr_t arg, int arg_exp_info_set, int
}
}
auto sp = make_unique<UnaryOpNode>(*this, node_list.size(), op_code, arg, arg_exp_info_set, param1_symb_id, param2_symb_id, adl_param_name, adl_lags);
auto sp = make_unique<UnaryOpNode>(*this, node_list.size(), op_code, arg, arg_exp_info_set,
param1_symb_id, param2_symb_id, adl_param_name, adl_lags);
auto p = sp.get();
node_list.push_back(move(sp));
unary_op_node_map.try_emplace({ arg, op_code, arg_exp_info_set, param1_symb_id, param2_symb_id, adl_param_name, adl_lags }, p);
unary_op_node_map.try_emplace(
{arg, op_code, arg_exp_info_set, param1_symb_id, param2_symb_id, adl_param_name, adl_lags},
p);
return p;
}
......@@ -444,8 +467,8 @@ DataTree::AddBinaryOp(expr_t arg1, BinaryOpcode op_code, expr_t arg2, int powerD
// Try to reduce to a constant
try
{
double argval1 = arg1->eval({});
double argval2 = arg2->eval({});
double argval1 = arg1->eval({}); // NOLINT(clang-analyzer-core.CallAndMessage)
double argval2 = arg2->eval({}); // NOLINT(clang-analyzer-core.CallAndMessage)
double val = BinaryOpNode::eval_opcode(argval1, op_code, argval2, powerDerivOrder);
return AddPossiblyNegativeConstant(val);
}
......@@ -453,7 +476,8 @@ DataTree::AddBinaryOp(expr_t arg1, BinaryOpcode op_code, expr_t arg2, int powerD
{
}
auto sp = make_unique<BinaryOpNode>(*this, node_list.size(), arg1, op_code, arg2, powerDerivOrder);
auto sp
= make_unique<BinaryOpNode>(*this, node_list.size(), arg1, op_code, arg2, powerDerivOrder);
auto p = sp.get();
node_list.push_back(move(sp));
binary_op_node_map.try_emplace({arg1, arg2, op_code, powerDerivOrder}, p);
......