From e2d5a83592634f0604d8c86409748cd2ec5906d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Villemot?= <sebastien@dynare.org> Date: Fri, 20 Dec 2019 16:59:30 +0100 Subject: [PATCH] Global reindentation --- src/CodeInterpreter.hh | 304 +++---- src/ComputingTasks.cc | 46 +- src/ComputingTasks.hh | 1 - src/ConfigFile.cc | 38 +- src/DataTree.cc | 42 +- src/DataTree.hh | 9 +- src/DynamicModel.cc | 607 +++++++------ src/DynamicModel.hh | 35 +- src/DynareMain1.cc | 2 +- src/ExprNode.cc | 108 ++- src/ExprNode.hh | 1364 +++++++++++++++--------------- src/ExtendedPreprocessorTypes.hh | 28 +- src/ExternalFunctionsTable.cc | 8 +- src/MinimumFeedbackSet.cc | 4 +- src/ModFile.cc | 50 +- src/ModelEquationBlock.cc | 18 +- src/ModelEquationBlock.hh | 17 +- src/ModelTree.cc | 175 ++-- src/ModelTree.hh | 43 +- src/NumericalInitialization.cc | 14 +- src/ParsingDriver.cc | 58 +- src/ParsingDriver.hh | 42 +- src/Shocks.cc | 12 +- src/SigmaeInitialization.hh | 4 +- src/Statement.cc | 4 +- src/Statement.hh | 4 +- src/StaticModel.cc | 128 +-- src/StaticModel.hh | 10 +- src/SubModel.cc | 37 +- src/SubModel.hh | 1 - src/SymbolList.cc | 4 +- src/SymbolList.hh | 4 +- src/SymbolTable.cc | 46 +- src/SymbolTable.hh | 24 +- src/WarningConsolidation.cc | 2 +- src/WarningConsolidation.hh | 4 +- src/macro/Directives.cc | 12 +- src/macro/Directives.hh | 78 +- src/macro/Driver.cc | 2 +- src/macro/Driver.hh | 48 +- src/macro/Environment.cc | 16 +- src/macro/Environment.hh | 30 +- src/macro/Expressions.cc | 71 +- src/macro/Expressions.hh | 1045 ++++++++++++++++++----- 44 files changed, 2650 insertions(+), 1949 deletions(-) diff --git a/src/CodeInterpreter.hh b/src/CodeInterpreter.hh index e9ff2a28..075c6e7f 100644 --- a/src/CodeInterpreter.hh +++ b/src/CodeInterpreter.hh @@ -46,212 +46,212 @@ const double near_zero{1e-12}; */ enum Tags { - FLDZ, //!< Stores zero in the stack - 0 (0) - FLDC, //!< Stores a constant term in the stack - 1 (1) + FLDZ, //!< Stores zero in the stack - 0 (0) + FLDC, //!< Stores a constant term in the stack - 1 (1) - FDIMT, //!< Defines the number of temporary terms - dynamic context (the period has to be indicated) - 2 (2) - FDIMST, //!< Defines the number of temporary terms - static context (the period hasn't to be indicated) - 3 (3) - FLDT, //!< Stores a temporary term in the stack - dynamic context (the period has to be indicated) - 4 (4) - FLDST, //!< Stores a temporary term in the stack - static context (the period hasn't to be indicated) - 5 (5) - FSTPT, //!< Loads a temporary term from the stack - dynamic context (the period has to be indicated) - 6 (6) - FSTPST, //!< Loads a temporary term from the stack - static context (the period hasn't to be indicated) - 7 (7) + FDIMT, //!< Defines the number of temporary terms - dynamic context (the period has to be indicated) - 2 (2) + FDIMST, //!< Defines the number of temporary terms - static context (the period hasn't to be indicated) - 3 (3) + FLDT, //!< Stores a temporary term in the stack - dynamic context (the period has to be indicated) - 4 (4) + FLDST, //!< Stores a temporary term in the stack - static context (the period hasn't to be indicated) - 5 (5) + FSTPT, //!< Loads a temporary term from the stack - dynamic context (the period has to be indicated) - 6 (6) + FSTPST, //!< Loads a temporary term from the stack - static context (the period hasn't to be indicated) - 7 (7) - FLDU, //!< Stores an element of the vector U in the stack - dynamic context (the period has to be indicated) - 8 (8) - FLDSU, //!< Stores an element of the vector U in the stack - static context (the period hasn't to be indicated) - 9 (9) - FSTPU, //!< Loads an element of the vector U from the stack - dynamic context (the period has to be indicated) - A (10) - FSTPSU, //!< Loads an element of the vector U from the stack - static context (the period hasn't to be indicated) - B (11) + FLDU, //!< Stores an element of the vector U in the stack - dynamic context (the period has to be indicated) - 8 (8) + FLDSU, //!< Stores an element of the vector U in the stack - static context (the period hasn't to be indicated) - 9 (9) + FSTPU, //!< Loads an element of the vector U from the stack - dynamic context (the period has to be indicated) - A (10) + FSTPSU, //!< Loads an element of the vector U from the stack - static context (the period hasn't to be indicated) - B (11) - FLDV, //!< Stores a variable (described in SymbolType) in the stack - dynamic context (the period has to be indicated) - C (12) - FLDSV, //!< Stores a variable (described in SymbolType) in the stack - static context (the period hasn't to be indicated) - D (13) - FLDVS, //!< Stores a variable (described in SymbolType) in the stack - dynamic context but inside the STEADYSTATE function (the period hasn't to be indicated) - E (14) - FSTPV, //!< Loads a variable (described in SymbolType) from the stack - dynamic context (the period has to be indicated) - F (15) - FSTPSV, //!< Loads a variable (described in SymbolType) from the stack - static context (the period hasn't to be indicated) - 10 (16) + FLDV, //!< Stores a variable (described in SymbolType) in the stack - dynamic context (the period has to be indicated) - C (12) + FLDSV, //!< Stores a variable (described in SymbolType) in the stack - static context (the period hasn't to be indicated) - D (13) + FLDVS, //!< Stores a variable (described in SymbolType) in the stack - dynamic context but inside the STEADYSTATE function (the period hasn't to be indicated) - E (14) + FSTPV, //!< Loads a variable (described in SymbolType) from the stack - dynamic context (the period has to be indicated) - F (15) + FSTPSV, //!< Loads a variable (described in SymbolType) from the stack - static context (the period hasn't to be indicated) - 10 (16) - FLDR, //!< Stores a residual in the stack - 11 (17) - FSTPR, //!< Loads a residual from the stack - 12 (18) + FLDR, //!< Stores a residual in the stack - 11 (17) + FSTPR, //!< Loads a residual from the stack - 12 (18) - FSTPG, //!< Loads a derivative from the stack - 13 (19) - FSTPG2, //!< Loads a derivative matrix for static model from the stack - 14 (20) - FSTPG3, //!< Loads a derivative matrix for a dynamic model from the stack - 15 (21) - FSTPG4, //!< Loads a second order derivative matrix for a dynamic model from the stack - 16 (22) + FSTPG, //!< Loads a derivative from the stack - 13 (19) + FSTPG2, //!< Loads a derivative matrix for static model from the stack - 14 (20) + FSTPG3, //!< Loads a derivative matrix for a dynamic model from the stack - 15 (21) + FSTPG4, //!< Loads a second order derivative matrix for a dynamic model from the stack - 16 (22) - FUNARY, //!< A Unary operator - 17 (23) - FBINARY, //!< A binary operator - 18 (24) - FTRINARY, //!< A trinary operator - 19 (25) + FUNARY, //!< A Unary operator - 17 (23) + FBINARY, //!< A binary operator - 18 (24) + FTRINARY, //!< A trinary operator - 19 (25) - FCUML, //!< Cumulates the result - 1A (26) + FCUML, //!< Cumulates the result - 1A (26) - FJMPIFEVAL, //!< Jump if evaluate = true - 1B (27) - FJMP, //!< Jump - 1C (28) + FJMPIFEVAL, //!< Jump if evaluate = true - 1B (27) + FJMP, //!< Jump - 1C (28) - FBEGINBLOCK, //!< Defines the begining of a model block - 1D (29) - FENDBLOCK, //!< Defines the end of a model block - 1E (30) - FENDEQU, //!< Defines the last equation of the block. For block that has to be solved, the derivatives appear just after this flag - 1F (31) - FEND, //!< Defines the end of the model code - 20 (32) + FBEGINBLOCK, //!< Defines the begining of a model block - 1D (29) + FENDBLOCK, //!< Defines the end of a model block - 1E (30) + FENDEQU, //!< Defines the last equation of the block. For block that has to be solved, the derivatives appear just after this flag - 1F (31) + FEND, //!< Defines the end of the model code - 20 (32) - FOK, //!< Used for debugging purpose - 21 (33) + FOK, //!< Used for debugging purpose - 21 (33) - FNUMEXPR, //!< Store the expression type and references - 22 (34) + FNUMEXPR, //!< Store the expression type and references - 22 (34) - FCALL, //!< Call an external function - 23 (35) - FPUSH, //!< Push a double in the stack - 24 (36) - FPOP, //!< Pop a double from the stack - 25 (37) - FLDTEF, //!< Stores the result of an external function in the stack - 26 (38) - FSTPTEF, //!< Loads the result of an external function from the stack- 27 (39) - FLDTEFD, //!< Stores the result of an external function in the stack - 28 (40) - FSTPTEFD, //!< Loads the result of an external function from the stack- 29 (41) - FLDTEFDD, //!< Stores the result of an external function in the stack - 28 (42) - FSTPTEFDD //!< Loads the result of an external function from the stack- 29 (43) + FCALL, //!< Call an external function - 23 (35) + FPUSH, //!< Push a double in the stack - 24 (36) + FPOP, //!< Pop a double from the stack - 25 (37) + FLDTEF, //!< Stores the result of an external function in the stack - 26 (38) + FSTPTEF, //!< Loads the result of an external function from the stack- 27 (39) + FLDTEFD, //!< Stores the result of an external function in the stack - 28 (40) + FSTPTEFD, //!< Loads the result of an external function from the stack- 29 (41) + FLDTEFDD, //!< Stores the result of an external function in the stack - 28 (42) + FSTPTEFDD //!< Loads the result of an external function from the stack- 29 (43) }; enum BlockType { - SIMULTANS, //!< Simultaneous time separable block - PROLOGUE, //!< Prologue block (one equation at the beginning, later merged) - EPILOGUE, //!< Epilogue block (one equation at the beginning, later merged) - SIMULTAN //!< Simultaneous time unseparable block + SIMULTANS, //!< Simultaneous time separable block + PROLOGUE, //!< Prologue block (one equation at the beginning, later merged) + EPILOGUE, //!< Epilogue block (one equation at the beginning, later merged) + SIMULTAN //!< Simultaneous time unseparable block }; enum EquationType { - E_UNKNOWN, //!< Unknown equation type - E_EVALUATE, //!< Simple evaluation, normalized variable on left-hand side - E_EVALUATE_S, //!< Simple evaluation, normalize using the first order derivative - E_SOLVE //!< No simple evaluation of the equation, it has to be solved + E_UNKNOWN, //!< Unknown equation type + E_EVALUATE, //!< Simple evaluation, normalized variable on left-hand side + E_EVALUATE_S, //!< Simple evaluation, normalize using the first order derivative + E_SOLVE //!< No simple evaluation of the equation, it has to be solved }; enum BlockSimulationType { - UNKNOWN, //!< Unknown simulation type - EVALUATE_FORWARD, //!< Simple evaluation, normalized variable on left-hand side, forward - EVALUATE_BACKWARD, //!< Simple evaluation, normalized variable on left-hand side, backward - SOLVE_FORWARD_SIMPLE, //!< Block of one equation, newton solver needed, forward - SOLVE_BACKWARD_SIMPLE, //!< Block of one equation, newton solver needed, backward - SOLVE_TWO_BOUNDARIES_SIMPLE, //!< Block of one equation, newton solver needed, forward & ackward - SOLVE_FORWARD_COMPLETE, //!< Block of several equations, newton solver needed, forward - SOLVE_BACKWARD_COMPLETE, //!< Block of several equations, newton solver needed, backward - SOLVE_TWO_BOUNDARIES_COMPLETE //!< Block of several equations, newton solver needed, forward and backwar + UNKNOWN, //!< Unknown simulation type + EVALUATE_FORWARD, //!< Simple evaluation, normalized variable on left-hand side, forward + EVALUATE_BACKWARD, //!< Simple evaluation, normalized variable on left-hand side, backward + SOLVE_FORWARD_SIMPLE, //!< Block of one equation, newton solver needed, forward + SOLVE_BACKWARD_SIMPLE, //!< Block of one equation, newton solver needed, backward + SOLVE_TWO_BOUNDARIES_SIMPLE, //!< Block of one equation, newton solver needed, forward & ackward + SOLVE_FORWARD_COMPLETE, //!< Block of several equations, newton solver needed, forward + SOLVE_BACKWARD_COMPLETE, //!< Block of several equations, newton solver needed, backward + SOLVE_TWO_BOUNDARIES_COMPLETE //!< Block of several equations, newton solver needed, forward and backwar }; //! Enumeration of possible symbol types /*! 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) - logTrend = 15, //!< Log-trend variable - unusedEndogenous = 16, //!< Type to mark unused endogenous variables when `nostrict` option is passed - endogenousVAR = 17, //!< Variables declared in a var_model statement - epilogue = 18, //!< Variables created in epilogue block - excludedVariable = 19 //!< Type to use when an equation is excluded via include/exclude_eqs and the LHS variable is not used elsewhere in the model + 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) + logTrend = 15, //!< Log-trend variable + unusedEndogenous = 16, //!< Type to mark unused endogenous variables when `nostrict` option is passed + endogenousVAR = 17, //!< Variables declared in a var_model statement + epilogue = 18, //!< Variables created in epilogue block + excludedVariable = 19 //!< Type to use when an equation is excluded via include/exclude_eqs and the LHS variable is not used elsewhere in the model }; enum ExpressionType { - TemporaryTerm, - ModelEquation, - FirstEndoDerivative, - FirstOtherEndoDerivative, - FirstExoDerivative, - FirstExodetDerivative, - FirstParamDerivative, - SecondEndoDerivative, - SecondExoDerivative, - SecondExodetDerivative, - SecondParamDerivative, - ThirdEndoDerivative, - ThirdExoDerivative, - ThirdExodetDerivative, - ThirdParamDerivative + TemporaryTerm, + ModelEquation, + FirstEndoDerivative, + FirstOtherEndoDerivative, + FirstExoDerivative, + FirstExodetDerivative, + FirstParamDerivative, + SecondEndoDerivative, + SecondExoDerivative, + SecondExodetDerivative, + SecondParamDerivative, + ThirdEndoDerivative, + ThirdExoDerivative, + ThirdExodetDerivative, + ThirdParamDerivative }; enum class UnaryOpcode { - uminus, - exp, - log, - log10, - cos, - sin, - tan, - acos, - asin, - atan, - cosh, - sinh, - tanh, - acosh, - asinh, - atanh, - sqrt, - cbrt, - abs, - 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 - expectation, - erf, - diff, - adl + uminus, + exp, + log, + log10, + cos, + sin, + tan, + acos, + asin, + atan, + cosh, + sinh, + tanh, + acosh, + asinh, + atanh, + sqrt, + cbrt, + abs, + 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 + expectation, + erf, + diff, + adl }; enum class BinaryOpcode { - plus, - minus, - times, - divide, - power, - powerDeriv, // for the derivative of the power function (see trac ticket #78) - equal, - max, - min, - less, - greater, - lessEqual, - greaterEqual, - equalEqual, - different + plus, + minus, + times, + divide, + power, + powerDeriv, // for the derivative of the power function (see trac ticket #78) + equal, + max, + min, + less, + greater, + lessEqual, + greaterEqual, + equalEqual, + different }; enum class TrinaryOpcode { - normcdf, - normpdf + normcdf, + normpdf }; enum class ExternalFunctionType { - withoutDerivative, - withFirstDerivative, - withFirstAndSecondDerivative, - numericalFirstDerivative, - firstDerivative, - numericalSecondDerivative, - secondDerivative + withoutDerivative, + withFirstDerivative, + withFirstAndSecondDerivative, + numericalFirstDerivative, + firstDerivative, + numericalSecondDerivative, + secondDerivative }; enum class PriorDistributions { - noShape = 0, - beta = 1, - gamma = 2, - normal = 3, - invGamma = 4, - invGamma1 = 4, - uniform = 5, - invGamma2 = 6, - dirichlet = 7, - weibull = 8 + noShape = 0, + beta = 1, + gamma = 2, + normal = 3, + invGamma = 4, + invGamma1 = 4, + uniform = 5, + invGamma2 = 6, + dirichlet = 7, + weibull = 8 }; struct Block_contain_type @@ -1429,7 +1429,7 @@ private: public: inline FBEGINBLOCK_() : size{0}, type{UNKNOWN}, - is_linear{false}, endo_nbr{0}, Max_Lag{0}, Max_Lead{0}, u_count_int{0}, nb_col_jacob{0} + is_linear{false}, endo_nbr{0}, Max_Lag{0}, Max_Lead{0}, u_count_int{0}, nb_col_jacob{0} { } inline diff --git a/src/ComputingTasks.cc b/src/ComputingTasks.cc index e7ce5678..5b8eaf55 100644 --- a/src/ComputingTasks.cc +++ b/src/ComputingTasks.cc @@ -501,7 +501,7 @@ VarRestrictionsStatement::writeOutput(ostream &output, const string &basename, b output << "struct('eq', " << findIdxInVector(vars, symbol_table.getName(it1->first)) + 1 << ", 'vars', ["; vector<string> excvars = it1->second.getSymbols(); - for (auto & excvar : excvars) + for (auto &excvar : excvars) output << findIdxInVector(vars, excvar) + 1 << " "; output << "])"; nrestrictions += it1->second.getSize(); @@ -775,7 +775,7 @@ DetCondForecast::writeOutput(ostream &output, const string &basename, bool minim } vector<string> symbols = symbol_list.get_symbols(); if (symbols.size() > 0) - output << symbols[1] << " = det_cond_forecast(" ; + output << symbols[1] << " = det_cond_forecast("; for (unsigned int i = 0; i < symbols.size() - 1; i++) output << symbols[i] << ", "; if (symbols.size() > 0) @@ -1004,7 +1004,7 @@ RamseyPolicyStatement::writeOutput(ostream &output, const string &basename, bool // Ensure that order 3 implies k_order (#844) if (auto it = options_list.num_options.find("order"), it1 = options_list.num_options.find("k_order_solver"); - (it1 != options_list.num_options.end() && it1->second == "true") + (it1 != options_list.num_options.end() && it1->second == "true") || (it != options_list.num_options.end() && stoi(it->second) >= 3)) output << "options_.k_order_solver = true;" << endl; @@ -1404,7 +1404,7 @@ EstimatedParamsStatement::EstimatedParamsStatement(vector<EstimationParams> esti void EstimatedParamsStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) { - for (const auto & it : estim_params_list) + for (const auto &it : estim_params_list) { if (it.name == "dsge_prior_weight") mod_file_struct.dsge_prior_weight_in_estimated_params = true; @@ -1429,7 +1429,7 @@ EstimatedParamsStatement::checkPass(ModFileStructure &mod_file_struct, WarningCo // Check that no parameter/endogenous is declared twice in the block set<string> already_declared; set<pair<string, string>> already_declared_corr; - for (const auto & it : estim_params_list) + for (const auto &it : estim_params_list) { if (it.type == 3) // Correlation { @@ -1457,7 +1457,7 @@ EstimatedParamsStatement::checkPass(ModFileStructure &mod_file_struct, WarningCo } // Fill in mod_file_struct.estimated_parameters (related to #469) - for (const auto & it : estim_params_list) + for (const auto &it : estim_params_list) if (it.type == 2 && it.name != "dsge_prior_weight") mod_file_struct.estimated_parameters.insert(symbol_table.getID(it.name)); } @@ -1471,7 +1471,7 @@ EstimatedParamsStatement::writeOutput(ostream &output, const string &basename, b << "estim_params_.corrn = zeros(0, 11);" << endl << "estim_params_.param_vals = zeros(0, 10);" << endl; - for (const auto & it : estim_params_list) + for (const auto &it : estim_params_list) { int symb_id = symbol_table.getTypeSpecificID(it.name) + 1; SymbolType symb_type = symbol_table.getType(it.name); @@ -1590,7 +1590,7 @@ EstimatedParamsInitStatement::writeOutput(ostream &output, const string &basenam bool skipline = false; - for (const auto & it : estim_params_list) + for (const auto &it : estim_params_list) { int symb_id = symbol_table.getTypeSpecificID(it.name) + 1; SymbolType symb_type = symbol_table.getType(it.name); @@ -1715,7 +1715,7 @@ EstimatedParamsBoundsStatement::EstimatedParamsBoundsStatement(vector<Estimation void EstimatedParamsBoundsStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const { - for (const auto & it : estim_params_list) + for (const auto &it : estim_params_list) { int symb_id = symbol_table.getTypeSpecificID(it.name) + 1; SymbolType symb_type = symbol_table.getType(it.name); @@ -1835,7 +1835,7 @@ void ObservationTrendsStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const { output << "options_.trend_coeff = {};" << endl; - for (const auto & trend_element : trend_elements) + for (const auto &trend_element : trend_elements) { SymbolType type = symbol_table.getType(trend_element.first); if (type == SymbolType::endogenous) @@ -1856,7 +1856,7 @@ ObservationTrendsStatement::writeJsonOutput(ostream &output) const output << R"({"statementName": "observation_trends", )" << R"("trends" : {)"; bool printed = false; - for (const auto & trend_element : trend_elements) + for (const auto &trend_element : trend_elements) { if (symbol_table.getType(trend_element.first) == SymbolType::endogenous) { @@ -1896,7 +1896,7 @@ OsrParamsStatement::writeOutput(ostream &output, const string &basename, bool mi << "M_.osr.param_indices = zeros(length(M_.osr.param_names), 1);" << endl; int i = 0; vector<string> symbols = symbol_list.get_symbols(); - for (auto & symbol : symbols) + for (auto &symbol : symbols) output << "M_.osr.param_indices(" << ++i <<") = " << symbol_table.getTypeSpecificID(symbol) + 1 << ";" << endl; } @@ -1933,7 +1933,7 @@ OsrParamsBoundsStatement::writeOutput(ostream &output, const string &basename, b 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) + for (const auto &it : osr_params_list) { output << "M_.osr.param_bounds(strcmp(M_.osr.param_names, '" << it.name << "'), :) = ["; it.low_bound->writeOutput(output); @@ -2207,7 +2207,7 @@ ModelComparisonStatement::writeOutput(ostream &output, const string &basename, b output << "ModelNames_ = {};" << endl; output << "ModelPriors_ = [];" << endl; - for (const auto & it : filename_list) + for (const auto &it : filename_list) { output << "ModelNames_ = { ModelNames_{:} '" << it.first << "'};" << endl; output << "ModelPriors_ = [ ModelPriors_ ; " << it.second << "];" << endl; @@ -2243,7 +2243,7 @@ ModelComparisonStatement::writeJsonOutput(ostream &output) const } PlannerObjectiveStatement::PlannerObjectiveStatement(const StaticModel &model_tree_arg) : - model_tree {model_tree_arg} + model_tree{model_tree_arg} { } @@ -3145,7 +3145,7 @@ int SvarIdentificationStatement::getMaxLag() const { int max_lag = 0; - for (const auto & restriction : restrictions) + for (const auto &restriction : restrictions) if (restriction.lag > max_lag) max_lag = restriction.lag; @@ -3282,12 +3282,12 @@ MarkovSwitchingStatement::MarkovSwitchingStatement(OptionsList options_list_arg) { using namespace boost; auto it_num_regimes = options_list.num_options.find("ms.number_of_regimes"); - assert(it_num_regimes != options_list.num_options.end()); + assert(it_num_regimes != options_list.num_options.end()); auto num_regimes = stoi(it_num_regimes->second); vector<string> tokenizedRestrictions; split(tokenizedRestrictions, it_num->second, is_any_of("["), token_compress_on); - for (auto & tokenizedRestriction : tokenizedRestrictions) + for (auto &tokenizedRestriction : tokenizedRestrictions) if (tokenizedRestriction.size() > 0) { vector<string> restriction; @@ -3859,13 +3859,13 @@ JointPriorStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli void JointPriorStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const { - for (const auto & joint_parameter : joint_parameters) + 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; output << "key = {["; - for (const auto & joint_parameter : joint_parameters) + for (const auto &joint_parameter : joint_parameters) output << "get_new_or_existing_ei_index('joint_parameter_prior_index', '" << joint_parameter << "', '') ..." << endl << " "; output << "]};" << endl; @@ -4734,7 +4734,7 @@ ExtendedPathStatement::writeOutput(ostream &output, const string &basename, bool { // Beware: options do not have the same name in the interface and in the M code... - for (const auto & num_option : options_list.num_options) + for (const auto &num_option : options_list.num_options) if (num_option.first != "periods") output << "options_." << num_option.first << " = " << num_option.second << ";" << endl; @@ -4902,7 +4902,7 @@ GenerateIRFsStatement::writeOutput(ostream &output, const string &basename, bool return; output << "options_.irf_opt.irf_shock_graphtitles = { "; - for (const auto & generate_irf_name : generate_irf_names) + for (const auto &generate_irf_name : generate_irf_names) output << "'" << generate_irf_name << "'; "; output << "};" << endl; @@ -4912,7 +4912,7 @@ GenerateIRFsStatement::writeOutput(ostream &output, const string &basename, bool for (size_t i = 0; i < generate_irf_names.size(); i++) { map<string, double> m = generate_irf_elements[i]; - for (auto & it : m) + for (auto &it : m) output << "options_.irf_opt.irf_shocks(M_.exo_names == '" << it.first << "', " << i + 1 << ") = " << it.second << ";" << endl; diff --git a/src/ComputingTasks.hh b/src/ComputingTasks.hh index 47f647a1..4c0be196 100644 --- a/src/ComputingTasks.hh +++ b/src/ComputingTasks.hh @@ -95,7 +95,6 @@ public: void writeJsonOutput(ostream &output) const override; }; - class DetCondForecast : public Statement { private: diff --git a/src/ConfigFile.cc b/src/ConfigFile.cc index 6165a0c0..51bdac17 100644 --- a/src/ConfigFile.cc +++ b/src/ConfigFile.cc @@ -86,7 +86,7 @@ SlaveNode::SlaveNode(string computerName_arg, string port_arg, int minCpuNbr_arg } } -Cluster::Cluster(member_nodes_t member_nodes_arg) : +Cluster::Cluster(member_nodes_t member_nodes_arg) : member_nodes{move(member_nodes_arg)} { if (member_nodes.empty()) @@ -276,7 +276,7 @@ ConfigFile::getConfigFileInfo(const string &config_file) { vector<string> tokenizedPath; split(tokenizedPath, tokenizedLine.back(), is_any_of(":"), token_compress_on); - for (auto & it : tokenizedPath) + for (auto &it : tokenizedPath) if (!it.empty()) { trim(it); @@ -377,7 +377,7 @@ ConfigFile::getConfigFileInfo(const string &config_file) tokenizer<char_separator<char>> tokens(tokenizedLine.back(), sep); bool begin_weight = false; string node_name; - for (const auto & token : tokens) + for (const auto &token : tokens) { if (token.compare("(") == 0) { @@ -497,9 +497,9 @@ ConfigFile::addParallelConfFileElement(bool inNode, bool inCluster, const member } else slave_nodes.emplace(name, SlaveNode{computerName, port, minCpuNbr, maxCpuNbr, userName, - password, remoteDrive, remoteDirectory, dynarePath, - matlabOctavePath, singleCompThread, numberOfThreadsPerJob, - operatingSystem}); + password, remoteDrive, remoteDirectory, dynarePath, + matlabOctavePath, singleCompThread, numberOfThreadsPerJob, + operatingSystem}); //! ADD CLUSTER else if (inCluster) if (minCpuNbr > 0 || maxCpuNbr > 0 || !userName.empty() @@ -527,9 +527,9 @@ void ConfigFile::checkPass(WarningConsolidation &warnings) const { bool global_init_file_declared = false; - for (const auto & hook : hooks) + for (const auto &hook : hooks) { - for (const auto & mapit : hook.get_hooks()) + for (const auto &mapit : hook.get_hooks()) if (mapit.first.compare("global_init_file") == 0) if (global_init_file_declared == true) { @@ -550,7 +550,7 @@ ConfigFile::checkPass(WarningConsolidation &warnings) const exit(EXIT_FAILURE); } - for (const auto & slave_node : slave_nodes) + for (const auto &slave_node : slave_nodes) { #if !defined(_WIN32) && !defined(__CYGWIN32__) //For Linux/Mac, check that cpuNbr starts at 0 @@ -638,8 +638,8 @@ ConfigFile::checkPass(WarningConsolidation &warnings) const exit(EXIT_FAILURE); } - for (const auto & cluster : clusters) - for (const auto & itmn : cluster.second.member_nodes) + for (const auto &cluster : clusters) + for (const auto &itmn : cluster.second.member_nodes) if (slave_nodes.find(itmn.first) == slave_nodes.end()) { cerr << "Error: node " << itmn.first << " specified in cluster " << cluster.first << " was not found" << endl; @@ -655,7 +655,7 @@ ConfigFile::transformPass() #if !defined(_WIN32) && !defined(__CYGWIN32__) //For Linux/Mac, check that cpuNbr starts at 0 - for (auto & it : slave_nodes) + for (auto &it : slave_nodes) if (it.second.minCpuNbr != 0) { it.second.maxCpuNbr = it.second.maxCpuNbr - it.second.minCpuNbr; @@ -666,10 +666,10 @@ ConfigFile::transformPass() auto cluster_it = cluster_name.empty() ? clusters.find(firstClusterName) : clusters.find(cluster_name); double weight_denominator{0.0}; - for (const auto & it : cluster_it->second.member_nodes) + for (const auto &it : cluster_it->second.member_nodes) weight_denominator += it.second; - for (auto & member_node : cluster_it->second.member_nodes) + for (auto &member_node : cluster_it->second.member_nodes) member_node.second /= weight_denominator; } @@ -678,8 +678,8 @@ ConfigFile::getIncludePaths() const { vector<filesystem::path> include_paths; for (auto path : paths) - for (const auto & mapit : path.get_paths()) - for (const auto & vecit : mapit.second) + for (const auto &mapit : path.get_paths()) + for (const auto &vecit : mapit.second) include_paths.emplace_back(vecit); return include_paths; } @@ -688,7 +688,7 @@ void ConfigFile::writeHooks(ostream &output) const { for (auto hook : hooks) - for (const auto & mapit : hook.get_hooks()) + for (const auto &mapit : hook.get_hooks()) output << "options_." << mapit.first << " = '" << mapit.second << "';" << endl; } @@ -701,10 +701,10 @@ ConfigFile::writeCluster(ostream &output) const auto cluster_it = cluster_name.empty() ? clusters.find(firstClusterName) : clusters.find(cluster_name); int i{1}; - for (const auto & slave_node : slave_nodes) + for (const auto &slave_node : slave_nodes) { bool slave_node_in_member_nodes = false; - for (const auto & itmn : cluster_it->second.member_nodes) + for (const auto &itmn : cluster_it->second.member_nodes) if (!slave_node.first.compare(itmn.first)) slave_node_in_member_nodes = true; diff --git a/src/DataTree.cc b/src/DataTree.cc index 869416cb..e2f6ed1e 100644 --- a/src/DataTree.cc +++ b/src/DataTree.cc @@ -50,27 +50,27 @@ DataTree::DataTree(SymbolTable &symbol_table_arg, symbol_table{symbol_table_arg}, num_constants{num_constants_arg}, external_functions_table{external_functions_table_arg}, - is_dynamic {is_dynamic_arg} + is_dynamic{is_dynamic_arg} { initConstants(); } DataTree::DataTree(const DataTree &d) : - symbol_table {d.symbol_table}, - num_constants {d.num_constants}, - external_functions_table {d.external_functions_table}, - is_dynamic {d.is_dynamic}, - local_variables_vector {d.local_variables_vector} + symbol_table{d.symbol_table}, + num_constants{d.num_constants}, + external_functions_table{d.external_functions_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(); - for (const auto & it : d.node_list) + for (const auto &it : d.node_list) it->clone(*this); assert(node_list.size() == d.node_list.size()); - for (const auto & it : d.local_variables_table) + for (const auto &it : d.local_variables_table) local_variables_table[it.first] = it.second->clone(*this); } @@ -98,14 +98,14 @@ DataTree::operator=(const DataTree &d) // Constants must be initialized first because they are used in some Add* methods initConstants(); - for (const auto & it : d.node_list) + for (const auto &it : d.node_list) it->clone(*this); assert(node_list.size() == d.node_list.size()); local_variables_vector = d.local_variables_vector; - for (const auto & it : d.local_variables_table) + for (const auto &it : d.local_variables_table) local_variables_table[it.first] = it.second->clone(*this); return *this; @@ -162,7 +162,7 @@ DataTree::getVariable(int symb_id, int lag) const bool DataTree::ParamUsedWithLeadLagInternal() const { - for (const auto & it : variable_node_map) + for (const auto &it : variable_node_map) if (symbol_table.getType(it.first.first) == SymbolType::parameter && it.first.second != 0) return true; return false; @@ -759,7 +759,7 @@ DataTree::AddSecondDerivExternalFunction(int top_level_symb_id, const vector<exp bool DataTree::isSymbolUsed(int symb_id) const { - for (const auto & it : variable_node_map) + for (const auto &it : variable_node_map) if (it.first.first == symb_id) return true; @@ -807,7 +807,7 @@ DataTree::getDynJacobianCol(int deriv_id) const noexcept(false) bool DataTree::isUnaryOpUsed(UnaryOpcode opcode) const { - for (const auto & it : unary_op_node_map) + for (const auto &it : unary_op_node_map) if (get<1>(it.first) == opcode) return true; @@ -818,7 +818,7 @@ bool DataTree::isUnaryOpUsedOnType(SymbolType type, UnaryOpcode opcode) const { set<int> var; - for (const auto & it : unary_op_node_map) + for (const auto &it : unary_op_node_map) if (get<1>(it.first) == opcode) { it.second->collectVariables(type, var); @@ -831,7 +831,7 @@ DataTree::isUnaryOpUsedOnType(SymbolType type, UnaryOpcode opcode) const bool DataTree::isBinaryOpUsed(BinaryOpcode opcode) const { - for (const auto & it : binary_op_node_map) + for (const auto &it : binary_op_node_map) if (get<2>(it.first) == opcode) return true; @@ -842,7 +842,7 @@ bool DataTree::isBinaryOpUsedOnType(SymbolType type, BinaryOpcode opcode) const { set<int> var; - for (const auto & it : binary_op_node_map) + for (const auto &it : binary_op_node_map) if (get<2>(it.first) == opcode) { it.second->collectVariables(type, var); @@ -855,7 +855,7 @@ DataTree::isBinaryOpUsedOnType(SymbolType type, BinaryOpcode opcode) const bool DataTree::isTrinaryOpUsed(TrinaryOpcode opcode) const { - for (const auto & it : trinary_op_node_map) + for (const auto &it : trinary_op_node_map) if (get<3>(it.first) == opcode) return true; @@ -865,7 +865,7 @@ DataTree::isTrinaryOpUsed(TrinaryOpcode opcode) const bool DataTree::isExternalFunctionUsed(int symb_id) const { - for (const auto & it : external_function_node_map) + for (const auto &it : external_function_node_map) if (it.first.second == symb_id) return true; @@ -875,7 +875,7 @@ DataTree::isExternalFunctionUsed(int symb_id) const bool DataTree::isFirstDerivExternalFunctionUsed(int symb_id) const { - for (const auto & it : first_deriv_external_function_node_map) + for (const auto &it : first_deriv_external_function_node_map) if (get<2>(it.first) == symb_id) return true; @@ -885,7 +885,7 @@ DataTree::isFirstDerivExternalFunctionUsed(int symb_id) const bool DataTree::isSecondDerivExternalFunctionUsed(int symb_id) const { - for (const auto & it : second_deriv_external_function_node_map) + for (const auto &it : second_deriv_external_function_node_map) if (get<3>(it.first) == symb_id) return true; @@ -896,7 +896,7 @@ int DataTree::minLagForSymbol(int symb_id) const { int r = 0; - for (const auto & it : variable_node_map) + for (const auto &it : variable_node_map) if (it.first.first == symb_id && it.first.second < r) r = it.first.second; return r; diff --git a/src/DataTree.hh b/src/DataTree.hh index b5fcd6eb..a99be8ab 100644 --- a/src/DataTree.hh +++ b/src/DataTree.hh @@ -128,8 +128,8 @@ public: DataTree(const DataTree &d); DataTree(DataTree &&) = delete; - DataTree & operator=(const DataTree &d); - DataTree & operator=(DataTree &&) = delete; + DataTree &operator=(const DataTree &d); + DataTree &operator=(DataTree &&) = delete; //! Some predefined constants expr_t Zero, One, Two, Three, MinusOne, NaN, Infinity, MinusInfinity, Pi; @@ -155,7 +155,7 @@ public: VariableNode *AddVariable(int symb_id, int lag = 0); //! Gets a variable /*! Same as AddVariable, except that it fails if the variable node has not - already been created */ + already been created */ VariableNode *getVariable(int symb_id, int lag = 0) const; //! Adds "arg1+arg2" to model tree expr_t AddPlus(expr_t iArg1, expr_t iArg2); @@ -324,7 +324,8 @@ public: } }; - expr_t getLocalVariable(int symb_id) const + expr_t + getLocalVariable(int symb_id) const { auto it = local_variables_table.find(symb_id); if (it == local_variables_table.end()) diff --git a/src/DynamicModel.cc b/src/DynamicModel.cc index d6fd7075..14135914 100644 --- a/src/DynamicModel.cc +++ b/src/DynamicModel.cc @@ -36,17 +36,17 @@ DynamicModel::copyHelper(const DynamicModel &m) static_only_equations.push_back(dynamic_cast<BinaryOpNode *>(f(it))); auto convert_vector_tt = [f](vector<temporary_terms_t> vtt) - { - vector<temporary_terms_t> vtt2; - for (const auto &tt : vtt) - { - temporary_terms_t tt2; - for (const auto &it : tt) - tt2.insert(f(it)); - vtt2.push_back(tt2); - } - return vtt2; - }; + { + vector<temporary_terms_t> vtt2; + for (const auto &tt : vtt) + { + temporary_terms_t tt2; + for (const auto &it : tt) + tt2.insert(f(it)); + vtt2.push_back(tt2); + } + return vtt2; + }; for (const auto &it : m.v_temporary_terms) v_temporary_terms.push_back(convert_vector_tt(it)); @@ -69,12 +69,12 @@ DynamicModel::copyHelper(const DynamicModel &m) dynamic_jacobian[it.first] = f(it.second); auto convert_derivative_t = [f](derivative_t dt) - { - derivative_t dt2; - for (const auto &it : dt) - dt2[it.first] = f(it.second); - return dt2; - }; + { + derivative_t dt2; + for (const auto &it : dt) + dt2[it.first] = f(it.second); + return dt2; + }; for (const auto &it : m.derivative_endo) derivative_endo.push_back(convert_derivative_t(it)); for (const auto &it : m.derivative_other_endo) @@ -85,73 +85,72 @@ DynamicModel::copyHelper(const DynamicModel &m) derivative_exo_det.push_back(convert_derivative_t(it)); } - DynamicModel::DynamicModel(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg, ExternalFunctionsTable &external_functions_table_arg, TrendComponentModelTable &trend_component_model_table_arg, VarModelTable &var_model_table_arg) : - ModelTree {symbol_table_arg, num_constants_arg, external_functions_table_arg, true}, + ModelTree{symbol_table_arg, num_constants_arg, external_functions_table_arg, true}, trend_component_model_table{trend_component_model_table_arg}, var_model_table{var_model_table_arg} { } DynamicModel::DynamicModel(const DynamicModel &m) : - ModelTree {m}, - trend_component_model_table {m.trend_component_model_table}, - var_model_table {m.var_model_table}, - balanced_growth_test_tol {m.balanced_growth_test_tol}, - static_only_equations_lineno {m.static_only_equations_lineno}, - static_only_equations_equation_tags {m.static_only_equations_equation_tags}, - static_only_equation_tags_xref {m.static_only_equation_tags_xref}, - deriv_id_table {m.deriv_id_table}, - inv_deriv_id_table {m.inv_deriv_id_table}, - dyn_jacobian_cols_table {m.dyn_jacobian_cols_table}, - max_lag {m.max_lag}, - max_lead {m.max_lead}, - max_endo_lag {m.max_endo_lag}, - max_endo_lead {m.max_endo_lead}, - max_exo_lag {m.max_exo_lag}, - max_exo_lead {m.max_exo_lead}, - max_exo_det_lag {m.max_exo_det_lag}, - max_exo_det_lead {m.max_exo_det_lead}, - max_lag_orig {m.max_lag_orig}, - max_lead_orig {m.max_lead_orig}, - max_lag_with_diffs_expanded_orig {m.max_lag_with_diffs_expanded_orig}, - max_endo_lag_orig {m.max_endo_lag_orig}, - max_endo_lead_orig {m.max_endo_lead_orig}, - max_exo_lag_orig {m.max_exo_lag_orig}, - max_exo_lead_orig {m.max_exo_lead_orig}, - max_exo_det_lag_orig {m.max_exo_det_lag_orig}, - max_exo_det_lead_orig {m.max_exo_det_lead_orig}, - xrefs {m.xrefs}, - xref_param {m.xref_param}, - xref_endo {m.xref_endo}, - xref_exo {m.xref_exo}, - xref_exo_det {m.xref_exo_det}, - nonzero_hessian_eqs {m.nonzero_hessian_eqs}, - v_temporary_terms_inuse {m.v_temporary_terms_inuse}, - map_idx {m.map_idx}, - global_temporary_terms {m.global_temporary_terms}, - block_type_firstequation_size_mfs {m.block_type_firstequation_size_mfs}, - blocks_linear {m.blocks_linear}, - other_endo_block {m.other_endo_block}, - exo_block {m.exo_block}, - exo_det_block {m.exo_det_block}, - block_var_exo {m.block_var_exo}, - block_exo_index {m.block_exo_index}, - block_det_exo_index {m.block_det_exo_index}, - block_other_endo_index {m.block_other_endo_index}, - block_col_type {m.block_col_type}, - variable_block_lead_lag {m.variable_block_lead_lag}, - equation_block {m.equation_block}, - var_expectation_functions_to_write {m.var_expectation_functions_to_write}, - endo_max_leadlag_block {m.endo_max_leadlag_block}, - other_endo_max_leadlag_block {m.other_endo_max_leadlag_block}, - exo_max_leadlag_block {m.exo_max_leadlag_block}, - exo_det_max_leadlag_block {m.exo_det_max_leadlag_block}, - max_leadlag_block {m.max_leadlag_block} + ModelTree{m}, + trend_component_model_table{m.trend_component_model_table}, + var_model_table{m.var_model_table}, + balanced_growth_test_tol{m.balanced_growth_test_tol}, + static_only_equations_lineno{m.static_only_equations_lineno}, + static_only_equations_equation_tags{m.static_only_equations_equation_tags}, + static_only_equation_tags_xref{m.static_only_equation_tags_xref}, + deriv_id_table{m.deriv_id_table}, + inv_deriv_id_table{m.inv_deriv_id_table}, + dyn_jacobian_cols_table{m.dyn_jacobian_cols_table}, + max_lag{m.max_lag}, + max_lead{m.max_lead}, + max_endo_lag{m.max_endo_lag}, + max_endo_lead{m.max_endo_lead}, + max_exo_lag{m.max_exo_lag}, + max_exo_lead{m.max_exo_lead}, + max_exo_det_lag{m.max_exo_det_lag}, + max_exo_det_lead{m.max_exo_det_lead}, + max_lag_orig{m.max_lag_orig}, + max_lead_orig{m.max_lead_orig}, + max_lag_with_diffs_expanded_orig{m.max_lag_with_diffs_expanded_orig}, + max_endo_lag_orig{m.max_endo_lag_orig}, + max_endo_lead_orig{m.max_endo_lead_orig}, + max_exo_lag_orig{m.max_exo_lag_orig}, + max_exo_lead_orig{m.max_exo_lead_orig}, + max_exo_det_lag_orig{m.max_exo_det_lag_orig}, + max_exo_det_lead_orig{m.max_exo_det_lead_orig}, + xrefs{m.xrefs}, + xref_param{m.xref_param}, + xref_endo{m.xref_endo}, + xref_exo{m.xref_exo}, + xref_exo_det{m.xref_exo_det}, + nonzero_hessian_eqs{m.nonzero_hessian_eqs}, + v_temporary_terms_inuse{m.v_temporary_terms_inuse}, + map_idx{m.map_idx}, + global_temporary_terms{m.global_temporary_terms}, + block_type_firstequation_size_mfs{m.block_type_firstequation_size_mfs}, + blocks_linear{m.blocks_linear}, + other_endo_block{m.other_endo_block}, + exo_block{m.exo_block}, + exo_det_block{m.exo_det_block}, + block_var_exo{m.block_var_exo}, + block_exo_index{m.block_exo_index}, + block_det_exo_index{m.block_det_exo_index}, + block_other_endo_index{m.block_other_endo_index}, + block_col_type{m.block_col_type}, + variable_block_lead_lag{m.variable_block_lead_lag}, + equation_block{m.equation_block}, + var_expectation_functions_to_write{m.var_expectation_functions_to_write}, + endo_max_leadlag_block{m.endo_max_leadlag_block}, + other_endo_max_leadlag_block{m.other_endo_max_leadlag_block}, + exo_max_leadlag_block{m.exo_max_leadlag_block}, + exo_det_max_leadlag_block{m.exo_det_max_leadlag_block}, + max_leadlag_block{m.max_leadlag_block} { copyHelper(m); } @@ -189,7 +188,7 @@ DynamicModel::operator=(const DynamicModel &m) max_exo_det_lag_orig = m.max_exo_det_lag_orig; max_exo_det_lead_orig = m.max_exo_det_lead_orig; xrefs = m.xrefs; - xref_param = m.xref_param; + xref_param = m.xref_param; xref_endo = m.xref_endo; xref_exo = m.xref_exo; xref_exo_det = m.xref_exo_det; @@ -295,22 +294,22 @@ DynamicModel::computeTemporaryTermsOrdered() for (unsigned int i = 0; i < block_size; i++) { if (i < block_nb_recursives && isBlockEquationRenormalized(block, i)) - getBlockEquationRenormalizedExpr(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); + getBlockEquationRenormalizedExpr(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); else { eq_node = static_cast<BinaryOpNode *>(getBlockEquationExpr(block, i)); - eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); + eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); } } for (const auto &it : blocks_derivatives[block]) { expr_t id = get<3>(it); - id->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1); + id->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1); } for (const auto &it : derivative_endo[block]) - it.second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1); + it.second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1); for (const auto &it : derivative_other_endo[block]) - it.second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1); + it.second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1); v_temporary_terms_inuse[block] = {}; } } @@ -326,7 +325,7 @@ DynamicModel::computeTemporaryTermsOrdered() for (unsigned int i = 0; i < block_size; i++) { if (i < block_nb_recursives && isBlockEquationRenormalized(block, i)) - getBlockEquationRenormalizedExpr(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); + getBlockEquationRenormalizedExpr(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); else { eq_node = static_cast<BinaryOpNode *>(getBlockEquationExpr(block, i)); @@ -399,7 +398,7 @@ DynamicModel::writeModelEquationsOrdered_M(const string &basename) const vector<string> Uf(symbol_table.endo_nbr(), ""); map<expr_t, int> reference_count; temporary_terms_t local_temporary_terms; - ofstream output; + ofstream output; int nze, nze_exo, nze_exo_det, nze_other_endo; vector<int> feedback_variables; ExprNodeOutputType local_output_type; @@ -525,11 +524,11 @@ DynamicModel::writeModelEquationsOrdered_M(const string &basename) const else if (simulation_type == SOLVE_FORWARD_COMPLETE || simulation_type == SOLVE_BACKWARD_COMPLETE) block_type = SIMULTANS; else if ((simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_SIMPLE - || simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + || simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) && getBlockFirstEquation(block) < prologue) block_type = PROLOGUE; else if ((simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_SIMPLE - || simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + || simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) && getBlockFirstEquation(block) >= equations.size() - epilogue) block_type = EPILOGUE; else @@ -727,7 +726,7 @@ DynamicModel::writeModelEquationsOrdered_M(const string &basename) const if (simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE) output << " " << sps << "% Jacobian " << endl << " if jacobian_eval" << endl; else - if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE + if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE) output << " % Jacobian " << endl << " if jacobian_eval" << endl; else @@ -1036,7 +1035,7 @@ DynamicModel::writeModelEquationsCode(const string &basename, const map_idx_t &m int count_col_exo = 0; int count_col_det_exo = 0; - for (const auto & it : first_derivatives_reordered_exo) + for (const auto &it : first_derivatives_reordered_exo) { int var, lag; SymbolType type; @@ -1177,7 +1176,7 @@ DynamicModel::writeModelEquationsCode(const string &basename, const map_idx_t &m prev_var = -1; prev_lag = -999999999; count_col_exo = 0; - for (const auto & it : first_derivatives_reordered_exo) + for (const auto &it : first_derivatives_reordered_exo) { int lag, var, eq; tie(lag, ignore, var, eq) = it.first; @@ -1303,7 +1302,7 @@ DynamicModel::writeModelEquationsCode_Block(const string &basename, const map_id } unsigned int count_col_det_exo = 0; vector<unsigned int> exo_det; - for (const auto & it : exo_det_block[block]) + for (const auto &it : exo_det_block[block]) for (const auto &it1 : it.second) { count_col_det_exo++; @@ -1313,7 +1312,7 @@ DynamicModel::writeModelEquationsCode_Block(const string &basename, const map_id unsigned int count_col_exo = 0; vector<unsigned int> exo; - for (const auto & it : exo_block[block]) + for (const auto &it : exo_block[block]) for (const auto &it1 : it.second) { count_col_exo++; @@ -1323,7 +1322,7 @@ DynamicModel::writeModelEquationsCode_Block(const string &basename, const map_id vector<unsigned int> other_endo; unsigned int count_col_other_endo = 0; - for (const auto & it : other_endo_block[block]) + for (const auto &it : other_endo_block[block]) for (const auto &it1 : it.second) { count_col_other_endo++; @@ -2272,7 +2271,7 @@ DynamicModel::writeWrapperFunctions(const string &basename, const string &ending if (ending == "g1") name = "dynamic_resid_g1"; else if (ending == "g2") - name= "dynamic_resid_g1_g2"; + name = "dynamic_resid_g1_g2"; else if (ending == "g3") name = "dynamic_resid_g1_g2_g3"; @@ -2450,7 +2449,7 @@ DynamicModel::writeDynamicModel(const string &basename, bool use_dll, bool julia void DynamicModel::writeDynamicModel(const string &basename, ostream &DynamicOutput, bool use_dll, bool julia) const { - vector<ostringstream> d_output(derivatives.size()); // Derivatives output (at all orders, including 0=residual) + vector<ostringstream> d_output(derivatives.size()); // Derivatives output (at all orders, including 0=residual) vector<ostringstream> tt_output(derivatives.size()); // Temp terms output (at all orders) ExprNodeOutputType output_type = (use_dll ? ExprNodeOutputType::CDynamicModel : @@ -2480,7 +2479,7 @@ DynamicModel::writeDynamicModel(const string &basename, ostream &DynamicOutput, temporary_terms_idxs, tt_output[1], output_type, tef_terms); - for (const auto & first_derivative : derivatives[1]) + for (const auto &first_derivative : derivatives[1]) { auto [eq, var] = vectorToTuple<2>(first_derivative.first); expr_t d1 = first_derivative.second; @@ -2712,7 +2711,7 @@ DynamicModel::writeDynamicModel(const string &basename, ostream &DynamicOutput, << " stored in model_.lead_lag_incidence" << endl << endl << "## Remarks ##" << endl << " [1] `num_dynamic_vars` is the number of non zero entries in the lead lag incidence matrix, `model_.lead_lag_incidence.`" << endl - << " [2] The size of `T`, ie the value of `num_temp_terms`, depends on the version of the dynamic model called. The number of temporary variables" << endl + << " [2] The size of `T`, ie the value of `num_temp_terms`, depends on the version of the dynamic model called. The number of temporary variables" << endl << " used for the different returned objects (residuals, jacobian, hessian or third order derivatives) is given by the elements in `tmp_nbr`" << endl << " exported vector. The first element is the number of temporaries used for the computation of the residuals, the second element is the" << endl << " number of temporaries used for the evaluation of the jacobian matrix, etc. If one calls the version of the dynamic model computing the" << endl @@ -2890,16 +2889,16 @@ DynamicModel::writeDynamicJacobianNonZeroElts(const string &basename) const ofstream output{"+" + basename + "/dynamic_g1_nz.m", ios::out | ios::binary}; output << "function [nzij_pred, nzij_current, nzij_fwrd] = dynamic_g1_nz()" << endl << "% Returns the coordinates of non-zero elements in the Jacobian, in column-major order, for each lead/lag (only for endogenous)" << endl; - auto print_nzij = [&output](const vector<pair<int, int>> &nzij, const string &name) { - output << " " << name << " = zeros(" << nzij.size() << ", 2, 'int32');" << endl; - int idx = 1; - for (const auto &it : nzij) - { - output << " " << name << "(" << idx << ",1)=" << it.second+1 << ';' - << " " << name << "(" << idx << ",2)=" << it.first+1 << ';' << endl; - idx++; - } - }; + auto print_nzij = [&output](const vector<pair<int, int>> &nzij, const string &name) { + output << " " << name << " = zeros(" << nzij.size() << ", 2, 'int32');" << endl; + int idx = 1; + for (const auto &it : nzij) + { + output << " " << name << "(" << idx << ",1)=" << it.second+1 << ';' + << " " << name << "(" << idx << ",2)=" << it.first+1 << ';' << endl; + idx++; + } + }; print_nzij(nzij_pred, "nzij_pred"); print_nzij(nzij_current, "nzij_current"); print_nzij(nzij_fwrd, "nzij_fwrd"); @@ -2908,7 +2907,7 @@ DynamicModel::writeDynamicJacobianNonZeroElts(const string &basename) const } void -DynamicModel::parseIncludeExcludeEquations(const string &inc_exc_eq_tags, set<pair<string, string>> & eq_tag_set, bool exclude_eqs) +DynamicModel::parseIncludeExcludeEquations(const string &inc_exc_eq_tags, set<pair<string, string>> &eq_tag_set, bool exclude_eqs) { string tags; if (filesystem::exists(inc_exc_eq_tags)) @@ -2961,7 +2960,7 @@ DynamicModel::parseIncludeExcludeEquations(const string &inc_exc_eq_tags, set<pa tags = tags.substr(1, tags.length() - 2); removeLeadingTrailingWhitespace(tags); - regex q (R"(^\w+\s*=)"); + regex q(R"(^\w+\s*=)"); smatch matches; string tagname = "name"; if (regex_search(tags, matches, q)) @@ -2980,17 +2979,17 @@ DynamicModel::parseIncludeExcludeEquations(const string &inc_exc_eq_tags, set<pa string quote_regex = "'[^']+'"; string non_quote_regex = R"([^,\s]+)"; - regex r (R"((\s*)" + quote_regex + "|" + non_quote_regex + R"(\s*)(,\s*()" + quote_regex + "|" + non_quote_regex + R"()\s*)*)"); - if (!regex_match (tags, r)) + regex r(R"((\s*)" + quote_regex + "|" + non_quote_regex + R"(\s*)(,\s*()" + quote_regex + "|" + non_quote_regex + R"()\s*)*)"); + if (!regex_match(tags, r)) { cerr << "Error: " << (exclude_eqs ? "exclude_eqs" : "include_eqs") << ": argument is of incorrect format." << endl; exit(EXIT_FAILURE); } - regex s (quote_regex + "|" + non_quote_regex); + regex s(quote_regex + "|" + non_quote_regex); for (auto it = sregex_iterator(tags.begin(), tags.end(), s); - it != sregex_iterator(); ++it) + it != sregex_iterator(); ++it) { auto str = it->str(); if (str[0] == '\'' && str[str.size()-1] == '\'') @@ -3000,7 +2999,7 @@ DynamicModel::parseIncludeExcludeEquations(const string &inc_exc_eq_tags, set<pa } void -DynamicModel::includeExcludeEquations(const string & eqs, bool exclude_eqs) +DynamicModel::includeExcludeEquations(const string &eqs, bool exclude_eqs) { if (eqs.empty()) return; @@ -3008,19 +3007,19 @@ DynamicModel::includeExcludeEquations(const string & eqs, bool exclude_eqs) set<pair<string, string>> eq_tag_set; parseIncludeExcludeEquations(eqs, eq_tag_set, exclude_eqs); - vector<int> excluded_vars = - ModelTree::includeExcludeEquations(eq_tag_set, exclude_eqs, - equations, equations_lineno, - equation_tags, equation_tags_xref, false); + vector<int> excluded_vars + = ModelTree::includeExcludeEquations(eq_tag_set, exclude_eqs, + equations, equations_lineno, + equation_tags, equation_tags_xref, false); // `static_only_equation_tags` is `vector<vector<pair<string, string>>>` // while `equation_tags` is `vector<pair<int, pair<string, string>>>` // so convert former structure to latter to conform with function call int n = 0; vector<pair<int, pair<string, string>>> tmp_static_only_equation_tags; - for (auto & eqn_tags : static_only_equations_equation_tags) + for (auto &eqn_tags : static_only_equations_equation_tags) { - for (auto & eqn_tag : eqn_tags) + for (auto &eqn_tag : eqn_tags) tmp_static_only_equation_tags.emplace_back(make_pair(n, eqn_tag)); n++; } @@ -3033,7 +3032,7 @@ DynamicModel::includeExcludeEquations(const string & eqs, bool exclude_eqs) { cerr << "ERROR: " << (exclude_eqs ? "exclude_eqs" : "include_eqs") << ": The equations specified by `"; cerr << eq_tag_set.begin()->first << "= "; - for (auto & it : eq_tag_set) + for (auto &it : eq_tag_set) cerr << it.second << ", "; cerr << "` were not found." << endl; exit(EXIT_FAILURE); @@ -3053,22 +3052,22 @@ DynamicModel::includeExcludeEquations(const string & eqs, bool exclude_eqs) { static_only_equations_equation_tags.resize(static_only_equations.size()); fill(static_only_equations_equation_tags.begin(), static_only_equations_equation_tags.end(), vector<pair<string, string>>()); - for (auto & it : tmp_static_only_equation_tags) + for (auto &it : tmp_static_only_equation_tags) static_only_equations_equation_tags.at(it.first).emplace_back(it.second); } // Collect list of used variables in updated list of equations set<pair<int, int>> eqn_vars; - for (const auto & eqn : equations) + for (const auto &eqn : equations) eqn->collectDynamicVariables(SymbolType::endogenous, eqn_vars); - for (const auto & eqn : static_only_equations) + for (const auto &eqn : static_only_equations) eqn->collectDynamicVariables(SymbolType::endogenous, eqn_vars); // Change LHS variable type of excluded equation if it is used in an eqution that has been kept for (auto ev : excluded_vars) { bool found = false; - for (const auto & it : eqn_vars) + for (const auto &it : eqn_vars) if (it.first == ev) { symbol_table.changeType(ev, SymbolType::exogenous); @@ -3159,9 +3158,9 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } } nstatic += sstatic; - nfwrd += sfwrd; - npred += spred; - nboth += sboth; + nfwrd += sfwrd; + npred += spred; + nboth += sboth; output << ";"; } output << "]';" << endl; @@ -3184,7 +3183,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de if (julia) { output << modstruct << "equation_tags = [" << endl; - for (const auto & equation_tag : equation_tags) + for (const auto &equation_tag : equation_tags) output << " EquationTag(" << equation_tag.first + 1 << R"( , ")" << equation_tag.second.first << R"(" , ")" @@ -3194,7 +3193,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de else { output << modstruct << "equations_tags = {" << endl; - for (const auto & equation_tag : equation_tags) + for (const auto &equation_tag : equation_tags) output << " " << equation_tag.first + 1 << " , '" << equation_tag.second.first << "' , '" << equation_tag.second.second << "' ;" << endl; @@ -3202,7 +3201,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } // Write mapping for variables and equations they are present in - for (const auto & variable : variableMapping) + for (const auto &variable : variableMapping) { output << modstruct << "mapping." << symbol_table.getName(variable.first) << ".eqidx = ["; for (auto equation : variable.second) @@ -3213,7 +3212,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de /* Say if static and dynamic models differ (because of [static] and [dynamic] equation tags) */ output << modstruct << "static_and_dynamic_models_differ = " - << (static_only_equations.size() > 0 ? "true" :"false") + << (static_only_equations.size() > 0 ? "true" : "false") << ";" << endl; // Say if model contains an external function call @@ -3255,7 +3254,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de count_lead_lag_incidence = 0; BlockSimulationType simulation_type = getBlockSimulationType(block); int block_size = getBlockSize(block); - max_lag = max_leadlag_block[block].first; + max_lag = max_leadlag_block[block].first; max_lead = max_leadlag_block[block].second; max_lag_endo = endo_max_leadlag_block[block].first; max_lead_endo = endo_max_leadlag_block[block].second; @@ -3272,15 +3271,15 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de tmp_s_eq << " " << getBlockEquationID(block, i)+1; } set<int> exogenous; - for (const auto & it : exo_block[block]) + for (const auto &it : exo_block[block]) for (int it1 : it.second) exogenous.insert(it1); set<int> exogenous_det; - for (const auto & it : exo_det_block[block]) + for (const auto &it : exo_det_block[block]) for (int it1 : it.second) exogenous_det.insert(it1); set<int> other_endogenous; - for (const auto & it : other_endo_block[block]) + for (const auto &it : other_endo_block[block]) for (int it1 : it.second) other_endogenous.insert(it1); output << "block_structure.block(" << block+1 << ").Simulation_Type = " << simulation_type << ";" << endl @@ -3358,7 +3357,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de tmp_s.str(""); count_lead_lag_incidence = 0; dynamic_jacob_map_t reordered_dynamic_jacobian; - for (const auto & it : blocks_derivatives[block]) + for (const auto &it : blocks_derivatives[block]) reordered_dynamic_jacobian[{ get<2>(it), get<1>(it), get<0>(it) }] = get<3>(it); output << "block_structure.block(" << block+1 << ").lead_lag_incidence = [];" << endl; int last_var = -1; @@ -3414,7 +3413,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de tmp_s.str(""); } vector<int> inter_state_var; - for (int & it_l : local_state_var) + for (int &it_l : local_state_var) for (auto it = state_var.begin(); it != state_var.end(); ++it) if (*it == it_l) inter_state_var.push_back(it - state_var.begin()+1); @@ -3471,7 +3470,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de for (int it : state_var) state_equ.push_back(equation_reordered[variable_inv_reordered[it - 1]]+1); - map<tuple<int, int, int>, int> lag_row_incidence; + map<tuple<int, int, int>, int> lag_row_incidence; for (const auto & [indices, d1] : derivatives[1]) { int deriv_id = indices[1]; @@ -3555,7 +3554,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } set<pair<int, int>> col_state_var_incidence; - for (const auto & it : row_state_var_incidence) + for (const auto &it : row_state_var_incidence) col_state_var_incidence.emplace(it.second, it.first); auto col_state_var_incidence_it = col_state_var_incidence.begin(); diag = true; @@ -3600,7 +3599,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de int size_v_index_KF = v_index_KF.size(); KF_index_file.write(reinterpret_cast<char *>(&size_v_index_KF), sizeof(size_v_index_KF)); - for (auto & it : v_index_KF) + for (auto &it : v_index_KF) KF_index_file.write(reinterpret_cast<char *>(&it), sizeof(index_KF)); vector<index_KF> v_index_KF_2; @@ -3618,7 +3617,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de int size_v_index_KF_2 = v_index_KF_2.size(); KF_index_file.write(reinterpret_cast<char *>(&size_v_index_KF_2), sizeof(size_v_index_KF_2)); - for (auto & it : v_index_KF_2) + for (auto &it : v_index_KF_2) KF_index_file.write(reinterpret_cast<char *>(&it), sizeof(index_KF)); KF_index_file.close(); } @@ -3694,7 +3693,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de output << "];" << endl; // Write Pac Model Consistent Expectation parameter info - for (auto & it : pac_mce_alpha_symb_ids) + for (auto &it : pac_mce_alpha_symb_ids) { output << modstruct << "pac." << it.first.first << ".equations." << it.first.second << ".mce.alpha = ["; for (auto it : it.second) @@ -3703,28 +3702,28 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } // Write Pac Model Consistent Expectation Z1 info - for (auto & it : pac_mce_z1_symb_ids) + for (auto &it : pac_mce_z1_symb_ids) output << modstruct << "pac." << it.first.first << ".equations." << it.first.second << ".mce.z1 = " << symbol_table.getTypeSpecificID(it.second) + 1 << ";" << endl; // Write Pac lag info - for (auto & it : pac_eqtag_and_lag) + for (auto &it : pac_eqtag_and_lag) output << modstruct << "pac." << it.first.first << ".equations." << it.second.first << ".max_lag = " << it.second.second << ";" << endl; // Write Pac equation tag info map<string, vector<pair<string, string>>> for_writing; - for (auto & it : pac_eqtag_and_lag) + for (auto &it : pac_eqtag_and_lag) for_writing[it.first.first].emplace_back(it.first.second, it.second.first); - for (auto & it : for_writing) + for (auto &it : for_writing) { output << modstruct << "pac." << it.first << ".tag_map = ["; - for (auto & it1 : it.second) - output << "{'" << it1.first << "', '" << it1.second << "'};" ; + for (auto &it1 : it.second) + output << "{'" << it1.first << "', '" << it1.second << "'};"; output << "];" << endl; } - for (auto & it : pac_model_info) + for (auto &it : pac_model_info) { vector<int> lhs = get<0>(it.second); output << modstruct << "pac." << it.first << ".lhs = ["; @@ -3740,7 +3739,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de output << modstruct << "pac." << it.first << ".auxiliary_model_type = '" << get<2>(it.second) << "';" << endl; } - for (auto & pit : pac_equation_info) + for (auto &pit : pac_equation_info) { auto [lhs_pac_var, optim_share_index, ar_params_and_vars, ec_params_and_vars, non_optim_vars_params_and_constants, additive_vars_params_and_constants, optim_additive_vars_params_and_constants] = pit.second; string substruct = pit.first.first + ".equations." + pit.first.second + "."; @@ -3782,32 +3781,32 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } output << "];" << endl << modstruct << "pac." << substruct << "ar.params = ["; - for (auto & it : ar_params_and_vars) + for (auto &it : ar_params_and_vars) output << symbol_table.getTypeSpecificID(it.first) + 1 << " "; output << "];" << endl << modstruct << "pac." << substruct << "ar.vars = ["; - for (auto & it : ar_params_and_vars) + for (auto &it : ar_params_and_vars) output << symbol_table.getTypeSpecificID(it.second.first) + 1 << " "; output << "];" << endl << modstruct << "pac." << substruct << "ar.lags = ["; - for (auto & it : ar_params_and_vars) + for (auto &it : ar_params_and_vars) output << it.second.second << " "; output << "];" << endl; if (!non_optim_vars_params_and_constants.empty()) { output << modstruct << "pac." << substruct << "non_optimizing_behaviour.params = ["; - for (auto & it : non_optim_vars_params_and_constants) + for (auto &it : non_optim_vars_params_and_constants) if (get<2>(it) >= 0) output << symbol_table.getTypeSpecificID(get<2>(it)) + 1 << " "; else output << "NaN "; output << "];" << endl << modstruct << "pac." << substruct << "non_optimizing_behaviour.vars = ["; - for (auto & it : non_optim_vars_params_and_constants) + for (auto &it : non_optim_vars_params_and_constants) output << symbol_table.getTypeSpecificID(get<0>(it)) + 1 << " "; output << "];" << endl << modstruct << "pac." << substruct << "non_optimizing_behaviour.isendo = ["; - for (auto & it : non_optim_vars_params_and_constants) + for (auto &it : non_optim_vars_params_and_constants) switch (symbol_table.getType(get<0>(it))) { case SymbolType::endogenous: @@ -3822,29 +3821,29 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } output << "];" << endl << modstruct << "pac." << substruct << "non_optimizing_behaviour.lags = ["; - for (auto & it : non_optim_vars_params_and_constants) + for (auto &it : non_optim_vars_params_and_constants) output << get<1>(it) << " "; output << "];" << endl << modstruct << "pac." << substruct << "non_optimizing_behaviour.scaling_factor = ["; - for (auto & it : non_optim_vars_params_and_constants) + for (auto &it : non_optim_vars_params_and_constants) output << get<3>(it) << " "; output << "];" << endl; } if (!additive_vars_params_and_constants.empty()) { output << modstruct << "pac." << substruct << "additive.params = ["; - for (auto & it : additive_vars_params_and_constants) + for (auto &it : additive_vars_params_and_constants) if (get<2>(it) >= 0) output << symbol_table.getTypeSpecificID(get<2>(it)) + 1 << " "; else output << "NaN "; output << "];" << endl << modstruct << "pac." << substruct << "additive.vars = ["; - for (auto & it : additive_vars_params_and_constants) + for (auto &it : additive_vars_params_and_constants) output << symbol_table.getTypeSpecificID(get<0>(it)) + 1 << " "; output << "];" << endl << modstruct << "pac." << substruct << "additive.isendo = ["; - for (auto & it : additive_vars_params_and_constants) + for (auto &it : additive_vars_params_and_constants) switch (symbol_table.getType(get<0>(it))) { case SymbolType::endogenous: @@ -3859,29 +3858,29 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } output << "];" << endl << modstruct << "pac." << substruct << "additive.lags = ["; - for (auto & it : additive_vars_params_and_constants) + for (auto &it : additive_vars_params_and_constants) output << get<1>(it) << " "; output << "];" << endl << modstruct << "pac." << substruct << "additive.scaling_factor = ["; - for (auto & it : additive_vars_params_and_constants) + for (auto &it : additive_vars_params_and_constants) output << get<3>(it) << " "; output << "];" << endl; } if (!optim_additive_vars_params_and_constants.empty()) { output << modstruct << "pac." << substruct << "optim_additive.params = ["; - for (auto & it : optim_additive_vars_params_and_constants) + for (auto &it : optim_additive_vars_params_and_constants) if (get<2>(it) >= 0) output << symbol_table.getTypeSpecificID(get<2>(it)) + 1 << " "; else output << "NaN "; output << "];" << endl << modstruct << "pac." << substruct << "optim_additive.vars = ["; - for (auto & it : optim_additive_vars_params_and_constants) + for (auto &it : optim_additive_vars_params_and_constants) output << symbol_table.getTypeSpecificID(get<0>(it)) + 1 << " "; output << "];" << endl << modstruct << "pac." << substruct << "optim_additive.isendo = ["; - for (auto & it : optim_additive_vars_params_and_constants) + for (auto &it : optim_additive_vars_params_and_constants) switch (symbol_table.getType(get<0>(it))) { case SymbolType::endogenous: @@ -3896,11 +3895,11 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } output << "];" << endl << modstruct << "pac." << substruct << "optim_additive.lags = ["; - for (auto & it : optim_additive_vars_params_and_constants) + for (auto &it : optim_additive_vars_params_and_constants) output << get<1>(it) << " "; output << "];" << endl << modstruct << "pac." << substruct << "optim_additive.scaling_factor = ["; - for (auto & it : optim_additive_vars_params_and_constants) + for (auto &it : optim_additive_vars_params_and_constants) output << get<3>(it) << " "; output << "];" << endl; } @@ -3909,7 +3908,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de << modstruct << "pac." << substruct << "h1_param_indices = [];" << endl; } - for (auto & it : pac_h0_indices) + for (auto &it : pac_h0_indices) { output << modstruct << "pac." << it.first.first << ".equations." << it.first.second << ".h0_param_indices = ["; for (auto it1 : it.second) @@ -3917,7 +3916,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de output << "];" << endl; } - for (auto & it : pac_h1_indices) + for (auto &it : pac_h1_indices) { output << modstruct << "pac." << it.first.first << ".equations." << it.first.second << ".h1_param_indices = ["; for (auto it1 : it.second) @@ -3964,7 +3963,7 @@ DynamicModel::updateVarAndTrendModel() const map<string, vector<int>> trend_varr; map<string, vector<set<pair<int, int>>>> rhsr; - for (const auto & it : eqnums) + for (const auto &it : eqnums) { vector<int> lhs, trend_var, trend_lhs; vector<set<pair<int, int>>> rhs; @@ -4047,17 +4046,17 @@ DynamicModel::fillVarModelTable() const map<string, vector<set<pair<int, int>>>> rhsr; map<string, vector<string>> eqtags = var_model_table.getEqTags(); - for (const auto & it : eqtags) + for (const auto &it : eqtags) { vector<int> eqnumber, lhs; vector<expr_t> lhs_expr_t; vector<set<pair<int, int>>> rhs; - for (const auto & eqtag : it.second) + for (const auto &eqtag : it.second) { int eqn = -1; set<pair<int, int>> lhs_set, lhs_tmp_set, rhs_set; - for (const auto & equation_tag : equation_tags) + for (const auto &equation_tag : equation_tags) if (equation_tag.second.first == "name" && equation_tag.second.second == eqtag) { @@ -4099,7 +4098,7 @@ DynamicModel::fillVarModelTable() const lhs_expr_t.push_back(*(lhs_expr_t_set.begin())); equations[eqn]->arg2->collectDynamicVariables(SymbolType::endogenous, rhs_set); - for (const auto & itrhs : rhs_set) + for (const auto &itrhs : rhs_set) if (itrhs.second > 0) { cerr << "ERROR: in Equation " << eqtag @@ -4127,7 +4126,7 @@ DynamicModel::fillVarModelTableFromOrigModel() const { map<string, vector<int>> lags, orig_diff_var; map<string, vector<bool>> diff; - for (const auto & it : var_model_table.getEqNums()) + for (const auto &it : var_model_table.getEqNums()) { set<expr_t> lhs; vector<int> orig_diff_var_vec; @@ -4174,7 +4173,7 @@ DynamicModel::fillVarModelTableFromOrigModel() const } set<expr_t> lhs_lag_equiv; - for(const auto & lh : lhs) + for (const auto &lh : lhs) { auto [lag_equiv_repr, index] = lh->getLagEquivalenceClass(); lhs_lag_equiv.insert(lag_equiv_repr); @@ -4198,7 +4197,7 @@ DynamicModel::fillAutoregressiveMatrix(bool is_var) const map<string, map<tuple<int, int, int>, expr_t>> ARr; auto eqnums = is_var ? var_model_table.getEqNums() : trend_component_model_table.getNonTargetEqNums(); - for (const auto & it : eqnums) + for (const auto &it : eqnums) { int i = 0; map<tuple<int, int, int>, expr_t> AR; @@ -4222,13 +4221,13 @@ DynamicModel::fillTrendComponentModelTable() const map<string, vector<set<pair<int, int>>>> rhsr; map<string, vector<string>> eqtags = trend_component_model_table.getEqTags(); map<string, vector<string>> trend_eqtags = trend_component_model_table.getTargetEqTags(); - for (const auto & it : trend_eqtags) + for (const auto &it : trend_eqtags) { vector<int> trend_eqnumber; - for (const auto & eqtag : it.second) + for (const auto &eqtag : it.second) { int eqn = -1; - for (const auto & equation_tag : equation_tags) + for (const auto &equation_tag : equation_tags) if (equation_tag.second.first == "name" && equation_tag.second.second == eqtag) { @@ -4246,17 +4245,17 @@ DynamicModel::fillTrendComponentModelTable() const trend_eqnums[it.first] = trend_eqnumber; } - for (const auto & it : eqtags) + for (const auto &it : eqtags) { vector<int> eqnumber, lhs; vector<expr_t> lhs_expr_t; vector<set<pair<int, int>>> rhs; - for (const auto & eqtag : it.second) + for (const auto &eqtag : it.second) { int eqn = -1; set<pair<int, int>> lhs_set, lhs_tmp_set, rhs_set; - for (const auto & equation_tag : equation_tags) + for (const auto &equation_tag : equation_tags) if (equation_tag.second.first == "name" && equation_tag.second.second == eqtag) { @@ -4298,7 +4297,7 @@ DynamicModel::fillTrendComponentModelTable() const lhs_expr_t.push_back(*(lhs_expr_t_set.begin())); equations[eqn]->arg2->collectDynamicVariables(SymbolType::endogenous, rhs_set); - for (const auto & itrhs : rhs_set) + for (const auto &itrhs : rhs_set) if (itrhs.second > 0) { cerr << "ERROR: in Equation " << eqtag @@ -4321,7 +4320,7 @@ DynamicModel::fillErrorComponentMatrix(const ExprNode::subst_table_t &diff_subst { map<string, map<tuple<int, int, int>, expr_t>> A0r, A0starr; - for (const auto & it : trend_component_model_table.getEqNums()) + for (const auto &it : trend_component_model_table.getEqNums()) { int i = 0; map<tuple<int, int, int>, expr_t> A0, A0star; @@ -4353,7 +4352,7 @@ DynamicModel::fillTrendComponentModelTableFromOrigModel() const { map<string, vector<int>> lags, orig_diff_var; map<string, vector<bool>> diff; - for (const auto & it : trend_component_model_table.getEqNums()) + for (const auto &it : trend_component_model_table.getEqNums()) { set<expr_t> lhs; vector<int> orig_diff_var_vec; @@ -4402,7 +4401,7 @@ DynamicModel::fillTrendComponentModelTableFromOrigModel() const } set<expr_t> lhs_lag_equiv; - for(const auto & lh : lhs) + for (const auto &lh : lhs) { auto [lag_equiv_repr, index] = lh->getLagEquivalenceClass(); lhs_lag_equiv.insert(lag_equiv_repr); @@ -4438,13 +4437,13 @@ DynamicModel::addEquationsForVar() // List of endogenous variables and the minimum lag value that must exist in the model equations map<string, int> var_endos_and_lags, model_endos_and_lags; - for (const auto & it : var_symbol_list_and_order) - for (auto & equation : equations) + for (const auto &it : var_symbol_list_and_order) + for (auto &equation : equations) if (equation->isVarModelReferenced(it.first)) { vector<string> symbol_list = it.second.first.get_symbols(); int order = it.second.second; - for (auto & it1 : symbol_list) + for (auto &it1 : symbol_list) if (order > 2) if (var_endos_and_lags.find(it1) != var_endos_and_lags.end()) var_endos_and_lags[it1] = min(var_endos_and_lags[it1], -order); @@ -4458,11 +4457,11 @@ DynamicModel::addEquationsForVar() // Ensure that the minimum lag value exists in the model equations. // If not, add an equation for it - for (auto & equation : equations) + for (auto &equation : equations) equation->getEndosAndMaxLags(model_endos_and_lags); int count = 0; - for (auto & it : var_endos_and_lags) + for (auto &it : var_endos_and_lags) if (auto it2 = model_endos_and_lags.find(it.first); it2 == model_endos_and_lags.end()) cerr << "WARNING: Variable used in VAR that is not used in the model: " << it.first << endl; @@ -4555,7 +4554,7 @@ DynamicModel::walkPacParameters(const string &name) map<pair<string, string>, pair<string, int>> eqtag_and_lag; int i = 0; - for (auto & equation : equations) + for (auto &equation : equations) { pair<int, int> lhs(-1, -1); pair<int, vector<tuple<int, bool, int>>> ec_params_and_vars; @@ -4584,8 +4583,8 @@ DynamicModel::walkPacParameters(const string &name) cerr << "Pac equation in incorrect format" << endl; exit(EXIT_FAILURE); } - auto [optim_share_index, optim_part, non_optim_part, additive_part] = - arg2->getPacOptimizingShareAndExprNodes(lhs_symb_id, lhs_orig_symb_id); + auto [optim_share_index, optim_part, non_optim_part, additive_part] + = arg2->getPacOptimizingShareAndExprNodes(lhs_symb_id, lhs_orig_symb_id); if (!optim_part) { @@ -4621,7 +4620,7 @@ DynamicModel::walkPacParameters(const string &name) } string eqtag; - for (auto & tag : equation_tags) + for (auto &tag : equation_tags) if (tag.first == (&equation - &equations[0])) if (tag.second.first == "name") { @@ -4658,7 +4657,7 @@ DynamicModel::walkPacParameters(const string &name) void DynamicModel::getPacMaxLag(const string &pac_model_name, map<pair<string, string>, pair<string, int>> &eqtag_and_lag) const { - for (auto & equation : equations) + for (auto &equation : equations) if (equation->containsPacExpectation(pac_model_name)) { set<pair<int, int>> endogs; @@ -4671,7 +4670,7 @@ DynamicModel::getPacMaxLag(const string &pac_model_name, map<pair<string, string } string eqtag; - for (auto & tag : equation_tags) + for (auto &tag : equation_tags) if (tag.first == (&equation - &equations[0])) if (tag.second.first == "name") { @@ -4686,7 +4685,7 @@ DynamicModel::getPacMaxLag(const string &pac_model_name, map<pair<string, string int DynamicModel::getPacTargetSymbId(const string &pac_model_name) const { - for (auto & equation : equations) + for (auto &equation : equations) if (equation->containsPacExpectation(pac_model_name)) { pair<int, int> lhs(-1, -1); @@ -4708,16 +4707,15 @@ DynamicModel::getPacTargetSymbId(const string &pac_model_name) const return -1; } - void DynamicModel::declarePacModelConsistentExpectationEndogs(const string &name) { int i = 0; - for (auto & equation : equations) + for (auto &equation : equations) if (equation->containsPacExpectation()) { string eqtag; - for (auto & tag : equation_tags) + for (auto &tag : equation_tags) if (tag.first == (&equation - &equations[0])) if (tag.second.first == "name") { @@ -4732,8 +4730,8 @@ DynamicModel::declarePacModelConsistentExpectationEndogs(const string &name) string standard_eqtag = "eq" + to_string(i++); try { - pac_mce_z1_symb_ids[{name, standard_eqtag}] = - symbol_table.addSymbol("mce_Z1_" + name + "_" + standard_eqtag, SymbolType::endogenous); + pac_mce_z1_symb_ids[{name, standard_eqtag}] + = symbol_table.addSymbol("mce_Z1_" + name + "_" + standard_eqtag, SymbolType::endogenous); } catch (SymbolTable::AlreadyDeclaredException &e) { @@ -4744,14 +4742,14 @@ DynamicModel::declarePacModelConsistentExpectationEndogs(const string &name) } void -DynamicModel::addPacModelConsistentExpectationEquation(const string & name, int discount_symb_id, +DynamicModel::addPacModelConsistentExpectationEquation(const string &name, int discount_symb_id, const map<pair<string, string>, pair<string, int>> &eqtag_and_lag, ExprNode::subst_table_t &diff_subst_table) { int pac_target_symb_id = getPacTargetSymbId(name); pac_eqtag_and_lag.insert(eqtag_and_lag.begin(), eqtag_and_lag.end()); int neqs = 0; - for (auto & it : eqtag_and_lag) + for (auto &it : eqtag_and_lag) { string eqtag = it.first.second; string standard_eqtag = it.second.first; @@ -4842,7 +4840,7 @@ DynamicModel::addPacModelConsistentExpectationEquation(const string & name, int neqs++; pac_expectation_substitution[{name, eqtag}] = AddVariable(mce_z1_symb_id); } - cout << "Pac Model Consistent Expectation: added " << neqs << " auxiliary variables and equations." << endl; + cout << "Pac Model Consistent Expectation: added " << neqs << " auxiliary variables and equations." << endl; } void @@ -4861,8 +4859,8 @@ DynamicModel::fillPacModelInfo(const string &pac_model_name, int growth_param_index = -1; if (growth) - growth_param_index = symbol_table.addSymbol(pac_model_name + - "_pac_growth_neutrality_correction", + growth_param_index = symbol_table.addSymbol(pac_model_name + +"_pac_growth_neutrality_correction", SymbolType::parameter); for (auto pac_models_and_eqtags : pac_eqtag_and_lag) @@ -4914,14 +4912,14 @@ DynamicModel::fillPacModelInfo(const string &pac_model_name, } void -DynamicModel::substitutePacExpectation(const string & pac_model_name) +DynamicModel::substitutePacExpectation(const string &pac_model_name) { - for (auto & it : pac_expectation_substitution) + for (auto &it : pac_expectation_substitution) if (it.first.first == pac_model_name) - for (auto & equation : equations) + for (auto &equation : equations) for (auto & [tagged_eq, tag_pair] : equation_tags) - if (tagged_eq == (&equation - &equations[0]) && - tag_pair.first == "name" && tag_pair.second == it.first.second) + if (tagged_eq == (&equation - &equations[0]) + && tag_pair.first == "name" && tag_pair.second == it.first.second) { auto substeq = dynamic_cast<BinaryOpNode *>(equation->substitutePacExpectation(pac_model_name, it.second)); assert(substeq); @@ -4947,7 +4945,7 @@ DynamicModel::computingPass(bool jacobianExo, int derivsOrder, int paramsDerivsO // Compute derivatives w.r. to all endogenous, and possibly exogenous and exogenous deterministic set<int> vars; - for (auto & it : deriv_id_table) + for (auto &it : deriv_id_table) { SymbolType type = symbol_table.getType(it.first.first); if (type == SymbolType::endogenous || (jacobianExo && (type == SymbolType::exogenous || type == SymbolType::exogenousDet))) @@ -5079,7 +5077,7 @@ void DynamicModel::computeXrefs() { int i = 0; - for (auto & equation : equations) + for (auto &equation : equations) { ExprNode::EquationInfo ei; equation->computeXrefs(ei); @@ -5099,7 +5097,7 @@ DynamicModel::computeXrefs() void DynamicModel::computeRevXref(map<pair<int, int>, set<int>> &xrefset, const set<pair<int, int>> &eiref, int eqn) { - for (const auto & it : eiref) + for (const auto &it : eiref) { set<int> eq; if (xrefset.find(it) != xrefset.end()) @@ -5120,22 +5118,22 @@ DynamicModel::writeXrefs(ostream &output) const for (auto it = xrefs.begin(); it != xrefs.end(); ++it, i++) { output << "M_.xref1.param{" << i << "} = [ "; - for (const auto & it1 : it->second.param) + for (const auto &it1 : it->second.param) output << symbol_table.getTypeSpecificID(it1.first) + 1 << " "; output << "];" << endl; output << "M_.xref1.endo{" << i << "} = [ "; - for (const auto & it1 : it->second.endo) + for (const auto &it1 : it->second.endo) output << "struct('id', " << symbol_table.getTypeSpecificID(it1.first) + 1 << ", 'shift', " << it1.second << ");"; output << "];" << endl; output << "M_.xref1.exo{" << i << "} = [ "; - for (const auto & it1 : it->second.exo) + for (const auto &it1 : it->second.exo) output << "struct('id', " << symbol_table.getTypeSpecificID(it1.first) + 1 << ", 'shift', " << it1.second << ");"; output << "];" << endl; output << "M_.xref1.exo_det{" << i << "} = [ "; - for (const auto & it1 : it->second.exo_det) + for (const auto &it1 : it->second.exo_det) output << "struct('id', " << symbol_table.getTypeSpecificID(it1.first) + 1 << ", 'shift', " << it1.second << ");"; output << "];" << endl; } @@ -5154,7 +5152,7 @@ void DynamicModel::writeRevXrefs(ostream &output, const map<pair<int, int>, set<int>> &xrefmap, const string &type) const { int last_tsid = -1; - for (const auto & it : xrefmap) + for (const auto &it : xrefmap) { int tsid = symbol_table.getTypeSpecificID(it.first.first) + 1; output << "M_.xref2." << type << "{" << tsid << "} = [ "; @@ -5180,13 +5178,13 @@ DynamicModel::get_Derivatives(int block) BlockSimulationType simulation_type = getBlockSimulationType(block); if (simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) { - max_lag = 1; + max_lag = 1; max_lead = 1; setBlockLeadLag(block, max_lag, max_lead); } else { - max_lag = getBlockMaxLag(block); + max_lag = getBlockMaxLag(block); max_lead = getBlockMaxLead(block); } int block_size = getBlockSize(block); @@ -5549,10 +5547,10 @@ DynamicModel::computeRamseyPolicyFOCs(const StaticModel &static_model) set<pair<int, int>> dynvars; int max_eq_lead = 0; int max_eq_lag = 0; - for (auto & equation : equations) + for (auto &equation : equations) equation->collectDynamicVariables(SymbolType::endogenous, dynvars); - for (const auto & dynvar : dynvars) + for (const auto &dynvar : dynvars) { int lag = dynvar.second; if (max_eq_lead < lag) @@ -5592,14 +5590,14 @@ DynamicModel::computeRamseyPolicyFOCs(const StaticModel &static_model) //Compute derivatives and overwrite equations vector<expr_t> neweqs; - for (auto & it : deriv_id_table) + for (auto &it : deriv_id_table) // For all endogenous variables with zero lag if (symbol_table.getType(it.first.first) == SymbolType::endogenous && it.first.second == 0) neweqs.push_back(AddEqual(equations[0]->getNonZeroPartofEquation()->getDerivative(it.second), Zero)); // Add new equations equations.clear(); - for (auto & neweq : neweqs) + for (auto &neweq : neweqs) addEquation(neweq, -1); } @@ -5607,7 +5605,7 @@ void DynamicModel::toNonlinearPart(DynamicModel &non_linear_equations_dynamic_model) const { // Convert model local variables (need to be done first) - for (const auto & it : local_variables_table) + for (const auto &it : local_variables_table) non_linear_equations_dynamic_model.AddLocalVariable(it.first, it.second); } @@ -5638,7 +5636,7 @@ void DynamicModel::expandEqTags() { set<int> existing_tags; - for (const auto & eqn : equation_tags) + for (const auto &eqn : equation_tags) if (eqn.second.first == "name") existing_tags.insert(eqn.first); @@ -5649,7 +5647,7 @@ DynamicModel::expandEqTags() equation_tags.emplace_back(eq, pair("name", symbol_table.getName(lhs_expr->symb_id))); equation_tags_xref.emplace(pair("name", symbol_table.getName(lhs_expr->symb_id)), eq); } - else if (equation_tags_xref.find({ "name",to_string(eq+1) }) == equation_tags_xref.end()) + else if (equation_tags_xref.find({ "name", to_string(eq+1) }) == equation_tags_xref.end()) { equation_tags.emplace_back(eq, pair("name", to_string(eq+1))); equation_tags_xref.emplace(pair("name", to_string(eq+1)), eq); @@ -5667,7 +5665,7 @@ set<int> DynamicModel::findUnusedEndogenous() { set<int> usedEndo, unusedEndo; - for (auto & equation : equations) + for (auto &equation : equations) equation->collectVariables(SymbolType::endogenous, usedEndo); set<int> allEndo = symbol_table.getEndogenous(); set_difference(allEndo.begin(), allEndo.end(), @@ -5680,7 +5678,7 @@ set<int> DynamicModel::findUnusedExogenous() { set<int> usedExo, unusedExo, unobservedExo; - for (auto & equation : equations) + for (auto &equation : equations) equation->collectVariables(SymbolType::exogenous, usedExo); set<int> observedExo = symbol_table.getObservedExogenous(); set<int> allExo = symbol_table.getExogenous(); @@ -5698,7 +5696,7 @@ DynamicModel::setLeadsLagsOrig() { set<pair<int, int>> dynvars; - for (auto & equation : equations) + for (auto &equation : equations) { equation->collectDynamicVariables(SymbolType::endogenous, dynvars); equation->collectDynamicVariables(SymbolType::exogenous, dynvars); @@ -5708,7 +5706,7 @@ DynamicModel::setLeadsLagsOrig() max_lag_with_diffs_expanded_orig); } - for (const auto & dynvar : dynvars) + for (const auto &dynvar : dynvars) { int lag = dynvar.second; SymbolType type = symbol_table.getType(dynvar.first); @@ -5741,12 +5739,12 @@ DynamicModel::computeDerivIDs() { set<pair<int, int>> dynvars; - for (auto & equation : equations) + for (auto &equation : equations) equation->collectDynamicVariables(SymbolType::endogenous, dynvars); dynJacobianColsNbr = dynvars.size(); - for (auto & equation : equations) + for (auto &equation : equations) { equation->collectDynamicVariables(SymbolType::exogenous, dynvars); equation->collectDynamicVariables(SymbolType::exogenousDet, dynvars); @@ -5755,7 +5753,7 @@ DynamicModel::computeDerivIDs() equation->collectDynamicVariables(SymbolType::logTrend, dynvars); } - for (const auto & dynvar : dynvars) + for (const auto &dynvar : dynvars) { int lag = dynvar.second; SymbolType type = symbol_table.getType(dynvar.first); @@ -5846,7 +5844,7 @@ DynamicModel::computeDynJacobianCols(bool jacobianExo) and fill the dynamic columns for exogenous and exogenous deterministic */ map<pair<int, int>, int> ordered_dyn_endo; - for (auto & it : deriv_id_table) + for (auto &it : deriv_id_table) { int symb_id = it.first.first; int lag = it.first.second; @@ -5883,7 +5881,7 @@ DynamicModel::computeDynJacobianCols(bool jacobianExo) // Fill in dynamic jacobian columns for endogenous int sorted_id = 0; - for (auto & it : ordered_dyn_endo) + for (auto &it : ordered_dyn_endo) dyn_jacobian_cols_table[it.second] = sorted_id++; // Set final value for dynJacobianColsNbr @@ -5917,7 +5915,7 @@ DynamicModel::testTrendDerivativesEqualToZero(const eval_context_t &eval_context { expr_t testeq = AddLog(homogeneq); // F = log(lhs-rhs) testeq = testeq->getDerivative(it.second); // d F / d Trend - for (auto & endogit : deriv_id_table) + for (auto &endogit : deriv_id_table) if (symbol_table.getType(endogit.first.first) == SymbolType::endogenous) { double nearZero = testeq->getDerivative(endogit.second)->eval(eval_context); // eval d F / d Trend d Endog @@ -5942,13 +5940,13 @@ DynamicModel::writeParamsDerivativesFile(const string &basename, bool julia) con return; ExprNodeOutputType output_type = (julia ? ExprNodeOutputType::juliaDynamicModel : ExprNodeOutputType::matlabDynamicModel); - ostringstream tt_output; // Used for storing model temp vars and equations - ostringstream rp_output; // 1st deriv. of residuals w.r.t. parameters - ostringstream gp_output; // 1st deriv. of Jacobian w.r.t. parameters - ostringstream rpp_output; // 2nd deriv of residuals w.r.t. parameters - ostringstream gpp_output; // 2nd deriv of Jacobian w.r.t. parameters - ostringstream hp_output; // 1st deriv. of Hessian w.r.t. parameters - ostringstream g3p_output; // 1st deriv. of 3rd deriv. matrix w.r.t. parameters + ostringstream tt_output; // Used for storing model temp vars and equations + ostringstream rp_output; // 1st deriv. of residuals w.r.t. parameters + ostringstream gp_output; // 1st deriv. of Jacobian w.r.t. parameters + ostringstream rpp_output; // 2nd deriv of residuals w.r.t. parameters + ostringstream gpp_output; // 2nd deriv of Jacobian w.r.t. parameters + ostringstream hp_output; // 1st deriv. of Hessian w.r.t. parameters + ostringstream g3p_output; // 1st deriv. of 3rd deriv. matrix w.r.t. parameters temporary_terms_t temp_term_union; deriv_node_temp_terms_t tef_terms; @@ -6304,7 +6302,7 @@ DynamicModel::substituteLeadLagInternal(AuxVarType type, bool deterministic_mode // Substitute in used model local variables set<int> used_local_vars; - for (auto & equation : equations) + for (auto &equation : equations) equation->collectVariables(SymbolType::modelLocalVariable, used_local_vars); for (int used_local_var : used_local_vars) @@ -6336,7 +6334,7 @@ DynamicModel::substituteLeadLagInternal(AuxVarType type, bool deterministic_mode } // Substitute in equations - for (auto & equation : equations) + for (auto &equation : equations) { expr_t subst; switch (type) @@ -6366,7 +6364,7 @@ DynamicModel::substituteLeadLagInternal(AuxVarType type, bool deterministic_mode } // Add new equations - for (auto & neweq : neweqs) + for (auto &neweq : neweqs) { addEquation(neweq, -1); aux_equations.push_back(neweq); @@ -6406,7 +6404,7 @@ DynamicModel::substituteLeadLagInternal(AuxVarType type, bool deterministic_mode void DynamicModel::substituteAdl() { - for (auto & equation : equations) + for (auto &equation : equations) equation = dynamic_cast<BinaryOpNode *>(equation->substituteAdl()); } @@ -6414,10 +6412,10 @@ vector<int> DynamicModel::getEquationNumbersFromTags(const set<string> &eqtags) const { vector<int> eqnumbers; - for (auto & eqtag : eqtags) + for (auto &eqtag : eqtags) { bool found = false; - for (const auto & equation_tag : equation_tags) + for (const auto &equation_tag : equation_tags) if (equation_tag.second.first == "name" && equation_tag.second.second == eqtag) { @@ -6438,10 +6436,10 @@ void DynamicModel::findPacExpectationEquationNumbers(vector<int> &eqnumbers) const { int i = 0; - for (auto & equation : equations) + for (auto &equation : equations) { - if (equation->containsPacExpectation() && - find(eqnumbers.begin(), eqnumbers.end(), i) == eqnumbers.end()) + if (equation->containsPacExpectation() + && find(eqnumbers.begin(), eqnumbers.end(), i) == eqnumbers.end()) eqnumbers.push_back(i); i++; } @@ -6473,7 +6471,7 @@ DynamicModel::substituteUnaryOps(const vector<int> &eqnumbers) set<int> used_local_vars; for (int eqnumber : eqnumbers) equations[eqnumber]->collectVariables(SymbolType::modelLocalVariable, used_local_vars); - for (auto & it : local_variables_table) + for (auto &it : local_variables_table) if (used_local_vars.find(it.first) != used_local_vars.end()) it.second->findUnaryOpNodesForAuxVarCreation(nodes); @@ -6483,11 +6481,11 @@ DynamicModel::substituteUnaryOps(const vector<int> &eqnumbers) // Substitute in model local variables vector<BinaryOpNode *> neweqs; - for (auto & it : local_variables_table) + for (auto &it : local_variables_table) it.second = it.second->substituteUnaryOpNodes(nodes, subst_table, neweqs); // Substitute in equations - for (auto & equation : equations) + for (auto &equation : equations) { auto substeq = dynamic_cast<BinaryOpNode *>(equation-> substituteUnaryOpNodes(nodes, subst_table, neweqs)); @@ -6496,7 +6494,7 @@ DynamicModel::substituteUnaryOps(const vector<int> &eqnumbers) } // Add new equations - for (auto & neweq : neweqs) + for (auto &neweq : neweqs) { addEquation(neweq, -1); aux_equations.push_back(neweq); @@ -6521,27 +6519,27 @@ DynamicModel::substituteDiff(vector<expr_t> &pac_growth) // Mark diff operators to be substituted in model local variables set<int> used_local_vars; - for (const auto & equation : equations) + for (const auto &equation : equations) equation->collectVariables(SymbolType::modelLocalVariable, used_local_vars); - for (auto & it : local_variables_table) + for (auto &it : local_variables_table) if (used_local_vars.find(it.first) != used_local_vars.end()) it.second->findDiffNodes(diff_nodes); // Mark diff operators to be substituted in equations - for (const auto & equation : equations) + for (const auto &equation : equations) equation->findDiffNodes(diff_nodes); - for (const auto & gv : pac_growth) + for (const auto &gv : pac_growth) if (gv) gv->findDiffNodes(diff_nodes); // Substitute in model local variables vector<BinaryOpNode *> neweqs; - for (auto & it : local_variables_table) + for (auto &it : local_variables_table) it.second = it.second->substituteDiff(diff_nodes, diff_subst_table, neweqs); // Substitute in equations - for (auto & equation : equations) + for (auto &equation : equations) { auto substeq = dynamic_cast<BinaryOpNode *>(equation-> substituteDiff(diff_nodes, diff_subst_table, neweqs)); @@ -6549,12 +6547,12 @@ DynamicModel::substituteDiff(vector<expr_t> &pac_growth) equation = substeq; } - for (auto & it : pac_growth) + for (auto &it : pac_growth) if (it) it = it->substituteDiff(diff_nodes, diff_subst_table, neweqs); // Add new equations - for (auto & neweq : neweqs) + for (auto &neweq : neweqs) { addEquation(neweq, -1); aux_equations.push_back(neweq); @@ -6573,11 +6571,11 @@ DynamicModel::substituteExpectation(bool partial_information_model) vector<BinaryOpNode *> neweqs; // Substitute in model local variables - for (auto & it : local_variables_table) + for (auto &it : local_variables_table) it.second = it.second->substituteExpectation(subst_table, neweqs, partial_information_model); // Substitute in equations - for (auto & equation : equations) + for (auto &equation : equations) { auto substeq = dynamic_cast<BinaryOpNode *>(equation->substituteExpectation(subst_table, neweqs, partial_information_model)); assert(substeq); @@ -6585,7 +6583,7 @@ DynamicModel::substituteExpectation(bool partial_information_model) } // Add new equations - for (auto & neweq : neweqs) + for (auto &neweq : neweqs) { addEquation(neweq, -1); aux_equations.push_back(neweq); @@ -6603,10 +6601,10 @@ DynamicModel::substituteExpectation(bool partial_information_model) void DynamicModel::transformPredeterminedVariables() { - for (auto & it : local_variables_table) + for (auto &it : local_variables_table) it.second = it.second->decreaseLeadsLagsPredeterminedVariables(); - for (auto & equation : equations) + for (auto &equation : equations) { auto substeq = dynamic_cast<BinaryOpNode *>(equation->decreaseLeadsLagsPredeterminedVariables()); assert(substeq); @@ -6620,14 +6618,14 @@ DynamicModel::detrendEquations() // We go backwards in the list of trend_vars, to deal correctly with I(2) processes for (auto it = nonstationary_symbols_map.crbegin(); it != nonstationary_symbols_map.crend(); ++it) - for (auto & equation : equations) + for (auto &equation : equations) { auto substeq = dynamic_cast<BinaryOpNode *>(equation->detrend(it->first, it->second.first, it->second.second)); assert(substeq); equation = dynamic_cast<BinaryOpNode *>(substeq); } - for (auto & equation : equations) + for (auto &equation : equations) { auto substeq = dynamic_cast<BinaryOpNode *>(equation->removeTrendLeadLag(trend_symbols_map)); assert(substeq); @@ -6638,7 +6636,7 @@ DynamicModel::detrendEquations() void DynamicModel::removeTrendVariableFromEquations() { - for (auto & equation : equations) + for (auto &equation : equations) { auto substeq = dynamic_cast<BinaryOpNode *>(equation->replaceTrendVar()); assert(substeq); @@ -6689,8 +6687,8 @@ DynamicModel::fillEvalContext(eval_context_t &eval_context) const //Third, trend variables vector <int> trendVars = symbol_table.getTrendVarIds(); - for (int & trendVar : trendVars) - eval_context[trendVar] = 2; //not <= 0 bc of log, not 1 bc of powers + for (int &trendVar : trendVars) + eval_context[trendVar] = 2; //not <= 0 bc of log, not 1 bc of powers } bool @@ -6713,14 +6711,14 @@ DynamicModel::addStaticOnlyEquation(expr_t eq, int lineno, const vector<pair<str assert(beq && beq->op_code == BinaryOpcode::equal); vector<pair<string, string>> soe_eq_tags; - for (const auto & eq_tag : eq_tags) + for (const auto &eq_tag : eq_tags) soe_eq_tags.push_back(eq_tag); int n = static_only_equations.size(); static_only_equations.push_back(beq); static_only_equations_lineno.push_back(lineno); static_only_equations_equation_tags.push_back(soe_eq_tags); - for (auto & it : soe_eq_tags) + for (auto &it : soe_eq_tags) static_only_equation_tags_xref.emplace(it, n); } @@ -6735,7 +6733,7 @@ DynamicModel::dynamicOnlyEquationsNbr() const { set<int> eqs; - for (const auto & equation_tag : equation_tags) + for (const auto &equation_tag : equation_tags) if (equation_tag.second.first == "dynamic") eqs.insert(equation_tag.first); @@ -6748,7 +6746,7 @@ DynamicModel::isChecksumMatching(const string &basename, bool block) const stringstream buffer; // Write equation tags - for (const auto & equation_tag : equation_tags) + for (const auto &equation_tag : equation_tags) buffer << " " << equation_tag.first + 1 << equation_tag.second.first << equation_tag.second.second << endl; @@ -6822,7 +6820,7 @@ DynamicModel::writeJsonAST(ostream &output) const output << R"({ "number":)" << eq << R"(, "line":)" << equations_lineno[eq]; - for (const auto & equation_tag : equation_tags) + for (const auto &equation_tag : equation_tags) if (equation_tag.first == eq) eqtags.push_back(equation_tag.second); @@ -6854,16 +6852,16 @@ DynamicModel::writeJsonVariableMapping(ostream &output) const output << R"("variable_mapping":[)" << endl; int ii = 0; int end_idx_map = static_cast<int>(variableMapping.size()-1); - for (const auto & variable : variableMapping) + for (const auto &variable : variableMapping) { output << R"({"name": ")" << symbol_table.getName(variable.first) << R"(", "equations":[)"; int it = 0; int end_idx_eq = static_cast<int>(variable.second.size())-1; - for (const auto & equation : variable.second) - for (const auto & equation_tag : equation_tags) + for (const auto &equation : variable.second) + for (const auto &equation_tag : equation_tags) if (equation_tag.first == equation && equation_tag.second.first == "name") - output << R"(")" << equation_tag.second.second << (it++ == end_idx_eq ? R"("])":R"(", )"); - output << (ii++ == end_idx_map ? R"(})":R"(},)") << endl; + output << R"(")" << equation_tag.second.second << (it++ == end_idx_eq ? R"("])" : R"(", )"); + output << (ii++ == end_idx_map ? R"(})" : R"(},)") << endl; } output << "]"; } @@ -6968,9 +6966,9 @@ DynamicModel::writeJsonDynamicModelInfo(ostream &output) const } } nstatic += sstatic; - nfwrd += sfwrd; - npred += spred; - nboth += sboth; + nfwrd += sfwrd; + npred += spred; + nboth += sboth; output << "]"; } output << "], " @@ -6987,8 +6985,8 @@ DynamicModel::writeJsonDynamicModelInfo(ostream &output) const void DynamicModel::writeJsonComputingPassOutput(ostream &output, bool writeDetails) const { - ostringstream model_local_vars_output; // Used for storing model local vars - vector<ostringstream> d_output(derivatives.size()); // Derivatives output (at all orders, including 0=residual) + ostringstream model_local_vars_output; // Used for storing model local vars + vector<ostringstream> d_output(derivatives.size()); // Derivatives output (at all orders, including 0=residual) deriv_node_temp_terms_t tef_terms; temporary_terms_t temp_term_union; @@ -7044,15 +7042,15 @@ DynamicModel::writeJsonComputingPassOutput(ostream &output, bool writeDetails) c if (writeDetails) for (size_t j = 1; j < vidx.size(); j++) d_output[i] << R"(, "var)" << (i > 1 ? to_string(j) : "") << R"(": ")" << symbol_table.getName(getSymbIDByDerivID(vidx[j])) << R"(")" - << R"(, "shift)" << (i > 1 ? to_string(j) : "") << R"(": )" << getLagByDerivID(vidx[j]); + << R"(, "shift)" << (i > 1 ? to_string(j) : "") << R"(": )" << getLagByDerivID(vidx[j]); d_output[i] << R"(, "val": ")"; d->writeJsonOutput(d_output[i], temp_term_union, tef_terms); d_output[i] << R"("})" << endl; } - d_output[i] << "]}"; + d_output[i] << "]}"; - ncols *= dynJacobianColsNbr; + ncols *= dynJacobianColsNbr; } if (writeDetails) @@ -7071,14 +7069,14 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output, bool writeDetails) if (!params_derivatives.size()) return; - ostringstream model_local_vars_output; // Used for storing model local vars - ostringstream model_output; // Used for storing model temp vars and equations - ostringstream rp_output; // 1st deriv. of residuals w.r.t. parameters - ostringstream gp_output; // 1st deriv. of Jacobian w.r.t. parameters - ostringstream rpp_output; // 2nd deriv of residuals w.r.t. parameters - ostringstream gpp_output; // 2nd deriv of Jacobian w.r.t. parameters - ostringstream hp_output; // 1st deriv. of Hessian w.r.t. parameters - ostringstream g3p_output; // 1st deriv. of 3rd deriv. matrix w.r.t. parameters + ostringstream model_local_vars_output; // Used for storing model local vars + ostringstream model_output; // Used for storing model temp vars and equations + ostringstream rp_output; // 1st deriv. of residuals w.r.t. parameters + ostringstream gp_output; // 1st deriv. of Jacobian w.r.t. parameters + ostringstream rpp_output; // 2nd deriv of residuals w.r.t. parameters + ostringstream gpp_output; // 2nd deriv of Jacobian w.r.t. parameters + ostringstream hp_output; // 1st deriv. of Hessian w.r.t. parameters + ostringstream g3p_output; // 1st deriv. of 3rd deriv. matrix w.r.t. parameters deriv_node_temp_terms_t tef_terms; writeJsonModelLocalVariables(model_local_vars_output, tef_terms); @@ -7315,7 +7313,6 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output, bool writeDetails) } g3p_output << "]}" << endl; - if (writeDetails) output << R"("dynamic_model_params_derivative": {)"; else @@ -7334,6 +7331,6 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output, bool writeDetails) void DynamicModel::substituteVarExpectation(const map<string, expr_t> &subst_table) { - for (auto & equation : equations) + for (auto &equation : equations) equation = dynamic_cast<BinaryOpNode *>(equation->substituteVarExpectation(subst_table)); } diff --git a/src/DynamicModel.hh b/src/DynamicModel.hh index dc615173..9a2db5c7 100644 --- a/src/DynamicModel.hh +++ b/src/DynamicModel.hh @@ -288,10 +288,11 @@ private: X Y */ - void parseIncludeExcludeEquations(const string &inc_exc_eq_tags, set<pair<string, string>> & eq_tag_set, bool exclude_eqs); + void parseIncludeExcludeEquations(const string &inc_exc_eq_tags, set<pair<string, string>> &eq_tag_set, bool exclude_eqs); // General function that removes leading/trailing whitespace from a string - inline void removeLeadingTrailingWhitespace(string & str) + inline void + removeLeadingTrailingWhitespace(string &str) { str.erase(0, str.find_first_not_of("\t\n\v\f\r ")); str.erase(str.find_last_not_of("\t\n\v\f\r ") + 1); @@ -306,8 +307,8 @@ public: DynamicModel(const DynamicModel &m); DynamicModel(DynamicModel &&) = delete; - DynamicModel & operator=(const DynamicModel &m); - DynamicModel & operator=(DynamicModel &&) = delete; + DynamicModel &operator=(const DynamicModel &m); + DynamicModel &operator=(DynamicModel &&) = delete; //! Compute cross references void computeXrefs(); @@ -358,13 +359,15 @@ public: //! Tells whether Hessian has been computed /*! This is needed to know whether no non-zero equation in Hessian means a - zero Hessian or Hessian not computed */ - inline bool isHessianComputed() const + zero Hessian or Hessian not computed */ + inline bool + isHessianComputed() const { return hessian_computed; } //! Returns equations that have non-zero second derivatives - inline set<int> getNonZeroHessianEquations() const + inline set<int> + getNonZeroHessianEquations() const { return nonzero_hessian_eqs; } @@ -406,7 +409,7 @@ public: expr_t growth); //! Substitutes pac_expectation operator with expectation based on auxiliary model - void substitutePacExpectation(const string & pac_model_name); + void substitutePacExpectation(const string &pac_model_name); //! Adds informations for simulation in a binary file void Write_Inf_To_Bin_File_Block(const string &basename, @@ -439,7 +442,7 @@ public: void setLeadsLagsOrig(); //! Removes equations from the model according to name tags - void includeExcludeEquations(const string & eqs, bool exclude_eqs); + void includeExcludeEquations(const string &eqs, bool exclude_eqs); //! Replaces model equations with derivatives of Lagrangian w.r.t. endogenous void computeRamseyPolicyFOCs(const StaticModel &static_model); @@ -498,12 +501,14 @@ public: //! Transforms the model by removing trends specified by the user void detrendEquations(); - inline const nonstationary_symbols_map_t & getNonstationarySymbolsMap() const + inline const nonstationary_symbols_map_t & + getNonstationarySymbolsMap() const { return nonstationary_symbols_map; } - inline const map<int, expr_t> & getTrendSymbolsMap() const + inline const map<int, expr_t> & + getTrendSymbolsMap() const { return trend_symbols_map; } @@ -536,7 +541,7 @@ public: void declarePacModelConsistentExpectationEndogs(const string &name); //! Add model consistent expectation equation for pac model - void addPacModelConsistentExpectationEquation(const string & name, int discount, + void addPacModelConsistentExpectationEquation(const string &name, int discount, const map<pair<string, string>, pair<string, int>> &eqtag_and_lag, ExprNode::subst_table_t &diff_subst_table); @@ -581,7 +586,11 @@ public: //! Fills eval context with values of model local variables and auxiliary variables void fillEvalContext(eval_context_t &eval_context) const; - auto getStaticOnlyEquationsInfo() const { return tuple(static_only_equations, static_only_equations_lineno, static_only_equations_equation_tags); }; + auto + getStaticOnlyEquationsInfo() const + { + return tuple(static_only_equations, static_only_equations_lineno, static_only_equations_equation_tags); + }; //! Return the number of blocks unsigned int diff --git a/src/DynareMain1.cc b/src/DynareMain1.cc index 2063c68e..93e5c354 100644 --- a/src/DynareMain1.cc +++ b/src/DynareMain1.cc @@ -44,7 +44,7 @@ main1(const string &filename, const string &basename, istream &modfile, bool deb exit(EXIT_FAILURE); } - string str (macro_output.str()); + string str(macro_output.str()); if (no_empty_line_macro) { auto compareNewline = [](char i, char j) { return i == '\n' && j == '\n'; }; diff --git a/src/ExprNode.cc b/src/ExprNode.cc index b1a73493..5807a282 100644 --- a/src/ExprNode.cc +++ b/src/ExprNode.cc @@ -138,7 +138,7 @@ ExprNode::collectEndogenous(set<pair<int, int>> &result) const { set<pair<int, int>> symb_ids; collectDynamicVariables(SymbolType::endogenous, symb_ids); - for (const auto & symb_id : symb_ids) + for (const auto &symb_id : symb_ids) result.emplace(datatree.symbol_table.getTypeSpecificID(symb_id.first), symb_id.second); } @@ -147,7 +147,7 @@ ExprNode::collectExogenous(set<pair<int, int>> &result) const { set<pair<int, int>> symb_ids; collectDynamicVariables(SymbolType::exogenous, symb_ids); - for (const auto & symb_id : symb_ids) + for (const auto &symb_id : symb_ids) result.emplace(datatree.symbol_table.getTypeSpecificID(symb_id.first), symb_id.second); } @@ -346,9 +346,9 @@ ExprNode::fillErrorCorrectionRow(int eqn, // Helper function auto one_step_orig = [this](int symb_id) { - return datatree.symbol_table.isAuxiliaryVariable(symb_id) ? - datatree.symbol_table.getOrigSymbIdForDiffAuxVar(symb_id) : symb_id; - }; + return datatree.symbol_table.isAuxiliaryVariable(symb_id) ? + datatree.symbol_table.getOrigSymbIdForDiffAuxVar(symb_id) : symb_id; + }; /* Verify that all variables belong to the error-correction term. FIXME: same remark as above about skipping terms. */ @@ -684,7 +684,7 @@ NumConstNode::substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst } expr_t -NumConstNode::substitutePacExpectation(const string & name, expr_t subexpr) +NumConstNode::substitutePacExpectation(const string &name, expr_t subexpr) { return const_cast<NumConstNode *>(this); } @@ -1273,7 +1273,7 @@ VariableNode::compile(ostream &CompileCode, unsigned int &instruction_number, { if (dynamic) { - if (steady_dynamic) // steady state values in a dynamic model + if (steady_dynamic) // steady state values in a dynamic model { FLDVS_ fldvs{static_cast<uint8_t>(type), static_cast<unsigned int>(tsid)}; fldvs.write(CompileCode, instruction_number); @@ -1302,7 +1302,7 @@ VariableNode::compile(ostream &CompileCode, unsigned int &instruction_number, { if (dynamic) { - if (steady_dynamic) // steady state values in a dynamic model + if (steady_dynamic) // steady state values in a dynamic model { cerr << "Impossible case: steady_state in rhs of equation" << endl; exit(EXIT_FAILURE); @@ -1697,7 +1697,7 @@ VariableNode::substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst } expr_t -VariableNode::substitutePacExpectation(const string & name, expr_t subexpr) +VariableNode::substitutePacExpectation(const string &name, expr_t subexpr) { return const_cast<VariableNode *>(this); } @@ -2062,7 +2062,7 @@ VariableNode::findConstantEquations(map<VariableNode *, NumConstNode *> &table) expr_t VariableNode::replaceVarsInEquation(map<VariableNode *, NumConstNode *> &table) const { - for (auto & it : table) + for (auto &it : table) if (it.first->symb_id == symb_id) return it.second; return const_cast<VariableNode *>(this); @@ -2218,7 +2218,7 @@ UnaryOpNode::composeDerivatives(expr_t darg, int deriv_id) // x^2 t11 = datatree.AddPower(arg, datatree.Two); // exp(x^2) - t12 = datatree.AddExp(t11); + t12 = datatree.AddExp(t11); // sqrt(pi) t11 = datatree.AddSqrt(datatree.Pi); // sqrt(pi)*exp(x^2) @@ -2249,7 +2249,7 @@ int UnaryOpNode::cost(const map<pair<int, int>, temporary_terms_t> &temp_terms_map, bool is_matlab) const { // For a temporary term, the cost is null - for (const auto & it : temp_terms_map) + for (const auto &it : temp_terms_map) if (it.second.find(const_cast<UnaryOpNode *>(this)) != it.second.end()) return 0; @@ -2548,7 +2548,7 @@ void UnaryOpNode::writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, const deriv_node_temp_terms_t &tef_terms, - bool isdynamic) const + bool isdynamic) const { if (temporary_terms.find(const_cast<UnaryOpNode *>(this)) != temporary_terms.end()) { @@ -3537,7 +3537,7 @@ UnaryOpNode::substituteDiff(const lag_equivalence_table_t &nodes, subst_table_t for (auto rit = it->second.rbegin(); rit != it->second.rend(); ++rit) { expr_t argsubst = dynamic_cast<UnaryOpNode *>(rit->second)-> - arg->substituteDiff(nodes, subst_table, neweqs); + arg->substituteDiff(nodes, subst_table, neweqs); auto vn = dynamic_cast<VariableNode *>(argsubst); int symb_id; if (rit == it->second.rbegin()) @@ -3703,7 +3703,7 @@ UnaryOpNode::substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst_ } expr_t -UnaryOpNode::substitutePacExpectation(const string & name, expr_t subexpr) +UnaryOpNode::substitutePacExpectation(const string &name, expr_t subexpr) { expr_t argsubst = arg->substitutePacExpectation(name, subexpr); return buildSimilarUnaryOpNode(argsubst, datatree); @@ -3920,7 +3920,7 @@ UnaryOpNode::findConstantEquations(map<VariableNode *, NumConstNode *> &table) c expr_t UnaryOpNode::replaceVarsInEquation(map<VariableNode *, NumConstNode *> &table) const { - expr_t argsubst = arg->replaceVarsInEquation(table); + expr_t argsubst = arg->replaceVarsInEquation(table); return buildSimilarUnaryOpNode(argsubst, datatree); } @@ -4031,7 +4031,7 @@ BinaryOpNode::composeDerivatives(expr_t darg1, expr_t darg2) t14 = datatree.AddDivide(t13, arg1); t15 = datatree.AddPlus(t11, t14); expr_t f = datatree.AddPower(arg1, t12); - expr_t first_part = datatree.AddTimes(f, t15); + expr_t first_part = datatree.AddTimes(f, t15); for (int i = 0; i < powerDerivOrder; i++) first_part = datatree.AddTimes(first_part, datatree.AddMinus(arg2, datatree.AddPossiblyNegativeConstant(i))); @@ -4176,7 +4176,7 @@ int BinaryOpNode::cost(const map<pair<int, int>, temporary_terms_t> &temp_terms_map, bool is_matlab) const { // For a temporary term, the cost is null - for (const auto & it : temp_terms_map) + for (const auto &it : temp_terms_map) if (it.second.find(const_cast<BinaryOpNode *>(this)) != it.second.end()) return 0; @@ -4928,8 +4928,8 @@ BinaryOpNode::normalizeEquation(int var_endo, vector<tuple<int, expr_t, expr_t>> else if (is_endogenous_present_1) /*If the current values of the endogenous variable associated to the equation is present only in the first operand of the expression, we try to normalize the equation*/ { - if (op_code == BinaryOpcode::equal) /* The end of the normalization process : - All the operations needed to normalize the equation are applied. */ + if (op_code == BinaryOpcode::equal) /* The end of the normalization process : + All the operations needed to normalize the equation are applied. */ for (int i = 0; i < static_cast<int>(List_of_Op_RHS1.size()); i++) { tuple<int, expr_t, expr_t> it = List_of_Op_RHS1.back(); @@ -5259,11 +5259,11 @@ BinaryOpNode::PacMaxLag(int lhs_symb_id) const } int -BinaryOpNode::getPacTargetSymbIdHelper(int lhs_symb_id, int undiff_lhs_symb_id, const set<pair<int, int>> & endogs) const +BinaryOpNode::getPacTargetSymbIdHelper(int lhs_symb_id, int undiff_lhs_symb_id, const set<pair<int, int>> &endogs) const { int target_symb_id = -1; bool found_lagged_lhs = false; - for (auto & it : endogs) + for (auto &it : endogs) { int id = datatree.symbol_table.getUltimateOrigSymbID(it.first); if (id == lhs_symb_id || id == undiff_lhs_symb_id) @@ -5431,7 +5431,6 @@ BinaryOpNode::substituteAdl() const return buildSimilarBinaryOpNode(arg1subst, arg2subst, datatree); } - expr_t BinaryOpNode::substituteVarExpectation(const map<string, expr_t> &subst_table) const { @@ -5478,7 +5477,7 @@ BinaryOpNode::countDiffs() const } expr_t -BinaryOpNode::substitutePacExpectation(const string & name, expr_t subexpr) +BinaryOpNode::substitutePacExpectation(const string &name, expr_t subexpr) { expr_t arg1subst = arg1->substitutePacExpectation(name, subexpr); expr_t arg2subst = arg2->substitutePacExpectation(name, subexpr); @@ -5651,7 +5650,7 @@ BinaryOpNode::getPacEC(BinaryOpNode *bopn, int lhs_symb_id, int lhs_orig_symb_id vector<pair<expr_t, int>> terms; vector<tuple<int, bool, int>> ordered_symb_ids; optim_part->decomposeAdditiveTerms(terms, 1); - for (const auto & it : terms) + for (const auto &it : terms) { int scale = it.second; auto vn = dynamic_cast<VariableNode *>(it.first); @@ -5699,7 +5698,7 @@ BinaryOpNode::getPacAREC(int lhs_symb_id, int lhs_orig_symb_id, exit(EXIT_FAILURE); } - for (const auto & it : terms) + for (const auto &it : terms) { if (dynamic_cast<PacExpectationNode *>(it.first)) continue; @@ -5712,9 +5711,9 @@ BinaryOpNode::getPacAREC(int lhs_symb_id, int lhs_orig_symb_id, catch (MatchFailureException &e) { try - { - m = it.first->matchParamTimesLinearCombinationOfVariables(); - } + { + m = it.first->matchParamTimesLinearCombinationOfVariables(); + } catch (MatchFailureException &e) { cerr << "Unsupported expression in PAC equation" << endl; @@ -5855,7 +5854,7 @@ BinaryOpNode::getPacOptimizingShareAndExprNodes(int lhs_symb_id, int lhs_orig_sy { vector<pair<expr_t, int>> terms; decomposeAdditiveTerms(terms, 1); - for (auto & it : terms) + for (auto &it : terms) if (dynamic_cast<PacExpectationNode *>(it.first)) // if the pac_expectation operator is additive in the expression // there are no optimizing shares @@ -5868,8 +5867,8 @@ BinaryOpNode::getPacOptimizingShareAndExprNodes(int lhs_symb_id, int lhs_orig_sy for (auto it = terms.begin(); it != terms.end(); ++it) if (auto bopn = dynamic_cast<BinaryOpNode *>(it->first); bopn) { - tie(optim_share, optim_part) = - getPacOptimizingShareAndExprNodesHelper(bopn, lhs_symb_id, lhs_orig_symb_id); + tie(optim_share, optim_part) + = getPacOptimizingShareAndExprNodesHelper(bopn, lhs_symb_id, lhs_orig_symb_id); if (optim_share >= 0 && optim_part) { terms.erase(it); @@ -5910,7 +5909,7 @@ BinaryOpNode::fillAutoregressiveRow(int eqn, const vector<int> &lhs, map<tuple<i { vector<pair<expr_t, int>> terms; decomposeAdditiveTerms(terms, 1); - for (const auto & it : terms) + for (const auto &it : terms) { int vid, lag, param_id; double constant; @@ -5969,7 +5968,7 @@ expr_t BinaryOpNode::replaceVarsInEquation(map<VariableNode *, NumConstNode *> &table) const { if (op_code == BinaryOpcode::equal) - for (auto & it : table) + for (auto &it : table) if ((it.first == arg1 && it.second == arg2) || (it.first == arg2 && it.second == arg1)) return const_cast<BinaryOpNode *>(this); expr_t arg1subst = arg1->replaceVarsInEquation(table); @@ -6141,7 +6140,7 @@ int TrinaryOpNode::cost(const map<pair<int, int>, temporary_terms_t> &temp_terms_map, bool is_matlab) const { // For a temporary term, the cost is null - for (const auto & it : temp_terms_map) + for (const auto &it : temp_terms_map) if (it.second.find(const_cast<TrinaryOpNode *>(this)) != it.second.end()) return 0; @@ -6726,7 +6725,6 @@ TrinaryOpNode::substituteAdl() const return buildSimilarTrinaryOpNode(arg1subst, arg2subst, arg3subst, datatree); } - expr_t TrinaryOpNode::substituteVarExpectation(const map<string, expr_t> &subst_table) const { @@ -6789,7 +6787,7 @@ TrinaryOpNode::countDiffs() const } expr_t -TrinaryOpNode::substitutePacExpectation(const string & name, expr_t subexpr) +TrinaryOpNode::substitutePacExpectation(const string &name, expr_t subexpr) { expr_t arg1subst = arg1->substitutePacExpectation(name, subexpr); expr_t arg2subst = arg2->substitutePacExpectation(name, subexpr); @@ -6977,7 +6975,7 @@ AbstractExternalFunctionNode::compileExternalFunctionArguments(ostream &CompileC { for (auto argument : arguments) argument->compile(CompileCode, instruction_number, lhs_rhs, temporary_terms, map_idx, - dynamic, steady_dynamic, tef_terms); + dynamic, steady_dynamic, tef_terms); return (arguments.size()); } @@ -7086,7 +7084,7 @@ AbstractExternalFunctionNode::undiff() const int AbstractExternalFunctionNode::VarMinLag() const { -int val = 0; + int val = 0; for (auto argument : arguments) val = min(val, argument->VarMinLag()); return val; @@ -7257,7 +7255,7 @@ AbstractExternalFunctionNode::countDiffs() const } expr_t -AbstractExternalFunctionNode::substitutePacExpectation(const string & name, expr_t subexpr) +AbstractExternalFunctionNode::substitutePacExpectation(const string &name, expr_t subexpr) { vector<expr_t> arguments_subst; for (auto argument : arguments) @@ -7331,7 +7329,6 @@ AbstractExternalFunctionNode::isVariableNodeEqualTo(SymbolType type_arg, int var return false; } - bool AbstractExternalFunctionNode::containsPacExpectation(const string &pac_model_name) const { @@ -7418,7 +7415,7 @@ AbstractExternalFunctionNode::getEndosAndMaxLags(map<string, int> &model_endos_a } pair<int, expr_t> -AbstractExternalFunctionNode::normalizeEquation(int var_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const +AbstractExternalFunctionNode::normalizeEquation(int var_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const { vector<pair<bool, expr_t>> V_arguments; vector<expr_t> V_expr_t; @@ -7463,7 +7460,7 @@ AbstractExternalFunctionNode::writeJsonASTExternalFunctionArguments(ostream &out output << R"("arg)" << i << R"(" : )"; (*it)->writeJsonAST(output); } - output << "}"; + output << "}"; } void @@ -7545,7 +7542,7 @@ ExternalFunctionNode::composeDerivatives(const vector<expr_t> &dargs) datatree.AddFirstDerivExternalFunction(symb_id, arguments, i+1))); expr_t theDeriv = datatree.Zero; - for (auto & dNode : dNodes) + for (auto &dNode : dNodes) theDeriv = datatree.AddPlus(theDeriv, dNode); return theDeriv; } @@ -7610,7 +7607,7 @@ ExternalFunctionNode::compileExternalFunctionOutput(ostream &CompileCode, unsign for (auto argument : arguments) argument->compileExternalFunctionOutput(CompileCode, instruction_number, lhs_rhs, temporary_terms, - map_idx, dynamic, steady_dynamic, tef_terms); + map_idx, dynamic, steady_dynamic, tef_terms); if (!alreadyWrittenAsTefTerm(symb_id, tef_terms)) { @@ -7851,9 +7848,9 @@ function<bool (expr_t)> ExternalFunctionNode::sameTefTermPredicate() const { return [this](expr_t e) { - auto e2 = dynamic_cast<ExternalFunctionNode *>(e); - return (e2 != nullptr && e2->symb_id == symb_id); - }; + auto e2 = dynamic_cast<ExternalFunctionNode *>(e); + return (e2 != nullptr && e2->symb_id == symb_id); + }; } FirstDerivExternalFunctionNode::FirstDerivExternalFunctionNode(DataTree &datatree_arg, @@ -7888,7 +7885,7 @@ FirstDerivExternalFunctionNode::composeDerivatives(const vector<expr_t> &dargs) dNodes.push_back(datatree.AddTimes(dargs.at(i), datatree.AddSecondDerivExternalFunction(symb_id, arguments, inputIndex, i+1))); expr_t theDeriv = datatree.Zero; - for (auto & dNode : dNodes) + for (auto &dNode : dNodes) theDeriv = datatree.AddPlus(theDeriv, dNode); return theDeriv; } @@ -8203,7 +8200,7 @@ FirstDerivExternalFunctionNode::clone(DataTree &datatree) const for (auto argument : arguments) dynamic_arguments.push_back(argument->clone(datatree)); return datatree.AddFirstDerivExternalFunction(symb_id, dynamic_arguments, - inputIndex); + inputIndex); } expr_t @@ -8274,7 +8271,6 @@ SecondDerivExternalFunctionNode::computeTemporaryTerms(map<expr_t, int> &referen expr_t SecondDerivExternalFunctionNode::composeDerivatives(const vector<expr_t> &dargs) - { cerr << "ERROR: third order derivatives of external functions are not implemented" << endl; exit(EXIT_FAILURE); @@ -8908,7 +8904,7 @@ VarExpectationNode::substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, } expr_t -VarExpectationNode::substitutePacExpectation(const string & name, expr_t subexpr) +VarExpectationNode::substitutePacExpectation(const string &name, expr_t subexpr) { return const_cast<VarExpectationNode *>(this); } @@ -9452,7 +9448,7 @@ PacExpectationNode::isParamTimesEndogExpr() const } expr_t -PacExpectationNode::substitutePacExpectation(const string & name, expr_t subexpr) +PacExpectationNode::substitutePacExpectation(const string &name, expr_t subexpr) { if (model_name != name) return const_cast<PacExpectationNode *>(this); @@ -9596,9 +9592,9 @@ ExprNode::matchParamTimesLinearCombinationOfVariables() const expr_t param = bopn->arg1, lincomb = bopn->arg2; auto is_param = [](expr_t e) { - auto vn = dynamic_cast<VariableNode *>(e); - return vn && vn->get_type() == SymbolType::parameter; - }; + auto vn = dynamic_cast<VariableNode *>(e); + return vn && vn->get_type() == SymbolType::parameter; + }; if (!is_param(param)) { diff --git a/src/ExprNode.hh b/src/ExprNode.hh index ef233e6b..210c0360 100644 --- a/src/ExprNode.hh +++ b/src/ExprNode.hh @@ -44,7 +44,7 @@ struct ExprNodeLess; //! Type for set of temporary terms /*! The ExprNodeLess ordering is important for the temporary terms algorithm, - see the definition of ExprNodeLess */ + see the definition of ExprNodeLess */ using temporary_terms_t = set<expr_t, ExprNodeLess>; /*! Keeps track of array indices of temporary_terms for writing */ using temporary_terms_idxs_t = map<expr_t, int>; @@ -86,26 +86,26 @@ using lag_equivalence_table_t = map<expr_t, map<int, expr_t>>; //! Possible types of output when writing ExprNode(s) enum class ExprNodeOutputType { - matlabStaticModel, //!< Matlab code, static model - matlabDynamicModel, //!< Matlab code, dynamic model - matlabStaticModelSparse, //!< Matlab code, static block decomposed model - matlabDynamicModelSparse, //!< Matlab code, dynamic block decomposed model - CDynamicModel, //!< C code, dynamic model - CStaticModel, //!< C code, static model - juliaStaticModel, //!< Julia code, static model - juliaDynamicModel, //!< Julia code, dynamic model - matlabOutsideModel, //!< Matlab code, outside model block (for example in initval) - latexStaticModel, //!< LaTeX code, static model - latexDynamicModel, //!< LaTeX code, dynamic model - latexDynamicSteadyStateOperator, //!< LaTeX code, dynamic model, inside a steady state operator - matlabDynamicSteadyStateOperator, //!< Matlab code, dynamic model, inside a steady state operator - matlabDynamicSparseSteadyStateOperator, //!< Matlab code, dynamic block decomposed model, inside a steady state operator - CDynamicSteadyStateOperator, //!< C code, dynamic model, inside a steady state operator - juliaDynamicSteadyStateOperator, //!< Julia code, dynamic model, inside a steady state operator - steadyStateFile, //!< Matlab code, in the generated steady state file - juliaSteadyStateFile, //!< Julia code, in the generated steady state file - matlabDseries, //!< Matlab code for dseries - epilogueFile //!< Matlab code, in the generated epilogue file + matlabStaticModel, //!< Matlab code, static model + matlabDynamicModel, //!< Matlab code, dynamic model + matlabStaticModelSparse, //!< Matlab code, static block decomposed model + matlabDynamicModelSparse, //!< Matlab code, dynamic block decomposed model + CDynamicModel, //!< C code, dynamic model + CStaticModel, //!< C code, static model + juliaStaticModel, //!< Julia code, static model + juliaDynamicModel, //!< Julia code, dynamic model + matlabOutsideModel, //!< Matlab code, outside model block (for example in initval) + latexStaticModel, //!< LaTeX code, static model + latexDynamicModel, //!< LaTeX code, dynamic model + latexDynamicSteadyStateOperator, //!< LaTeX code, dynamic model, inside a steady state operator + matlabDynamicSteadyStateOperator, //!< Matlab code, dynamic model, inside a steady state operator + matlabDynamicSparseSteadyStateOperator, //!< Matlab code, dynamic block decomposed model, inside a steady state operator + CDynamicSteadyStateOperator, //!< C code, dynamic model, inside a steady state operator + juliaDynamicSteadyStateOperator, //!< Julia code, dynamic model, inside a steady state operator + steadyStateFile, //!< Matlab code, in the generated steady state file + juliaSteadyStateFile, //!< Julia code, in the generated steady state file + matlabDseries, //!< Matlab code for dseries + epilogueFile //!< Matlab code, in the generated epilogue file }; inline bool @@ -184,528 +184,532 @@ RIGHT_PAR(ExprNodeOutputType output_type) //! Base class for expression nodes class ExprNode - { - friend class DataTree; - friend class DynamicModel; - friend class StaticModel; - friend class ModelTree; - friend struct ExprNodeLess; - friend class NumConstNode; - friend class VariableNode; - friend class UnaryOpNode; - friend class BinaryOpNode; - friend class TrinaryOpNode; - friend class AbstractExternalFunctionNode; - friend class VarExpectationNode; - friend class PacExpectationNode; - private: - //! Computes derivative w.r. to a derivation ID (but doesn't store it in derivatives map) - /*! You shoud use getDerivative() to get the benefit of symbolic a priori and of caching */ - virtual expr_t computeDerivative(int deriv_id) = 0; - - protected: - //! Reference to the enclosing DataTree - DataTree &datatree; - - //! Index number - const int idx; - - //! Is the data member non_null_derivatives initialized ? - bool preparedForDerivation{false}; - - //! Set of derivation IDs with respect to which the derivative is potentially non-null - set<int> non_null_derivatives; - - //! Used for caching of first order derivatives (when non-null) - map<int, expr_t> derivatives; - - constexpr static int min_cost_matlab{40*90}; - constexpr static int min_cost_c{40*4}; - inline static int min_cost(bool is_matlab) { return(is_matlab ? min_cost_matlab : min_cost_c); }; - - //! Cost of computing current node - /*! Nodes included in temporary_terms are considered having a null cost */ - virtual int cost(int cost, bool is_matlab) const; - virtual int cost(const temporary_terms_t &temporary_terms, bool is_matlab) const; - virtual int cost(const map<pair<int, int>, temporary_terms_t> &temp_terms_map, bool is_matlab) const; - - //! For creating equation cross references - struct EquationInfo - { - set<pair<int, int>> param; - set<pair<int, int>> endo; - set<pair<int, int>> exo; - set<pair<int, int>> exo_det; - }; - - //! If this node is a temporary term, writes its temporary term representation - /*! Returns true if node is a temporary term and has therefore been - written to output*/ - bool checkIfTemporaryTermThenWrite(ostream &output, ExprNodeOutputType output_type, - const temporary_terms_t &temporary_terms, - const temporary_terms_idxs_t &temporary_terms_idxs) const; - - // Internal helper for matchVariableTimesConstantTimesParam() - virtual void matchVTCTPHelper(int &var_id, int &lag, int ¶m_id, double &constant, bool at_denominator) const; - - /* Computes the representative element and the index under the - lag-equivalence relationship. See the comment above - lag_equivalence_table_t for an explanation of these concepts. */ - pair<expr_t, int> getLagEquivalenceClass() const; - - public: - ExprNode(DataTree &datatree_arg, int idx_arg); - virtual ~ExprNode() = default; - - ExprNode(const ExprNode &) = delete; - ExprNode(ExprNode &&) = delete; - ExprNode & operator=(const ExprNode &) = delete; - ExprNode & operator=(ExprNode &&) = delete; - - //! Initializes data member non_null_derivatives - virtual void prepareForDerivation() = 0; - - //! Returns derivative w.r. to derivation ID - /*! Uses a symbolic a priori to pre-detect null derivatives, and caches the result for other derivatives (to avoid computing it several times) - For an equal node, returns the derivative of lhs minus rhs */ - expr_t getDerivative(int deriv_id); - - //! Computes derivatives by applying the chain rule for some variables - /*! - \param deriv_id The derivation ID with respect to which we are derivating - \param recursive_variables Contains the derivation ID for which chain rules must be applied. Keys are derivation IDs, values are equations of the form x=f(y) where x is the key variable and x doesn't appear in y - */ - virtual expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables) = 0; - - //! Returns precedence of node - /*! Equals 100 for constants, variables, unary ops, and temporary terms */ - virtual int precedence(ExprNodeOutputType output_t, const temporary_terms_t &temporary_terms) const; - - //! Compute temporary terms in this expression - /*! - \param[in] derivOrder the derivation order (first w.r.t. endo/exo, - second w.r.t. params) - \param[out] temp_terms_map the computed temporary terms, associated - with their derivation order - \param[out] reference_count a temporary structure, used to count - references to each node (integer in outer pair is the - reference count, the inner pair is the derivation order) - \param[in] is_matlab whether we are in a MATLAB context, since that - affects the cost of each operator - - A node will be marked as a temporary term if it is referenced at least - two times (i.e. has at least two parents), and has a computing cost - (multiplied by reference count) greater to datatree.min_cost - */ - virtual void computeTemporaryTerms(const pair<int, int> &derivOrder, - map<pair<int, int>, temporary_terms_t> &temp_terms_map, - map<expr_t, pair<int, pair<int, int>>> &reference_count, - bool is_matlab) const; - - //! Writes output of node, using a Txxx notation for nodes in temporary_terms, and specifiying the set of already written external functions - /*! - \param[in] output the output stream - \param[in] output_type the type of output (MATLAB, C, LaTeX...) - \param[in] temporary_terms the nodes that are marked as temporary terms - \param[in] a map from temporary_terms to integers indexes (in the - MATLAB, C or Julia vector of temporary terms); can be empty - when writing MATLAB with block decomposition) - \param[in] tef_terms the set of already written external function nodes - */ - virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, const temporary_terms_idxs_t &temporary_terms_idxs, const deriv_node_temp_terms_t &tef_terms) const = 0; - - //! returns true if the expr node contains an external function - virtual bool containsExternalFunction() const = 0; - - //! Writes output of node (with no temporary terms and with "outside model" output type) - void writeOutput(ostream &output) const; - - //! Writes output of node (with no temporary terms) - void writeOutput(ostream &output, ExprNodeOutputType output_type) const; - - //! Writes output of node, using a Txxx notation for nodes in temporary_terms - void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, const temporary_terms_idxs_t &temporary_terms_idxs) const; - - //! Writes output of node in JSON syntax - virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, const deriv_node_temp_terms_t &tef_terms, bool isdynamic = true) const = 0; - - //! Writes the Abstract Syntax Tree in JSON - virtual void writeJsonAST(ostream &output) const = 0; - - virtual int precedenceJson(const temporary_terms_t &temporary_terms) const; - - //! Writes the output for an external function, ensuring that the external function is called as few times as possible using temporary terms - virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, +{ + friend class DataTree; + friend class DynamicModel; + friend class StaticModel; + friend class ModelTree; + friend struct ExprNodeLess; + friend class NumConstNode; + friend class VariableNode; + friend class UnaryOpNode; + friend class BinaryOpNode; + friend class TrinaryOpNode; + friend class AbstractExternalFunctionNode; + friend class VarExpectationNode; + friend class PacExpectationNode; +private: + //! Computes derivative w.r. to a derivation ID (but doesn't store it in derivatives map) + /*! You shoud use getDerivative() to get the benefit of symbolic a priori and of caching */ + virtual expr_t computeDerivative(int deriv_id) = 0; + +protected: + //! Reference to the enclosing DataTree + DataTree &datatree; + + //! Index number + const int idx; + + //! Is the data member non_null_derivatives initialized ? + bool preparedForDerivation{false}; + + //! Set of derivation IDs with respect to which the derivative is potentially non-null + set<int> non_null_derivatives; + + //! Used for caching of first order derivatives (when non-null) + map<int, expr_t> derivatives; + + constexpr static int min_cost_matlab{40*90}; + constexpr static int min_cost_c{40*4}; + inline static int + min_cost(bool is_matlab) + { + return (is_matlab ? min_cost_matlab : min_cost_c); + }; + + //! Cost of computing current node + /*! Nodes included in temporary_terms are considered having a null cost */ + virtual int cost(int cost, bool is_matlab) const; + virtual int cost(const temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual int cost(const map<pair<int, int>, temporary_terms_t> &temp_terms_map, bool is_matlab) const; + + //! For creating equation cross references + struct EquationInfo + { + set<pair<int, int>> param; + set<pair<int, int>> endo; + set<pair<int, int>> exo; + set<pair<int, int>> exo_det; + }; + + //! If this node is a temporary term, writes its temporary term representation + /*! Returns true if node is a temporary term and has therefore been + written to output*/ + bool checkIfTemporaryTermThenWrite(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_t &temporary_terms, + const temporary_terms_idxs_t &temporary_terms_idxs) const; + + // Internal helper for matchVariableTimesConstantTimesParam() + virtual void matchVTCTPHelper(int &var_id, int &lag, int ¶m_id, double &constant, bool at_denominator) const; + + /* Computes the representative element and the index under the + lag-equivalence relationship. See the comment above + lag_equivalence_table_t for an explanation of these concepts. */ + pair<expr_t, int> getLagEquivalenceClass() const; + +public: + ExprNode(DataTree &datatree_arg, int idx_arg); + virtual ~ExprNode() = default; + + ExprNode(const ExprNode &) = delete; + ExprNode(ExprNode &&) = delete; + ExprNode &operator=(const ExprNode &) = delete; + ExprNode &operator=(ExprNode &&) = delete; + + //! Initializes data member non_null_derivatives + virtual void prepareForDerivation() = 0; + + //! Returns derivative w.r. to derivation ID + /*! Uses a symbolic a priori to pre-detect null derivatives, and caches the result for other derivatives (to avoid computing it several times) + For an equal node, returns the derivative of lhs minus rhs */ + expr_t getDerivative(int deriv_id); + + //! Computes derivatives by applying the chain rule for some variables + /*! + \param deriv_id The derivation ID with respect to which we are derivating + \param recursive_variables Contains the derivation ID for which chain rules must be applied. Keys are derivation IDs, values are equations of the form x=f(y) where x is the key variable and x doesn't appear in y + */ + virtual expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables) = 0; + + //! Returns precedence of node + /*! Equals 100 for constants, variables, unary ops, and temporary terms */ + virtual int precedence(ExprNodeOutputType output_t, const temporary_terms_t &temporary_terms) const; + + //! Compute temporary terms in this expression + /*! + \param[in] derivOrder the derivation order (first w.r.t. endo/exo, + second w.r.t. params) + \param[out] temp_terms_map the computed temporary terms, associated + with their derivation order + \param[out] reference_count a temporary structure, used to count + references to each node (integer in outer pair is the + reference count, the inner pair is the derivation order) + \param[in] is_matlab whether we are in a MATLAB context, since that + affects the cost of each operator + + A node will be marked as a temporary term if it is referenced at least + two times (i.e. has at least two parents), and has a computing cost + (multiplied by reference count) greater to datatree.min_cost + */ + virtual void computeTemporaryTerms(const pair<int, int> &derivOrder, + map<pair<int, int>, temporary_terms_t> &temp_terms_map, + map<expr_t, pair<int, pair<int, int>>> &reference_count, + bool is_matlab) const; + + //! Writes output of node, using a Txxx notation for nodes in temporary_terms, and specifiying the set of already written external functions + /*! + \param[in] output the output stream + \param[in] output_type the type of output (MATLAB, C, LaTeX...) + \param[in] temporary_terms the nodes that are marked as temporary terms + \param[in] a map from temporary_terms to integers indexes (in the + MATLAB, C or Julia vector of temporary terms); can be empty + when writing MATLAB with block decomposition) + \param[in] tef_terms the set of already written external function nodes + */ + virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, const temporary_terms_idxs_t &temporary_terms_idxs, const deriv_node_temp_terms_t &tef_terms) const = 0; + + //! returns true if the expr node contains an external function + virtual bool containsExternalFunction() const = 0; + + //! Writes output of node (with no temporary terms and with "outside model" output type) + void writeOutput(ostream &output) const; + + //! Writes output of node (with no temporary terms) + void writeOutput(ostream &output, ExprNodeOutputType output_type) const; + + //! Writes output of node, using a Txxx notation for nodes in temporary_terms + void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, const temporary_terms_idxs_t &temporary_terms_idxs) const; + + //! Writes output of node in JSON syntax + virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, const deriv_node_temp_terms_t &tef_terms, bool isdynamic = true) const = 0; + + //! Writes the Abstract Syntax Tree in JSON + virtual void writeJsonAST(ostream &output) const = 0; + + virtual int precedenceJson(const temporary_terms_t &temporary_terms) const; + + //! Writes the output for an external function, ensuring that the external function is called as few times as possible using temporary terms + virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_t &temporary_terms, + const temporary_terms_idxs_t &temporary_terms_idxs, + deriv_node_temp_terms_t &tef_terms) const; + + //! Write the JSON output of an external function in a string vector + //! Allows the insertion of commas if necessary + virtual void writeJsonExternalFunctionOutput(vector<string> &efout, const temporary_terms_t &temporary_terms, - const temporary_terms_idxs_t &temporary_terms_idxs, - deriv_node_temp_terms_t &tef_terms) const; - - //! Write the JSON output of an external function in a string vector - //! Allows the insertion of commas if necessary - virtual void writeJsonExternalFunctionOutput(vector<string> &efout, - const temporary_terms_t &temporary_terms, - deriv_node_temp_terms_t &tef_terms, - bool isdynamic = true) const; - - virtual void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - deriv_node_temp_terms_t &tef_terms) const; - - //! Computes the set of all variables of a given symbol type in the expression (with information on lags) - /*! - Variables are stored as integer pairs of the form (symb_id, lag). - They are added to the set given in argument. - Note that model local variables are substituted by their expression in the computation - (and added if type_arg = ModelLocalVariable). - */ - virtual void collectDynamicVariables(SymbolType type_arg, set<pair<int, int>> &result) const = 0; - - //! Find lowest lag for VAR - virtual int VarMinLag() const = 0; - - //! Find the maximum lag in a VAR: handles case where LHS is diff - virtual int VarMaxLag(const set<expr_t> &lhs_lag_equiv) const = 0; - - //! Finds LHS variable in a VAR equation - virtual void collectVARLHSVariable(set<expr_t> &result) const = 0; - - //! Computes the set of all variables of a given symbol type in the expression (without information on lags) - /*! - Variables are stored as symb_id. - They are added to the set given in argument. - Note that model local variables are substituted by their expression in the computation - (and added if type_arg = ModelLocalVariable). - */ - void collectVariables(SymbolType type_arg, set<int> &result) const; - - //! Computes the set of endogenous variables in the expression - /*! - Endogenous are stored as integer pairs of the form (type_specific_id, lag). - They are added to the set given in argument. - Note that model local variables are substituted by their expression in the computation. - */ - virtual void collectEndogenous(set<pair<int, int>> &result) const; - - //! Computes the set of exogenous variables in the expression - /*! - Exogenous are stored as integer pairs of the form (type_specific_id, lag). - They are added to the set given in argument. - Note that model local variables are substituted by their expression in the computation. - */ - virtual void collectExogenous(set<pair<int, int>> &result) const; - - virtual void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const = 0; - - virtual void computeTemporaryTerms(map<expr_t, int> &reference_count, - temporary_terms_t &temporary_terms, - map<expr_t, pair<int, int>> &first_occurence, - int Curr_block, - vector< vector<temporary_terms_t>> &v_temporary_terms, - int equation) const; - - class EvalException - - { - }; - - class EvalExternalFunctionException : public EvalException - - { - }; - - virtual double eval(const eval_context_t &eval_context) const noexcept(false) = 0; - virtual void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, const deriv_node_temp_terms_t &tef_terms) const = 0; - void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic) const; - //! Creates a static version of this node - /*! - This method duplicates the current node by creating a similar node from which all leads/lags have been stripped, - adds the result in the static_datatree argument (and not in the original datatree), and returns it. - */ - virtual expr_t toStatic(DataTree &static_datatree) const = 0; - - /*! - Compute cross references for equations - */ - // virtual void computeXrefs(set<int> ¶m, set<int> &endo, set<int> &exo, set<int> &exo_det) const = 0; - virtual void computeXrefs(EquationInfo &ei) const = 0; - //! Try to normalize an equation linear in its endogenous variable - virtual pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const = 0; - - //! Returns the maximum lead of endogenous in this expression - /*! Always returns a non-negative value */ - virtual int maxEndoLead() const = 0; - - //! Returns the maximum lead of exogenous in this expression - /*! Always returns a non-negative value */ - virtual int maxExoLead() const = 0; - - //! Returns the maximum lag of endogenous in this expression - /*! Always returns a non-negative value */ - virtual int maxEndoLag() const = 0; - - //! Returns the maximum lag of exogenous in this expression - /*! Always returns a non-negative value */ - virtual int maxExoLag() const = 0; - - //! Returns the maximum lead of endo/exo/exodet in this expression - /*! A negative value means that the expression contains only lagged - variables. A value of numeric_limits<int>::min() means that there is - no variable. */ - virtual int maxLead() const = 0; - - //! Returns the maximum lag of endo/exo/exodet in this expression - /*! A negative value means that the expression contains only leaded - variables. A value of numeric_limits<int>::min() means that there is - no variable. */ - virtual int maxLag() const = 0; - - //! Returns the maximum lag of endo/exo/exodet, as if diffs were expanded - /*! This function behaves as maxLag(), except that it treats diff() - differently. For e.g., on diff(diff(x(-1))), maxLag() returns 1 while - maxLagWithDiffsExpanded() returns 3. */ - virtual int maxLagWithDiffsExpanded() const = 0; - - //! Get Max lag of var associated with Pac model - //! Takes account of undiffed LHS variables in calculating the max lag - virtual int PacMaxLag(int lhs_symb_id) const = 0; - - //! Get the target variable of the PAC model - virtual int getPacTargetSymbId(int lhs_symb_id, int undiff_lhs_symb_id) const = 0; - - virtual expr_t undiff() const = 0; - - //! Returns a new expression where all the leads/lags have been shifted backwards by the same amount - /*! - Only acts on endogenous, exogenous, exogenous det - \param[in] n The number of lags by which to shift - \return The same expression except that leads/lags have been shifted backwards - */ - virtual expr_t decreaseLeadsLags(int n) const = 0; - - //! Type for the substitution map used in the process of creating auxiliary vars - using subst_table_t = map<const ExprNode *, const VariableNode *>; - - //! Type for the substitution map used in the process of substituting adl expressions - using subst_table_adl_t = map<const ExprNode *, const expr_t>; - - //! Creates auxiliary endo lead variables corresponding to this expression - /*! - If maximum endogenous lead >= 3, this method will also create intermediary auxiliary var, and will add the equations of the form aux1 = aux2(+1) to the substitution table. - \pre This expression is assumed to have maximum endogenous lead >= 2 - \param[in,out] subst_table The table to which new auxiliary variables and their correspondance will be added - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - \return The new variable node corresponding to the current expression - */ - VariableNode *createEndoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const; - - //! Creates auxiliary exo lead variables corresponding to this expression - /*! - If maximum exogenous lead >= 2, this method will also create intermediary auxiliary var, and will add the equations of the form aux1 = aux2(+1) to the substitution table. - \pre This expression is assumed to have maximum exogenous lead >= 1 - \param[in,out] subst_table The table to which new auxiliary variables and their correspondance will be added - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - \return The new variable node corresponding to the current expression - */ - VariableNode *createExoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const; - - //! Constructs a new expression where sub-expressions with max endo lead >= 2 have been replaced by auxiliary variables - /*! - \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - - If the method detects a sub-expr which needs to be substituted, two cases are possible: - - if this expr is in the table, then it will use the corresponding variable and return the substituted expression - - if this expr is not in the table, then it will create an auxiliary endogenous variable, add the substitution in the table and return the substituted expression - - \return A new equivalent expression where sub-expressions with max endo lead >= 2 have been replaced by auxiliary variables - */ - virtual expr_t substituteEndoLeadGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const = 0; - - //! Constructs a new expression where endo variables with max endo lag >= 2 have been replaced by auxiliary variables - /*! - \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - */ - virtual expr_t substituteEndoLagGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; - - //! Constructs a new expression where exogenous variables with a lead have been replaced by auxiliary variables - /*! - \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - */ - virtual expr_t substituteExoLead(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const = 0; - //! Constructs a new expression where exogenous variables with a lag have been replaced by auxiliary variables - /*! - \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - */ - virtual expr_t substituteExoLag(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; - - //! Constructs a new expression where the expectation operator has been replaced by auxiliary variables - /*! - \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - \param[in] partial_information_model Are we substituting in a partial information model? - */ - virtual expr_t substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool partial_information_model) const = 0; - - virtual expr_t decreaseLeadsLagsPredeterminedVariables() const = 0; - - //! Constructs a new expression where forward variables (supposed to be at most in t+1) have been replaced by themselves at t, plus a new aux var representing their (time) differentiate - /*! - \param[in] subset variables to which to limit the transformation; transform - all fwrd vars if empty - \param[in,out] subst_table Map used to store mapping between a given - forward variable and the aux var that contains its differentiate - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - */ - virtual expr_t differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; - - //! Return true if the nodeID is a numerical constant equal to value and false otherwise - /*! - \param[in] value of the numerical constante - \param[out] the boolean equal to true if NodeId is a constant equal to value - */ - virtual bool isNumConstNodeEqualTo(double value) const = 0; - - //! Returns true if the expression contains one or several endogenous variable - virtual bool containsEndogenous() const = 0; - - //! Returns true if the expression contains one or several exogenous variable - virtual bool containsExogenous() const = 0; - - //! Returns the maximum number of nested diffs in the expression - virtual int countDiffs() const = 0; - - //! Return true if the nodeID is a variable withe a type equal to type_arg, a specific variable id aqual to varfiable_id and a lag equal to lag_arg and false otherwise - /*! - \param[in] the type (type_arg), specifique variable id (variable_id and the lag (lag_arg) - \param[out] the boolean equal to true if NodeId is the variable - */ - virtual bool isVariableNodeEqualTo(SymbolType type_arg, int variable_id, int lag_arg) const = 0; - - //! Replaces the Trend var with datatree.One - virtual expr_t replaceTrendVar() const = 0; - - //! Constructs a new expression where the variable indicated by symb_id has been detrended - /*! - \param[in] symb_id indicating the variable to be detrended - \param[in] log_trend indicates if the trend is in log - \param[in] trend indicating the trend - \return the new binary op pointing to a detrended variable - */ - virtual expr_t detrend(int symb_id, bool log_trend, expr_t trend) const = 0; - - //! Substitute adl operator - virtual expr_t substituteAdl() const = 0; - - //! Substitute VarExpectation nodes - virtual expr_t substituteVarExpectation(const map<string, expr_t> &subst_table) const = 0; - - //! Mark diff nodes to be substituted - /*! The various nodes that are equivalent up to a shift of leads/lags are - grouped together in the “nodes” table. See the comment above - lag_equivalence_table_t for more details. */ - virtual void findDiffNodes(lag_equivalence_table_t &nodes) const = 0; - //! Substitute diff operator - virtual expr_t substituteDiff(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; - - //! Mark unary ops nodes to be substituted - /*! The various nodes that are equivalent up to a shift of leads/lags are - grouped together in the “nodes” table. See the comment above - lag_equivalence_table_t for more details. */ - virtual void findUnaryOpNodesForAuxVarCreation(lag_equivalence_table_t &nodes) const = 0; - //! Substitute unary ops nodes - virtual expr_t substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; - - //! Substitute pac_expectation operator - virtual expr_t substitutePacExpectation(const string & name, expr_t subexpr) = 0; - - virtual int findTargetVariable(int lhs_symb_id) const = 0; - - //! Add ExprNodes to the provided datatree - virtual expr_t clone(DataTree &datatree) const = 0; - - //! Move a trend variable with lag/lead to time t by dividing/multiplying by its growth factor - virtual expr_t removeTrendLeadLag(const map<int, expr_t> &trend_symbols_map) const = 0; - - //! Returns true if the expression is in static form (no lead, no lag, no expectation, no STEADY_STATE) - virtual bool isInStaticForm() const = 0; - - //! Substitute auxiliary variables by their expression in static model - virtual expr_t substituteStaticAuxiliaryVariable() const = 0; - - //! Returns true if model_info_name is referenced by a VarExpectationNode - virtual bool isVarModelReferenced(const string &model_info_name) const = 0; - - //! Matches a linear combination of variables, where scalars can be constant*parameter - /*! Returns a list of (variable_id, lag, param_id, constant) - corresponding to the terms in the expression. When there is no - parameter in a term, param_id == -1. - Can throw a MatchFailureException. - if `variable_obligatory_in_each_term` is true, then every part of the linear combination must contain a variable; - otherwise, if `variable_obligatory_in_each_term`, then any linear combination of constant/variable/param is matched - */ - vector<tuple<int, int, int, double>> matchLinearCombinationOfVariables(bool variable_obligatory_in_each_term = true) const; - - pair<int, vector<tuple<int, int, int, double>>> matchParamTimesLinearCombinationOfVariables() const; - - //! Returns true if expression is of the form: - //! param * (endog op endog op ...) + param * (endog op endog op ...) + ... - virtual bool isParamTimesEndogExpr() const = 0; - - //! Fills the EC matrix structure - void fillErrorCorrectionRow(int eqn, const vector<int> &nontarget_lhs, const vector<int> &target_lhs, - map<tuple<int, int, int>, expr_t> &A0, - map<tuple<int, int, int>, expr_t> &A0star) const; - - //! Finds equations where a variable is equal to a constant - virtual void findConstantEquations(map<VariableNode *, NumConstNode *> &table) const = 0; - - //! Replaces variables found in findConstantEquations() with their constant values - virtual expr_t replaceVarsInEquation(map<VariableNode *, NumConstNode *> &table) const = 0; - - //! Returns true if PacExpectationNode encountered - virtual bool containsPacExpectation(const string &pac_model_name = "") const = 0; - - //! Fills map - virtual void getEndosAndMaxLags(map<string, int> &model_endos_and_lags) const = 0; - - //! Decompose an expression into its additive terms - /*! Returns a list of terms, with their sign (either 1 or -1, depending - on whether the terms appears with a plus or a minus). - The current_sign argument should normally be left to 1. - If current_sign == -1, then all signs are inverted */ - virtual void decomposeAdditiveTerms(vector<pair<expr_t, int>> &terms, int current_sign = 1) const; - - // Matches an expression of the form variable*constant*parameter - /* Returns a tuple (variable_id, lag, param_id, constant). - The variable must be an exogenous or an endogenous. - The constant is optional (in which case 1 is returned); there can be - several multiplicative constants; constants can also appear at the - denominator (i.e. after a divide sign). - The parameter is optional (in which case param_id == -1). - If the expression is not of the expected form, throws a - MatchFailureException - if `variable_obligatory` is true, then the linear combination must contain a variable; - otherwise, if `variable_obligatory`, then an expression is matched that has any mix of constant/variable/param - */ - tuple<int, int, int, double> matchVariableTimesConstantTimesParam(bool variable_obligatory = true) const; - - //! Exception thrown by matchVariableTimesConstantTimesParam when matching fails - class MatchFailureException - { - public: - const string message; - MatchFailureException(string message_arg) : message{move(message_arg)} {}; - }; + deriv_node_temp_terms_t &tef_terms, + bool isdynamic = true) const; + + virtual void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + deriv_node_temp_terms_t &tef_terms) const; + + //! Computes the set of all variables of a given symbol type in the expression (with information on lags) + /*! + Variables are stored as integer pairs of the form (symb_id, lag). + They are added to the set given in argument. + Note that model local variables are substituted by their expression in the computation + (and added if type_arg = ModelLocalVariable). + */ + virtual void collectDynamicVariables(SymbolType type_arg, set<pair<int, int>> &result) const = 0; + + //! Find lowest lag for VAR + virtual int VarMinLag() const = 0; + + //! Find the maximum lag in a VAR: handles case where LHS is diff + virtual int VarMaxLag(const set<expr_t> &lhs_lag_equiv) const = 0; + + //! Finds LHS variable in a VAR equation + virtual void collectVARLHSVariable(set<expr_t> &result) const = 0; + + //! Computes the set of all variables of a given symbol type in the expression (without information on lags) + /*! + Variables are stored as symb_id. + They are added to the set given in argument. + Note that model local variables are substituted by their expression in the computation + (and added if type_arg = ModelLocalVariable). + */ + void collectVariables(SymbolType type_arg, set<int> &result) const; + + //! Computes the set of endogenous variables in the expression + /*! + Endogenous are stored as integer pairs of the form (type_specific_id, lag). + They are added to the set given in argument. + Note that model local variables are substituted by their expression in the computation. + */ + virtual void collectEndogenous(set<pair<int, int>> &result) const; + + //! Computes the set of exogenous variables in the expression + /*! + Exogenous are stored as integer pairs of the form (type_specific_id, lag). + They are added to the set given in argument. + Note that model local variables are substituted by their expression in the computation. + */ + virtual void collectExogenous(set<pair<int, int>> &result) const; + + virtual void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const = 0; + + virtual void computeTemporaryTerms(map<expr_t, int> &reference_count, + temporary_terms_t &temporary_terms, + map<expr_t, pair<int, int>> &first_occurence, + int Curr_block, + vector< vector<temporary_terms_t>> &v_temporary_terms, + int equation) const; + + class EvalException + { + }; + + class EvalExternalFunctionException : public EvalException + { + }; + + virtual double eval(const eval_context_t &eval_context) const noexcept(false) = 0; + virtual void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, const deriv_node_temp_terms_t &tef_terms) const = 0; + void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic) const; + //! Creates a static version of this node + /*! + This method duplicates the current node by creating a similar node from which all leads/lags have been stripped, + adds the result in the static_datatree argument (and not in the original datatree), and returns it. + */ + virtual expr_t toStatic(DataTree &static_datatree) const = 0; + + /*! + Compute cross references for equations + */ + // virtual void computeXrefs(set<int> ¶m, set<int> &endo, set<int> &exo, set<int> &exo_det) const = 0; + virtual void computeXrefs(EquationInfo &ei) const = 0; + //! Try to normalize an equation linear in its endogenous variable + virtual pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const = 0; + + //! Returns the maximum lead of endogenous in this expression + /*! Always returns a non-negative value */ + virtual int maxEndoLead() const = 0; + + //! Returns the maximum lead of exogenous in this expression + /*! Always returns a non-negative value */ + virtual int maxExoLead() const = 0; + + //! Returns the maximum lag of endogenous in this expression + /*! Always returns a non-negative value */ + virtual int maxEndoLag() const = 0; + + //! Returns the maximum lag of exogenous in this expression + /*! Always returns a non-negative value */ + virtual int maxExoLag() const = 0; + + //! Returns the maximum lead of endo/exo/exodet in this expression + /*! A negative value means that the expression contains only lagged + variables. A value of numeric_limits<int>::min() means that there is + no variable. */ + virtual int maxLead() const = 0; + + //! Returns the maximum lag of endo/exo/exodet in this expression + /*! A negative value means that the expression contains only leaded + variables. A value of numeric_limits<int>::min() means that there is + no variable. */ + virtual int maxLag() const = 0; + + //! Returns the maximum lag of endo/exo/exodet, as if diffs were expanded + /*! This function behaves as maxLag(), except that it treats diff() + differently. For e.g., on diff(diff(x(-1))), maxLag() returns 1 while + maxLagWithDiffsExpanded() returns 3. */ + virtual int maxLagWithDiffsExpanded() const = 0; + + //! Get Max lag of var associated with Pac model + //! Takes account of undiffed LHS variables in calculating the max lag + virtual int PacMaxLag(int lhs_symb_id) const = 0; + + //! Get the target variable of the PAC model + virtual int getPacTargetSymbId(int lhs_symb_id, int undiff_lhs_symb_id) const = 0; + + virtual expr_t undiff() const = 0; + + //! Returns a new expression where all the leads/lags have been shifted backwards by the same amount + /*! + Only acts on endogenous, exogenous, exogenous det + \param[in] n The number of lags by which to shift + \return The same expression except that leads/lags have been shifted backwards + */ + virtual expr_t decreaseLeadsLags(int n) const = 0; + + //! Type for the substitution map used in the process of creating auxiliary vars + using subst_table_t = map<const ExprNode *, const VariableNode *>; + + //! Type for the substitution map used in the process of substituting adl expressions + using subst_table_adl_t = map<const ExprNode *, const expr_t>; + + //! Creates auxiliary endo lead variables corresponding to this expression + /*! + If maximum endogenous lead >= 3, this method will also create intermediary auxiliary var, and will add the equations of the form aux1 = aux2(+1) to the substitution table. + \pre This expression is assumed to have maximum endogenous lead >= 2 + \param[in,out] subst_table The table to which new auxiliary variables and their correspondance will be added + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + \return The new variable node corresponding to the current expression + */ + VariableNode *createEndoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const; + + //! Creates auxiliary exo lead variables corresponding to this expression + /*! + If maximum exogenous lead >= 2, this method will also create intermediary auxiliary var, and will add the equations of the form aux1 = aux2(+1) to the substitution table. + \pre This expression is assumed to have maximum exogenous lead >= 1 + \param[in,out] subst_table The table to which new auxiliary variables and their correspondance will be added + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + \return The new variable node corresponding to the current expression + */ + VariableNode *createExoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const; + + //! Constructs a new expression where sub-expressions with max endo lead >= 2 have been replaced by auxiliary variables + /*! + \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + + If the method detects a sub-expr which needs to be substituted, two cases are possible: + - if this expr is in the table, then it will use the corresponding variable and return the substituted expression + - if this expr is not in the table, then it will create an auxiliary endogenous variable, add the substitution in the table and return the substituted expression + + \return A new equivalent expression where sub-expressions with max endo lead >= 2 have been replaced by auxiliary variables + */ + virtual expr_t substituteEndoLeadGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const = 0; + + //! Constructs a new expression where endo variables with max endo lag >= 2 have been replaced by auxiliary variables + /*! + \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + */ + virtual expr_t substituteEndoLagGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; + + //! Constructs a new expression where exogenous variables with a lead have been replaced by auxiliary variables + /*! + \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + */ + virtual expr_t substituteExoLead(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const = 0; + //! Constructs a new expression where exogenous variables with a lag have been replaced by auxiliary variables + /*! + \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + */ + virtual expr_t substituteExoLag(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; + + //! Constructs a new expression where the expectation operator has been replaced by auxiliary variables + /*! + \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + \param[in] partial_information_model Are we substituting in a partial information model? + */ + virtual expr_t substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool partial_information_model) const = 0; + + virtual expr_t decreaseLeadsLagsPredeterminedVariables() const = 0; + + //! Constructs a new expression where forward variables (supposed to be at most in t+1) have been replaced by themselves at t, plus a new aux var representing their (time) differentiate + /*! + \param[in] subset variables to which to limit the transformation; transform + all fwrd vars if empty + \param[in,out] subst_table Map used to store mapping between a given + forward variable and the aux var that contains its differentiate + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + */ + virtual expr_t differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; + + //! Return true if the nodeID is a numerical constant equal to value and false otherwise + /*! + \param[in] value of the numerical constante + \param[out] the boolean equal to true if NodeId is a constant equal to value + */ + virtual bool isNumConstNodeEqualTo(double value) const = 0; + + //! Returns true if the expression contains one or several endogenous variable + virtual bool containsEndogenous() const = 0; + + //! Returns true if the expression contains one or several exogenous variable + virtual bool containsExogenous() const = 0; + + //! Returns the maximum number of nested diffs in the expression + virtual int countDiffs() const = 0; + + //! Return true if the nodeID is a variable withe a type equal to type_arg, a specific variable id aqual to varfiable_id and a lag equal to lag_arg and false otherwise + /*! + \param[in] the type (type_arg), specifique variable id (variable_id and the lag (lag_arg) + \param[out] the boolean equal to true if NodeId is the variable + */ + virtual bool isVariableNodeEqualTo(SymbolType type_arg, int variable_id, int lag_arg) const = 0; + + //! Replaces the Trend var with datatree.One + virtual expr_t replaceTrendVar() const = 0; + + //! Constructs a new expression where the variable indicated by symb_id has been detrended + /*! + \param[in] symb_id indicating the variable to be detrended + \param[in] log_trend indicates if the trend is in log + \param[in] trend indicating the trend + \return the new binary op pointing to a detrended variable + */ + virtual expr_t detrend(int symb_id, bool log_trend, expr_t trend) const = 0; + + //! Substitute adl operator + virtual expr_t substituteAdl() const = 0; + + //! Substitute VarExpectation nodes + virtual expr_t substituteVarExpectation(const map<string, expr_t> &subst_table) const = 0; + + //! Mark diff nodes to be substituted + /*! The various nodes that are equivalent up to a shift of leads/lags are + grouped together in the “nodes” table. See the comment above + lag_equivalence_table_t for more details. */ + virtual void findDiffNodes(lag_equivalence_table_t &nodes) const = 0; + //! Substitute diff operator + virtual expr_t substituteDiff(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; + + //! Mark unary ops nodes to be substituted + /*! The various nodes that are equivalent up to a shift of leads/lags are + grouped together in the “nodes” table. See the comment above + lag_equivalence_table_t for more details. */ + virtual void findUnaryOpNodesForAuxVarCreation(lag_equivalence_table_t &nodes) const = 0; + //! Substitute unary ops nodes + virtual expr_t substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; + + //! Substitute pac_expectation operator + virtual expr_t substitutePacExpectation(const string &name, expr_t subexpr) = 0; + + virtual int findTargetVariable(int lhs_symb_id) const = 0; + + //! Add ExprNodes to the provided datatree + virtual expr_t clone(DataTree &datatree) const = 0; + + //! Move a trend variable with lag/lead to time t by dividing/multiplying by its growth factor + virtual expr_t removeTrendLeadLag(const map<int, expr_t> &trend_symbols_map) const = 0; + + //! Returns true if the expression is in static form (no lead, no lag, no expectation, no STEADY_STATE) + virtual bool isInStaticForm() const = 0; + + //! Substitute auxiliary variables by their expression in static model + virtual expr_t substituteStaticAuxiliaryVariable() const = 0; + + //! Returns true if model_info_name is referenced by a VarExpectationNode + virtual bool isVarModelReferenced(const string &model_info_name) const = 0; + + //! Matches a linear combination of variables, where scalars can be constant*parameter + /*! Returns a list of (variable_id, lag, param_id, constant) + corresponding to the terms in the expression. When there is no + parameter in a term, param_id == -1. + Can throw a MatchFailureException. + if `variable_obligatory_in_each_term` is true, then every part of the linear combination must contain a variable; + otherwise, if `variable_obligatory_in_each_term`, then any linear combination of constant/variable/param is matched + */ + vector<tuple<int, int, int, double>> matchLinearCombinationOfVariables(bool variable_obligatory_in_each_term = true) const; + + pair<int, vector<tuple<int, int, int, double>>> matchParamTimesLinearCombinationOfVariables() const; + + //! Returns true if expression is of the form: + //! param * (endog op endog op ...) + param * (endog op endog op ...) + ... + virtual bool isParamTimesEndogExpr() const = 0; + + //! Fills the EC matrix structure + void fillErrorCorrectionRow(int eqn, const vector<int> &nontarget_lhs, const vector<int> &target_lhs, + map<tuple<int, int, int>, expr_t> &A0, + map<tuple<int, int, int>, expr_t> &A0star) const; + + //! Finds equations where a variable is equal to a constant + virtual void findConstantEquations(map<VariableNode *, NumConstNode *> &table) const = 0; + + //! Replaces variables found in findConstantEquations() with their constant values + virtual expr_t replaceVarsInEquation(map<VariableNode *, NumConstNode *> &table) const = 0; + + //! Returns true if PacExpectationNode encountered + virtual bool containsPacExpectation(const string &pac_model_name = "") const = 0; + + //! Fills map + virtual void getEndosAndMaxLags(map<string, int> &model_endos_and_lags) const = 0; + + //! Decompose an expression into its additive terms + /*! Returns a list of terms, with their sign (either 1 or -1, depending + on whether the terms appears with a plus or a minus). + The current_sign argument should normally be left to 1. + If current_sign == -1, then all signs are inverted */ + virtual void decomposeAdditiveTerms(vector<pair<expr_t, int>> &terms, int current_sign = 1) const; + + // Matches an expression of the form variable*constant*parameter + /* Returns a tuple (variable_id, lag, param_id, constant). + The variable must be an exogenous or an endogenous. + The constant is optional (in which case 1 is returned); there can be + several multiplicative constants; constants can also appear at the + denominator (i.e. after a divide sign). + The parameter is optional (in which case param_id == -1). + If the expression is not of the expected form, throws a + MatchFailureException + if `variable_obligatory` is true, then the linear combination must contain a variable; + otherwise, if `variable_obligatory`, then an expression is matched that has any mix of constant/variable/param + */ + tuple<int, int, int, double> matchVariableTimesConstantTimesParam(bool variable_obligatory = true) const; + + //! Exception thrown by matchVariableTimesConstantTimesParam when matching fails + class MatchFailureException + { + public: + const string message; + MatchFailureException(string message_arg) : message{move(message_arg)} + { + }; + }; }; //! Object used to compare two nodes (using their indexes) /*! Note that in this ordering, a subexpression is always less than the - expression from which it is extracted. This property is used extensively in - the temporary terms computations. */ + expression from which it is extracted. This property is used extensively in + the temporary terms computations. */ struct ExprNodeLess { bool @@ -740,7 +744,7 @@ public: void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, const deriv_node_temp_terms_t &tef_terms) const override; expr_t toStatic(DataTree &static_datatree) const override; void computeXrefs(EquationInfo &ei) const override; - pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; + pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables) override; int maxEndoLead() const override; int maxExoLead() const override; @@ -767,7 +771,7 @@ public: int findTargetVariable(int lhs_symb_id) const override; expr_t substituteDiff(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; expr_t substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; - expr_t substitutePacExpectation(const string & name, expr_t subexpr) override; + expr_t substitutePacExpectation(const string &name, expr_t subexpr) override; expr_t decreaseLeadsLagsPredeterminedVariables() const override; expr_t differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; bool isNumConstNodeEqualTo(double value) const override; @@ -812,18 +816,18 @@ public: void collectVARLHSVariable(set<expr_t> &result) const override; void collectDynamicVariables(SymbolType type_arg, set<pair<int, int>> &result) const override; void computeTemporaryTerms(map<expr_t, int > &reference_count, - temporary_terms_t &temporary_terms, - map<expr_t, pair<int, int>> &first_occurence, - int Curr_block, - vector< vector<temporary_terms_t>> &v_temporary_terms, - int equation) const override; + temporary_terms_t &temporary_terms, + map<expr_t, pair<int, int>> &first_occurence, + int Curr_block, + vector< vector<temporary_terms_t>> &v_temporary_terms, + int equation) const override; void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const override; double eval(const eval_context_t &eval_context) const noexcept(false) override; void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, const deriv_node_temp_terms_t &tef_terms) const override; expr_t toStatic(DataTree &static_datatree) const override; void computeXrefs(EquationInfo &ei) const override; SymbolType get_type() const; - pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; + pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables) override; int maxEndoLead() const override; int maxExoLead() const override; @@ -850,7 +854,7 @@ public: int findTargetVariable(int lhs_symb_id) const override; expr_t substituteDiff(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; expr_t substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; - expr_t substitutePacExpectation(const string & name, expr_t subexpr) override; + expr_t substitutePacExpectation(const string &name, expr_t subexpr) override; expr_t decreaseLeadsLagsPredeterminedVariables() const override; expr_t differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; bool isNumConstNodeEqualTo(double value) const override; @@ -906,23 +910,23 @@ public: void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, const deriv_node_temp_terms_t &tef_terms, bool isdynamic) const override; bool containsExternalFunction() const override; void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, - const temporary_terms_t &temporary_terms, - const temporary_terms_idxs_t &temporary_terms_idxs, - deriv_node_temp_terms_t &tef_terms) const override; + const temporary_terms_t &temporary_terms, + const temporary_terms_idxs_t &temporary_terms_idxs, + deriv_node_temp_terms_t &tef_terms) const override; void writeJsonExternalFunctionOutput(vector<string> &efout, - const temporary_terms_t &temporary_terms, - deriv_node_temp_terms_t &tef_terms, - bool isdynamic) const override; + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms, + bool isdynamic) const override; void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - deriv_node_temp_terms_t &tef_terms) const override; + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + deriv_node_temp_terms_t &tef_terms) const override; void computeTemporaryTerms(map<expr_t, int> &reference_count, - temporary_terms_t &temporary_terms, - map<expr_t, pair<int, int>> &first_occurence, - int Curr_block, - vector< vector<temporary_terms_t>> &v_temporary_terms, - int equation) const override; + temporary_terms_t &temporary_terms, + map<expr_t, pair<int, int>> &first_occurence, + int Curr_block, + vector< vector<temporary_terms_t>> &v_temporary_terms, + int equation) const override; void collectVARLHSVariable(set<expr_t> &result) const override; void collectDynamicVariables(SymbolType type_arg, set<pair<int, int>> &result) const override; void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const override; @@ -931,7 +935,7 @@ public: void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, const deriv_node_temp_terms_t &tef_terms) const override; expr_t toStatic(DataTree &static_datatree) const override; void computeXrefs(EquationInfo &ei) const override; - pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; + pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables) override; int maxEndoLead() const override; int maxExoLead() const override; @@ -961,7 +965,7 @@ public: int findTargetVariable(int lhs_symb_id) const override; expr_t substituteDiff(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; expr_t substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; - expr_t substitutePacExpectation(const string & name, expr_t subexpr) override; + expr_t substitutePacExpectation(const string &name, expr_t subexpr) override; expr_t decreaseLeadsLagsPredeterminedVariables() const override; expr_t differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; bool isNumConstNodeEqualTo(double value) const override; @@ -1017,23 +1021,23 @@ public: void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, const deriv_node_temp_terms_t &tef_terms, bool isdynamic) const override; bool containsExternalFunction() const override; void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, - const temporary_terms_t &temporary_terms, - const temporary_terms_idxs_t &temporary_terms_idxs, - deriv_node_temp_terms_t &tef_terms) const override; + const temporary_terms_t &temporary_terms, + const temporary_terms_idxs_t &temporary_terms_idxs, + deriv_node_temp_terms_t &tef_terms) const override; void writeJsonExternalFunctionOutput(vector<string> &efout, - const temporary_terms_t &temporary_terms, - deriv_node_temp_terms_t &tef_terms, - bool isdynamic) const override; + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms, + bool isdynamic) const override; void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - deriv_node_temp_terms_t &tef_terms) const override; + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + deriv_node_temp_terms_t &tef_terms) const override; void computeTemporaryTerms(map<expr_t, int> &reference_count, - temporary_terms_t &temporary_terms, - map<expr_t, pair<int, int>> &first_occurence, - int Curr_block, - vector< vector<temporary_terms_t>> &v_temporary_terms, - int equation) const override; + temporary_terms_t &temporary_terms, + map<expr_t, pair<int, int>> &first_occurence, + int Curr_block, + vector< vector<temporary_terms_t>> &v_temporary_terms, + int equation) const override; void collectVARLHSVariable(set<expr_t> &result) const override; void collectDynamicVariables(SymbolType type_arg, set<pair<int, int>> &result) const override; void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const override; @@ -1043,7 +1047,7 @@ public: expr_t Compute_RHS(expr_t arg1, expr_t arg2, int op, int op_type) const; expr_t toStatic(DataTree &static_datatree) const override; void computeXrefs(EquationInfo &ei) const override; - pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; + pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables) override; int maxEndoLead() const override; int maxExoLead() const override; @@ -1055,7 +1059,7 @@ public: int VarMinLag() const override; int VarMaxLag(const set<expr_t> &lhs_lag_equiv) const override; int PacMaxLag(int lhs_symb_id) const override; - int getPacTargetSymbIdHelper(int lhs_symb_id, int undiff_lhs_symb_id, const set<pair<int, int>> & endogs) const; + int getPacTargetSymbIdHelper(int lhs_symb_id, int undiff_lhs_symb_id, const set<pair<int, int>> &endogs) const; int getPacTargetSymbId(int lhs_symb_id, int undiff_lhs_symb_id) const override; expr_t undiff() const override; expr_t decreaseLeadsLags(int n) const override; @@ -1075,7 +1079,7 @@ public: int findTargetVariable(int lhs_symb_id) const override; expr_t substituteDiff(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; expr_t substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; - expr_t substitutePacExpectation(const string & name, expr_t subexpr) override; + expr_t substitutePacExpectation(const string &name, expr_t subexpr) override; expr_t decreaseLeadsLagsPredeterminedVariables() const override; expr_t differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; bool isNumConstNodeEqualTo(double value) const override; @@ -1149,23 +1153,23 @@ public: void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, const deriv_node_temp_terms_t &tef_terms, bool isdynamic) const override; bool containsExternalFunction() const override; void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, - const temporary_terms_t &temporary_terms, - const temporary_terms_idxs_t &temporary_terms_idxs, - deriv_node_temp_terms_t &tef_terms) const override; + const temporary_terms_t &temporary_terms, + const temporary_terms_idxs_t &temporary_terms_idxs, + deriv_node_temp_terms_t &tef_terms) const override; void writeJsonExternalFunctionOutput(vector<string> &efout, - const temporary_terms_t &temporary_terms, - deriv_node_temp_terms_t &tef_terms, - bool isdynamic) const override; + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms, + bool isdynamic) const override; void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - deriv_node_temp_terms_t &tef_terms) const override; + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + deriv_node_temp_terms_t &tef_terms) const override; void computeTemporaryTerms(map<expr_t, int> &reference_count, - temporary_terms_t &temporary_terms, - map<expr_t, pair<int, int>> &first_occurence, - int Curr_block, - vector< vector<temporary_terms_t>> &v_temporary_terms, - int equation) const override; + temporary_terms_t &temporary_terms, + map<expr_t, pair<int, int>> &first_occurence, + int Curr_block, + vector< vector<temporary_terms_t>> &v_temporary_terms, + int equation) const override; void collectVARLHSVariable(set<expr_t> &result) const override; void collectDynamicVariables(SymbolType type_arg, set<pair<int, int>> &result) const override; void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const override; @@ -1174,7 +1178,7 @@ public: void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, const deriv_node_temp_terms_t &tef_terms) const override; expr_t toStatic(DataTree &static_datatree) const override; void computeXrefs(EquationInfo &ei) const override; - pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; + pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables) override; int maxEndoLead() const override; int maxExoLead() const override; @@ -1203,7 +1207,7 @@ public: int findTargetVariable(int lhs_symb_id) const override; expr_t substituteDiff(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; expr_t substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; - expr_t substitutePacExpectation(const string & name, expr_t subexpr) override; + expr_t substitutePacExpectation(const string &name, expr_t subexpr) override; expr_t decreaseLeadsLagsPredeterminedVariables() const override; expr_t differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; bool isNumConstNodeEqualTo(double value) const override; @@ -1265,23 +1269,23 @@ public: void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, const deriv_node_temp_terms_t &tef_terms, bool isdynamic = true) const override = 0; bool containsExternalFunction() const override; void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, - const temporary_terms_t &temporary_terms, - const temporary_terms_idxs_t &temporary_terms_idxs, - deriv_node_temp_terms_t &tef_terms) const override = 0; + const temporary_terms_t &temporary_terms, + const temporary_terms_idxs_t &temporary_terms_idxs, + deriv_node_temp_terms_t &tef_terms) const override = 0; void writeJsonExternalFunctionOutput(vector<string> &efout, - const temporary_terms_t &temporary_terms, - deriv_node_temp_terms_t &tef_terms, - bool isdynamic = true) const override = 0; + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms, + bool isdynamic = true) const override = 0; void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - deriv_node_temp_terms_t &tef_terms) const override = 0; + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + deriv_node_temp_terms_t &tef_terms) const override = 0; void computeTemporaryTerms(map<expr_t, int> &reference_count, - temporary_terms_t &temporary_terms, - map<expr_t, pair<int, int>> &first_occurence, - int Curr_block, - vector< vector<temporary_terms_t>> &v_temporary_terms, - int equation) const override = 0; + temporary_terms_t &temporary_terms, + map<expr_t, pair<int, int>> &first_occurence, + int Curr_block, + vector< vector<temporary_terms_t>> &v_temporary_terms, + int equation) const override = 0; void collectVARLHSVariable(set<expr_t> &result) const override; void collectDynamicVariables(SymbolType type_arg, set<pair<int, int>> &result) const override; void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const override; @@ -1294,7 +1298,7 @@ public: void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, const deriv_node_temp_terms_t &tef_terms) const override = 0; expr_t toStatic(DataTree &static_datatree) const override = 0; void computeXrefs(EquationInfo &ei) const override = 0; - pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; + pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables) override; int maxEndoLead() const override; int maxExoLead() const override; @@ -1321,7 +1325,7 @@ public: int findTargetVariable(int lhs_symb_id) const override; expr_t substituteDiff(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; expr_t substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; - expr_t substitutePacExpectation(const string & name, expr_t subexpr) override; + expr_t substitutePacExpectation(const string &name, expr_t subexpr) override; virtual expr_t buildSimilarExternalFunctionNode(vector<expr_t> &alt_args, DataTree &alt_datatree) const = 0; expr_t decreaseLeadsLagsPredeterminedVariables() const override; expr_t differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; @@ -1361,23 +1365,23 @@ public: void writeJsonAST(ostream &output) const override; void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, const deriv_node_temp_terms_t &tef_terms, bool isdynamic) const override; void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, - const temporary_terms_t &temporary_terms, - const temporary_terms_idxs_t &temporary_terms_idxs, - deriv_node_temp_terms_t &tef_terms) const override; + const temporary_terms_t &temporary_terms, + const temporary_terms_idxs_t &temporary_terms_idxs, + deriv_node_temp_terms_t &tef_terms) const override; void writeJsonExternalFunctionOutput(vector<string> &efout, - const temporary_terms_t &temporary_terms, - deriv_node_temp_terms_t &tef_terms, - bool isdynamic) const override; + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms, + bool isdynamic) const override; void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - deriv_node_temp_terms_t &tef_terms) const override; + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + deriv_node_temp_terms_t &tef_terms) const override; void computeTemporaryTerms(map<expr_t, int> &reference_count, - temporary_terms_t &temporary_terms, - map<expr_t, pair<int, int>> &first_occurence, - int Curr_block, - vector< vector<temporary_terms_t>> &v_temporary_terms, - int equation) const override; + temporary_terms_t &temporary_terms, + map<expr_t, pair<int, int>> &first_occurence, + int Curr_block, + vector< vector<temporary_terms_t>> &v_temporary_terms, + int equation) const override; void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, const deriv_node_temp_terms_t &tef_terms) const override; expr_t toStatic(DataTree &static_datatree) const override; void computeXrefs(EquationInfo &ei) const override; @@ -1399,30 +1403,30 @@ public: const vector<expr_t> &arguments_arg, int inputIndex_arg); void computeTemporaryTerms(map<expr_t, int> &reference_count, - temporary_terms_t &temporary_terms, - map<expr_t, pair<int, int>> &first_occurence, - int Curr_block, - vector< vector<temporary_terms_t>> &v_temporary_terms, - int equation) const override; + temporary_terms_t &temporary_terms, + map<expr_t, pair<int, int>> &first_occurence, + int Curr_block, + vector< vector<temporary_terms_t>> &v_temporary_terms, + int equation) const override; void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, const temporary_terms_idxs_t &temporary_terms_idxs, const deriv_node_temp_terms_t &tef_terms) const override; void writeJsonAST(ostream &output) const override; void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, const deriv_node_temp_terms_t &tef_terms, bool isdynamic) const override; void compile(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - const deriv_node_temp_terms_t &tef_terms) const override; + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + const deriv_node_temp_terms_t &tef_terms) const override; void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, - const temporary_terms_t &temporary_terms, - const temporary_terms_idxs_t &temporary_terms_idxs, - deriv_node_temp_terms_t &tef_terms) const override; + const temporary_terms_t &temporary_terms, + const temporary_terms_idxs_t &temporary_terms_idxs, + deriv_node_temp_terms_t &tef_terms) const override; void writeJsonExternalFunctionOutput(vector<string> &efout, - const temporary_terms_t &temporary_terms, - deriv_node_temp_terms_t &tef_terms, - bool isdynamic) const override; + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms, + bool isdynamic) const override; void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - deriv_node_temp_terms_t &tef_terms) const override; + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + deriv_node_temp_terms_t &tef_terms) const override; expr_t toStatic(DataTree &static_datatree) const override; void computeXrefs(EquationInfo &ei) const override; expr_t buildSimilarExternalFunctionNode(vector<expr_t> &alt_args, DataTree &alt_datatree) const override; @@ -1445,30 +1449,30 @@ public: int inputIndex1_arg, int inputIndex2_arg); void computeTemporaryTerms(map<expr_t, int> &reference_count, - temporary_terms_t &temporary_terms, - map<expr_t, pair<int, int>> &first_occurence, - int Curr_block, - vector< vector<temporary_terms_t>> &v_temporary_terms, - int equation) const override; + temporary_terms_t &temporary_terms, + map<expr_t, pair<int, int>> &first_occurence, + int Curr_block, + vector< vector<temporary_terms_t>> &v_temporary_terms, + int equation) const override; void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, const temporary_terms_idxs_t &temporary_terms_idxs, const deriv_node_temp_terms_t &tef_terms) const override; void writeJsonAST(ostream &output) const override; void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, const deriv_node_temp_terms_t &tef_terms, bool isdynamic) const override; void compile(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - const deriv_node_temp_terms_t &tef_terms) const override; + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + const deriv_node_temp_terms_t &tef_terms) const override; void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, - const temporary_terms_t &temporary_terms, - const temporary_terms_idxs_t &temporary_terms_idxs, - deriv_node_temp_terms_t &tef_terms) const override; + const temporary_terms_t &temporary_terms, + const temporary_terms_idxs_t &temporary_terms_idxs, + deriv_node_temp_terms_t &tef_terms) const override; void writeJsonExternalFunctionOutput(vector<string> &efout, - const temporary_terms_t &temporary_terms, - deriv_node_temp_terms_t &tef_terms, - bool isdynamic) const override; + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms, + bool isdynamic) const override; void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - deriv_node_temp_terms_t &tef_terms) const override; + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + deriv_node_temp_terms_t &tef_terms) const override; expr_t toStatic(DataTree &static_datatree) const override; void computeXrefs(EquationInfo &ei) const override; expr_t buildSimilarExternalFunctionNode(vector<expr_t> &alt_args, DataTree &alt_datatree) const override; @@ -1486,11 +1490,11 @@ public: bool is_matlab) const override; void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, const temporary_terms_idxs_t &temporary_terms_idxs, const deriv_node_temp_terms_t &tef_terms) const override; void computeTemporaryTerms(map<expr_t, int> &reference_count, - temporary_terms_t &temporary_terms, - map<expr_t, pair<int, int>> &first_occurence, - int Curr_block, - vector< vector<temporary_terms_t>> &v_temporary_terms, - int equation) const override; + temporary_terms_t &temporary_terms, + map<expr_t, pair<int, int>> &first_occurence, + int Curr_block, + vector< vector<temporary_terms_t>> &v_temporary_terms, + int equation) const override; expr_t toStatic(DataTree &static_datatree) const override; expr_t clone(DataTree &datatree) const override; int maxEndoLead() const override; @@ -1524,12 +1528,12 @@ public: int findTargetVariable(int lhs_symb_id) const override; expr_t substituteDiff(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; expr_t substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; - expr_t substitutePacExpectation(const string & name, expr_t subexpr) override; - pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; + expr_t substitutePacExpectation(const string &name, expr_t subexpr) override; + pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; void compile(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - const deriv_node_temp_terms_t &tef_terms) const override; + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + const deriv_node_temp_terms_t &tef_terms) const override; void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const override; void collectVARLHSVariable(set<expr_t> &result) const override; void collectDynamicVariables(SymbolType type_arg, set<pair<int, int>> &result) const override; @@ -1567,11 +1571,11 @@ public: bool is_matlab) const override; void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, const temporary_terms_idxs_t &temporary_terms_idxs, const deriv_node_temp_terms_t &tef_terms) const override; void computeTemporaryTerms(map<expr_t, int> &reference_count, - temporary_terms_t &temporary_terms, - map<expr_t, pair<int, int>> &first_occurence, - int Curr_block, - vector< vector<temporary_terms_t>> &v_temporary_terms, - int equation) const override; + temporary_terms_t &temporary_terms, + map<expr_t, pair<int, int>> &first_occurence, + int Curr_block, + vector< vector<temporary_terms_t>> &v_temporary_terms, + int equation) const override; expr_t toStatic(DataTree &static_datatree) const override; expr_t clone(DataTree &datatree) const override; int maxEndoLead() const override; @@ -1605,12 +1609,12 @@ public: int findTargetVariable(int lhs_symb_id) const override; expr_t substituteDiff(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; expr_t substituteUnaryOpNodes(const lag_equivalence_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const override; - expr_t substitutePacExpectation(const string & name, expr_t subexpr) override; - pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; + expr_t substitutePacExpectation(const string &name, expr_t subexpr) override; + pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const override; void compile(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - const deriv_node_temp_terms_t &tef_terms) const override; + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + const deriv_node_temp_terms_t &tef_terms) const override; void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const override; void collectVARLHSVariable(set<expr_t> &result) const override; void collectDynamicVariables(SymbolType type_arg, set<pair<int, int>> &result) const override; diff --git a/src/ExtendedPreprocessorTypes.hh b/src/ExtendedPreprocessorTypes.hh index 544a282e..68dacb90 100644 --- a/src/ExtendedPreprocessorTypes.hh +++ b/src/ExtendedPreprocessorTypes.hh @@ -22,31 +22,31 @@ enum class FileOutputType { - none, // outputs files for Matlab/Octave processing - dynamic, // outputs <fname>_dynamic.* and related files - first, // outputs <fname>_first_derivatives.* and related files - second, // outputs <fname>_first_derivatives.*, <fname>_second_derivatives.* and related files - third, // outputs <fname>_first_derivatives.*, <fname>_second_derivatives.*, <fname>_third_derivatives.* and related files + none, // outputs files for Matlab/Octave processing + dynamic, // outputs <fname>_dynamic.* and related files + first, // outputs <fname>_first_derivatives.* and related files + second, // outputs <fname>_first_derivatives.*, <fname>_second_derivatives.* and related files + third, // outputs <fname>_first_derivatives.*, <fname>_second_derivatives.*, <fname>_third_derivatives.* and related files }; enum class LanguageOutputType { - matlab, // outputs files for Matlab/Octave processing - julia, // outputs files for Julia + matlab, // outputs files for Matlab/Octave processing + julia, // outputs files for Julia }; enum class JsonFileOutputType { - file, // output JSON files to file - standardout, // output JSON files to stdout + file, // output JSON files to file + standardout, // output JSON files to stdout }; enum class JsonOutputPointType { - nojson, // don't output JSON - parsing, // output JSON after the parsing step - checkpass, // output JSON after the check pass - transformpass, // output JSON after the transform pass - computingpass // output JSON after the computing pass + nojson, // don't output JSON + parsing, // output JSON after the parsing step + checkpass, // output JSON after the check pass + transformpass, // output JSON after the transform pass + computingpass // output JSON after the computing pass }; #endif diff --git a/src/ExternalFunctionsTable.cc b/src/ExternalFunctionsTable.cc index 0383af28..427fc552 100644 --- a/src/ExternalFunctionsTable.cc +++ b/src/ExternalFunctionsTable.cc @@ -33,7 +33,7 @@ ExternalFunctionsTable::addExternalFunction(int symb_id, const external_function // Change options to be saved so the table is consistent external_function_options external_function_options_chng = external_function_options_arg; - if (external_function_options_arg.firstDerivSymbID == IDSetButNoNameProvided) + if (external_function_options_arg.firstDerivSymbID == IDSetButNoNameProvided) external_function_options_chng.firstDerivSymbID = symb_id; if (external_function_options_arg.secondDerivSymbID == IDSetButNoNameProvided) @@ -44,7 +44,7 @@ ExternalFunctionsTable::addExternalFunction(int symb_id, const external_function // Ensure 1st & 2nd deriv option consistency if (external_function_options_chng.secondDerivSymbID == symb_id - && external_function_options_chng.firstDerivSymbID != symb_id) + && external_function_options_chng.firstDerivSymbID != symb_id) { cerr << "ERROR: If the second derivative is provided by the top-level function " << "the first derivative must also be provided by the same function." << endl; @@ -52,7 +52,7 @@ ExternalFunctionsTable::addExternalFunction(int symb_id, const external_function } if ((external_function_options_chng.secondDerivSymbID != symb_id - && external_function_options_chng.firstDerivSymbID == symb_id) + && external_function_options_chng.firstDerivSymbID == symb_id) && external_function_options_chng.secondDerivSymbID != IDNotSet) { cerr << "ERROR: If the first derivative is provided by the top-level function, the " @@ -84,7 +84,7 @@ ExternalFunctionsTable::addExternalFunction(int symb_id, const external_function ok_to_overwrite = true; if (!ok_to_overwrite) // prevents multiple non-compatible calls to external_function(name=funcname) - { // e.g. e_f(name=a,nargs=1,fd,sd) and e_f(name=a,nargs=2,fd=b,sd=c) should cause an error + { // e.g. e_f(name=a,nargs=1,fd,sd) and e_f(name=a,nargs=2,fd=b,sd=c) should cause an error if (external_function_options_chng.nargs != getNargs(symb_id)) { cerr << "ERROR: The number of arguments passed to the external_function() statement do not " diff --git a/src/MinimumFeedbackSet.cc b/src/MinimumFeedbackSet.cc index 7f7f41fb..9406560b 100644 --- a/src/MinimumFeedbackSet.cc +++ b/src/MinimumFeedbackSet.cc @@ -101,7 +101,7 @@ namespace MFS void Print(AdjacencyList_t &G) { - AdjacencyList_t::vertex_iterator it, it_end; + AdjacencyList_t::vertex_iterator it, it_end; auto v_index = get(vertex_index, G); cout << "Graph\n" << "-----\n"; @@ -193,7 +193,7 @@ namespace MFS tie(it_out, out_end) = out_edges(vertex, G); while (it_in != in_end && it_out != out_end && agree) { - agree = (source(*it_in, G) == target(*it_out, G) && source(*it_in, G) != target(*it_in, G)); //not a loop + agree = (source(*it_in, G) == target(*it_out, G) && source(*it_in, G) != target(*it_in, G)); //not a loop liste.push_back(source(*it_in, G)); ++it_in; ++it_out; diff --git a/src/ModFile.cc b/src/ModFile.cc index 06cb68fe..47707d04 100644 --- a/src/ModFile.cc +++ b/src/ModFile.cc @@ -46,7 +46,7 @@ ModFile::ModFile(WarningConsolidation &warnings_arg) orig_ramsey_dynamic_model{symbol_table, num_constants, external_functions_table, trend_component_model_table, var_model_table}, non_linear_equations_dynamic_model{symbol_table, num_constants, external_functions_table, - trend_component_model_table, var_model_table}, + trend_component_model_table, var_model_table}, epilogue{symbol_table, num_constants, external_functions_table, trend_component_model_table, var_model_table}, static_model{symbol_table, num_constants, external_functions_table}, @@ -107,7 +107,7 @@ ModFile::addStatementAtFront(unique_ptr<Statement> st) void ModFile::checkPass(bool nostrict, bool stochastic) { - for (auto & statement : statements) + for (auto &statement : statements) statement->checkPass(mod_file_struct, warnings); // Check the steady state block @@ -116,8 +116,8 @@ ModFile::checkPass(bool nostrict, bool stochastic) // Check epilogue block epilogue.checkPass(mod_file_struct, warnings); - if (mod_file_struct.write_latex_steady_state_model_present && - !mod_file_struct.steady_state_model_present) + if (mod_file_struct.write_latex_steady_state_model_present + && !mod_file_struct.steady_state_model_present) { cerr << "ERROR: You cannot have a write_latex_steady_state_model statement without a steady_state_model block." << endl; exit(EXIT_FAILURE); @@ -414,7 +414,7 @@ ModFile::transformPass(bool nostrict, bool stochastic, bool compute_xrefs, bool exit(EXIT_FAILURE); // Declare endogenous used for PAC model-consistent expectations - for (auto & statement : statements) + for (auto &statement : statements) if (auto pms = dynamic_cast<PacModelStatement *>(statement.get()); pms) { @@ -426,12 +426,12 @@ ModFile::transformPass(bool nostrict, bool stochastic, bool compute_xrefs, bool // Get all equation tags associated with VARs and Trend Component Models set<string> eqtags; - for (const auto & it : trend_component_model_table.getEqTags()) - for (auto & it1 : it.second) + for (const auto &it : trend_component_model_table.getEqTags()) + for (auto &it1 : it.second) eqtags.insert(it1); - for (const auto & it : var_model_table.getEqTags()) - for (auto & it1 : it.second) + for (const auto &it : var_model_table.getEqTags()) + for (auto &it1 : it.second) eqtags.insert(it1); // Create auxiliary variables and equations for unary ops @@ -455,7 +455,7 @@ ModFile::transformPass(bool nostrict, bool stochastic, bool compute_xrefs, bool // Pac Model int i = 0; - for (auto & statement : statements) + for (auto &statement : statements) if (auto pms = dynamic_cast<PacModelStatement *>(statement.get()); pms) { if (pms->growth) @@ -512,8 +512,8 @@ ModFile::transformPass(bool nostrict, bool stochastic, bool compute_xrefs, bool dynamic_model.detrendEquations(); trend_dynamic_model = dynamic_model; dynamic_model.removeTrendVariableFromEquations(); - const auto & trend_symbols = dynamic_model.getTrendSymbolsMap(); - const auto & nonstationary_symbols = dynamic_model.getNonstationarySymbolsMap(); + const auto &trend_symbols = dynamic_model.getTrendSymbolsMap(); + const auto &nonstationary_symbols = dynamic_model.getNonstationarySymbolsMap(); epilogue.detrend(trend_symbols, nonstationary_symbols); } @@ -523,7 +523,7 @@ ModFile::transformPass(bool nostrict, bool stochastic, bool compute_xrefs, bool if (mod_file_struct.ramsey_model_present) { PlannerObjectiveStatement *pos = nullptr; - for (auto & statement : statements) + for (auto &statement : statements) if (auto pos2 = dynamic_cast<PlannerObjectiveStatement *>(statement.get()); pos2) if (pos) { @@ -553,7 +553,7 @@ ModFile::transformPass(bool nostrict, bool stochastic, bool compute_xrefs, bool TODO: move information collection to checkPass(), within a new VarModelTable class */ map<string, expr_t> var_expectation_subst_table; - for (auto & statement : statements) + for (auto &statement : statements) { auto vems = dynamic_cast<VarExpectationModelStatement *>(statement.get()); if (!vems) @@ -619,7 +619,7 @@ ModFile::transformPass(bool nostrict, bool stochastic, bool compute_xrefs, bool || mod_file_struct.calib_smoother_present || mod_file_struct.identification_present || mod_file_struct.sensitivity_present - || stochastic ) + || stochastic) { // In stochastic models, create auxiliary vars for leads and lags greater than 2, on both endos and exos dynamic_model.substituteEndoLeadGreaterThanTwo(false); @@ -734,7 +734,7 @@ ModFile::computingPass(bool no_tmp_terms, FileOutputType output, int params_deri // Compute static model and its derivatives static_model = static_cast<StaticModel>(dynamic_model); - if (linear_decomposition) + if (linear_decomposition) { non_linear_equations_dynamic_model = dynamic_model; non_linear_equations_dynamic_model.set_cutoff_to_zero(); @@ -823,7 +823,7 @@ ModFile::computingPass(bool no_tmp_terms, FileOutputType output, int params_deri } } - for (auto & statement : statements) + for (auto &statement : statements) statement->computingPass(); // Compute epilogue derivatives (but silence standard output) @@ -853,7 +853,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo otherwise it may file if the destination is not on the same filesystem). */ if (filesystem::path plusfolder{"+" + basename}; filesystem::exists(plusfolder)) - { + { if (filesystem::exists(plusfolder / "+objective")) { // Do it recursively for the +objective folder, created by ramsey_policy @@ -862,10 +862,10 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo filesystem::remove_all(tmp2); } - auto tmp = unique_path(); - filesystem::rename(plusfolder, tmp); - filesystem::remove_all(tmp); - } + auto tmp = unique_path(); + filesystem::rename(plusfolder, tmp); + filesystem::remove_all(tmp); + } filesystem::remove_all(basename + "/model/src"); filesystem::remove_all(basename + "/model/bytecode"); } @@ -980,7 +980,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo if (parallel_local_files.size() > 0) { mOutputFile << "options_.parallel_info.local_files = {" << endl; - for (const auto & parallel_local_file : parallel_local_files) + for (const auto ¶llel_local_file : parallel_local_files) { size_t j = parallel_local_file.find_last_of(R"(/\)"); if (j == string::npos) @@ -1353,7 +1353,7 @@ ModFile::writeJsonOutputParsingCheck(const string &basename, JsonFileOutputType if (!var_model_table.empty()) { var_model_table.writeJsonOutput(output); - output << ", "; + output << ", "; } if (!trend_component_model_table.empty()) @@ -1398,7 +1398,7 @@ ModFile::writeJsonOutputParsingCheck(const string &basename, JsonFileOutputType original_model_output << ", "; } int i = 0; - for (const auto & it : statements) + for (const auto &it : statements) { original_model_output << (i++ > 0 ? "," : "") << endl; it->writeJsonOutput(original_model_output); diff --git a/src/ModelEquationBlock.cc b/src/ModelEquationBlock.cc index e901b88a..c136805f 100644 --- a/src/ModelEquationBlock.cc +++ b/src/ModelEquationBlock.cc @@ -32,8 +32,8 @@ SteadyStateModel::SteadyStateModel(SymbolTable &symbol_table_arg, } SteadyStateModel::SteadyStateModel(const SteadyStateModel &m) : - DataTree {m}, - static_model {m.static_model} + DataTree{m}, + static_model{m.static_model} { for (const auto &it : m.def_table) def_table.emplace_back(it.first, it.second->clone(*this)); @@ -90,7 +90,7 @@ SteadyStateModel::checkPass(ModFileStructure &mod_file_struct, WarningConsolidat mod_file_struct.steady_state_model_present = true; vector<int> so_far_defined; - for (const auto & i : def_table) + for (const auto &i : def_table) { const vector<int> &symb_ids = i.first; @@ -296,7 +296,7 @@ Epilogue::Epilogue(SymbolTable &symbol_table_arg, } Epilogue::Epilogue(const Epilogue &m) : - DynamicModel {m} + DynamicModel{m} { for (const auto &it : m.dynamic_def_table) dynamic_def_table.emplace_back(it.first, it.second->clone(*this)); @@ -334,7 +334,7 @@ Epilogue::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &war } vector<int> so_far_defined; - for (const auto & it : dynamic_def_table) + for (const auto &it : dynamic_def_table) if (find(so_far_defined.begin(), so_far_defined.end(), it.first) != so_far_defined.end()) { cerr << "WARNING: in the 'epilogue' block, variable '" << it.first @@ -353,8 +353,8 @@ Epilogue::toStatic() } void -Epilogue::detrend(const map<int, expr_t> & trend_symbols_map, - const nonstationary_symbols_map_t & nonstationary_symbols_map) +Epilogue::detrend(const map<int, expr_t> &trend_symbols_map, + const nonstationary_symbols_map_t &nonstationary_symbols_map) { for (auto it = nonstationary_symbols_map.crbegin(); it != nonstationary_symbols_map.crend(); ++it) @@ -388,7 +388,7 @@ Epilogue::writeEpilogueFile(const string &basename) const } void -Epilogue::writeStaticEpilogueFile(const string & basename) const +Epilogue::writeStaticEpilogueFile(const string &basename) const { string filename = packageDir(basename) + "/epilogue_static.m"; ofstream output; @@ -427,7 +427,7 @@ Epilogue::writeStaticEpilogueFile(const string & basename) const } void -Epilogue::writeDynamicEpilogueFile(const string & basename) const +Epilogue::writeDynamicEpilogueFile(const string &basename) const { string filename = packageDir(basename) + "/epilogue_dynamic.m"; ofstream output; diff --git a/src/ModelEquationBlock.hh b/src/ModelEquationBlock.hh index c51a6f2e..cf048dd6 100644 --- a/src/ModelEquationBlock.hh +++ b/src/ModelEquationBlock.hh @@ -43,8 +43,8 @@ public: SteadyStateModel(const SteadyStateModel &m); SteadyStateModel(SteadyStateModel &&) = delete; - SteadyStateModel & operator=(const SteadyStateModel &m); - SteadyStateModel & operator=(SteadyStateModel &&) = delete; + SteadyStateModel &operator=(const SteadyStateModel &m); + SteadyStateModel &operator=(SteadyStateModel &&) = delete; //! Add an expression of the form "var = expr;" void addDefinition(int symb_id, expr_t expr); @@ -80,8 +80,8 @@ public: Epilogue(const Epilogue &m); Epilogue(Epilogue &&) = delete; - Epilogue & operator=(const Epilogue &m); - Epilogue & operator=(Epilogue &&) = delete; + Epilogue &operator=(const Epilogue &m); + Epilogue &operator=(Epilogue &&) = delete; //! Add an expression of the form "var = expr;" void addDefinition(int symb_id, expr_t expr); @@ -93,8 +93,8 @@ public: void toStatic(); //! Deal with trend variables in the epilogue block - void detrend(const map<int, expr_t> & trend_symbols_map, - const nonstationary_symbols_map_t & nonstationary_symbols_map); + void detrend(const map<int, expr_t> &trend_symbols_map, + const nonstationary_symbols_map_t &nonstationary_symbols_map); //! Write the steady state file void writeEpilogueFile(const string &basename) const; @@ -103,9 +103,8 @@ public: void writeOutput(ostream &output) const; private: //! Helper for public writeEpilogueFile - void writeStaticEpilogueFile(const string & basename) const; - void writeDynamicEpilogueFile(const string & basename) const; + void writeStaticEpilogueFile(const string &basename) const; + void writeDynamicEpilogueFile(const string &basename) const; }; - #endif diff --git a/src/ModelTree.cc b/src/ModelTree.cc index d4fd5c65..e6513450 100644 --- a/src/ModelTree.cc +++ b/src/ModelTree.cc @@ -30,7 +30,7 @@ #pragma GCC diagnostic pop #ifdef __APPLE__ -#include <mach-o/dyld.h> +# include <mach-o/dyld.h> #endif using namespace MFS; @@ -41,18 +41,18 @@ ModelTree::copyHelper(const ModelTree &m) auto f = [this](expr_t e) { return e->clone(*this); }; // Equations - for (const auto & it : m.equations) + for (const auto &it : m.equations) equations.push_back(dynamic_cast<BinaryOpNode *>(f(it))); - for (const auto & it : m.aux_equations) + for (const auto &it : m.aux_equations) aux_equations.push_back(dynamic_cast<BinaryOpNode *>(f(it))); auto convert_deriv_map = [f](map<vector<int>, expr_t> dm) - { - map<vector<int>, expr_t> dm2; - for (const auto &it : dm) - dm2.emplace(it.first, f(it.second)); - return dm2; - }; + { + map<vector<int>, expr_t> dm2; + for (const auto &it : dm) + dm2.emplace(it.first, f(it.second)); + return dm2; + }; // Derivatives for (const auto &it : m.derivatives) @@ -61,31 +61,31 @@ ModelTree::copyHelper(const ModelTree &m) params_derivatives[it.first] = convert_deriv_map(it.second); auto convert_temporary_terms_t = [f](temporary_terms_t tt) - { - temporary_terms_t tt2; - for (const auto &it : tt) - tt2.insert(f(it)); - return tt2; - }; + { + temporary_terms_t tt2; + for (const auto &it : tt) + tt2.insert(f(it)); + return tt2; + }; // Temporary terms - for (const auto & it : m.temporary_terms) + for (const auto &it : m.temporary_terms) temporary_terms.insert(f(it)); - for (const auto & it : m.temporary_terms_mlv) + for (const auto &it : m.temporary_terms_mlv) temporary_terms_mlv[f(it.first)] = f(it.second); for (const auto &it : m.temporary_terms_derivatives) temporary_terms_derivatives.push_back(convert_temporary_terms_t(it)); - for (const auto & it : m.temporary_terms_idxs) + for (const auto &it : m.temporary_terms_idxs) temporary_terms_idxs[f(it.first)] = it.second; - for (const auto & it : m.params_derivs_temporary_terms) + for (const auto &it : m.params_derivs_temporary_terms) params_derivs_temporary_terms[it.first] = convert_temporary_terms_t(it.second); - for (const auto & it : m.params_derivs_temporary_terms_idxs) + for (const auto &it : m.params_derivs_temporary_terms_idxs) params_derivs_temporary_terms_idxs[f(it.first)] = it.second; // Other stuff - for (const auto & it : m.trend_symbols_map) + for (const auto &it : m.trend_symbols_map) trend_symbols_map[it.first] = f(it.second); - for (const auto & it : m.nonstationary_symbols_map) + for (const auto &it : m.nonstationary_symbols_map) nonstationary_symbols_map[it.first] = {it.second.first, f(it.second.second)}; } @@ -93,7 +93,7 @@ ModelTree::ModelTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg, ExternalFunctionsTable &external_functions_table_arg, bool is_dynamic_arg) : - DataTree {symbol_table_arg, num_constants_arg, external_functions_table_arg, is_dynamic_arg}, + DataTree{symbol_table_arg, num_constants_arg, external_functions_table_arg, is_dynamic_arg}, derivatives(4), NNZDerivatives(4, 0), temporary_terms_derivatives(4) @@ -101,27 +101,27 @@ ModelTree::ModelTree(SymbolTable &symbol_table_arg, } ModelTree::ModelTree(const ModelTree &m) : - DataTree {m}, - user_set_add_flags {m.user_set_add_flags}, - user_set_subst_flags {m.user_set_subst_flags}, - user_set_add_libs {m.user_set_add_libs}, - user_set_subst_libs {m.user_set_subst_libs}, - user_set_compiler {m.user_set_compiler}, - equations_lineno {m.equations_lineno}, - equation_tags {m.equation_tags}, - equation_tags_xref {m.equation_tags_xref}, - NNZDerivatives {m.NNZDerivatives}, - equation_reordered {m.equation_reordered}, - variable_reordered {m.variable_reordered}, - inv_equation_reordered {m.inv_equation_reordered}, - inv_variable_reordered {m.inv_variable_reordered}, - is_equation_linear {m.is_equation_linear}, - endo2eq {m.endo2eq}, - epilogue {m.epilogue}, - prologue {m.prologue}, - block_lag_lead {m.block_lag_lead}, - cutoff {m.cutoff}, - mfs {m.mfs} + DataTree{m}, + user_set_add_flags{m.user_set_add_flags}, + user_set_subst_flags{m.user_set_subst_flags}, + user_set_add_libs{m.user_set_add_libs}, + user_set_subst_libs{m.user_set_subst_libs}, + user_set_compiler{m.user_set_compiler}, + equations_lineno{m.equations_lineno}, + equation_tags{m.equation_tags}, + equation_tags_xref{m.equation_tags_xref}, + NNZDerivatives{m.NNZDerivatives}, + equation_reordered{m.equation_reordered}, + variable_reordered{m.variable_reordered}, + inv_equation_reordered{m.inv_equation_reordered}, + inv_variable_reordered{m.inv_variable_reordered}, + is_equation_linear{m.is_equation_linear}, + endo2eq{m.endo2eq}, + epilogue{m.epilogue}, + prologue{m.prologue}, + block_lag_lead{m.block_lag_lead}, + cutoff{m.cutoff}, + mfs{m.mfs} { copyHelper(m); } @@ -173,7 +173,6 @@ ModelTree::operator=(const ModelTree &m) return *this; } - bool ModelTree::computeNormalization(const jacob_map_t &contemporaneous_jacobian, bool verbose) { @@ -192,7 +191,7 @@ ModelTree::computeNormalization(const jacob_map_t &contemporaneous_jacobian, boo // Fill in the graph set<pair<int, int>> endo; - for (const auto & it : contemporaneous_jacobian) + for (const auto &it : contemporaneous_jacobian) add_edge(it.first.first + n, it.first.second, g); // Compute maximum cardinality matching @@ -291,7 +290,7 @@ ModelTree::computeNonSingularNormalization(jacob_map_t &contemporaneous_jacobian if (fabs(it.second) > max_val[it.first.first]) max_val[it.first.first] = fabs(it.second); - for (auto & iter : normalized_contemporaneous_jacobian) + for (auto &iter : normalized_contemporaneous_jacobian) iter.second /= max_val[iter.first.first]; //We start with the highest value of the cutoff and try to normalize the model @@ -302,7 +301,7 @@ ModelTree::computeNonSingularNormalization(jacob_map_t &contemporaneous_jacobian { jacob_map_t tmp_normalized_contemporaneous_jacobian; int suppress = 0; - for (auto & iter : normalized_contemporaneous_jacobian) + for (auto &iter : normalized_contemporaneous_jacobian) if (fabs(iter.second) > max(current_cutoff, cutoff)) tmp_normalized_contemporaneous_jacobian[{ iter.first.first, iter.first.second }] = iter.second; else @@ -330,7 +329,7 @@ ModelTree::computeNonSingularNormalization(jacob_map_t &contemporaneous_jacobian { endo.clear(); equations[i]->collectEndogenous(endo); - for (const auto & it : endo) + for (const auto &it : endo) tmp_normalized_contemporaneous_jacobian[{ i, it.first }] = 1; } check = computeNormalization(tmp_normalized_contemporaneous_jacobian, true); @@ -445,7 +444,7 @@ ModelTree::evaluateAndReduceJacobian(const eval_context_t &eval_context, jacob_m } // Get rid of the elements of the Jacobian matrix below the cutoff - for (const auto & it : jacobian_elements_to_delete) + for (const auto &it : jacobian_elements_to_delete) derivatives[1].erase(it); if (jacobian_elements_to_delete.size() > 0) @@ -455,7 +454,7 @@ ModelTree::evaluateAndReduceJacobian(const eval_context_t &eval_context, jacob_m } } -vector<pair<int, int> > +vector<pair<int, int>> ModelTree::select_non_linear_equations_and_variables(vector<bool> is_equation_linear, const dynamic_jacob_map_t &dynamic_jacobian, vector<int> &equation_reordered, vector<int> &variable_reordered, vector<int> &inv_equation_reordered, vector<int> &inv_variable_reordered, lag_lead_vector_t &equation_lag_lead, lag_lead_vector_t &variable_lag_lead, @@ -463,7 +462,7 @@ ModelTree::select_non_linear_equations_and_variables(vector<bool> is_equation_li { vector<int> eq2endo(equations.size(), 0); /*equation_reordered.resize(equations.size()); - variable_reordered.resize(equations.size());*/ + variable_reordered.resize(equations.size());*/ unsigned int num = 0; for (auto it : endo2eq) if (!is_equation_linear[it]) @@ -514,7 +513,7 @@ bool ModelTree::computeNaturalNormalization() { bool bool_result = true; - set<pair<int, int> > result; + set<pair<int, int>> result; endo2eq.resize(equations.size()); for (int eq = 0; eq < static_cast<int>(equations.size()); eq++) if (!is_equation_linear[eq]) @@ -561,12 +560,12 @@ ModelTree::computePrologueAndEpilogue(const jacob_map_t &static_jacobian_arg, ve { endo.clear(); equations[i]->collectEndogenous(endo); - for (const auto & it : endo) + for (const auto &it : endo) IM[i * n + endo2eq[it.first]] = true; } } else - for (const auto & it : static_jacobian_arg) + for (const auto &it : static_jacobian_arg) IM[it.first.first * n + endo2eq[it.first.second]] = true; bool something_has_been_done = true; prologue = 0; @@ -683,7 +682,7 @@ ModelTree::equationTypeDetermination(const map<tuple<int, int, int>, expr_t> &fi else { vector<tuple<int, expr_t, expr_t>> List_of_Op_RHS; - res = equations[eq]->normalizeEquation(var, List_of_Op_RHS); + res = equations[eq]->normalizeEquation(var, List_of_Op_RHS); if (mfs == 2) { if (d_endo_variable == result.end() && res.second) @@ -726,7 +725,7 @@ ModelTree::getVariableLeadLagByBlock(const dynamic_jacob_map_t &dynamic_jacobian equation_blck[equation_reordered[i]] = i- (nb_endo - nb_blck_sim - prologue - epilogue); } } - for (const auto & it : dynamic_jacobian) + for (const auto &it : dynamic_jacobian) { auto [lag, j_1, i_1] = it.first; if (variable_blck[i_1] == equation_blck[j_1]) @@ -771,7 +770,7 @@ ModelTree::computeBlockDecompositionAndFeedbackVariablesForEachBlock(const jacob { endo.clear(); equations[i]->collectEndogenous(endo); - for (const auto & it : endo) + for (const auto &it : endo) tmp_normalized_contemporaneous_jacobian[{ i, it.first }] = 1; } } @@ -1036,7 +1035,7 @@ ModelTree::reduceBlocksAndTypeDetermination(const dynamic_jacob_map_t &dynamic_j { endo.clear(); equations[equation_reordered[count_equ]]->collectEndogenous(endo); - for (const auto & it : endo) + for (const auto &it : endo) { int curr_variable = it.first; int curr_lag = it.second; @@ -1103,8 +1102,8 @@ ModelTree::reduceBlocksAndTypeDetermination(const dynamic_jacob_map_t &dynamic_j bool is_lead = false, is_lag = false; int c_Size = get<2>(block_type_size_mfs[block_type_size_mfs.size()-1]); int first_equation = get<1>(block_type_size_mfs[block_type_size_mfs.size()-1]); - if (c_Size > 0 && ((prev_Type == EVALUATE_FORWARD && Simulation_Type == EVALUATE_FORWARD && !is_lead) - || (prev_Type == EVALUATE_BACKWARD && Simulation_Type == EVALUATE_BACKWARD && !is_lag))) + if (c_Size > 0 && ((prev_Type == EVALUATE_FORWARD && Simulation_Type == EVALUATE_FORWARD && !is_lead) + || (prev_Type == EVALUATE_BACKWARD && Simulation_Type == EVALUATE_BACKWARD && !is_lag))) { for (int j = first_equation; j < first_equation+c_Size; j++) { @@ -1116,8 +1115,8 @@ ModelTree::reduceBlocksAndTypeDetermination(const dynamic_jacob_map_t &dynamic_j is_lead = true; } } - if ((prev_Type == EVALUATE_FORWARD && Simulation_Type == EVALUATE_FORWARD && !is_lead) - || (prev_Type == EVALUATE_BACKWARD && Simulation_Type == EVALUATE_BACKWARD && !is_lag)) + if ((prev_Type == EVALUATE_FORWARD && Simulation_Type == EVALUATE_FORWARD && !is_lead) + || (prev_Type == EVALUATE_BACKWARD && Simulation_Type == EVALUATE_BACKWARD && !is_lag)) { //merge the current block with the previous one BlockSimulationType c_Type = get<0>(block_type_size_mfs[block_type_size_mfs.size()-1]); @@ -1163,14 +1162,14 @@ ModelTree::equationLinear(map<tuple<int, int, int>, expr_t> first_order_endo_der vector<bool> is_linear(symbol_table.endo_nbr(), true); for (const auto &it : first_order_endo_derivatives) { - expr_t Id = it.second; - set<pair<int, int>> endogenous; - Id->collectEndogenous(endogenous); - if (endogenous.size() > 0) - { - int eq = get<0>(it.first); - is_linear[eq] = false; - } + expr_t Id = it.second; + set<pair<int, int>> endogenous; + Id->collectEndogenous(endogenous); + if (endogenous.size() > 0) + { + int eq = get<0>(it.first); + is_linear[eq] = false; + } } return is_linear; } @@ -1242,7 +1241,7 @@ ModelTree::writeDerivative(ostream &output, int eq, int symb_id, int lag, void ModelTree::computeDerivatives(int order, const set<int> &vars) { - assert (order >= 1); + assert(order >= 1); // Do not shrink the vectors, since they have a minimal size of 4 (see constructor) derivatives.resize(max(static_cast<size_t>(order+1), derivatives.size())); @@ -1293,7 +1292,7 @@ ModelTree::computeTemporaryTerms(bool is_matlab, bool no_tmp_terms) be treated as the rest of temporary terms. */ temporary_terms_mlv.clear(); set<int> used_local_vars; - for (auto & equation : equations) + for (auto &equation : equations) equation->collectVariables(SymbolType::modelLocalVariable, used_local_vars); for (int used_local_var : used_local_vars) { @@ -1305,7 +1304,7 @@ ModelTree::computeTemporaryTerms(bool is_matlab, bool no_tmp_terms) map<pair<int, int>, temporary_terms_t> temp_terms_map; map<expr_t, pair<int, pair<int, int>>> reference_count; - for (auto & equation : equations) + for (auto &equation : equations) equation->computeTemporaryTerms({ 0, 0 }, temp_terms_map, reference_count, @@ -1324,7 +1323,7 @@ ModelTree::computeTemporaryTerms(bool is_matlab, bool no_tmp_terms) if (no_tmp_terms) for (auto &it : temp_terms_map) // The following loop can be simplified with std::erase_if() in C++20 - for (auto it2 = it.second.begin(); it2 != it.second.end(); ) + for (auto it2 = it.second.begin(); it2 != it.second.end();) if (!dynamic_cast<AbstractExternalFunctionNode *>(*it2)) it2 = it.second.erase(it2); else @@ -1499,7 +1498,7 @@ ModelTree::fixNestedParenthesis(ostringstream &output, map<string, string> &tmp_ string repstr, varname; while (testNestedParenthesis(str1)) { - size_t open_paren_idx = string::npos; + size_t open_paren_idx = string::npos; size_t match_paren_idx = string::npos; size_t last_open_paren = string::npos; for (size_t j = 0; j < str1.length(); j++) @@ -1798,7 +1797,7 @@ ModelTree::Write_Inf_To_Bin_File(const string &filename, } } if (is_two_boundaries) - u_count_int += symbol_table.endo_nbr(); + u_count_int += symbol_table.endo_nbr(); for (j = 0; j < static_cast<int>(symbol_table.endo_nbr()); j++) SaveCode.write(reinterpret_cast<char *>(&j), sizeof(j)); for (j = 0; j < static_cast<int>(symbol_table.endo_nbr()); j++) @@ -1909,11 +1908,11 @@ ModelTree::includeExcludeEquations(set<pair<string, string>> &eqs, bool exclude_ // Get equation numbers of tags set<int> tag_eqns; - for (auto & it : eqs) + for (auto &it : eqs) if (equation_tags_xref.find(it) != equation_tags_xref.end()) { auto range = equation_tags_xref.equal_range(it); - for_each (range.first, range.second, [&tag_eqns](auto & x){ tag_eqns.insert(x.second); }); + for_each(range.first, range.second, [&tag_eqns](auto &x) { tag_eqns.insert(x.second); }); eqs.erase(it); } if (tag_eqns.empty()) @@ -1968,15 +1967,15 @@ ModelTree::includeExcludeEquations(set<pair<string, string>> &eqs, bool exclude_ equations_lineno = new_equations_lineno; equation_tags.erase(remove_if(equation_tags.begin(), equation_tags.end(), - [&](const auto& it) { return eqns.find(it.first) != eqns.end(); }), + [&](const auto &it) { return eqns.find(it.first) != eqns.end(); }), equation_tags.end()); - for (auto & it : old_eqn_num_2_new) - for (auto & it1 : equation_tags) + for (auto &it : old_eqn_num_2_new) + for (auto &it1 : equation_tags) if (it1.first == it.first) it1.first = it.second; equation_tags_xref.clear(); - for (const auto & it : equation_tags) + for (const auto &it : equation_tags) equation_tags_xref.emplace(it.second, it.first); if (!static_equations) @@ -1990,7 +1989,7 @@ ModelTree::includeExcludeEquations(set<pair<string, string>> &eqs, bool exclude_ } cout << "Excluded " << n_excl << (static_equations ? " static " : " dynamic ") - << "equation" << (n_excl > 1 ? "s" : "" ) << " via in/exclude_eqs option" << endl; + << "equation" << (n_excl > 1 ? "s" : "") << " via in/exclude_eqs option" << endl; return excluded_vars; } @@ -2004,7 +2003,7 @@ ModelTree::simplifyEquations() while (subst_table.size() != last_subst_table_size) { last_subst_table_size = subst_table.size(); - for (auto & equation : equations) + for (auto &equation : equations) equation = dynamic_cast<BinaryOpNode *>(equation->replaceVarsInEquation(subst_table)); subst_table.clear(); findConstantEquations(subst_table); @@ -2014,7 +2013,7 @@ ModelTree::simplifyEquations() void ModelTree::findConstantEquations(map<VariableNode *, NumConstNode *> &subst_table) const { - for (auto & equation : equations) + for (auto &equation : equations) equation->findConstantEquations(subst_table); } @@ -2022,7 +2021,7 @@ void ModelTree::addEquation(expr_t eq, int lineno, const vector<pair<string, string>> &eq_tags) { int n = equations.size(); - for (const auto & eq_tag : eq_tags) + for (const auto &eq_tag : eq_tags) { equation_tags.emplace_back(n, eq_tag); equation_tags_xref.emplace(eq_tag, n); @@ -2322,7 +2321,7 @@ ModelTree::compileDll(const string &basename, const string &static_or_dynamic, c cerr << "Can't set PATH" << endl; exit(EXIT_FAILURE); } - } + } else { // macOS diff --git a/src/ModelTree.hh b/src/ModelTree.hh index 3b3426bb..d04f5d4d 100644 --- a/src/ModelTree.hh +++ b/src/ModelTree.hh @@ -34,12 +34,16 @@ using namespace std; #include "ExtendedPreprocessorTypes.hh" // Helper to convert a vector into a tuple -template <typename T, size_t... Indices> -auto vectorToTupleHelper(const vector<T>& v, index_sequence<Indices...>) { - return tuple(v[Indices]...); +template<typename T, size_t... Indices> +auto +vectorToTupleHelper(const vector<T> &v, index_sequence<Indices...>) +{ + return tuple(v[Indices] ...); } -template <size_t N, typename T> -auto vectorToTuple(const vector<T>& v) { +template<size_t N, typename T> +auto +vectorToTuple(const vector<T> &v) +{ assert(v.size() >= N); return vectorToTupleHelper(v, make_index_sequence<N>()); } @@ -138,7 +142,7 @@ protected: //! Temporary terms for parameter derivatives, under a disaggregated form /*! The pair of integers is to be interpreted as in param_derivatives */ - map<pair<int,int>, temporary_terms_t> params_derivs_temporary_terms; + map<pair<int, int>, temporary_terms_t> params_derivs_temporary_terms; //! Stores, for each temporary term in param. derivs, its index in the MATLAB/Julia vector temporary_terms_idxs_t params_derivs_temporary_terms_idxs; @@ -157,7 +161,7 @@ protected: //! the file containing the model and the derivatives code ofstream code_file; - + //! Vector indicating if the equation is linear in endogenous variable (true) or not (false) vector<bool> is_equation_linear; @@ -242,10 +246,10 @@ protected: //! Evaluate the jacobian and suppress all the elements below the cutoff void evaluateAndReduceJacobian(const eval_context_t &eval_context, jacob_map_t &contemporaneous_jacobian, jacob_map_t &static_jacobian, dynamic_jacob_map_t &dynamic_jacobian, double cutoff, bool verbose); //! Select and reorder the non linear equations of the model - vector<pair<int, int> > select_non_linear_equations_and_variables(vector<bool> is_equation_linear, const dynamic_jacob_map_t &dynamic_jacobian, vector<int> &equation_reordered, vector<int> &variable_reordered, - vector<int> &inv_equation_reordered, vector<int> &inv_variable_reordered, - lag_lead_vector_t &equation_lag_lead, lag_lead_vector_t &variable_lag_lead, - vector<unsigned int> &n_static, vector<unsigned int> &n_forward, vector<unsigned int> &n_backward, vector<unsigned int> &n_mixed); + vector<pair<int, int>> select_non_linear_equations_and_variables(vector<bool> is_equation_linear, const dynamic_jacob_map_t &dynamic_jacobian, vector<int> &equation_reordered, vector<int> &variable_reordered, + vector<int> &inv_equation_reordered, vector<int> &inv_variable_reordered, + lag_lead_vector_t &equation_lag_lead, lag_lead_vector_t &variable_lag_lead, + vector<unsigned int> &n_static, vector<unsigned int> &n_forward, vector<unsigned int> &n_backward, vector<unsigned int> &n_mixed); //! Search the equations and variables belonging to the prologue and the epilogue of the model void computePrologueAndEpilogue(const jacob_map_t &static_jacobian, vector<int> &equation_reordered, vector<int> &variable_reordered); //! Determine the type of each equation of model and try to normalized the unnormalized equation using computeNormalizedEquations @@ -337,8 +341,8 @@ public: ModelTree(const ModelTree &m); ModelTree(ModelTree &&) = delete; - ModelTree & operator=(const ModelTree &m); - ModelTree & operator=(ModelTree &&) = delete; + ModelTree &operator=(const ModelTree &m); + ModelTree &operator=(ModelTree &&) = delete; //! Absolute value under which a number is considered to be zero double cutoff{1e-15}; @@ -380,10 +384,11 @@ public: void sparseHelper(int order, ostream &output, int row_nb, int col_nb, ExprNodeOutputType output_type) const; //! Returns all the equation tags associated to an equation - inline map<string, string> getEquationTags(int eq) const + inline map<string, string> + getEquationTags(int eq) const { map<string, string> r; - for (auto &[eq2, tagpair]: equation_tags) + for (auto &[eq2, tagpair] : equation_tags) if (eq2 == eq) r[tagpair.first] = tagpair.second; return r; @@ -394,10 +399,10 @@ public: { vector<string> c_Equation_Type = { - "E_UNKNOWN ", - "E_EVALUATE ", - "E_EVALUATE_S", - "E_SOLVE " + "E_UNKNOWN ", + "E_EVALUATE ", + "E_EVALUATE_S", + "E_SOLVE " }; return c_Equation_Type[type]; }; diff --git a/src/NumericalInitialization.cc b/src/NumericalInitialization.cc index cfd12825..3f7446c3 100644 --- a/src/NumericalInitialization.cc +++ b/src/NumericalInitialization.cc @@ -94,7 +94,7 @@ InitOrEndValStatement::InitOrEndValStatement(init_values_t init_values_arg, void InitOrEndValStatement::fillEvalContext(eval_context_t &eval_context) const { - for (const auto & init_value : init_values) + for (const auto &init_value : init_values) { try { @@ -124,7 +124,7 @@ InitOrEndValStatement::getUninitializedVariables(SymbolType type) exit(EXIT_FAILURE); } - for (const auto & init_value : init_values) + for (const auto &init_value : init_values) if (auto sit = unused.find(init_value.first); sit != unused.end()) unused.erase(sit); @@ -135,7 +135,7 @@ InitOrEndValStatement::getUninitializedVariables(SymbolType type) void InitOrEndValStatement::writeInitValues(ostream &output) const { - for (const auto & init_value : init_values) + for (const auto &init_value : init_values) { const int symb_id = init_value.first; const expr_t expression = init_value.second; @@ -318,7 +318,7 @@ HistValStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidat set<int> unused_endo = symbol_table.getEndogenous(); set<int> unused_exo = symbol_table.getExogenous(); - for (const auto & hist_value : hist_values) + for (const auto &hist_value : hist_values) { if (auto sit = unused_endo.find(hist_value.first.first); sit != unused_endo.end()) @@ -366,7 +366,7 @@ HistValStatement::writeOutput(ostream &output, const string &basename, bool mini << (symbol_table.exo_det_nbr() > 0 ? "M_.exo_det_names; " : "") << "]);" << endl; - for (const auto & hist_value : hist_values) + for (const auto &hist_value : hist_values) { int symb_id = hist_value.first.first; int lag = hist_value.first.second; @@ -378,8 +378,8 @@ HistValStatement::writeOutput(ostream &output, const string &basename, bool mini } output << "if exist(['+' M_.fname '/dynamic_set_auxiliary_series.m'])" << endl - << " eval(['M_.histval_dseries = ' M_.fname '.dynamic_set_auxiliary_series(M_.histval_dseries, M_.params);']);" << endl - << "end" << endl + << " eval(['M_.histval_dseries = ' M_.fname '.dynamic_set_auxiliary_series(M_.histval_dseries, M_.params);']);" << endl + << "end" << endl << "M_.endo_histval = M_.histval_dseries{M_.endo_names{:}}(dates(sprintf('%dY', 1-M_.maximum_lag)):dates('0Y')).data';" << endl << "M_.endo_histval(isnan(M_.endo_histval)) = 0;" << endl; // Ensure that lead aux variables do not have a NaN diff --git a/src/ParsingDriver.cc b/src/ParsingDriver.cc index b7db2f03..98a8192f 100644 --- a/src/ParsingDriver.cc +++ b/src/ParsingDriver.cc @@ -391,12 +391,12 @@ ParsingDriver::add_model_variable(int symb_id, int lag) SymbolType type = mod_file->symbol_table.getType(symb_id); if (type == SymbolType::modFileLocalVariable) - error("Variable " + mod_file->symbol_table.getName(symb_id) + - " not allowed inside model declaration. Its scope is only outside model."); + error("Variable " + mod_file->symbol_table.getName(symb_id) + +" not allowed inside model declaration. Its scope is only outside model."); if (type == SymbolType::externalFunction) - error("Symbol " + mod_file->symbol_table.getName(symb_id) + - " is a function name external to Dynare. It cannot be used like a variable without input argument inside model."); + error("Symbol " + mod_file->symbol_table.getName(symb_id) + +" is a function name external to Dynare. It cannot be used like a variable without input argument inside model."); if (type == SymbolType::modelLocalVariable && lag != 0) error("Model local variable " + mod_file->symbol_table.getName(symb_id) + " cannot be given a lead or a lag."); @@ -511,7 +511,7 @@ ParsingDriver::add_VAR_exclusion_restriction(const string &lagstr) it == exclusion_restrictions.end()) exclusion_restrictions[lag] = exclusion_restriction; else - for (auto & it1 : exclusion_restriction) + for (auto &it1 : exclusion_restriction) it->second[it1.first] = it1.second; exclusion_restriction.clear(); @@ -775,7 +775,7 @@ ParsingDriver::differentiate_forward_vars_some() { mod_file->differentiate_forward_vars = true; mod_file->differentiate_forward_vars_subset = symbol_list.get_symbols(); - for (auto & it : mod_file->differentiate_forward_vars_subset) + for (auto &it : mod_file->differentiate_forward_vars_subset) check_symbol_is_endogenous(it); symbol_list.clear(); } @@ -797,31 +797,31 @@ ParsingDriver::mfs(const string &value) } void -ParsingDriver::compilation_setup_substitute_flags(const string & flags) +ParsingDriver::compilation_setup_substitute_flags(const string &flags) { mod_file->dynamic_model.user_set_subst_flags = flags; } void -ParsingDriver::compilation_setup_add_flags(const string & flags) +ParsingDriver::compilation_setup_add_flags(const string &flags) { mod_file->dynamic_model.user_set_add_flags = flags; } void -ParsingDriver::compilation_setup_substitute_libs(const string & libs) +ParsingDriver::compilation_setup_substitute_libs(const string &libs) { mod_file->dynamic_model.user_set_subst_libs = libs; } void -ParsingDriver::compilation_setup_add_libs(const string & libs) +ParsingDriver::compilation_setup_add_libs(const string &libs) { mod_file->dynamic_model.user_set_add_libs = libs; } void -ParsingDriver::compilation_setup_compiler(const string & compiler) +ParsingDriver::compilation_setup_compiler(const string &compiler) { mod_file->dynamic_model.user_set_compiler = compiler; } @@ -897,7 +897,7 @@ ParsingDriver::end_model() { bool exit_after_write = false; if (model_errors.size() > 0) - for (auto & it : model_errors) + for (auto &it : model_errors) { if (it.first.empty()) exit_after_write = true; @@ -905,7 +905,7 @@ ParsingDriver::end_model() } if (undeclared_model_variable_errors.size() > 0) - for (auto & it : undeclared_model_variable_errors) + for (auto &it : undeclared_model_variable_errors) if (nostrict) warning(it.second); else @@ -1412,7 +1412,7 @@ ParsingDriver::option_symbol_list(string name_option) if (name_option.compare("irf_shocks") == 0) { vector<string> shocks = symbol_list.get_symbols(); - for (auto & shock : shocks) + for (auto &shock : shocks) if (mod_file->symbol_table.getType(shock) != SymbolType::exogenous) error("Variables passed to irf_shocks must be exogenous. Caused by: " + shock); } @@ -1420,7 +1420,7 @@ ParsingDriver::option_symbol_list(string name_option) if (name_option.compare("ms.parameters") == 0) { vector<string> parameters = symbol_list.get_symbols(); - for (auto & it : parameters) + for (auto &it : parameters) if (mod_file->symbol_table.getType(it) != SymbolType::parameter) error("Variables passed to the parameters option of the markov_switching statement must be parameters. Caused by: " + it); } @@ -1517,8 +1517,8 @@ ParsingDriver::var_model() if (itn != options_list.num_options.end()) order = stoi(itn->second); else - if (!symbol_list.empty()) - error("You must pass the order option when passing a symbol list to the var_model statement"); + if (!symbol_list.empty()) + error("You must pass the order option when passing a symbol list to the var_model statement"); vector<string> eqtags; auto itvs = options_list.vector_str_options.find("var.eqtags"); @@ -2137,7 +2137,7 @@ ParsingDriver::run_identification() void ParsingDriver::add_mc_filename(string filename, string prior) { - for (auto & it : filename_list) + for (auto &it : filename_list) if (it.first == filename) error("model_comparison: filename " + filename + " declared twice"); filename_list.emplace_back(move(filename), move(prior)); @@ -2447,7 +2447,7 @@ ParsingDriver::conditional_forecast_paths() } void -ParsingDriver::det_cond_forecast_linear_decomposition(const string & plan) +ParsingDriver::det_cond_forecast_linear_decomposition(const string &plan) { symbol_list.clear(); symbol_list.addSymbol(plan); @@ -2489,7 +2489,7 @@ ParsingDriver::add_model_equal(expr_t arg1, expr_t arg2) // Detect if the equation is tagged [static] bool is_static_only = false; - for (auto & eq_tag : eq_tags) + for (auto &eq_tag : eq_tags) if (eq_tag.first == "static") { is_static_only = true; @@ -2551,7 +2551,7 @@ ParsingDriver::declare_and_init_model_local_variable(const string &name, expr_t void ParsingDriver::change_type(SymbolType new_type, const vector<string> &var_list) { - for (auto & it : var_list) + for (auto &it : var_list) { int id; try @@ -2720,7 +2720,7 @@ ParsingDriver::pac_model() } else if (pac_growth_is_param - && (pac_steady_state_growth_rate_number >= 0 || pac_steady_state_growth_rate_symb_id >=0)) + && (pac_steady_state_growth_rate_number >= 0 || pac_steady_state_growth_rate_symb_id >= 0)) warning("If growth option is constant, steady_state_growth is ignored"); else if (pac_growth && !pac_growth_is_param && (pac_steady_state_growth_rate_number < 0 || pac_steady_state_growth_rate_symb_id < 0)) @@ -3007,11 +3007,11 @@ ParsingDriver::external_function() error("The 'name' option must be passed to external_function()."); if (current_external_function_options.secondDerivSymbID >= 0 - && current_external_function_options.firstDerivSymbID == ExternalFunctionsTable::IDNotSet) + && current_external_function_options.firstDerivSymbID == ExternalFunctionsTable::IDNotSet) error("If the second derivative is provided to the external_function command, the first derivative must also be provided."); if (current_external_function_options.secondDerivSymbID == ExternalFunctionsTable::IDSetButNoNameProvided - && current_external_function_options.firstDerivSymbID != ExternalFunctionsTable::IDSetButNoNameProvided) + && current_external_function_options.firstDerivSymbID != ExternalFunctionsTable::IDSetButNoNameProvided) error("If the second derivative is provided in the top-level function, the first derivative must also be provided in that function."); mod_file->external_functions_table.addExternalFunction(current_external_function_id, current_external_function_options, true); @@ -3096,8 +3096,8 @@ ParsingDriver::add_model_var_or_external_function(const string &function_name, b pair<bool, double> rv = is_there_one_integer_argument(); if (!rv.first) - model_error("Symbol " + function_name + - " is being treated as if it were a function (i.e., takes an argument that is not an integer).", ""); + model_error("Symbol " + function_name + +" is being treated as if it were a function (i.e., takes an argument that is not an integer).", ""); nid = add_model_variable(mod_file->symbol_table.getID(function_name), static_cast<int>(rv.second)); stack_external_function_args.pop(); @@ -3138,8 +3138,8 @@ ParsingDriver::add_model_var_or_external_function(const string &function_name, b return add_model_variable(mod_file->symbol_table.getID(function_name), static_cast<int>(rv.second)); } else - error("To use an external function (" + function_name + - ") within the model block, you must first declare it via the external_function() statement."); + error("To use an external function (" + function_name + +") within the model block, you must first declare it via the external_function() statement."); } declare_symbol(function_name, SymbolType::externalFunction, "", {}); current_external_function_options.nargs = stack_external_function_args.top().size(); @@ -3220,7 +3220,7 @@ ParsingDriver::add_steady_state_model_equal_multiple(expr_t expr) const vector<string> &symbs = symbol_list.get_symbols(); vector<int> ids; - for (const auto & symb : symbs) + for (const auto &symb : symbs) { int id; try diff --git a/src/ParsingDriver.hh b/src/ParsingDriver.hh index a8f1d72f..32eee6ff 100644 --- a/src/ParsingDriver.hh +++ b/src/ParsingDriver.hh @@ -62,8 +62,8 @@ public: DynareFlex(const DynareFlex &) = delete; DynareFlex(DynareFlex &&) = delete; - DynareFlex & operator=(const DynareFlex &) = delete; - DynareFlex & operator=(DynareFlex &&) = delete; + DynareFlex &operator=(const DynareFlex &) = delete; + DynareFlex &operator=(DynareFlex &&) = delete; //! The main lexing function Dynare::parser::token_type lex(Dynare::parser::semantic_type *yylval, @@ -205,9 +205,9 @@ private: //! Temporary storage for restriction type enum class SvarRestrictionType { - NOT_SET, - Qi_TYPE, - Ri_TYPE + NOT_SET, + Qi_TYPE, + Ri_TYPE }; SvarRestrictionType svar_restriction_type; //! Temporary storage for generate_irfs @@ -215,7 +215,7 @@ private: vector<map<string, double>> generate_irf_elements; map<string, double> generate_irf_exos; //! Temporary storage for argument list of external function - stack<vector<expr_t>> stack_external_function_args; + stack<vector<expr_t>> stack_external_function_args; //! Temporary storage for parameters in joint prior statement vector<string> joint_parameters; //! Temporary storage for the symb_id associated with the "name" symbol of the current external_function statement @@ -279,12 +279,14 @@ private: public: ParsingDriver(WarningConsolidation &warnings_arg, bool nostrict_arg) : - warnings{warnings_arg}, nostrict{nostrict_arg} { }; + warnings{warnings_arg}, nostrict{nostrict_arg} + { + }; ParsingDriver(const ParsingDriver &) = delete; ParsingDriver(ParsingDriver &&) = delete; - ParsingDriver & operator=(const ParsingDriver &) = delete; - ParsingDriver & operator=(ParsingDriver &&) = delete; + ParsingDriver &operator=(const ParsingDriver &) = delete; + ParsingDriver &operator=(ParsingDriver &&) = delete; //! Starts parsing, and constructs the MOD file representation unique_ptr<ModFile> parse(istream &in, bool debug); @@ -361,15 +363,15 @@ public: //! mfs option of model block void mfs(const string &value); //! the flags to substitute for the default compiler flags used by `use_dll` - void compilation_setup_substitute_flags(const string & flags); + void compilation_setup_substitute_flags(const string &flags); //! the flags to add to the default compiler flags used by `use_dll` - void compilation_setup_add_flags(const string & flags); + void compilation_setup_add_flags(const string &flags); //! the libs to substitute for the default compiler libs used by `use_dll` - void compilation_setup_substitute_libs(const string & libs); + void compilation_setup_substitute_libs(const string &libs); //! the libs to add to the default compiler libs used by `use_dll` - void compilation_setup_add_libs(const string & libs); + void compilation_setup_add_libs(const string &libs); //! the compiler to replace the default compiler used by `use_dll` - void compilation_setup_compiler(const string & path); + void compilation_setup_compiler(const string &path); //! balanced_growth_test_tol option of model block void balanced_growth_test_tol(const string &value); //! Sets the FILENAME for the initial value in initval @@ -557,7 +559,7 @@ public: void set_options(const string &name, const string &subsample_name); //! Copies the options from_name to_name void copy_options(const string &to_declaration_type, const string &to_name1, const string &to_name2, const string &to_subsample_name, - const string &from_declaration_type, const string &from_name1, const string &from_name2, const string &from_subsample_name); + const string &from_declaration_type, const string &from_name1, const string &from_name2, const string &from_subsample_name); //! Sets the prior for estimated std dev void set_std_prior(const string &name, const string &subsample_name); //! Sets the options for estimated std dev @@ -728,13 +730,13 @@ public: //! Writes token "arg1+arg2" to model tree expr_t add_plus(expr_t arg1, expr_t arg2); //! Writes token "arg1-arg2" to model tree - expr_t add_minus(expr_t arg1, expr_t arg2); + expr_t add_minus(expr_t arg1, expr_t arg2); //! Writes token "-arg1" to model tree expr_t add_uminus(expr_t arg1); //! Writes token "arg1*arg2" to model tree - expr_t add_times(expr_t arg1, expr_t arg2); + expr_t add_times(expr_t arg1, expr_t arg2); //! Writes token "arg1/arg2" to model tree - expr_t add_divide(expr_t arg1, expr_t arg2); + expr_t add_divide(expr_t arg1, expr_t arg2); //! Writes token "arg1<arg2" to model tree expr_t add_less(expr_t arg1, expr_t arg2); //! Writes token "arg1>arg2" to model treeexpr_t @@ -748,9 +750,9 @@ public: //! Writes token "arg1!=arg2" to model treeexpr_texpr_t expr_t add_different(expr_t arg1, expr_t arg2); //! Writes token "arg1^arg2" to model tree - expr_t add_power(expr_t arg1, expr_t arg2); + expr_t add_power(expr_t arg1, expr_t arg2); //! Writes token "E(arg1)(arg2)" to model tree - expr_t add_expectation(const string &arg1, expr_t arg2); + expr_t add_expectation(const string &arg1, expr_t arg2); //! Writes token "VAR_EXPECTATION(model_name)" to model tree expr_t add_var_expectation(const string &model_name); //! Writes token "PAC_EXPECTATION(model_name, discount, growth)" to model tree diff --git a/src/Shocks.cc b/src/Shocks.cc index 230fd278..ec946f13 100644 --- a/src/Shocks.cc +++ b/src/Shocks.cc @@ -432,7 +432,7 @@ ConditionalForecastPathsStatement::ConditionalForecastPathsStatement(AbstractSho void ConditionalForecastPathsStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) { - for (const auto & path : paths) + for (const auto &path : paths) { int this_path_length = 0; const vector<AbstractShocksStatement::DetShockElement> &elems = path.second; @@ -503,7 +503,7 @@ void MomentCalibration::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const { output << "options_.endogenous_prior_restrictions.moment = {" << endl; - for (const auto & c : constraints) + for (const auto &c : constraints) { output << "'" << symbol_table.getName(c.endo1) << "', " << "'" << symbol_table.getName(c.endo2) << "', " @@ -555,7 +555,7 @@ IrfCalibration::writeOutput(ostream &output, const string &basename, bool minima options_list.writeOutput(output); output << "options_.endogenous_prior_restrictions.irf = {" << endl; - for (const auto & c : constraints) + for (const auto &c : constraints) { output << "'" << symbol_table.getName(c.endo) << "', " << "'" << symbol_table.getName(c.exo) << "', " @@ -627,7 +627,7 @@ ShockGroupsStatement::writeOutput(ostream &output, const string &basename, bool << ".group" << i << ".label = '" << it->name << "';" << endl << "M_.shock_groups." << name << ".group" << i << ".shocks = {"; - for (const auto & it1 : it->list) + for (const auto &it1 : it->list) output << " '" << it1 << "'"; output << "};" << endl; i++; @@ -694,7 +694,7 @@ void Init2shocksStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const { output << "M_.init2shocks." << name << " = {" << endl; - for (auto & it : init2shocks) + for (auto &it : init2shocks) output << "{'" << symbol_table.getName(it.first) << "', '" << symbol_table.getName(it.second) << "'};" << endl; output << "};" << endl; } @@ -703,7 +703,7 @@ void Init2shocksStatement::writeJsonOutput(ostream &output) const { output << R"({"statementName": "init2shocks", "name": ")" << name << R"(", "groups": [)"; - for (auto & it : init2shocks) + for (auto &it : init2shocks) { if (it != *(init2shocks.begin())) output << ","; diff --git a/src/SigmaeInitialization.hh b/src/SigmaeInitialization.hh index 5a5428c2..39d53a9c 100644 --- a/src/SigmaeInitialization.hh +++ b/src/SigmaeInitialization.hh @@ -33,8 +33,8 @@ public: //! Matrix form (lower or upper triangular) enum enum class MatrixForm { - lower, //!< Lower triangular matrix - upper //!< Upper triangular matrix + lower, //!< Lower triangular matrix + upper //!< Upper triangular matrix }; //! Type of a matrix row using row_t = vector<expr_t>; diff --git a/src/Statement.cc b/src/Statement.cc index 850bde2b..ee1b4e11 100644 --- a/src/Statement.cc +++ b/src/Statement.cc @@ -128,7 +128,7 @@ OptionsList::writeOutput(ostream &output) const if (vals.size() > 1) { output << "{"; - for (const auto & viit : vals) + for (const auto &viit : vals) output << "'" << viit << "';"; output << "};" << endl; } @@ -187,7 +187,7 @@ OptionsList::writeOutput(ostream &output, const string &option_group) const if (vals.size() > 1) { output << "{"; - for (const auto & viit : vals) + for (const auto &viit : vals) output << "'" << viit << "';"; output << "};" << endl; } diff --git a/src/Statement.hh b/src/Statement.hh index cf439425..908260b9 100644 --- a/src/Statement.hh +++ b/src/Statement.hh @@ -144,8 +144,8 @@ public: Statement(const Statement &) = delete; Statement(Statement &&) = delete; - Statement & operator=(const Statement &) = delete; - Statement & operator=(Statement &&) = delete; + Statement &operator=(const Statement &) = delete; + Statement &operator=(Statement &&) = delete; //! Do some internal check, and fill the ModFileStructure class /*! Don't forget to update ComputingTasks.hh, Shocks.hh and diff --git a/src/StaticModel.cc b/src/StaticModel.cc index 2ae368c9..efaaf8a8 100644 --- a/src/StaticModel.cc +++ b/src/StaticModel.cc @@ -32,17 +32,17 @@ StaticModel::copyHelper(const StaticModel &m) auto f = [this](expr_t e) { return e->clone(*this); }; auto convert_vector_tt = [f](vector<temporary_terms_t> vtt) - { - vector<temporary_terms_t> vtt2; - for (const auto &tt : vtt) - { - temporary_terms_t tt2; - for (const auto &it : tt) - tt2.insert(f(it)); - vtt2.push_back(tt2); - } - return vtt2; - }; + { + vector<temporary_terms_t> vtt2; + for (const auto &tt : vtt) + { + temporary_terms_t tt2; + for (const auto &it : tt) + tt2.insert(f(it)); + vtt2.push_back(tt2); + } + return vtt2; + }; for (const auto &it : m.v_temporary_terms) v_temporary_terms.push_back(convert_vector_tt(it)); @@ -67,12 +67,12 @@ StaticModel::copyHelper(const StaticModel &m) dynamic_jacobian[it.first] = f(it.second); auto convert_derivative_t = [f](derivative_t dt) - { - derivative_t dt2; - for (const auto &it : dt) - dt2[it.first] = f(it.second); - return dt2; - }; + { + derivative_t dt2; + for (const auto &it : dt) + dt2[it.first] = f(it.second); + return dt2; + }; for (const auto &it : m.derivative_endo) derivative_endo.push_back(convert_derivative_t(it)); for (const auto &it : m.derivative_other_endo) @@ -91,19 +91,19 @@ StaticModel::StaticModel(SymbolTable &symbol_table_arg, } StaticModel::StaticModel(const StaticModel &m) : - ModelTree {m}, - v_temporary_terms_inuse {m.v_temporary_terms_inuse}, - map_idx {m.map_idx}, - map_idx2 {m.map_idx2}, - global_temporary_terms {m.global_temporary_terms}, - block_type_firstequation_size_mfs {m.block_type_firstequation_size_mfs}, - blocks_linear {m.blocks_linear}, - block_col_type {m.block_col_type}, - endo_max_leadlag_block {m.endo_max_leadlag_block}, - other_endo_max_leadlag_block {m.other_endo_max_leadlag_block}, - exo_max_leadlag_block {m.exo_max_leadlag_block}, - exo_det_max_leadlag_block {m.exo_det_max_leadlag_block}, - max_leadlag_block {m.max_leadlag_block} + ModelTree{m}, + v_temporary_terms_inuse{m.v_temporary_terms_inuse}, + map_idx{m.map_idx}, + map_idx2{m.map_idx2}, + global_temporary_terms{m.global_temporary_terms}, + block_type_firstequation_size_mfs{m.block_type_firstequation_size_mfs}, + blocks_linear{m.blocks_linear}, + block_col_type{m.block_col_type}, + endo_max_leadlag_block{m.endo_max_leadlag_block}, + other_endo_max_leadlag_block{m.other_endo_max_leadlag_block}, + exo_max_leadlag_block{m.exo_max_leadlag_block}, + exo_det_max_leadlag_block{m.exo_det_max_leadlag_block}, + max_leadlag_block{m.max_leadlag_block} { copyHelper(m); } @@ -151,7 +151,7 @@ StaticModel::operator=(const StaticModel &m) } StaticModel::StaticModel(const DynamicModel &m) : - ModelTree {m.symbol_table, m.num_constants, m.external_functions_table} + ModelTree{m.symbol_table, m.num_constants, m.external_functions_table} { // Convert model local variables (need to be done first) for (int it : m.local_variables_vector) @@ -264,17 +264,17 @@ StaticModel::computeTemporaryTermsOrdered() for (unsigned int i = 0; i < block_size; i++) { if (i < block_nb_recursives && isBlockEquationRenormalized(block, i)) - getBlockEquationRenormalizedExpr(block, i)->computeTemporaryTerms(reference_count_local, temporary_terms_l, first_occurence_local, block, v_temporary_terms_local, i); + getBlockEquationRenormalizedExpr(block, i)->computeTemporaryTerms(reference_count_local, temporary_terms_l, first_occurence_local, block, v_temporary_terms_local, i); else { eq_node = static_cast<BinaryOpNode *>(getBlockEquationExpr(block, i)); - eq_node->computeTemporaryTerms(reference_count_local, temporary_terms_l, first_occurence_local, block, v_temporary_terms_local, i); + eq_node->computeTemporaryTerms(reference_count_local, temporary_terms_l, first_occurence_local, block, v_temporary_terms_local, i); } } for (const auto &it : blocks_derivatives[block]) { expr_t id = get<3>(it); - id->computeTemporaryTerms(reference_count_local, temporary_terms_l, first_occurence_local, block, v_temporary_terms_local, block_size-1); + id->computeTemporaryTerms(reference_count_local, temporary_terms_l, first_occurence_local, block, v_temporary_terms_local, block_size-1); } v_temporary_terms_inuse[block] = {}; computeTemporaryTermsMapping(temporary_terms_l, map_idx2[block]); @@ -291,7 +291,7 @@ StaticModel::computeTemporaryTermsOrdered() for (unsigned int i = 0; i < block_size; i++) { if (i < block_nb_recursives && isBlockEquationRenormalized(block, i)) - getBlockEquationRenormalizedExpr(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); + getBlockEquationRenormalizedExpr(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); else { eq_node = static_cast<BinaryOpNode *>(getBlockEquationExpr(block, i)); @@ -353,7 +353,7 @@ StaticModel::writeModelEquationsOrdered_M(const string &basename) const BinaryOpNode *eq_node; map<expr_t, int> reference_count; temporary_terms_t local_temporary_terms; - ofstream output; + ofstream output; vector<int> feedback_variables; deriv_node_temp_terms_t tef_terms; ExprNodeOutputType local_output_type; @@ -392,11 +392,11 @@ StaticModel::writeModelEquationsOrdered_M(const string &basename) const if (simulation_type == SOLVE_FORWARD_COMPLETE || simulation_type == SOLVE_BACKWARD_COMPLETE) block_type = SIMULTANS; else if ((simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_SIMPLE - || simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + || simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) && getBlockFirstEquation(block) < prologue) block_type = PROLOGUE; else if ((simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_SIMPLE - || simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + || simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) && getBlockFirstEquation(block) >= equations.size() - epilogue) block_type = EPILOGUE; else @@ -409,7 +409,7 @@ StaticModel::writeModelEquationsOrdered_M(const string &basename) const << " % ////////////////////////////////////////////////////////////////////////" << endl; output << " global options_;" << endl; //The Temporary terms - if (simulation_type != EVALUATE_BACKWARD && simulation_type != EVALUATE_FORWARD) + if (simulation_type != EVALUATE_BACKWARD && simulation_type != EVALUATE_FORWARD) output << " g1 = spalloc(" << block_mfs << ", " << block_mfs << ", " << derivative_endo[block].size() << ");" << endl; if (v_temporary_terms_inuse[block].size()) @@ -515,7 +515,7 @@ StaticModel::writeModelEquationsOrdered_M(const string &basename) const } } // The Jacobian if we have to solve the block - if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE + if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE) output << " " << sps << "% Jacobian " << endl; switch (simulation_type) @@ -1191,7 +1191,7 @@ StaticModel::computingPass(int derivsOrder, int paramsDerivsOrder, const eval_co neweqs.push_back(dynamic_cast<BinaryOpNode *>(eq_tmp->toStatic(*this))); } - for (auto & aux_equation : aux_equations) + for (auto &aux_equation : aux_equations) { expr_t eq_tmp = aux_equation->substituteStaticAuxiliaryDefinition(); neweqs.push_back(dynamic_cast<BinaryOpNode *>(eq_tmp->toStatic(*this))); @@ -1453,7 +1453,7 @@ void StaticModel::writeStaticModel(const string &basename, ostream &StaticOutput, bool use_dll, bool julia) const { - vector<ostringstream> d_output(derivatives.size()); // Derivatives output (at all orders, including 0=residual) + vector<ostringstream> d_output(derivatives.size()); // Derivatives output (at all orders, including 0=residual) vector<ostringstream> tt_output(derivatives.size()); // Temp terms output (at all orders) ExprNodeOutputType output_type = (use_dll ? ExprNodeOutputType::CStaticModel : @@ -1721,7 +1721,7 @@ StaticModel::writeStaticModel(const string &basename, << " The columns and rows respectively correspond to the variables in declaration order and the" << endl << " equations in order of declaration" << endl << endl << "## Remarks ##" << endl - << " [1] The size of `T`, ie the value of `num_temp_terms`, depends on the version of the static model called. The number of temporary variables" << endl + << " [1] The size of `T`, ie the value of `num_temp_terms`, depends on the version of the static model called. The number of temporary variables" << endl << " used for the different returned objects (residuals, jacobian, hessian or third order derivatives) is given by the elements in `tmp_nbr`" << endl << " exported vector. The first element is the number of temporaries used for the computation of the residuals, the second element is the" << endl << " number of temporaries used for the evaluation of the jacobian matrix, etc. If one calls the version of the static model computing the" << endl @@ -2103,7 +2103,7 @@ void StaticModel::writeOutput(ostream &output, bool block) const { output << "M_.static_tmp_nbr = ["; - for (const auto & temporary_terms_derivative : temporary_terms_derivatives) + for (const auto &temporary_terms_derivative : temporary_terms_derivatives) output << temporary_terms_derivative.size() << "; "; output << "];" << endl; @@ -2342,7 +2342,7 @@ StaticModel::collect_block_first_order_derivatives() derivative_endo = vector<derivative_t>(nb_blocks); endo_max_leadlag_block = vector<pair<int, int>>(nb_blocks, { 0, 0 }); max_leadlag_block = vector<pair<int, int>>(nb_blocks, { 0, 0 }); - for (auto & first_derivative : derivatives[1]) + for (auto &first_derivative : derivatives[1]) { int eq = first_derivative.first[0]; int var = symbol_table.getTypeSpecificID(getSymbIDByDerivID(first_derivative.first[1])); @@ -2431,11 +2431,11 @@ StaticModel::writeLatexAuxVarRecursiveDefinitions(ostream &output) const { deriv_node_temp_terms_t tef_terms; temporary_terms_t temporary_terms; - temporary_terms_idxs_t temporary_terms_idxs; + temporary_terms_idxs_t temporary_terms_idxs; for (auto aux_equation : aux_equations) if (dynamic_cast<ExprNode *>(aux_equation)->containsExternalFunction()) dynamic_cast<ExprNode *>(aux_equation)->writeExternalFunctionOutput(output, ExprNodeOutputType::latexStaticModel, - temporary_terms, temporary_terms_idxs, tef_terms); + temporary_terms, temporary_terms_idxs, tef_terms); for (auto aux_equation : aux_equations) { output << R"(\begin{dmath})" << endl; @@ -2484,12 +2484,12 @@ StaticModel::writeParamsDerivativesFile(const string &basename, bool julia) cons ExprNodeOutputType output_type = (julia ? ExprNodeOutputType::juliaStaticModel : ExprNodeOutputType::matlabStaticModel); - ostringstream tt_output; // Used for storing temporary terms - ostringstream jacobian_output; // Used for storing jacobian equations - ostringstream hessian_output; // Used for storing Hessian equations - ostringstream hessian1_output; // Used for storing Hessian equations - ostringstream third_derivs_output; // Used for storing third order derivatives equations - ostringstream third_derivs1_output; // Used for storing third order derivatives equations + ostringstream tt_output; // Used for storing temporary terms + ostringstream jacobian_output; // Used for storing jacobian equations + ostringstream hessian_output; // Used for storing Hessian equations + ostringstream hessian1_output; // Used for storing Hessian equations + ostringstream third_derivs_output; // Used for storing third order derivatives equations + ostringstream third_derivs1_output; // Used for storing third order derivatives equations temporary_terms_t temp_term_union; deriv_node_temp_terms_t tef_terms; @@ -2759,8 +2759,8 @@ StaticModel::writeJsonOutput(ostream &output) const void StaticModel::writeJsonComputingPassOutput(ostream &output, bool writeDetails) const { - ostringstream model_local_vars_output; // Used for storing model local vars - vector<ostringstream> d_output(derivatives.size()); // Derivatives output (at all orders, including 0=residual) + ostringstream model_local_vars_output; // Used for storing model local vars + vector<ostringstream> d_output(derivatives.size()); // Derivatives output (at all orders, including 0=residual) deriv_node_temp_terms_t tef_terms; temporary_terms_t temp_term_union; @@ -2822,9 +2822,9 @@ StaticModel::writeJsonComputingPassOutput(ostream &output, bool writeDetails) co d->writeJsonOutput(d_output[i], temp_term_union, tef_terms); d_output[i] << R"("})" << endl; } - d_output[i] << "]}"; + d_output[i] << "]}"; - ncols *= symbol_table.endo_nbr(); + ncols *= symbol_table.endo_nbr(); } if (writeDetails) @@ -2843,13 +2843,13 @@ StaticModel::writeJsonParamsDerivativesFile(ostream &output, bool writeDetails) if (!params_derivatives.size()) return; - ostringstream model_local_vars_output; // Used for storing model local vars - ostringstream model_output; // Used for storing model temp vars and equations - ostringstream jacobian_output; // Used for storing jacobian equations - ostringstream hessian_output; // Used for storing Hessian equations - ostringstream hessian1_output; // Used for storing Hessian equations - ostringstream third_derivs_output; // Used for storing third order derivatives equations - ostringstream third_derivs1_output; // Used for storing third order derivatives equations + ostringstream model_local_vars_output; // Used for storing model local vars + ostringstream model_output; // Used for storing model temp vars and equations + ostringstream jacobian_output; // Used for storing jacobian equations + ostringstream hessian_output; // Used for storing Hessian equations + ostringstream hessian1_output; // Used for storing Hessian equations + ostringstream third_derivs_output; // Used for storing third order derivatives equations + ostringstream third_derivs1_output; // Used for storing third order derivatives equations deriv_node_temp_terms_t tef_terms; writeJsonModelLocalVariables(model_local_vars_output, tef_terms); diff --git a/src/StaticModel.hh b/src/StaticModel.hh index 4dc405e9..ae9ef967 100644 --- a/src/StaticModel.hh +++ b/src/StaticModel.hh @@ -168,12 +168,12 @@ public: StaticModel(const StaticModel &m); StaticModel(StaticModel &&) = delete; - StaticModel & operator=(const StaticModel &m); + StaticModel &operator=(const StaticModel &m); /* The move assignment operator is not explicitly deleted, otherwise the - static_cast from DynamicModel does not work. However it looks like this - operator will not be used in the end. See - https://en.cppreference.com/w/cpp/language/copy_initialization - With C++17, it should be possible to explicitly delete it */ + static_cast from DynamicModel does not work. However it looks like this + operator will not be used in the end. See + https://en.cppreference.com/w/cpp/language/copy_initialization + With C++17, it should be possible to explicitly delete it */ //StaticModel & operator=(StaticModel &&) = delete; //! Creates the static version of a dynamic model diff --git a/src/SubModel.cc b/src/SubModel.cc index 759312f0..8d1b9738 100644 --- a/src/SubModel.cc +++ b/src/SubModel.cc @@ -260,8 +260,8 @@ TrendComponentModelTable::writeOutput(const string &basename, ostream &output) c exit(EXIT_FAILURE); } ar_ec_output << "function [AR, A0, A0star] = trend_component_ar_a0(model_name, params)" << endl - << "%function [AR, A0, A0star] = trend_component_ar_a0(model_name, params)" << endl - << "% File automatically generated by the Dynare preprocessor" << endl << endl; + << "%function [AR, A0, A0star] = trend_component_ar_a0(model_name, params)" << endl + << "% File automatically generated by the Dynare preprocessor" << endl << endl; for (const auto &name : names) { @@ -348,9 +348,9 @@ TrendComponentModelTable::writeOutput(const string &basename, ostream &output) c vector<int> nontarget_lhs_vec = getNonTargetLhs(name); ar_ec_output << "if strcmp(model_name, '" << name << "')" << endl - << " % AR" << endl - << " AR = zeros(" << nontarget_lhs_vec.size() << ", " << nontarget_lhs_vec.size() << ", " << getMaxLag(name) << ");" << endl; - for (const auto & it : AR.at(name)) + << " % AR" << endl + << " AR = zeros(" << nontarget_lhs_vec.size() << ", " << nontarget_lhs_vec.size() << ", " << getMaxLag(name) << ");" << endl; + for (const auto &it : AR.at(name)) { auto [eqn, lag, lhs_symb_id] = it.first; int colidx = static_cast<int>(distance(nontarget_lhs_vec.begin(), find(nontarget_lhs_vec.begin(), nontarget_lhs_vec.end(), lhs_symb_id))); @@ -360,13 +360,13 @@ TrendComponentModelTable::writeOutput(const string &basename, ostream &output) c } int a0_lag = 0; - for (const auto & it : A0.at(name)) + for (const auto &it : A0.at(name)) if (get<1>(it.first) > a0_lag) a0_lag = get<1>(it.first); ar_ec_output << endl << " % A0" << endl << " A0 = zeros(" << nontarget_lhs_vec.size() << ", " << nontarget_lhs_vec.size() << ", " << a0_lag << ");" << endl; - for (const auto & it : A0.at(name)) + for (const auto &it : A0.at(name)) { auto [eqn, lag, colidx] = it.first; ar_ec_output << " A0(" << eqn + 1 << ", " << colidx + 1 << ", " << lag << ") = "; @@ -375,13 +375,13 @@ TrendComponentModelTable::writeOutput(const string &basename, ostream &output) c } int a0star_lag = 0; - for (const auto & it : A0star.at(name)) + for (const auto &it : A0star.at(name)) if (get<1>(it.first) > a0star_lag) a0star_lag = get<1>(it.first); ar_ec_output << endl << " % A0star" << endl << " A0star = zeros(" << nontarget_lhs_vec.size() << ", " << target_lhs_vec.size() << ", " << a0star_lag << ");" << endl; - for (const auto & it : A0star.at(name)) + for (const auto &it : A0star.at(name)) { auto [eqn, lag, colidx] = it.first; ar_ec_output << " A0star(" << eqn + 1 << ", " << colidx + 1 << ", " << lag << ") = "; @@ -390,10 +390,10 @@ TrendComponentModelTable::writeOutput(const string &basename, ostream &output) c } ar_ec_output << " return" << endl - << "end" << endl << endl; + << "end" << endl << endl; } ar_ec_output << "error([model_name ' is not a valid trend_component_model name'])" << endl - << "end" << endl; + << "end" << endl; ar_ec_output.close(); } @@ -474,8 +474,8 @@ VarModelTable::writeOutput(const string &basename, ostream &output) const if (!symbol_list_and_order.at(name).first.empty()) { symbol_list_and_order.at(name).first.writeOutput("M_.var." + name + ".var_list_", output); - output << "M_.var." << name << ".order = " - << symbol_list_and_order.at(name).second << ";" << endl; + output << "M_.var." << name << ".order = " + << symbol_list_and_order.at(name).second << ";" << endl; } output << "M_.var." << name << ".eqtags = {"; for (const auto &it : eqtags.at(name)) @@ -520,7 +520,7 @@ VarModelTable::writeOutput(const string &basename, ostream &output) const vector<int> lhs = getLhsOrigIds(name); ar_output << "if strcmp(model_name, '" << name << "')" << endl << " ar = zeros(" << lhs.size() << ", " << lhs.size() << ", " << getMaxLag(name) << ");" << endl; - for (const auto & it : AR.at(name)) + for (const auto &it : AR.at(name)) { auto [eqn, lag, lhs_symb_id] = it.first; int colidx = static_cast<int>(distance(lhs.begin(), find(lhs.begin(), lhs.end(), lhs_symb_id))); @@ -605,10 +605,10 @@ VarModelTable::setLhs(map<string, vector<int>> lhs_arg) int lhs_orig_symb_id = ids; if (symbol_table.isAuxiliaryVariable(lhs_orig_symb_id)) try - { - lhs_last_orig_symb_id = lhs_orig_symb_id; - lhs_orig_symb_id = symbol_table.getOrigSymbIdForAuxVar(lhs_orig_symb_id); - } + { + lhs_last_orig_symb_id = lhs_orig_symb_id; + lhs_orig_symb_id = symbol_table.getOrigSymbIdForAuxVar(lhs_orig_symb_id); + } catch (...) { } @@ -711,7 +711,6 @@ VarModelTable::getRhs(const string &name_arg) const return rhs.find(name_arg)->second; } - vector<expr_t> VarModelTable::getLhsExprT(const string &name_arg) const { diff --git a/src/SubModel.hh b/src/SubModel.hh index c09e83aa..7c478065 100644 --- a/src/SubModel.hh +++ b/src/SubModel.hh @@ -111,7 +111,6 @@ TrendComponentModelTable::empty() const return names.empty(); } - class VarModelTable { private: diff --git a/src/SymbolList.cc b/src/SymbolList.cc index e05d1d41..52044a51 100644 --- a/src/SymbolList.cc +++ b/src/SymbolList.cc @@ -38,7 +38,7 @@ SymbolList::checkPass(WarningConsolidation &warnings) const noexcept(false) { smatch m; regex re("^(AUX_EXPECT_|AUX_ENDO_|MULT_)"); - for (const auto & symbol : symbols) + for (const auto &symbol : symbols) { if (!symbol_table->exists(symbol)) { @@ -106,7 +106,7 @@ void SymbolList::removeDuplicates(const string &dynare_command, WarningConsolidation &warnings) { vector<string> unique_symbols; - for (const auto & it : symbols) + for (const auto &it : symbols) if (find(unique_symbols.begin(), unique_symbols.end(), it) == unique_symbols.end()) unique_symbols.push_back(it); else diff --git a/src/SymbolList.hh b/src/SymbolList.hh index 87657d9c..63c45e74 100644 --- a/src/SymbolList.hh +++ b/src/SymbolList.hh @@ -43,7 +43,9 @@ public: { public: const string message; - SymbolListException(string message_arg) : message{move(message_arg)} {}; + SymbolListException(string message_arg) : message{move(message_arg)} + { + }; }; //! Set symbol table pointer void setSymbolTable(const SymbolTable &symbol_table_arg); diff --git a/src/SymbolTable.cc b/src/SymbolTable.cc index fbb2f157..5363026f 100644 --- a/src/SymbolTable.cc +++ b/src/SymbolTable.cc @@ -196,7 +196,7 @@ map<string, map<int, string>> SymbolTable::getPartitionsForType(SymbolType st) const noexcept(false) { map<string, map<int, string>> partitions; - for (const auto & it : partition_value_map) + for (const auto &it : partition_value_map) if (getType(it.first) == st) for (const auto &it1 : it.second) { @@ -223,7 +223,7 @@ SymbolTable::writeOutput(ostream &output) const noexcept(false) << "M_.exo_names_tex(" << id+1 << ") = {'" << getTeXName(exo_ids[id]) << "'};" << endl << "M_.exo_names_long(" << id+1 << ") = {'" << getLongName(exo_ids[id]) << "'};" << endl; map<string, map<int, string>> partitions = getPartitionsForType(SymbolType::exogenous); - for (auto & partition : partitions) + for (auto &partition : partitions) if (partition.first != "long_name") { output << "M_.exo_partitions." << partition.first << " = { "; @@ -260,7 +260,7 @@ SymbolTable::writeOutput(ostream &output) const noexcept(false) << "M_.exo_det_names_long(" << id+1 << ") = {'" << getLongName(exo_det_ids[id]) << "'};" << endl; output << "M_.exo_det_partitions = struct();" << endl; map<string, map<int, string>> partitions = getPartitionsForType(SymbolType::exogenousDet); - for (auto & partition : partitions) + for (auto &partition : partitions) if (partition.first != "long_name") { output << "M_.exo_det_partitions." << partition.first << " = { "; @@ -287,7 +287,7 @@ SymbolTable::writeOutput(ostream &output) const noexcept(false) << "M_.endo_names_long(" << id+1 << ") = {'" << getLongName(endo_ids[id]) << "'};" << endl; output << "M_.endo_partitions = struct();" << endl; map<string, map<int, string>> partitions = getPartitionsForType(SymbolType::endogenous); - for (auto & partition : partitions) + for (auto &partition : partitions) if (partition.first != "long_name") { output << "M_.endo_partitions." << partition.first << " = { "; @@ -318,7 +318,7 @@ SymbolTable::writeOutput(ostream &output) const noexcept(false) } output << "M_.param_partitions = struct();" << endl; map<string, map<int, string>> partitions = getPartitionsForType(SymbolType::parameter); - for (auto & partition : partitions) + for (auto &partition : partitions) if (partition.first != "long_name") { output << "M_.param_partitions." << partition.first << " = { "; @@ -695,7 +695,7 @@ SymbolTable::addDiffForwardAuxiliaryVar(int orig_symb_id, expr_t expr_arg) noexc int SymbolTable::searchAuxiliaryVars(int orig_symb_id, int orig_lead_lag) const noexcept(false) { - for (const auto & aux_var : aux_vars) + for (const auto &aux_var : aux_vars) if ((aux_var.get_type() == AuxVarType::endoLag || aux_var.get_type() == AuxVarType::exoLag) && aux_var.get_orig_symb_id() == orig_symb_id && aux_var.get_orig_lead_lag() == orig_lead_lag) return aux_var.get_symb_id(); @@ -705,7 +705,7 @@ SymbolTable::searchAuxiliaryVars(int orig_symb_id, int orig_lead_lag) const noex int SymbolTable::getOrigSymbIdForAuxVar(int aux_var_symb_id) const noexcept(false) { - for (const auto & aux_var : aux_vars) + for (const auto &aux_var : aux_vars) if ((aux_var.get_type() == AuxVarType::endoLag || aux_var.get_type() == AuxVarType::exoLag || aux_var.get_type() == AuxVarType::diff @@ -720,7 +720,7 @@ int SymbolTable::getOrigLeadLagForDiffAuxVar(int diff_aux_var_symb_id) const noexcept(false) { int lag = 0; - for (const auto & aux_var : aux_vars) + for (const auto &aux_var : aux_vars) if ((aux_var.get_type() == AuxVarType::diffLag || aux_var.get_type() == AuxVarType::diffLead) && aux_var.get_symb_id() == diff_aux_var_symb_id) lag += 1 + getOrigLeadLagForDiffAuxVar(aux_var.get_orig_symb_id()); @@ -731,7 +731,7 @@ int SymbolTable::getOrigSymbIdForDiffAuxVar(int diff_aux_var_symb_id) const noexcept(false) { int orig_symb_id = -1; - for (const auto & aux_var : aux_vars) + for (const auto &aux_var : aux_vars) if (aux_var.get_symb_id() == diff_aux_var_symb_id) if (aux_var.get_type() == AuxVarType::diff) orig_symb_id = diff_aux_var_symb_id; @@ -744,7 +744,7 @@ expr_t SymbolTable::getAuxiliaryVarsExprNode(int symb_id) const noexcept(false) // throw exception if it is a Lagrange multiplier { - for (const auto & aux_var : aux_vars) + for (const auto &aux_var : aux_vars) if (aux_var.get_symb_id() == symb_id) if (expr_t expr_node = aux_var.get_expr_node(); expr_node) @@ -840,7 +840,7 @@ vector <int> SymbolTable::getTrendVarIds() const { vector <int> trendVars; - for (const auto & it : symbol_table) + for (const auto &it : symbol_table) if (getType(it.second) == SymbolType::trend || getType(it.second) == SymbolType::logTrend) trendVars.push_back(it.second); return trendVars; @@ -850,7 +850,7 @@ set<int> SymbolTable::getExogenous() const { set <int> exogs; - for (const auto & it : symbol_table) + for (const auto &it : symbol_table) if (getType(it.second) == SymbolType::exogenous) exogs.insert(it.second); return exogs; @@ -860,7 +860,7 @@ set<int> SymbolTable::getObservedExogenous() const { set <int> oexogs; - for (const auto & it : symbol_table) + for (const auto &it : symbol_table) if (getType(it.second) == SymbolType::exogenous) if (isObservedExogenousVariable(it.second)) oexogs.insert(it.second); @@ -871,7 +871,7 @@ set<int> SymbolTable::getEndogenous() const { set <int> endogs; - for (const auto & it : symbol_table) + for (const auto &it : symbol_table) if (getType(it.second) == SymbolType::endogenous) endogs.insert(it.second); return endogs; @@ -880,7 +880,7 @@ SymbolTable::getEndogenous() const bool SymbolTable::isAuxiliaryVariable(int symb_id) const { - for (const auto & aux_var : aux_vars) + for (const auto &aux_var : aux_vars) if (aux_var.get_symb_id() == symb_id) return true; return false; @@ -889,7 +889,7 @@ SymbolTable::isAuxiliaryVariable(int symb_id) const bool SymbolTable::isAuxiliaryVariableButNotMultiplier(int symb_id) const { - for (const auto & aux_var : aux_vars) + for (const auto &aux_var : aux_vars) if (aux_var.get_symb_id() == symb_id && aux_var.get_type() != AuxVarType::multiplier) return true; return false; @@ -898,11 +898,11 @@ SymbolTable::isAuxiliaryVariableButNotMultiplier(int symb_id) const bool SymbolTable::isDiffAuxiliaryVariable(int symb_id) const { - for (const auto & aux_var : aux_vars) - if (aux_var.get_symb_id() == symb_id && - (aux_var.get_type() == AuxVarType::diff - || aux_var.get_type() == AuxVarType::diffLag - || aux_var.get_type() == AuxVarType::diffLead)) + for (const auto &aux_var : aux_vars) + if (aux_var.get_symb_id() == symb_id + && (aux_var.get_type() == AuxVarType::diff + || aux_var.get_type() == AuxVarType::diffLag + || aux_var.get_type() == AuxVarType::diffLead)) return true; return false; } @@ -911,7 +911,7 @@ set<int> SymbolTable::getOrigEndogenous() const { set <int> origendogs; - for (const auto & it : symbol_table) + for (const auto &it : symbol_table) if (getType(it.second) == SymbolType::endogenous && !isAuxiliaryVariable(it.second)) origendogs.insert(it.second); return origendogs; @@ -976,7 +976,7 @@ SymbolTable::writeJuliaOutput(ostream &output) const noexcept(false) { output << "# Auxiliary Variables" << endl << "model_.aux_vars = [" << endl; - for (const auto & aux_var : aux_vars) + for (const auto &aux_var : aux_vars) { output << " DynareModel.AuxVars(" << getTypeSpecificID(aux_var.get_symb_id()) + 1 << ", " diff --git a/src/SymbolTable.hh b/src/SymbolTable.hh index 2552813a..d601f6f1 100644 --- a/src/SymbolTable.hh +++ b/src/SymbolTable.hh @@ -37,18 +37,18 @@ using expr_t = class ExprNode *; //! Types of auxiliary variables enum class AuxVarType { - endoLead = 0, //!< Substitute for endo leads >= 2 - endoLag = 1, //!< Substitute for endo lags >= 2 - exoLead = 2, //!< Substitute for exo leads >= 1 - exoLag = 3, //!< Substitute for exo lags >= 1 - expectation = 4, //!< Substitute for Expectation Operator - diffForward = 5, //!< Substitute for the differentiate of a forward variable - multiplier = 6, //!< Multipliers for FOC of Ramsey Problem - varModel = 7, //!< Variable for var_model with order > abs(min_lag()) present in model - diff = 8, //!< Variable for Diff operator - diffLag = 9, //!< Variable for timing between Diff operators - unaryOp = 10, //!< Variable for allowing the undiff operator to work when diff was taken of unary op, eg diff(log(x)) - diffLead = 11 //!< Variable for timing between Diff operators + endoLead = 0, //!< Substitute for endo leads >= 2 + endoLag = 1, //!< Substitute for endo lags >= 2 + exoLead = 2, //!< Substitute for exo leads >= 1 + exoLag = 3, //!< Substitute for exo lags >= 1 + expectation = 4, //!< Substitute for Expectation Operator + diffForward = 5, //!< Substitute for the differentiate of a forward variable + multiplier = 6, //!< Multipliers for FOC of Ramsey Problem + varModel = 7, //!< Variable for var_model with order > abs(min_lag()) present in model + diff = 8, //!< Variable for Diff operator + diffLag = 9, //!< Variable for timing between Diff operators + unaryOp = 10, //!< Variable for allowing the undiff operator to work when diff was taken of unary op, eg diff(log(x)) + diffLead = 11 //!< Variable for timing between Diff operators }; //! Information on some auxiliary variables diff --git a/src/WarningConsolidation.cc b/src/WarningConsolidation.cc index 3fc59227..bc398941 100644 --- a/src/WarningConsolidation.cc +++ b/src/WarningConsolidation.cc @@ -56,7 +56,7 @@ operator<<(WarningConsolidation &wcc, const Dynare::location &loc) }; WarningConsolidation & -operator<<(WarningConsolidation &wcc, ostream & (*pf)(ostream &)) +operator<<(WarningConsolidation &wcc, ostream &(*pf)(ostream &)) { if (wcc.no_warn) return wcc; diff --git a/src/WarningConsolidation.hh b/src/WarningConsolidation.hh index b973b370..417c29dd 100644 --- a/src/WarningConsolidation.hh +++ b/src/WarningConsolidation.hh @@ -41,7 +41,7 @@ public: //! Add A Warning to the StringStream friend WarningConsolidation &operator<<(WarningConsolidation &wcc, const string &warning); friend WarningConsolidation &operator<<(WarningConsolidation &wcc, const Dynare::location &loc); - friend WarningConsolidation &operator<<(WarningConsolidation &wcc, ostream & (*pf)(ostream &)); + friend WarningConsolidation &operator<<(WarningConsolidation &wcc, ostream &(*pf)(ostream &)); inline void addWarning(const string &w) @@ -49,7 +49,7 @@ public: warnings << w; }; inline void - addWarning(ostream & (*pf)(ostream &)) + addWarning(ostream &(*pf)(ostream &)) { warnings << pf; }; diff --git a/src/macro/Directives.cc b/src/macro/Directives.cc index 3fa42a67..95d8860d 100644 --- a/src/macro/Directives.cc +++ b/src/macro/Directives.cc @@ -55,7 +55,7 @@ Include::interpret(ostream &output, bool no_line_macro, vector<filesystem::path> ifstream incfile(filename, ios::binary); if (incfile.fail()) { - for (const auto & dir : paths) + for (const auto &dir : paths) { incfile = ifstream(dir / filename, ios::binary); if (incfile.good()) @@ -65,10 +65,10 @@ Include::interpret(ostream &output, bool no_line_macro, vector<filesystem::path> { ostringstream errmsg; errmsg << " * " << current_path().string() << endl; - for (const auto & dir : paths) + for (const auto &dir : paths) errmsg << " * " << absolute(dir).string() << endl; - error(StackTrace("@#includepath", "Could not open " + filename.string() + - ". The following directories were searched:\n" + errmsg.str(), location)); + error(StackTrace("@#includepath", "Could not open " + filename.string() + +". The following directories were searched:\n" + errmsg.str(), location)); } } Driver m(env, no_line_macro); @@ -228,7 +228,7 @@ For::interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &pa } bool printLine = true; - for (const auto & statement : statements) + for (const auto &statement : statements) { if (printLine) { @@ -275,7 +275,7 @@ void If::interpretBody(const vector<DirectivePtr> &body, ostream &output, bool no_line_macro, vector<filesystem::path> &paths) { bool printLine = !no_line_macro; - for (const auto & statement : body) + for (const auto &statement : body) { if (printLine) { diff --git a/src/macro/Directives.hh b/src/macro/Directives.hh index d3cb7147..d9b26d4e 100644 --- a/src/macro/Directives.hh +++ b/src/macro/Directives.hh @@ -30,12 +30,13 @@ namespace macro { // A Parent class just for clarity public: - Directive(Environment &env_arg, Tokenizer::location location_arg) : Node(env_arg, move(location_arg)) { } + Directive(Environment &env_arg, Tokenizer::location location_arg) : Node(env_arg, move(location_arg)) + { + } // Directives can be interpreted virtual void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) = 0; }; - class TextNode : public Directive { // Class for text not interpreted by macroprocessor @@ -45,11 +46,16 @@ namespace macro const string text; public: TextNode(string text_arg, Environment &env_arg, Tokenizer::location location_arg) : - Directive(env_arg, move(location_arg)), text{move(text_arg)} { } - inline void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override { output << text; } + Directive(env_arg, move(location_arg)), text{move(text_arg)} + { + } + inline void + interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override + { + output << text; + } }; - class Eval : public Directive { // Class for @{} statements @@ -59,33 +65,36 @@ namespace macro const ExpressionPtr expr; public: Eval(ExpressionPtr expr_arg, Environment &env_arg, Tokenizer::location location_arg) : - Directive(env_arg, move(location_arg)), expr{move(expr_arg)} { } + Directive(env_arg, move(location_arg)), expr{move(expr_arg)} + { + } void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override; }; - class Include : public Directive { private: const ExpressionPtr expr; public: Include(ExpressionPtr expr_arg, Environment &env_arg, Tokenizer::location location_arg) : - Directive(env_arg, move(location_arg)), expr{move(expr_arg)} { } + Directive(env_arg, move(location_arg)), expr{move(expr_arg)} + { + } void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override; }; - class IncludePath : public Directive { private: const ExpressionPtr expr; public: IncludePath(ExpressionPtr expr_arg, Environment &env_arg, Tokenizer::location location_arg) : - Directive(env_arg, move(location_arg)), expr{move(expr_arg)} { } + Directive(env_arg, move(location_arg)), expr{move(expr_arg)} + { + } void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override; }; - class Define : public Directive { private: @@ -96,15 +105,18 @@ namespace macro Define(VariablePtr var_arg, ExpressionPtr value_arg, Environment &env_arg, Tokenizer::location location_arg) : - Directive(env_arg, move(location_arg)), var{move(var_arg)}, value{move(value_arg)} { } + Directive(env_arg, move(location_arg)), var{move(var_arg)}, value{move(value_arg)} + { + } Define(FunctionPtr func_arg, ExpressionPtr value_arg, Environment &env_arg, Tokenizer::location location_arg) : - Directive(env_arg, move(location_arg)), func{move(func_arg)}, value{move(value_arg)} { } + Directive(env_arg, move(location_arg)), func{move(func_arg)}, value{move(value_arg)} + { + } void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override; }; - class Echo : public Directive { private: @@ -112,11 +124,12 @@ namespace macro public: Echo(ExpressionPtr expr_arg, Environment &env_arg, Tokenizer::location location_arg) : - Directive(env_arg, move(location_arg)), expr{move(expr_arg)} { } + Directive(env_arg, move(location_arg)), expr{move(expr_arg)} + { + } void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override; }; - class Error : public Directive { private: @@ -124,11 +137,12 @@ namespace macro public: Error(ExpressionPtr expr_arg, Environment &env_arg, Tokenizer::location location_arg) : - Directive(env_arg, move(location_arg)), expr{move(expr_arg)} { } + Directive(env_arg, move(location_arg)), expr{move(expr_arg)} + { + } void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override; }; - class EchoMacroVars : public Directive { private: @@ -137,14 +151,17 @@ namespace macro public: EchoMacroVars(bool save_arg, Environment &env_arg, Tokenizer::location location_arg) : - Directive(env_arg, move(location_arg)), save{save_arg} { } + Directive(env_arg, move(location_arg)), save{save_arg} + { + } EchoMacroVars(bool save_arg, vector<string> vars_arg, Environment &env_arg, Tokenizer::location location_arg) : - Directive(env_arg, move(location_arg)), save{save_arg}, vars{move(vars_arg)} { } + Directive(env_arg, move(location_arg)), save{save_arg}, vars{move(vars_arg)} + { + } void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override; }; - class For : public Directive { private: @@ -157,11 +174,12 @@ namespace macro vector<DirectivePtr> statements_arg, Environment &env_arg, Tokenizer::location location_arg) : Directive(env_arg, move(location_arg)), index_vec{move(index_vec_arg)}, - index_vals{move(index_vals_arg)}, statements{move(statements_arg)} { } + index_vals{move(index_vals_arg)}, statements{move(statements_arg)} + { + } void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override; }; - class If : public Directive { protected: @@ -177,29 +195,33 @@ namespace macro public: If(vector<pair<ExpressionPtr, vector<DirectivePtr>>> expr_and_body_arg, Environment &env_arg, Tokenizer::location location_arg) : - Directive(env_arg, move(location_arg)), expr_and_body{move(expr_and_body_arg)} { } + Directive(env_arg, move(location_arg)), expr_and_body{move(expr_and_body_arg)} + { + } void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override; protected: void interpretBody(const vector<DirectivePtr> &body, ostream &output, bool no_line_macro, vector<filesystem::path> &paths); }; - class Ifdef : public If { public: Ifdef(vector<pair<ExpressionPtr, vector<DirectivePtr>>> expr_and_body_arg, Environment &env_arg, Tokenizer::location location_arg) : - If(move(expr_and_body_arg), env_arg, move(location_arg)) { } + If(move(expr_and_body_arg), env_arg, move(location_arg)) + { + } void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override; }; - class Ifndef : public If { public: Ifndef(vector<pair<ExpressionPtr, vector<DirectivePtr>>> expr_and_body_arg, Environment &env_arg, Tokenizer::location location_arg) : - If(move(expr_and_body_arg), env_arg, move(location_arg)) { } + If(move(expr_and_body_arg), env_arg, move(location_arg)) + { + } void interpret(ostream &output, bool no_line_macro, vector<filesystem::path> &paths) override; }; } diff --git a/src/macro/Driver.cc b/src/macro/Driver.cc index b1ccc5cc..e408cc27 100644 --- a/src/macro/Driver.cc +++ b/src/macro/Driver.cc @@ -69,7 +69,7 @@ Driver::parse(const string &file_arg, const string &basename_arg, istream &modfi // Interpret parsed statements bool printLine = true; - for (const auto & statement : statements) + for (const auto &statement : statements) { if (printLine) { diff --git a/src/macro/Driver.hh b/src/macro/Driver.hh index e32db02b..c0aaa71f 100644 --- a/src/macro/Driver.hh +++ b/src/macro/Driver.hh @@ -46,11 +46,13 @@ namespace macro class TokenizerFlex : public TokenizerFlexLexer { public: - TokenizerFlex(istream *in) : TokenizerFlexLexer{in} { } + TokenizerFlex(istream *in) : TokenizerFlexLexer{in} + { + } TokenizerFlex(const TokenizerFlex &) = delete; TokenizerFlex(TokenizerFlex &&) = delete; - TokenizerFlex & operator=(const TokenizerFlex &) = delete; - TokenizerFlex & operator=(TokenizerFlex &&) = delete; + TokenizerFlex &operator=(const TokenizerFlex &) = delete; + TokenizerFlex &operator=(TokenizerFlex &&) = delete; //! The main lexing function Tokenizer::parser::token_type lex(Tokenizer::parser::semantic_type *yylval, @@ -69,11 +71,13 @@ namespace macro stack<vector<DirectivePtr>> directive_stack; public: Driver(Environment &env_arg, bool no_line_macro_arg) : - env{env_arg}, no_line_macro(no_line_macro_arg) { } + env{env_arg}, no_line_macro(no_line_macro_arg) + { + } Driver(const Driver &) = delete; Driver(Driver &&) = delete; - Driver & operator=(const Driver &) = delete; - Driver & operator=(Driver &&) = delete; + Driver &operator=(const Driver &) = delete; + Driver &operator=(Driver &&) = delete; //! Exception thrown when value of an unknown variable is requested class UnknownVariable @@ -102,15 +106,37 @@ namespace macro //! Error handler void error(const Tokenizer::parser::location_type &location, const string &message) const; - inline bool inContext() const { return !directive_stack.empty(); } + inline bool + inContext() const + { + return !directive_stack.empty(); + } - inline void pushContext() { directive_stack.emplace(vector<DirectivePtr>()); } + inline void + pushContext() + { + directive_stack.emplace(vector<DirectivePtr>()); + } - inline void pushContextTop(DirectivePtr statement) { directive_stack.top().emplace_back(move(statement)); } + inline void + pushContextTop(DirectivePtr statement) + { + directive_stack.top().emplace_back(move(statement)); + } - inline void pushStatements(DirectivePtr statement) { statements.emplace_back(move(statement)); } + inline void + pushStatements(DirectivePtr statement) + { + statements.emplace_back(move(statement)); + } - inline vector<DirectivePtr> popContext() { auto top = move(directive_stack.top()); directive_stack.pop(); return top; } + inline vector<DirectivePtr> + popContext() + { + auto top = move(directive_stack.top()); + directive_stack.pop(); + return top; + } }; } #endif diff --git a/src/macro/Environment.cc b/src/macro/Environment.cc index 87cd033d..8815588c 100644 --- a/src/macro/Environment.cc +++ b/src/macro/Environment.cc @@ -107,10 +107,10 @@ Environment::print(ostream &output, const vector<string> &vars, int line, bool s output << "Macro Variables:" << endl; if (vars.empty()) - for (const auto & it : variables) + for (const auto &it : variables) printVariable(output, it.first, line, save); else - for (const auto & it : vars) + for (const auto &it : vars) if (isVariableDefined(it)) printVariable(output, it, line, save); @@ -118,10 +118,10 @@ Environment::print(ostream &output, const vector<string> &vars, int line, bool s output << "Macro Functions:" << endl; if (vars.empty()) - for (const auto & it : functions) + for (const auto &it : functions) printFunction(output, it.second, line, save); else - for (const auto & it : vars) + for (const auto &it : vars) if (isFunctionDefined(it)) printFunction(output, functions.find(it)->second, line, save); @@ -130,9 +130,9 @@ Environment::print(ostream &output, const vector<string> &vars, int line, bool s } void -Environment::printVariable(ostream &output, const string & name, int line, bool save) const +Environment::printVariable(ostream &output, const string &name, int line, bool save) const { - output << (save ? "options_.macrovars_line_" + to_string(line) + "." : " " ) + output << (save ? "options_.macrovars_line_" + to_string(line) + "." : " ") << name << " = "; getVariable(name)->eval()->print(output, save); if (save) @@ -141,9 +141,9 @@ Environment::printVariable(ostream &output, const string & name, int line, bool } void -Environment::printFunction(ostream &output, const tuple<FunctionPtr, ExpressionPtr> & function, int line, bool save) const +Environment::printFunction(ostream &output, const tuple<FunctionPtr, ExpressionPtr> &function, int line, bool save) const { - output << (save ? "options_.macrovars_line_" + to_string(line) + ".function." : " " ); + output << (save ? "options_.macrovars_line_" + to_string(line) + ".function." : " "); if (save) { get<0>(function)->printName(output); diff --git a/src/macro/Environment.hh b/src/macro/Environment.hh index 06bb041c..f706edde 100644 --- a/src/macro/Environment.hh +++ b/src/macro/Environment.hh @@ -34,8 +34,12 @@ namespace macro map<string, ExpressionPtr> variables; map<string, tuple<FunctionPtr, ExpressionPtr>> functions; public: - Environment() : parent{nullptr} { } - Environment(const Environment *parent_arg) : parent{parent_arg} { } + Environment() : parent{nullptr} + { + } + Environment(const Environment *parent_arg) : parent{parent_arg} + { + } void define(VariablePtr var, ExpressionPtr value); void define(FunctionPtr func, ExpressionPtr value); ExpressionPtr getVariable(const string &name) const; @@ -43,12 +47,24 @@ namespace macro codes::BaseType getType(const string &name); bool isVariableDefined(const string &name) const noexcept; bool isFunctionDefined(const string &name) const noexcept; - inline bool isSymbolDefined(const string &name) const noexcept { return isVariableDefined(name) || isFunctionDefined(name); } + inline bool + isSymbolDefined(const string &name) const noexcept + { + return isVariableDefined(name) || isFunctionDefined(name); + } void print(ostream &output, const vector<string> &vars, int line = -1, bool save = false) const; - void printVariable(ostream &output, const string & name, int line, bool save) const; - void printFunction(ostream &output, const tuple<FunctionPtr, ExpressionPtr> & function, int line, bool save) const; - inline size_t size() const noexcept { return variables.size() + functions.size(); } - inline const Environment *getGlobalEnv() const noexcept { return parent == nullptr ? this : parent->getGlobalEnv(); } + void printVariable(ostream &output, const string &name, int line, bool save) const; + void printFunction(ostream &output, const tuple<FunctionPtr, ExpressionPtr> &function, int line, bool save) const; + inline size_t + size() const noexcept + { + return variables.size() + functions.size(); + } + inline const Environment * + getGlobalEnv() const noexcept + { + return parent == nullptr ? this : parent->getGlobalEnv(); + } }; } #endif diff --git a/src/macro/Expressions.cc b/src/macro/Expressions.cc index b132a9ab..a14b380f 100644 --- a/src/macro/Expressions.cc +++ b/src/macro/Expressions.cc @@ -308,7 +308,7 @@ String::is_equal(const BaseTypePtr &btp) const BoolPtr String::cast_bool() const { - auto f = [](const char& a, const char& b) { return (tolower(a) == tolower(b)); }; + auto f = [](const char &a, const char &b) { return (tolower(a) == tolower(b)); }; if (string tf = "true"; equal(value.begin(), value.end(), tf.begin(), tf.end(), f)) return make_shared<Bool>(true, env); @@ -369,7 +369,7 @@ Array::minus(const BaseTypePtr &btp) const /* Highly inefficient algorithm for computing set difference (but vector<T> is not suited for that...) */ vector<ExpressionPtr> arr_copy; - for (const auto & it : arr) + for (const auto &it : arr) { auto itbtp = dynamic_pointer_cast<BaseType>(it); auto it2 = btp2->arr.cbegin(); @@ -390,8 +390,8 @@ Array::times(const BaseTypePtr &btp) const if (!btp2) throw StackTrace("Type mismatch for operands of * operator"); - for (const auto & itl : arr) - for (const auto & itr : btp2->getValue()) + for (const auto &itl : arr) + for (const auto &itr : btp2->getValue()) { vector<ExpressionPtr> new_tuple; if (dynamic_pointer_cast<Real>(itl) || dynamic_pointer_cast<String>(itl)) @@ -404,7 +404,7 @@ Array::times(const BaseTypePtr &btp) const if (dynamic_pointer_cast<Real>(itr) || dynamic_pointer_cast<String>(itr)) new_tuple.push_back(itr); else if (dynamic_pointer_cast<Tuple>(itr)) - for (const auto & tit : dynamic_pointer_cast<Tuple>(itr)->getValue()) + for (const auto &tit : dynamic_pointer_cast<Tuple>(itr)->getValue()) new_tuple.push_back(tit); else throw StackTrace("Array::times: unsupported type on rhs"); @@ -459,13 +459,13 @@ Array::set_union(const BaseTypePtr &btp) const throw StackTrace("Arguments of the union operator (|) must be sets"); vector<ExpressionPtr> new_values = arr; - for (const auto & it : btp2->arr) + for (const auto &it : btp2->arr) { bool found = false; auto it2 = dynamic_pointer_cast<BaseType>(it); if (!it2) throw StackTrace("Type mismatch for operands of in operator"); - for (const auto & nvit : new_values) + for (const auto &nvit : new_values) { auto v2 = dynamic_pointer_cast<BaseType>(nvit); if (!v2) @@ -490,12 +490,12 @@ Array::set_intersection(const BaseTypePtr &btp) const throw StackTrace("Arguments of the intersection operator (|) must be sets"); vector<ExpressionPtr> new_values; - for (const auto & it : btp2->arr) + for (const auto &it : btp2->arr) { auto it2 = dynamic_pointer_cast<BaseType>(it); if (!it2) throw StackTrace("Type mismatch for operands of in operator"); - for (const auto & nvit : arr) + for (const auto &nvit : arr) { auto v2 = dynamic_pointer_cast<BaseType>(nvit); if (!v2) @@ -506,14 +506,14 @@ Array::set_intersection(const BaseTypePtr &btp) const break; } } - } + } return make_shared<Array>(new_values, env); } BoolPtr Array::contains(const BaseTypePtr &btp) const { - for (const auto & v : arr) + for (const auto &v : arr) { auto v2 = dynamic_pointer_cast<BaseType>(v); if (!v2) @@ -528,7 +528,7 @@ RealPtr Array::sum() const { double retval = 0; - for (const auto & v : arr) + for (const auto &v : arr) { auto v2 = dynamic_pointer_cast<Real>(v); if (!v2) @@ -577,7 +577,7 @@ Tuple::is_equal(const BaseTypePtr &btp) const BoolPtr Tuple::contains(const BaseTypePtr &btp) const { - for (const auto & v : tup) + for (const auto &v : tup) { auto v2 = dynamic_pointer_cast<BaseType>(v); if (!v2) @@ -631,7 +631,7 @@ BaseTypePtr Array::eval() { vector<ExpressionPtr> retval; - for (const auto & it : arr) + for (const auto &it : arr) retval.emplace_back(it->eval()); return make_shared<Array>(retval, env); } @@ -640,7 +640,7 @@ BaseTypePtr Tuple::eval() { vector<ExpressionPtr> retval; - for (const auto & it : tup) + for (const auto &it : tup) retval.emplace_back(it->eval()); return make_shared<Tuple>(retval, env); } @@ -653,7 +653,7 @@ Variable::eval() ArrayPtr map = dynamic_pointer_cast<Array>(indices->eval()); vector<ExpressionPtr> index = map->getValue(); vector<int> ind; - for (const auto & it : index) + for (const auto &it : index) // Necessary to handle indexes like: y[1:2,2] // In general this evaluates to [[1:2],2] but when subscripting we want to expand it to [1,2,2] if (auto db = dynamic_pointer_cast<Real>(it); db) @@ -664,7 +664,7 @@ Variable::eval() ind.emplace_back(*db); } else if (dynamic_pointer_cast<Array>(it)) - for (const auto & it1 : dynamic_pointer_cast<Array>(it)->getValue()) + for (const auto &it1 : dynamic_pointer_cast<Array>(it)->getValue()) if (db = dynamic_pointer_cast<Real>(it1); db) { if (!*(db->isinteger())) @@ -691,8 +691,8 @@ Variable::eval() throw StackTrace("variable", "Internal Error: Range: should not arrive here", location); case codes::BaseType::String: { - string orig_string = - dynamic_pointer_cast<String>(env.getVariable(name))->to_string(); + string orig_string + = dynamic_pointer_cast<String>(env.getVariable(name))->to_string(); string retvals; for (auto it : ind) try @@ -747,8 +747,8 @@ Function::eval() } if (func->args.size() != args.size()) - throw StackTrace("Function", "The number of arguments used to call " + name + - " does not match the number used in its definition", location); + throw StackTrace("Function", "The number of arguments used to call " + name + +" does not match the number used in its definition", location); try { @@ -873,7 +873,7 @@ BinaryOp::eval() { try { - switch(op_code) + switch (op_code) { case codes::BinaryOp::plus: return arg1->eval()->plus(arg2->eval()); @@ -884,7 +884,7 @@ BinaryOp::eval() case codes::BinaryOp::divide: return arg1->eval()->divide(arg2->eval()); case codes::BinaryOp::power: - return arg1->eval()->power( arg2->eval()); + return arg1->eval()->power(arg2->eval()); case codes::BinaryOp::equal_equal: return arg1->eval()->is_equal(arg2->eval()); case codes::BinaryOp::not_equal: @@ -933,7 +933,7 @@ TrinaryOp::eval() { try { - switch(op_code) + switch (op_code) { case codes::TrinaryOp::normpdf: return arg1->eval()->normpdf(arg2->eval(), arg3->eval()); @@ -1041,7 +1041,7 @@ ExpressionPtr Tuple::clone() const noexcept { vector<ExpressionPtr> tup_copy; - for (const auto & it : tup) + for (const auto &it : tup) tup_copy.emplace_back(it->clone()); return make_shared<Tuple>(tup_copy, env, location); } @@ -1050,7 +1050,7 @@ ExpressionPtr Array::clone() const noexcept { vector<ExpressionPtr> arr_copy; - for (const auto & it : arr) + for (const auto &it : arr) arr_copy.emplace_back(it->clone()); return make_shared<Array>(arr_copy, env, location); } @@ -1059,7 +1059,7 @@ ExpressionPtr Function::clone() const noexcept { vector<ExpressionPtr> args_copy; - for (const auto & it : args) + for (const auto &it : args) args_copy.emplace_back(it->clone()); return make_shared<Function>(name, args_copy, env, location); } @@ -1081,7 +1081,7 @@ Array::to_string() const noexcept if (arr.empty()) return "[]"; string retval = "["; - for (const auto & it : arr) + for (const auto &it : arr) retval += it->to_string() + ", "; return retval.substr(0, retval.size()-2) + "]"; } @@ -1090,7 +1090,7 @@ string Tuple::to_string() const noexcept { string retval = "("; - for (const auto & it : tup) + for (const auto &it : tup) retval += it->to_string() + ", "; return retval.substr(0, retval.size()-2) + ")"; } @@ -1099,7 +1099,7 @@ string Function::to_string() const noexcept { string retval = name + "("; - for (const auto & it : args) + for (const auto &it : args) retval += it->to_string() + ", "; return retval.substr(0, retval.size()-2) + ")"; } @@ -1197,7 +1197,7 @@ string BinaryOp::to_string() const noexcept { string retval = "(" + arg1->to_string(); - switch(op_code) + switch (op_code) { case codes::BinaryOp::plus: retval += " + "; @@ -1258,7 +1258,7 @@ BinaryOp::to_string() const noexcept string TrinaryOp::to_string() const noexcept { - switch(op_code) + switch (op_code) { case codes::TrinaryOp::normpdf: return "normpdf(" + arg1->to_string() + ", " + arg2->to_string() + ", " + arg3->to_string() + ")"; @@ -1474,7 +1474,7 @@ BinaryOp::print(ostream &output, bool matlab_output) const noexcept || op_code == codes::BinaryOp::min || op_code == codes::BinaryOp::mod) { - switch(op_code) + switch (op_code) { case codes::BinaryOp::set_union: output << "union("; @@ -1503,7 +1503,7 @@ BinaryOp::print(ostream &output, bool matlab_output) const noexcept output << "("; arg1->print(output, matlab_output); - switch(op_code) + switch (op_code) { case codes::BinaryOp::plus: output << " + "; @@ -1562,7 +1562,7 @@ BinaryOp::print(ostream &output, bool matlab_output) const noexcept void TrinaryOp::print(ostream &output, bool matlab_output) const noexcept { - switch(op_code) + switch (op_code) { case codes::TrinaryOp::normpdf: output << "normpdf("; @@ -1598,4 +1598,3 @@ Comprehension::print(ostream &output, bool matlab_output) const noexcept } output << "]"; } - diff --git a/src/macro/Expressions.hh b/src/macro/Expressions.hh index d6b6d868..7bbdcac0 100644 --- a/src/macro/Expressions.hh +++ b/src/macro/Expressions.hh @@ -36,20 +36,23 @@ namespace macro private: vector<string> message; public: - StackTrace (string message_arg) : message{move(message_arg)} { } - StackTrace (const string &prefix, const char *standard_exception_message, const Tokenizer::location &location) + StackTrace(string message_arg) : message{move(message_arg)} + { + } + StackTrace(const string &prefix, const char *standard_exception_message, const Tokenizer::location &location) { stringstream ss; ss << prefix << ": " << location << " " << standard_exception_message; message = {ss.str()}; } - StackTrace (const string &prefix, const string &msg, const Tokenizer::location &location) + StackTrace(const string &prefix, const string &msg, const Tokenizer::location &location) { stringstream ss; ss << prefix << ": " << location << " " << msg; message = {ss.str()}; } - void push(const string &prefix, const Tokenizer::location &location) + void + push(const string &prefix, const Tokenizer::location &location) { stringstream ss; auto end_col = 0 < location.end.column ? location.end.column - 1 : 0; @@ -68,16 +71,16 @@ namespace macro ss << "-" << end_col; message.emplace_back(ss.str()); } - string trace() const + string + trace() const { stringstream ss; - for (auto & msg : message) + for (auto &msg : message) ss << "- " << msg << endl; return ss.str(); } }; - class Node { protected: @@ -85,25 +88,36 @@ namespace macro const Tokenizer::location location; public: Node(Environment &env_arg, Tokenizer::location location_arg) : - env{env_arg}, location{move(location_arg)} { } - virtual ~Node() = default; + env{env_arg}, location{move(location_arg)} + { + } + virtual + ~Node() = default; public: - inline Tokenizer::location getLocation() const noexcept { return location; } - inline void error(const StackTrace &e) const noexcept + inline Tokenizer::location + getLocation() const noexcept + { + return location; + } + inline void + error(const StackTrace &e) const noexcept { cerr << endl << "Macro-processing error: backtrace..." << endl << e.trace(); exit(EXIT_FAILURE); } - inline void warning(const StackTrace &e) const noexcept + inline void + warning(const StackTrace &e) const noexcept { cerr << endl << "Macro-processing warning: backtrace..." << endl << e.trace(); } - inline void printLineInfo(ostream &output, bool no_line_macro) const noexcept + inline void + printLineInfo(ostream &output, bool no_line_macro) const noexcept { if (!no_line_macro) output << R"(@#line ")" << *(location.begin.filename) << R"(" )" << location.begin.line << endl; } - inline void printEndLineInfo(ostream &output, bool no_line_macro) const noexcept + inline void + printEndLineInfo(ostream &output, bool no_line_macro) const noexcept { if (!no_line_macro) // Add one to end line because we want to print the line number of the line *following* the end statement @@ -111,95 +125,352 @@ namespace macro } }; - class Expression : public Node { public: Expression(Environment &env_arg, Tokenizer::location location_arg) : - Node(env_arg, move(location_arg)) { } + Node(env_arg, move(location_arg)) + { + } virtual string to_string() const noexcept = 0; virtual void print(ostream &output, bool matlab_output = false) const noexcept = 0; virtual BaseTypePtr eval() = 0; virtual ExpressionPtr clone() const noexcept = 0; }; - class BaseType : public Expression, public enable_shared_from_this<BaseType> { public: BaseType(Environment &env_arg, Tokenizer::location location_arg = Tokenizer::location()) : - Expression(env_arg, move(location_arg)) { } + Expression(env_arg, move(location_arg)) + { + } virtual codes::BaseType getType() const noexcept = 0; - inline BaseTypePtr eval() override { return shared_from_this(); } + inline BaseTypePtr + eval() override + { + return shared_from_this(); + } public: - virtual BaseTypePtr plus(const BaseTypePtr &bt) const { throw StackTrace("Operator + does not exist for this type"); } - virtual BaseTypePtr unary_plus() const { throw StackTrace("Unary operator + does not exist for this type"); } - virtual BaseTypePtr minus(const BaseTypePtr &bt) const { throw StackTrace("Operator - does not exist for this type"); } - virtual BaseTypePtr unary_minus() const { throw StackTrace("Unary operator - does not exist for this type"); } - virtual BaseTypePtr times(const BaseTypePtr &bt) const { throw StackTrace("Operator * does not exist for this type"); } - virtual BaseTypePtr divide(const BaseTypePtr &bt) const { throw StackTrace("Operator / does not exist for this type"); } - virtual BaseTypePtr power(const BaseTypePtr &btp) const { throw StackTrace("Operator ^ does not exist for this type"); } - virtual BoolPtr is_less(const BaseTypePtr &btp) const { throw StackTrace("Operator < does not exist for this type"); } - virtual BoolPtr is_greater(const BaseTypePtr &btp) const { throw StackTrace("Operator > does not exist for this type"); } - virtual BoolPtr is_less_equal(const BaseTypePtr &btp) const { throw StackTrace("Operator <= does not exist for this type"); } - virtual BoolPtr is_greater_equal(const BaseTypePtr &btp) const { throw StackTrace("Operator >= does not exist for this type"); } + virtual BaseTypePtr + plus(const BaseTypePtr &bt) const + { + throw StackTrace("Operator + does not exist for this type"); + } + virtual BaseTypePtr + unary_plus() const + { + throw StackTrace("Unary operator + does not exist for this type"); + } + virtual BaseTypePtr + minus(const BaseTypePtr &bt) const + { + throw StackTrace("Operator - does not exist for this type"); + } + virtual BaseTypePtr + unary_minus() const + { + throw StackTrace("Unary operator - does not exist for this type"); + } + virtual BaseTypePtr + times(const BaseTypePtr &bt) const + { + throw StackTrace("Operator * does not exist for this type"); + } + virtual BaseTypePtr + divide(const BaseTypePtr &bt) const + { + throw StackTrace("Operator / does not exist for this type"); + } + virtual BaseTypePtr + power(const BaseTypePtr &btp) const + { + throw StackTrace("Operator ^ does not exist for this type"); + } + virtual BoolPtr + is_less(const BaseTypePtr &btp) const + { + throw StackTrace("Operator < does not exist for this type"); + } + virtual BoolPtr + is_greater(const BaseTypePtr &btp) const + { + throw StackTrace("Operator > does not exist for this type"); + } + virtual BoolPtr + is_less_equal(const BaseTypePtr &btp) const + { + throw StackTrace("Operator <= does not exist for this type"); + } + virtual BoolPtr + is_greater_equal(const BaseTypePtr &btp) const + { + throw StackTrace("Operator >= does not exist for this type"); + } virtual BoolPtr is_equal(const BaseTypePtr &btp) const = 0; virtual BoolPtr is_different(const BaseTypePtr &btp) const final; - virtual BoolPtr logical_and(const ExpressionPtr &ep) const { throw StackTrace("Operator && does not exist for this type"); } - virtual BoolPtr logical_or(const ExpressionPtr &ep) const { throw StackTrace("Operator || does not exist for this type"); } - virtual BoolPtr logical_not() const { throw StackTrace("Operator ! does not exist for this type"); } - virtual ArrayPtr set_union(const BaseTypePtr &btp) const { throw StackTrace("Operator | does not exist for this type"); } - virtual ArrayPtr set_intersection(const BaseTypePtr &btp) const { throw StackTrace("Operator & does not exist for this type"); } - virtual BoolPtr contains(const BaseTypePtr &btp) const { throw StackTrace("Second argument of `in` operator must be an array"); } - virtual RealPtr length() const { throw StackTrace("Operator `length` does not exist for this type"); } - virtual BoolPtr isempty() const { throw StackTrace("Operator `isempty` does not exist for this type"); } - virtual BoolPtr isboolean() const noexcept { return make_shared<Bool>(false, env, location); } - virtual BoolPtr isreal() const noexcept { return make_shared<Bool>(false, env, location); } - virtual BoolPtr isinteger() const noexcept { return make_shared<Bool>(false, env, location); } - virtual BoolPtr isstring() const noexcept { return make_shared<Bool>(false, env, location); } - virtual BoolPtr istuple() const noexcept { return make_shared<Bool>(false, env, location); } - virtual BoolPtr isarray() const noexcept { return make_shared<Bool>(false, env, location); } - virtual RealPtr max(const BaseTypePtr &btp) const { throw StackTrace("Operator `max` does not exist for this type"); } - virtual RealPtr min(const BaseTypePtr &btp) const { throw StackTrace("Operator `min` does not exist for this type"); } - virtual RealPtr mod(const BaseTypePtr &btp) const { throw StackTrace("Operator `mod` does not exist for this type"); } - virtual RealPtr exp() const { throw StackTrace("Operator `exp` does not exist for this type"); } - virtual RealPtr ln() const { throw StackTrace("Operator `ln` does not exist for this type"); } - virtual RealPtr log10() const { throw StackTrace("Operator `log10` does not exist for this type"); } - virtual BoolPtr isinf() const { throw StackTrace("Operator `isinf` does not exist for this type"); } - virtual BoolPtr isnan() const { throw StackTrace("Operator `isnan` does not exist for this type"); } - virtual BoolPtr isfinite() const { throw StackTrace("Operator `isfinite` does not exist for this type"); } - virtual BoolPtr isnormal() const { throw StackTrace("Operator `isnormal` does not exist for this type"); } - virtual RealPtr sin() const { throw StackTrace("Operator `sin` does not exist for this type"); } - virtual RealPtr cos() const { throw StackTrace("Operator `cos` does not exist for this type"); } - virtual RealPtr tan() const { throw StackTrace("Operator `tan` does not exist for this type"); } - virtual RealPtr asin() const { throw StackTrace("Operator `asin` does not exist for this type"); } - virtual RealPtr acos() const { throw StackTrace("Operator `acos` does not exist for this type"); } - virtual RealPtr atan() const { throw StackTrace("Operator `atan` does not exist for this type"); } - virtual RealPtr sqrt() const { throw StackTrace("Operator `sqrt` does not exist for this type"); } - virtual RealPtr cbrt() const { throw StackTrace("Operator `cbrt` does not exist for this type"); } - virtual RealPtr sign() const { throw StackTrace("Operator `sign` does not exist for this type"); } - virtual RealPtr floor() const { throw StackTrace("Operator `floor` does not exist for this type"); } - virtual RealPtr ceil() const { throw StackTrace("Operator `ceil` does not exist for this type"); } - virtual RealPtr trunc() const { throw StackTrace("Operator `trunc` does not exist for this type"); } - virtual RealPtr sum() const { throw StackTrace("Operator `sum` does not exist for this type"); } - virtual RealPtr erf() const { throw StackTrace("Operator `erf` does not exist for this type"); } - virtual RealPtr erfc() const { throw StackTrace("Operator `erfc` does not exist for this type"); } - virtual RealPtr gamma() const { throw StackTrace("Operator `gamma` does not exist for this type"); } - virtual RealPtr lgamma() const { throw StackTrace("Operator `lgamma` does not exist for this type"); } - virtual RealPtr round() const { throw StackTrace("Operator `round` does not exist for this type"); } - virtual RealPtr normpdf() const { throw StackTrace("Operator `normpdf` does not exist for this type"); } - virtual RealPtr normpdf(const BaseTypePtr &btp1, const BaseTypePtr &btp2) const { throw StackTrace("Operator `normpdf` does not exist for this type"); } - virtual RealPtr normcdf() const { throw StackTrace("Operator `normcdf` does not exist for this type"); } - virtual RealPtr normcdf(const BaseTypePtr &btp1, const BaseTypePtr &btp2) const { throw StackTrace("Operator `normcdf` does not exist for this type"); } - virtual BoolPtr cast_bool() const { throw StackTrace("This type cannot be cast to a boolean"); } - virtual RealPtr cast_real() const { throw StackTrace("This type cannot be cast to a real"); } - virtual StringPtr cast_string() const { throw StackTrace("This type cannot be cast to a string"); } - virtual TuplePtr cast_tuple() const { throw StackTrace("This type cannot be cast to a tuple"); } - virtual ArrayPtr cast_array() const { throw StackTrace("This type cannot be cast to an array"); } - virtual BoolPtr defined() const { throw StackTrace("Operator `defined` does not exist for this type"); } + virtual BoolPtr + logical_and(const ExpressionPtr &ep) const + { + throw StackTrace("Operator && does not exist for this type"); + } + virtual BoolPtr + logical_or(const ExpressionPtr &ep) const + { + throw StackTrace("Operator || does not exist for this type"); + } + virtual BoolPtr + logical_not() const + { + throw StackTrace("Operator ! does not exist for this type"); + } + virtual ArrayPtr + set_union(const BaseTypePtr &btp) const + { + throw StackTrace("Operator | does not exist for this type"); + } + virtual ArrayPtr + set_intersection(const BaseTypePtr &btp) const + { + throw StackTrace("Operator & does not exist for this type"); + } + virtual BoolPtr + contains(const BaseTypePtr &btp) const + { + throw StackTrace("Second argument of `in` operator must be an array"); + } + virtual RealPtr + length() const + { + throw StackTrace("Operator `length` does not exist for this type"); + } + virtual BoolPtr + isempty() const + { + throw StackTrace("Operator `isempty` does not exist for this type"); + } + virtual BoolPtr + isboolean() const noexcept + { + return make_shared<Bool>(false, env, location); + } + virtual BoolPtr + isreal() const noexcept + { + return make_shared<Bool>(false, env, location); + } + virtual BoolPtr + isinteger() const noexcept + { + return make_shared<Bool>(false, env, location); + } + virtual BoolPtr + isstring() const noexcept + { + return make_shared<Bool>(false, env, location); + } + virtual BoolPtr + istuple() const noexcept + { + return make_shared<Bool>(false, env, location); + } + virtual BoolPtr + isarray() const noexcept + { + return make_shared<Bool>(false, env, location); + } + virtual RealPtr + max(const BaseTypePtr &btp) const + { + throw StackTrace("Operator `max` does not exist for this type"); + } + virtual RealPtr + min(const BaseTypePtr &btp) const + { + throw StackTrace("Operator `min` does not exist for this type"); + } + virtual RealPtr + mod(const BaseTypePtr &btp) const + { + throw StackTrace("Operator `mod` does not exist for this type"); + } + virtual RealPtr + exp() const + { + throw StackTrace("Operator `exp` does not exist for this type"); + } + virtual RealPtr + ln() const + { + throw StackTrace("Operator `ln` does not exist for this type"); + } + virtual RealPtr + log10() const + { + throw StackTrace("Operator `log10` does not exist for this type"); + } + virtual BoolPtr + isinf() const + { + throw StackTrace("Operator `isinf` does not exist for this type"); + } + virtual BoolPtr + isnan() const + { + throw StackTrace("Operator `isnan` does not exist for this type"); + } + virtual BoolPtr + isfinite() const + { + throw StackTrace("Operator `isfinite` does not exist for this type"); + } + virtual BoolPtr + isnormal() const + { + throw StackTrace("Operator `isnormal` does not exist for this type"); + } + virtual RealPtr + sin() const + { + throw StackTrace("Operator `sin` does not exist for this type"); + } + virtual RealPtr + cos() const + { + throw StackTrace("Operator `cos` does not exist for this type"); + } + virtual RealPtr + tan() const + { + throw StackTrace("Operator `tan` does not exist for this type"); + } + virtual RealPtr + asin() const + { + throw StackTrace("Operator `asin` does not exist for this type"); + } + virtual RealPtr + acos() const + { + throw StackTrace("Operator `acos` does not exist for this type"); + } + virtual RealPtr + atan() const + { + throw StackTrace("Operator `atan` does not exist for this type"); + } + virtual RealPtr + sqrt() const + { + throw StackTrace("Operator `sqrt` does not exist for this type"); + } + virtual RealPtr + cbrt() const + { + throw StackTrace("Operator `cbrt` does not exist for this type"); + } + virtual RealPtr + sign() const + { + throw StackTrace("Operator `sign` does not exist for this type"); + } + virtual RealPtr + floor() const + { + throw StackTrace("Operator `floor` does not exist for this type"); + } + virtual RealPtr + ceil() const + { + throw StackTrace("Operator `ceil` does not exist for this type"); + } + virtual RealPtr + trunc() const + { + throw StackTrace("Operator `trunc` does not exist for this type"); + } + virtual RealPtr + sum() const + { + throw StackTrace("Operator `sum` does not exist for this type"); + } + virtual RealPtr + erf() const + { + throw StackTrace("Operator `erf` does not exist for this type"); + } + virtual RealPtr + erfc() const + { + throw StackTrace("Operator `erfc` does not exist for this type"); + } + virtual RealPtr + gamma() const + { + throw StackTrace("Operator `gamma` does not exist for this type"); + } + virtual RealPtr + lgamma() const + { + throw StackTrace("Operator `lgamma` does not exist for this type"); + } + virtual RealPtr + round() const + { + throw StackTrace("Operator `round` does not exist for this type"); + } + virtual RealPtr + normpdf() const + { + throw StackTrace("Operator `normpdf` does not exist for this type"); + } + virtual RealPtr + normpdf(const BaseTypePtr &btp1, const BaseTypePtr &btp2) const + { + throw StackTrace("Operator `normpdf` does not exist for this type"); + } + virtual RealPtr + normcdf() const + { + throw StackTrace("Operator `normcdf` does not exist for this type"); + } + virtual RealPtr + normcdf(const BaseTypePtr &btp1, const BaseTypePtr &btp2) const + { + throw StackTrace("Operator `normcdf` does not exist for this type"); + } + virtual BoolPtr + cast_bool() const + { + throw StackTrace("This type cannot be cast to a boolean"); + } + virtual RealPtr + cast_real() const + { + throw StackTrace("This type cannot be cast to a real"); + } + virtual StringPtr + cast_string() const + { + throw StackTrace("This type cannot be cast to a string"); + } + virtual TuplePtr + cast_tuple() const + { + throw StackTrace("This type cannot be cast to a tuple"); + } + virtual ArrayPtr + cast_array() const + { + throw StackTrace("This type cannot be cast to an array"); + } + virtual BoolPtr + defined() const + { + throw StackTrace("Operator `defined` does not exist for this type"); + } }; - class Bool final : public BaseType { private: @@ -208,32 +479,67 @@ namespace macro Bool(bool value_arg, Environment &env_arg, Tokenizer::location location_arg = Tokenizer::location()) : BaseType(env_arg, move(location_arg)), - value{value_arg} { } - inline codes::BaseType getType() const noexcept override { return codes::BaseType::Bool; } - inline string to_string() const noexcept override { return value ? "true" : "false"; } - inline void print(ostream &output, bool matlab_output = false) const noexcept override { output << to_string(); } - inline ExpressionPtr clone() const noexcept override { return make_shared<Bool>(value, env, location); } + value{value_arg} + { + } + inline codes::BaseType + getType() const noexcept override + { + return codes::BaseType::Bool; + } + inline string + to_string() const noexcept override + { + return value ? "true" : "false"; + } + inline void + print(ostream &output, bool matlab_output = false) const noexcept override + { + output << to_string(); + } + inline ExpressionPtr + clone() const noexcept override + { + return make_shared<Bool>(value, env, location); + } public: operator bool() const { return value; } BoolPtr is_equal(const BaseTypePtr &btp) const override; BoolPtr logical_and(const ExpressionPtr &ep) const override; BoolPtr logical_or(const ExpressionPtr &ep) const override; BoolPtr logical_not() const override; - inline BoolPtr isboolean() const noexcept override { return make_shared<Bool>(true, env, location); } - inline BoolPtr cast_bool() const override { return make_shared<Bool>(value, env); } - inline RealPtr cast_real() const override { return value ? make_shared<Real>(1, env) : make_shared<Real>(0, env); } - inline StringPtr cast_string() const override { return make_shared<String>(this->to_string(), env); } - inline TuplePtr cast_tuple() const override + inline BoolPtr + isboolean() const noexcept override + { + return make_shared<Bool>(true, env, location); + } + inline BoolPtr + cast_bool() const override + { + return make_shared<Bool>(value, env); + } + inline RealPtr + cast_real() const override + { + return value ? make_shared<Real>(1, env) : make_shared<Real>(0, env); + } + inline StringPtr + cast_string() const override + { + return make_shared<String>(this->to_string(), env); + } + inline TuplePtr + cast_tuple() const override { return make_shared<Tuple>(vector<ExpressionPtr>{make_shared<Bool>(value, env)}, env); } - inline ArrayPtr cast_array() const override + inline ArrayPtr + cast_array() const override { return make_shared<Array>(vector<ExpressionPtr>{make_shared<Bool>(value, env)}, env); } }; - class Real final : public BaseType { private: @@ -244,26 +550,51 @@ namespace macro Real(const string &value_arg, Environment &env_arg, Tokenizer::location location_arg = Tokenizer::location()) : BaseType(env_arg, move(location_arg)), - value{strtod(value_arg.c_str(), nullptr)} { } + value{strtod(value_arg.c_str(), nullptr)} + { + } Real(double value_arg, Environment &env_arg, Tokenizer::location location_arg = Tokenizer::location()) : BaseType(env_arg, move(location_arg)), - value{value_arg} { } - inline codes::BaseType getType() const noexcept override { return codes::BaseType::Real; } - inline string to_string() const noexcept override + value{value_arg} + { + } + inline codes::BaseType + getType() const noexcept override + { + return codes::BaseType::Real; + } + inline string + to_string() const noexcept override { ostringstream strs; strs << setprecision(15) << value; return strs.str(); } - inline void print(ostream &output, bool matlab_output = false) const noexcept override { output << to_string(); } - inline ExpressionPtr clone() const noexcept override { return make_shared<Real>(value, env, location); } + inline void + print(ostream &output, bool matlab_output = false) const noexcept override + { + output << to_string(); + } + inline ExpressionPtr + clone() const noexcept override + { + return make_shared<Real>(value, env, location); + } public: operator double() const { return value; } BaseTypePtr plus(const BaseTypePtr &bt) const override; - inline BaseTypePtr unary_plus() const override { return make_shared<Real>(value, env); } + inline BaseTypePtr + unary_plus() const override + { + return make_shared<Real>(value, env); + } BaseTypePtr minus(const BaseTypePtr &bt) const override; - inline BaseTypePtr unary_minus() const override { return make_shared<Real>(-value, env); } + inline BaseTypePtr + unary_minus() const override + { + return make_shared<Real>(-value, env); + } BaseTypePtr times(const BaseTypePtr &bt) const override; BaseTypePtr divide(const BaseTypePtr &bt) const override; BaseTypePtr power(const BaseTypePtr &btp) const override; @@ -272,8 +603,13 @@ namespace macro BoolPtr is_less_equal(const BaseTypePtr &btp) const override; BoolPtr is_greater_equal(const BaseTypePtr &btp) const override; BoolPtr is_equal(const BaseTypePtr &btp) const override; - inline BoolPtr isreal() const noexcept override { return make_shared<Bool>(true, env, location); } - inline BoolPtr isinteger() const noexcept override + inline BoolPtr + isreal() const noexcept override + { + return make_shared<Bool>(true, env, location); + } + inline BoolPtr + isinteger() const noexcept override { double intpart; return make_shared<Bool>(modf(value, &intpart) == 0.0, env, location); @@ -284,51 +620,160 @@ namespace macro RealPtr max(const BaseTypePtr &btp) const override; RealPtr min(const BaseTypePtr &btp) const override; RealPtr mod(const BaseTypePtr &btp) const override; - inline RealPtr exp() const override { return make_shared<Real>(std::exp(value), env); } - inline RealPtr ln() const override { return make_shared<Real>(std::log(value), env); } - inline RealPtr log10() const override { return make_shared<Real>(std::log10(value), env); } - inline BoolPtr isinf() const override { return make_shared<Bool>(std::isinf(value), env); } - inline BoolPtr isnan() const override { return make_shared<Bool>(std::isnan(value), env); } - inline BoolPtr isfinite() const override { return make_shared<Bool>(std::isfinite(value), env); } - inline BoolPtr isnormal() const override { return make_shared<Bool>(std::isnormal(value), env); } - inline RealPtr sin() const override { return make_shared<Real>(std::sin(value), env); } - inline RealPtr cos() const override { return make_shared<Real>(std::cos(value), env); } - inline RealPtr tan() const override { return make_shared<Real>(std::tan(value), env); } - inline RealPtr asin() const override { return make_shared<Real>(std::asin(value), env); } - inline RealPtr acos() const override { return make_shared<Real>(std::acos(value), env); } - inline RealPtr atan() const override { return make_shared<Real>(std::atan(value), env); } - inline RealPtr sqrt() const override { return make_shared<Real>(std::sqrt(value), env); } - inline RealPtr cbrt() const override { return make_shared<Real>(std::cbrt(value), env); } - inline RealPtr sign() const override + inline RealPtr + exp() const override + { + return make_shared<Real>(std::exp(value), env); + } + inline RealPtr + ln() const override + { + return make_shared<Real>(std::log(value), env); + } + inline RealPtr + log10() const override + { + return make_shared<Real>(std::log10(value), env); + } + inline BoolPtr + isinf() const override + { + return make_shared<Bool>(std::isinf(value), env); + } + inline BoolPtr + isnan() const override + { + return make_shared<Bool>(std::isnan(value), env); + } + inline BoolPtr + isfinite() const override + { + return make_shared<Bool>(std::isfinite(value), env); + } + inline BoolPtr + isnormal() const override + { + return make_shared<Bool>(std::isnormal(value), env); + } + inline RealPtr + sin() const override + { + return make_shared<Real>(std::sin(value), env); + } + inline RealPtr + cos() const override + { + return make_shared<Real>(std::cos(value), env); + } + inline RealPtr + tan() const override + { + return make_shared<Real>(std::tan(value), env); + } + inline RealPtr + asin() const override + { + return make_shared<Real>(std::asin(value), env); + } + inline RealPtr + acos() const override + { + return make_shared<Real>(std::acos(value), env); + } + inline RealPtr + atan() const override + { + return make_shared<Real>(std::atan(value), env); + } + inline RealPtr + sqrt() const override + { + return make_shared<Real>(std::sqrt(value), env); + } + inline RealPtr + cbrt() const override + { + return make_shared<Real>(std::cbrt(value), env); + } + inline RealPtr + sign() const override { return make_shared<Real>((value > 0) ? 1. : ((value < 0) ? -1. : 0.), env); } - inline RealPtr floor() const override { return make_shared<Real>(std::floor(value), env); } - inline RealPtr ceil() const override { return make_shared<Real>(std::ceil(value), env); } - inline RealPtr trunc() const override { return make_shared<Real>(std::trunc(value), env); } - inline RealPtr erf() const override { return make_shared<Real>(std::erf(value), env); } - inline RealPtr erfc() const override { return make_shared<Real>(std::erfc(value), env); } - inline RealPtr gamma() const override { return make_shared<Real>(std::tgamma(value), env); } - inline RealPtr lgamma() const override { return make_shared<Real>(std::lgamma(value), env); } - inline RealPtr round() const override { return make_shared<Real>(std::round(value), env); } - inline RealPtr normpdf() const override + inline RealPtr + floor() const override + { + return make_shared<Real>(std::floor(value), env); + } + inline RealPtr + ceil() const override + { + return make_shared<Real>(std::ceil(value), env); + } + inline RealPtr + trunc() const override + { + return make_shared<Real>(std::trunc(value), env); + } + inline RealPtr + erf() const override + { + return make_shared<Real>(std::erf(value), env); + } + inline RealPtr + erfc() const override + { + return make_shared<Real>(std::erfc(value), env); + } + inline RealPtr + gamma() const override + { + return make_shared<Real>(std::tgamma(value), env); + } + inline RealPtr + lgamma() const override + { + return make_shared<Real>(std::lgamma(value), env); + } + inline RealPtr + round() const override + { + return make_shared<Real>(std::round(value), env); + } + inline RealPtr + normpdf() const override { return normpdf(make_shared<Real>(0, env), make_shared<Real>(1, env)); } RealPtr normpdf(const BaseTypePtr &btp1, const BaseTypePtr &btp2) const override; - inline RealPtr normcdf() const override + inline RealPtr + normcdf() const override { return normcdf(make_shared<Real>(0, env), make_shared<Real>(1, env)); } RealPtr normcdf(const BaseTypePtr &btp1, const BaseTypePtr &btp2) const override; - inline BoolPtr cast_bool() const override { return make_shared<Bool>(static_cast<bool>(value), env); } - inline RealPtr cast_real() const override { return make_shared<Real>(value, env); } - inline StringPtr cast_string() const override { return make_shared<String>(this->to_string(), env); } - inline TuplePtr cast_tuple() const override + inline BoolPtr + cast_bool() const override + { + return make_shared<Bool>(static_cast<bool>(value), env); + } + inline RealPtr + cast_real() const override + { + return make_shared<Real>(value, env); + } + inline StringPtr + cast_string() const override + { + return make_shared<String>(this->to_string(), env); + } + inline TuplePtr + cast_tuple() const override { return make_shared<Tuple>(vector<ExpressionPtr>{make_shared<Real>(value, env)}, env); } - inline ArrayPtr cast_array() const override + inline ArrayPtr + cast_array() const override { return make_shared<Array>(vector<ExpressionPtr>{make_shared<Real>(value, env)}, env); } @@ -342,11 +787,25 @@ namespace macro String(string value_arg, Environment &env_arg, Tokenizer::location location_arg = Tokenizer::location()) : BaseType(env_arg, move(location_arg)), - value{move(value_arg)} { } - inline codes::BaseType getType() const noexcept override { return codes::BaseType::String; } - inline string to_string() const noexcept override { return value; } + value{move(value_arg)} + { + } + inline codes::BaseType + getType() const noexcept override + { + return codes::BaseType::String; + } + inline string + to_string() const noexcept override + { + return value; + } void print(ostream &output, bool matlab_output = false) const noexcept override; - inline ExpressionPtr clone() const noexcept override { return make_shared<String>(value, env, location); } + inline ExpressionPtr + clone() const noexcept override + { + return make_shared<String>(value, env, location); + } public: operator string() const { return value; } BaseTypePtr plus(const BaseTypePtr &bt) const override; @@ -355,27 +814,45 @@ namespace macro BoolPtr is_less_equal(const BaseTypePtr &btp) const override; BoolPtr is_greater_equal(const BaseTypePtr &btp) const override; BoolPtr is_equal(const BaseTypePtr &btp) const override; - inline BoolPtr isstring() const noexcept override { return make_shared<Bool>(true, env, location); } - inline RealPtr length() const override { return make_shared<Real>(value.size(), env); } - inline BoolPtr isempty() const override { return make_shared<Bool>(value.empty(), env); } + inline BoolPtr + isstring() const noexcept override + { + return make_shared<Bool>(true, env, location); + } + inline RealPtr + length() const override + { + return make_shared<Real>(value.size(), env); + } + inline BoolPtr + isempty() const override + { + return make_shared<Bool>(value.empty(), env); + } BoolPtr cast_bool() const override; RealPtr cast_real() const override; - inline StringPtr cast_string() const override { return make_shared<String>(value, env); } - inline TuplePtr cast_tuple() const override + inline StringPtr + cast_string() const override + { + return make_shared<String>(value, env); + } + inline TuplePtr + cast_tuple() const override { return make_shared<Tuple>(vector<ExpressionPtr>{make_shared<String>(value, env)}, env); } - inline ArrayPtr cast_array() const override + inline ArrayPtr + cast_array() const override { return make_shared<Array>(vector<ExpressionPtr>{make_shared<String>(value, env)}, env); } - inline BoolPtr defined() const override + inline BoolPtr + defined() const override { return make_shared<Bool>(env.isSymbolDefined(value), env); } }; - class Tuple final : public BaseType { private: @@ -384,30 +861,75 @@ namespace macro Tuple(vector<ExpressionPtr> tup_arg, Environment &env_arg, Tokenizer::location location_arg = Tokenizer::location()) : BaseType(env_arg, move(location_arg)), - tup{move(tup_arg)} { } - inline codes::BaseType getType() const noexcept override { return codes::BaseType::Tuple; } + tup{move(tup_arg)} + { + } + inline codes::BaseType + getType() const noexcept override + { + return codes::BaseType::Tuple; + } string to_string() const noexcept override; void print(ostream &output, bool matlab_output = false) const noexcept override; BaseTypePtr eval() override; ExpressionPtr clone() const noexcept override; public: - inline size_t size() const { return tup.size(); } - inline bool empty() const { return tup.empty(); } - inline const vector<ExpressionPtr> & getValue() const { return tup; } - inline const ExpressionPtr & at(int i) const { return tup.at(i); } + inline size_t + size() const + { + return tup.size(); + } + inline bool + empty() const + { + return tup.empty(); + } + inline const vector<ExpressionPtr> & + getValue() const + { + return tup; + } + inline const ExpressionPtr & + at(int i) const + { + return tup.at(i); + } BoolPtr is_equal(const BaseTypePtr &btp) const override; - inline BoolPtr istuple() const noexcept override { return make_shared<Bool>(true, env, location); } + inline BoolPtr + istuple() const noexcept override + { + return make_shared<Bool>(true, env, location); + } BoolPtr contains(const BaseTypePtr &btp) const override; - inline RealPtr length() const override { return make_shared<Real>(tup.size(), env); } - inline BoolPtr isempty() const override { return make_shared<Bool>(empty(), env); } + inline RealPtr + length() const override + { + return make_shared<Real>(tup.size(), env); + } + inline BoolPtr + isempty() const override + { + return make_shared<Bool>(empty(), env); + } BoolPtr cast_bool() const override; RealPtr cast_real() const override; - inline StringPtr cast_string() const override { return make_shared<String>(this->to_string(), env); } - inline TuplePtr cast_tuple() const override { return make_shared<Tuple>(tup, env); } - inline ArrayPtr cast_array() const override { return make_shared<Array>(tup, env); } + inline StringPtr + cast_string() const override + { + return make_shared<String>(this->to_string(), env); + } + inline TuplePtr + cast_tuple() const override + { + return make_shared<Tuple>(tup, env); + } + inline ArrayPtr + cast_array() const override + { + return make_shared<Array>(tup, env); + } }; - class Array final : public BaseType { private: @@ -415,37 +937,82 @@ namespace macro public: Array(vector<ExpressionPtr> arr_arg, Environment &env_arg, Tokenizer::location location_arg = Tokenizer::location()) : - BaseType(env_arg, move(location_arg)), arr{move(arr_arg)} { } - inline codes::BaseType getType() const noexcept override { return codes::BaseType::Array; } + BaseType(env_arg, move(location_arg)), arr{move(arr_arg)} + { + } + inline codes::BaseType + getType() const noexcept override + { + return codes::BaseType::Array; + } string to_string() const noexcept override; void print(ostream &output, bool matlab_output = false) const noexcept override; BaseTypePtr eval() override; ExpressionPtr clone() const noexcept override; public: - inline size_t size() const { return arr.size(); } - inline const vector<ExpressionPtr> & getValue() const { return arr; } - inline const ExpressionPtr & at(int i) const { return arr.at(i); } - inline bool empty() const { return arr.empty(); } + inline size_t + size() const + { + return arr.size(); + } + inline const vector<ExpressionPtr> & + getValue() const + { + return arr; + } + inline const ExpressionPtr & + at(int i) const + { + return arr.at(i); + } + inline bool + empty() const + { + return arr.empty(); + } BaseTypePtr plus(const BaseTypePtr &bt) const override; BaseTypePtr minus(const BaseTypePtr &bt) const override; BaseTypePtr times(const BaseTypePtr &bt) const override; BaseTypePtr power(const BaseTypePtr &btp) const override; BoolPtr is_equal(const BaseTypePtr &btp) const override; - inline BoolPtr isarray() const noexcept override { return make_shared<Bool>(true, env, location); } + inline BoolPtr + isarray() const noexcept override + { + return make_shared<Bool>(true, env, location); + } ArrayPtr set_union(const BaseTypePtr &btp) const override; ArrayPtr set_intersection(const BaseTypePtr &btp) const override; BoolPtr contains(const BaseTypePtr &btp) const override; - inline RealPtr length() const override { return make_shared<Real>(arr.size(), env); } - inline BoolPtr isempty() const override { return make_shared<Bool>(empty(), env); } + inline RealPtr + length() const override + { + return make_shared<Real>(arr.size(), env); + } + inline BoolPtr + isempty() const override + { + return make_shared<Bool>(empty(), env); + } RealPtr sum() const override; BoolPtr cast_bool() const override; RealPtr cast_real() const override; - inline StringPtr cast_string() const override { return make_shared<String>(this->to_string(), env); } - inline TuplePtr cast_tuple() const override { return make_shared<Tuple>(arr, env); } - inline ArrayPtr cast_array() const override { return make_shared<Array>(arr, env); } + inline StringPtr + cast_string() const override + { + return make_shared<String>(this->to_string(), env); + } + inline TuplePtr + cast_tuple() const override + { + return make_shared<Tuple>(arr, env); + } + inline ArrayPtr + cast_array() const override + { + return make_shared<Array>(arr, env); + } }; - class Range final : public BaseType { private: @@ -453,35 +1020,49 @@ namespace macro public: Range(ExpressionPtr start_arg, ExpressionPtr end_arg, Environment &env_arg, Tokenizer::location location_arg) : - BaseType(env_arg, move(location_arg)), start{move(start_arg)}, end{move(end_arg)} { } + BaseType(env_arg, move(location_arg)), start{move(start_arg)}, end{move(end_arg)} + { + } Range(ExpressionPtr start_arg, ExpressionPtr inc_arg, ExpressionPtr end_arg, Environment &env_arg, Tokenizer::location location_arg) : BaseType(env_arg, move(location_arg)), - start{move(start_arg)}, inc{move(inc_arg)}, end{move(end_arg)} { } - inline codes::BaseType getType() const noexcept override { return codes::BaseType::Range; } - inline string to_string() const noexcept override + start{move(start_arg)}, inc{move(inc_arg)}, end{move(end_arg)} + { + } + inline codes::BaseType + getType() const noexcept override + { + return codes::BaseType::Range; + } + inline string + to_string() const noexcept override { string retval = "[" + start->to_string() + ":"; if (inc) - retval += inc->to_string() + ":" ; + retval += inc->to_string() + ":"; return retval + end->to_string() + "]"; } - inline void print(ostream &output, bool matlab_output = false) const noexcept override { output << to_string(); } + inline void + print(ostream &output, bool matlab_output = false) const noexcept override + { + output << to_string(); + } BaseTypePtr eval() override; - inline ExpressionPtr clone() const noexcept override + inline ExpressionPtr + clone() const noexcept override { return inc ? make_shared<Range>(start, inc, end, env, location) : make_shared<Range>(start, end, env, location); } public: - inline BoolPtr is_equal(const BaseTypePtr &btp) const override + inline BoolPtr + is_equal(const BaseTypePtr &btp) const override { throw StackTrace("Internal error: Range: Should not arrive here: is_equal"); } }; - class Variable final : public Expression { private: @@ -490,24 +1071,44 @@ namespace macro public: Variable(string name_arg, Environment &env_arg, Tokenizer::location location_arg) : - Expression(env_arg, move(location_arg)), name{move(name_arg)} { } + Expression(env_arg, move(location_arg)), name{move(name_arg)} + { + } Variable(string name_arg, ArrayPtr indices_arg, Environment &env_arg, Tokenizer::location location_arg) : - Expression(env_arg, move(location_arg)), name{move(name_arg)}, indices{move(indices_arg)} { } - inline string to_string() const noexcept override { return name; } - inline void print(ostream &output, bool matlab_output = false) const noexcept override { output << name; } + Expression(env_arg, move(location_arg)), name{move(name_arg)}, indices{move(indices_arg)} + { + } + inline string + to_string() const noexcept override + { + return name; + } + inline void + print(ostream &output, bool matlab_output = false) const noexcept override + { + output << name; + } BaseTypePtr eval() override; - inline ExpressionPtr clone() const noexcept override + inline ExpressionPtr + clone() const noexcept override { return indices ? make_shared<Variable>(name, indices, env, location) : make_shared<Variable>(name, env, location); } public: - inline const string & getName() const noexcept { return name; } - inline codes::BaseType getType() const { return env.getType(name); } + inline const string & + getName() const noexcept + { + return name; + } + inline codes::BaseType + getType() const + { + return env.getType(name); + } }; - class Function final : public Expression { private: @@ -517,22 +1118,36 @@ namespace macro Function(string name_arg, vector<ExpressionPtr> args_arg, Environment &env_arg, Tokenizer::location location_arg) : - Expression(env_arg, move(location_arg)), name{move(name_arg)}, args{move(args_arg)} { } + Expression(env_arg, move(location_arg)), name{move(name_arg)}, args{move(args_arg)} + { + } string to_string() const noexcept override; - inline void print(ostream &output, bool matlab_output = false) const noexcept override + inline void + print(ostream &output, bool matlab_output = false) const noexcept override { printName(output); printArgs(output); } BaseTypePtr eval() override; ExpressionPtr clone() const noexcept override; public: - inline void printName(ostream &output) const noexcept { output << name; } + inline void + printName(ostream &output) const noexcept + { + output << name; + } void printArgs(ostream &output) const noexcept; - inline const string & getName() const { return name; } - inline const vector<ExpressionPtr> & getArgs() const { return args; } + inline const string & + getName() const + { + return name; + } + inline const vector<ExpressionPtr> & + getArgs() const + { + return args; + } }; - class UnaryOp final : public Expression { private: @@ -542,17 +1157,19 @@ namespace macro UnaryOp(codes::UnaryOp op_code_arg, ExpressionPtr arg_arg, Environment &env_arg, Tokenizer::location location_arg) : - Expression(env_arg, move(location_arg)), op_code{move(op_code_arg)}, arg{move(arg_arg)} { } + Expression(env_arg, move(location_arg)), op_code{move(op_code_arg)}, arg{move(arg_arg)} + { + } string to_string() const noexcept override; void print(ostream &output, bool matlab_output = false) const noexcept override; BaseTypePtr eval() override; - inline ExpressionPtr clone() const noexcept override + inline ExpressionPtr + clone() const noexcept override { return make_shared<UnaryOp>(op_code, arg->clone(), env, location); } }; - class BinaryOp final : public Expression { private: @@ -563,18 +1180,20 @@ namespace macro ExpressionPtr arg1_arg, ExpressionPtr arg2_arg, Environment &env_arg, Tokenizer::location location_arg) : Expression(env_arg, move(location_arg)), op_code{op_code_arg}, - arg1{move(arg1_arg)}, arg2{move(arg2_arg)} { } + arg1{move(arg1_arg)}, arg2{move(arg2_arg)} + { + } public: string to_string() const noexcept override; void print(ostream &output, bool matlab_output = false) const noexcept override; BaseTypePtr eval() override; - inline ExpressionPtr clone() const noexcept override + inline ExpressionPtr + clone() const noexcept override { return make_shared<BinaryOp>(op_code, arg1->clone(), arg2->clone(), env, location); } }; - class TrinaryOp final : public Expression { private: @@ -585,17 +1204,19 @@ namespace macro ExpressionPtr arg1_arg, ExpressionPtr arg2_arg, ExpressionPtr arg3_arg, Environment &env_arg, Tokenizer::location location_arg) : Expression(env_arg, move(location_arg)), op_code{op_code_arg}, - arg1{move(arg1_arg)}, arg2{move(arg2_arg)}, arg3{move(arg3_arg)} { } + arg1{move(arg1_arg)}, arg2{move(arg2_arg)}, arg3{move(arg3_arg)} + { + } string to_string() const noexcept override; void print(ostream &output, bool matlab_output = false) const noexcept override; BaseTypePtr eval() override; - inline ExpressionPtr clone() const noexcept override + inline ExpressionPtr + clone() const noexcept override { return make_shared<TrinaryOp>(op_code, arg1->clone(), arg2->clone(), arg3->clone(), env, location); } }; - class Comprehension final : public Expression { /* @@ -613,20 +1234,26 @@ namespace macro Environment &env_arg, Tokenizer::location location_arg) : Expression(env_arg, move(location_arg)), c_expr{move(c_expr_arg)}, c_vars{move(c_vars_arg)}, - c_set{move(c_set_arg)}, c_when{move(c_when_arg)} { } + c_set{move(c_set_arg)}, c_when{move(c_when_arg)} + { + } Comprehension(ExpressionPtr c_expr_arg, ExpressionPtr c_vars_arg, ExpressionPtr c_set_arg, Environment &env_arg, Tokenizer::location location_arg) : Expression(env_arg, move(location_arg)), - c_expr{move(c_expr_arg)}, c_vars{move(c_vars_arg)}, c_set{move(c_set_arg)} { } + c_expr{move(c_expr_arg)}, c_vars{move(c_vars_arg)}, c_set{move(c_set_arg)} + { + } Comprehension(bool filter_only_arg, ExpressionPtr c_vars_arg, ExpressionPtr c_set_arg, ExpressionPtr c_when_arg, Environment &env_arg, Tokenizer::location location_arg) : Expression(env_arg, move(location_arg)), - c_vars{move(c_vars_arg)}, c_set{move(c_set_arg)}, c_when{move(c_when_arg)} { } + c_vars{move(c_vars_arg)}, c_set{move(c_set_arg)}, c_when{move(c_when_arg)} + { + } string to_string() const noexcept override; void print(ostream &output, bool matlab_output = false) const noexcept override; BaseTypePtr eval() override; -- GitLab