From 64642d928c49d81ac016501b44b38b7cdb9f2752 Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Thu, 2 Feb 2017 15:09:43 +0100 Subject: [PATCH 01/18] preprocessor: write JSON output. #1387 --- DynamicModel.cc | 7 + DynamicModel.hh | 5 +- DynareMain.cc | 11 +- DynareMain2.cc | 8 + ExprNode.cc | 330 ++++++++++++++++++++++++++++++++++- ExprNode.hh | 15 +- ExtendedPreprocessorTypes.hh | 8 +- ModFile.cc | 69 ++++++++ ModFile.hh | 5 + ModelTree.cc | 35 ++++ ModelTree.hh | 2 + NumericalInitialization.cc | 62 ++++++- NumericalInitialization.hh | 7 +- Statement.cc | 6 +- Statement.hh | 3 +- SymbolTable.cc | 85 ++++++++- SymbolTable.hh | 10 +- 17 files changed, 656 insertions(+), 12 deletions(-) diff --git a/DynamicModel.cc b/DynamicModel.cc index 08dd2bc4..704592da 100644 --- a/DynamicModel.cc +++ b/DynamicModel.cc @@ -5336,3 +5336,10 @@ DynamicModel::writeCCOutput(ostream &output, const string &basename, bool block_ output << "NNZDerivatives.push_back(-1);" << endl << "NNZDerivatives.push_back(-1);" << endl; } + + +void +DynamicModel::writeJsonOutput(ostream &output) const +{ + writeJsonModelEquations(output); +} diff --git a/DynamicModel.hh b/DynamicModel.hh index 6b99423c..e79ac7f4 100644 --- a/DynamicModel.hh +++ b/DynamicModel.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -217,6 +217,9 @@ public: //! Writes model initialization and lead/lag incidence matrix to output void writeOutput(ostream &output, const string &basename, bool block, bool byte_code, bool use_dll, int order, bool estimation_present, bool compute_xrefs, bool julia) const; + //! Write JSON Output + void writeJsonOutput(ostream &output) const; + //! Return true if the hessian is equal to zero inline bool checkHessianZero() const; diff --git a/DynareMain.cc b/DynareMain.cc index adbb1b68..c5650926 100644 --- a/DynareMain.cc +++ b/DynareMain.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -45,6 +45,7 @@ void main2(stringstream &in, string &basename, bool debug, bool clear_all, bool #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) , bool cygwin, bool msvc, bool mingw #endif + , bool json, JsonFileOutputType json_output_mode ); void main1(char *modfile, string &basename, bool debug, bool save_macro, string &save_macro_file, @@ -61,6 +62,7 @@ usage() #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) << " [cygwin] [msvc] [mingw]" #endif + << "[json] [jsonstdout]" << endl; exit(EXIT_FAILURE); } @@ -113,6 +115,8 @@ main(int argc, char **argv) map defines; vector path; FileOutputType output_mode = none; + bool json = false; + JsonFileOutputType json_output_mode = file; LanguageOutputType language = matlab; // Parse options @@ -291,6 +295,10 @@ main(int argc, char **argv) } } } + else if (!strcmp(argv[arg], "jsonstdout")) + json_output_mode = standardout; + else if (!strcmp(argv[arg], "json")) + json = true; else { cerr << "Unknown option: " << argv[arg] << endl; @@ -337,6 +345,7 @@ main(int argc, char **argv) #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) , cygwin, msvc, mingw #endif + , json, json_output_mode ); return EXIT_SUCCESS; diff --git a/DynareMain2.cc b/DynareMain2.cc index bc5065b2..3bbc4b4f 100644 --- a/DynareMain2.cc +++ b/DynareMain2.cc @@ -34,12 +34,20 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) , bool cygwin, bool msvc, bool mingw #endif + , bool json, JsonFileOutputType json_output_mode ) { ParsingDriver p(warnings, nostrict); // Do parsing and construct internal representation of mod file ModFile *mod_file = p.parse(in, debug); + if (json) + { + mod_file->symbol_table.freeze(); + mod_file->writeJsonOutput(basename, json_output_mode); + mod_file->symbol_table.unfreeze(); + cout << "JSON file written after Parsing step." << endl; + } // Run checking pass mod_file->checkPass(nostrict); diff --git a/ExprNode.cc b/ExprNode.cc index d7d8374c..ccba75c2 100644 --- a/ExprNode.cc +++ b/ExprNode.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2016 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * @@ -322,6 +322,14 @@ NumConstNode::writeOutput(ostream &output, ExprNodeOutputType output_type, output << datatree.num_constants.get(id); } +void +NumConstNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + output << datatree.num_constants.get(id); +} + bool NumConstNode::containsExternalFunction() const { @@ -615,6 +623,16 @@ VariableNode::containsExternalFunction() const return false; } +void +VariableNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + output << datatree.symbol_table.getName(symb_id); + if (lag != 0) + output << "(" << lag << ")"; +} + void VariableNode::writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, @@ -1850,6 +1868,141 @@ UnaryOpNode::containsExternalFunction() const return arg->containsExternalFunction(); } +void +UnaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + // Always put parenthesis around uminus nodes + if (op_code == oUminus) + output << LEFT_PAR(output_type); + + switch (op_code) + { + case oUminus: + output << "-"; + break; + case oExp: + output << "exp"; + break; + case oLog: + output << "log"; + break; + case oLog10: + output << "log10"; + break; + case oCos: + output << "cos"; + break; + case oSin: + output << "sin"; + break; + case oTan: + output << "tan"; + break; + case oAcos: + output << "acos"; + break; + case oAsin: + output << "asin"; + break; + case oAtan: + output << "atan"; + break; + case oCosh: + output << "cosh"; + break; + case oSinh: + output << "sinh"; + break; + case oTanh: + output << "tanh"; + break; + case oAcosh: + output << "acosh"; + break; + case oAsinh: + output << "asinh"; + break; + case oAtanh: + output << "atanh"; + break; + case oSqrt: + output << "sqrt"; + break; + case oAbs: + output << "abs"; + break; + case oSign: + output << "sign"; + break; + case oSteadyState: + output << "("; + arg->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + output << ")"; + return; + case oSteadyStateParamDeriv: + { + VariableNode *varg = dynamic_cast(arg); + assert(varg != NULL); + assert(datatree.symbol_table.getType(varg->symb_id) == eEndogenous); + assert(datatree.symbol_table.getType(param1_symb_id) == eParameter); + int tsid_endo = datatree.symbol_table.getTypeSpecificID(varg->symb_id); + int tsid_param = datatree.symbol_table.getTypeSpecificID(param1_symb_id); + assert(IS_MATLAB(output_type)); + output << "ss_param_deriv(" << tsid_endo+1 << "," << tsid_param+1 << ")"; + } + return; + case oSteadyStateParam2ndDeriv: + { + VariableNode *varg = dynamic_cast(arg); + assert(varg != NULL); + assert(datatree.symbol_table.getType(varg->symb_id) == eEndogenous); + assert(datatree.symbol_table.getType(param1_symb_id) == eParameter); + assert(datatree.symbol_table.getType(param2_symb_id) == eParameter); + int tsid_endo = datatree.symbol_table.getTypeSpecificID(varg->symb_id); + int tsid_param1 = datatree.symbol_table.getTypeSpecificID(param1_symb_id); + int tsid_param2 = datatree.symbol_table.getTypeSpecificID(param2_symb_id); + assert(IS_MATLAB(output_type)); + output << "ss_param_2nd_deriv(" << tsid_endo+1 << "," << tsid_param1+1 + << "," << tsid_param2+1 << ")"; + } + return; + case oExpectation: + output << "EXPECTATION(" << expectation_information_set << ")"; + break; + case oErf: + output << "erf"; + break; + } + + bool close_parenthesis = false; + + /* Enclose argument with parentheses if: + - current opcode is not uminus, or + - current opcode is uminus and argument has lowest precedence + */ + if (op_code != oUminus + || (op_code == oUminus + && arg->precedence(output_type, temporary_terms) < precedence(output_type, temporary_terms))) + { + output << LEFT_PAR(output_type); + if (op_code == oSign && (output_type == oCDynamicModel || output_type == oCStaticModel)) + output << "1.0,"; + close_parenthesis = true; + } + + // Write argument + arg->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + + if (close_parenthesis) + output << RIGHT_PAR(output_type); + + // Close parenthesis for uminus + if (op_code == oUminus) + output << RIGHT_PAR(output_type); +} + void UnaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, @@ -3072,6 +3225,119 @@ BinaryOpNode::containsExternalFunction() const || arg2->containsExternalFunction(); } +void +BinaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + if (op_code == oMax || op_code == oMin) + { + switch (op_code) + { + case oMax: + output << "max("; + break; + case oMin: + output << "min("; + break; + default: + ; + } + arg1->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + output << ","; + arg2->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + output << ")"; + return; + } + + int prec = precedence(output_type, temporary_terms); + + bool close_parenthesis = false; + + // If left argument has a lower precedence, or if current and left argument are both power operators, + // add parenthesis around left argument + BinaryOpNode *barg1 = dynamic_cast(arg1); + if (arg1->precedence(output_type, temporary_terms) < prec + || (op_code == oPower && barg1 != NULL && barg1->op_code == oPower)) + { + output << LEFT_PAR(output_type); + close_parenthesis = true; + } + + // Write left argument + arg1->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + + if (close_parenthesis) + output << RIGHT_PAR(output_type); + + // Write current operator symbol + switch (op_code) + { + case oPlus: + output << "+"; + break; + case oMinus: + output << "-"; + break; + case oTimes: + output << "*"; + break; + case oDivide: + output << "/"; + break; + case oPower: + output << "^"; + break; + case oLess: + output << "<"; + break; + case oGreater: + output << ">"; + break; + case oLessEqual: + output << "<="; + break; + case oGreaterEqual: + output << ">="; + break; + case oEqualEqual: + output << "=="; + break; + case oDifferent: + output << "!="; + break; + case oEqual: + output << "="; + break; + default: + ; + } + + close_parenthesis = false; + + /* Add parenthesis around right argument if: + - its precedence is lower than those of the current node + - it is a power operator and current operator is also a power operator + - it is a minus operator with same precedence than current operator + - it is a divide operator with same precedence than current operator */ + BinaryOpNode *barg2 = dynamic_cast(arg2); + int arg2_prec = arg2->precedence(output_type, temporary_terms); + if (arg2_prec < prec + || (op_code == oPower && barg2 != NULL && barg2->op_code == oPower && !IS_LATEX(output_type)) + || (op_code == oMinus && arg2_prec == prec) + || (op_code == oDivide && arg2_prec == prec && !IS_LATEX(output_type))) + { + output << LEFT_PAR(output_type); + close_parenthesis = true; + } + + // Write right argument + arg2->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + + if (close_parenthesis) + output << RIGHT_PAR(output_type); +} + void BinaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, @@ -4211,6 +4477,29 @@ TrinaryOpNode::containsExternalFunction() const || arg3->containsExternalFunction(); } +void +TrinaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + switch (op_code) + { + case oNormcdf: + output << "normcdf("; + break; + case oNormpdf: + output << "normpdf("; + break; + } + + arg1->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + output << ","; + arg2->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + output << ","; + arg3->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + output << ")"; +} + void TrinaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, @@ -4891,6 +5180,21 @@ AbstractExternalFunctionNode::writeExternalFunctionArguments(ostream &output, Ex } } +void +AbstractExternalFunctionNode::writeJsonExternalFunctionArguments(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + for (vector::const_iterator it = arguments.begin(); + it != arguments.end(); it++) + { + if (it != arguments.begin()) + output << ","; + + (*it)->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + } +} + void AbstractExternalFunctionNode::writePrhs(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, @@ -5054,6 +5358,16 @@ ExternalFunctionNode::compileExternalFunctionOutput(ostream &CompileCode, unsign } } +void +ExternalFunctionNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + output << datatree.symbol_table.getName(symb_id) << "("; + writeJsonExternalFunctionArguments(output, output_type, temporary_terms, tef_terms); + output << ")"; +} + void ExternalFunctionNode::writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, @@ -5244,6 +5558,13 @@ FirstDerivExternalFunctionNode::composeDerivatives(const vector &dargs) return theDeriv; } +void +FirstDerivExternalFunctionNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ +} + void FirstDerivExternalFunctionNode::writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, @@ -5556,6 +5877,13 @@ SecondDerivExternalFunctionNode::composeDerivatives(const vector &dargs) exit(EXIT_FAILURE); } +void +SecondDerivExternalFunctionNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ +} + void SecondDerivExternalFunctionNode::writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, diff --git a/ExprNode.hh b/ExprNode.hh index 0440d807..32654071 100644 --- a/ExprNode.hh +++ b/ExprNode.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2007-2016 Dynare Team + * Copyright (C) 2007-2017 Dynare Team * * This file is part of Dynare. * @@ -221,6 +221,9 @@ public: //! 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; + //! Writes output of node in JSON syntax + virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; + //! 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, @@ -478,6 +481,7 @@ public: }; virtual void prepareForDerivation(); virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void collectDynamicVariables(SymbolType type_arg, set > &result) const; virtual void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const; @@ -527,6 +531,7 @@ public: VariableNode(DataTree &datatree_arg, int symb_id_arg, int lag_arg); virtual void prepareForDerivation(); virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void collectDynamicVariables(SymbolType type_arg, set > &result) const; virtual void computeTemporaryTerms(map &reference_count, @@ -602,6 +607,7 @@ public: map &temp_terms_map, bool is_matlab, NodeTreeReference tr) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, @@ -689,6 +695,7 @@ public: map &temp_terms_map, bool is_matlab, NodeTreeReference tr) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, @@ -794,6 +801,7 @@ public: map &temp_terms_map, bool is_matlab, NodeTreeReference tr) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, @@ -864,6 +872,7 @@ protected: int getIndxInTefTerms(int the_symb_id, deriv_node_temp_terms_t &tef_terms) const throw (UnknownFunctionNameAndArgs); //! Helper function to write output arguments of any given external function void writeExternalFunctionArguments(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + void writeJsonExternalFunctionArguments(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; public: AbstractExternalFunctionNode(DataTree &datatree_arg, int symb_id_arg, const vector &arguments_arg); @@ -872,6 +881,7 @@ public: map &temp_terms_map, bool is_matlab, NodeTreeReference tr) const = 0; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; + virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; virtual bool containsExternalFunction() const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, @@ -938,6 +948,7 @@ public: map &temp_terms_map, bool is_matlab, NodeTreeReference tr) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; @@ -978,6 +989,7 @@ public: vector< vector > &v_temporary_terms, int equation) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; 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, @@ -1017,6 +1029,7 @@ public: vector< vector > &v_temporary_terms, int equation) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; 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, diff --git a/ExtendedPreprocessorTypes.hh b/ExtendedPreprocessorTypes.hh index e0a955f2..1388cafc 100644 --- a/ExtendedPreprocessorTypes.hh +++ b/ExtendedPreprocessorTypes.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2015 Dynare Team + * Copyright (C) 2014-2017 Dynare Team * * This file is part of Dynare. * @@ -38,4 +38,10 @@ enum LanguageOutputType julia, // outputs files for Julia python, // outputs files for Python (not yet implemented) (not yet implemented) }; + +enum JsonFileOutputType + { + file, // output JSON files to file + standardout, // output JSON files to stdout + }; #endif diff --git a/ModFile.cc b/ModFile.cc index 794f1e46..d2698873 100644 --- a/ModFile.cc +++ b/ModFile.cc @@ -1246,3 +1246,72 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output) jlOutputFile.close(); cout << "done" << endl; } + +void +ModFile::writeJsonOutput(const string &basename, JsonFileOutputType json_output_mode) const +{ + ostringstream output; + output << "{" << endl; + + symbol_table.writeJsonOutput(output); + dynamic_model.writeJsonOutput(output); + + if (!statements.empty()) + { + output << ",\"statements\": ["; + bool printed_statement = false; + for (vector::const_iterator it = statements.begin(); + it != statements.end();) + { + (*it)->writeJsonOutput(output); + + if (dynamic_cast(*it) != NULL || + dynamic_cast(*it) != NULL || + dynamic_cast(*it) != NULL || + dynamic_cast(*it) != NULL) + printed_statement = true; + + if (++it == statements.end()) + break; + + // tests to see if the next statement will be one for which we support writing JSON files + // to be deleted once we support all statements + if (printed_statement && + (dynamic_cast(*it) != NULL || + dynamic_cast(*it) != NULL || + dynamic_cast(*it) != NULL || + dynamic_cast(*it) != NULL)) + output << "," << endl; + } + output << "]" << endl; + } + + output << "}" << endl; + + if (json_output_mode == standardout) + cout << output.str(); + else + { + ofstream jsonOutputFile; + + if (basename.size()) + { + string fname(basename); + fname += ".json"; + jsonOutputFile.open(fname.c_str(), ios::out | ios::binary); + if (!jsonOutputFile.is_open()) + { + cerr << "ERROR: Can't open file " << fname << " for writing" << endl; + exit(EXIT_FAILURE); + } + } + else + { + cerr << "ERROR: Missing file name" << endl; + exit(EXIT_FAILURE); + } + + jsonOutputFile << output.str(); + jsonOutputFile.close(); + } +} diff --git a/ModFile.hh b/ModFile.hh index 6ed24d33..b83f984d 100644 --- a/ModFile.hh +++ b/ModFile.hh @@ -167,6 +167,11 @@ public: void writeModelCC(const string &basename) const; void computeChecksum(); + //! Write JSON representation of ModFile object + //! Initially created to enable Julia to work with .mod files + //! Potentially outputs ModFile after the various parts of processing (parsing, checkPass, transformPass, computingPass) + //! Allows user of other host language platforms (python, fortran, etc) to provide support for dynare .mod files + void writeJsonOutput(const string &basename, JsonFileOutputType json_output_mode) const; }; #endif // ! MOD_FILE_HH diff --git a/ModelTree.cc b/ModelTree.cc index 70db28e0..444aec2b 100644 --- a/ModelTree.cc +++ b/ModelTree.cc @@ -1919,3 +1919,38 @@ bool ModelTree::isNonstationary(int symb_id) const != nonstationary_symbols_map.end()); } +void +ModelTree::writeJsonModelEquations(ostream &output) const +{ + deriv_node_temp_terms_t tef_terms; + vector > eqtags; + output << endl << ",\"model\":[" << endl; + for (int eq = 0; eq < (int) equations.size(); eq++) + { + output << "{ \"equation\": \""; + equations[eq]->writeJsonOutput(output, oMatlabDynamicModel, temporary_terms, tef_terms); + output << "\", \"line\": " << equations_lineno[eq]; + for (vector > >::const_iterator it = equation_tags.begin(); + it != equation_tags.end(); it++) + if (it->first == eq) + eqtags.push_back(it->second); + + if (!eqtags.empty()) + { + output << ", \"tags\": {"; + int i = 0; + for (vector >:: const_iterator it = eqtags.begin(); it != eqtags.end(); it++, i++) + { + if (i != 0) + output << ", "; + output << "\"" << it->first << "\": \"" << it->second << "\""; + } + output << "}"; + eqtags.clear(); + } + output << "}"; + if (eq < (int) equations.size() - 1) + output << "," << endl; + } + output << endl << "]" << endl; +} diff --git a/ModelTree.hh b/ModelTree.hh index 9b28fce4..d74598d8 100644 --- a/ModelTree.hh +++ b/ModelTree.hh @@ -199,6 +199,8 @@ protected: void writeModelLocalVariables(ostream &output, ExprNodeOutputType output_type, deriv_node_temp_terms_t &tef_terms) const; //! Writes model equations void writeModelEquations(ostream &output, ExprNodeOutputType output_type) const; + //! Writes JSON model equations + void writeJsonModelEquations(ostream &output) const; //! Compiles model equations void compileModelEquations(ostream &code_file, unsigned int &instruction_number, const temporary_terms_t &tt, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic) const; diff --git a/NumericalInitialization.cc b/NumericalInitialization.cc index 3bbd803e..6e4dcd26 100644 --- a/NumericalInitialization.cc +++ b/NumericalInitialization.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -63,6 +63,14 @@ InitParamStatement::writeJuliaOutput(ostream &output, const string &basename) // output << symbol_table.getName(symb_id) << " = model_.params[ " << id << " ]" << endl; } +void +InitParamStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"param_init\", \"name\": \"" << symbol_table.getName(symb_id) << "\", " << "\"value\": "; + param_value->writeOutput(output); + output << "}"; +} + void InitParamStatement::writeCOutput(ostream &output, const string &basename) { @@ -165,6 +173,22 @@ InitOrEndValStatement::writeInitValues(ostream &output) const } } +void +InitOrEndValStatement::writeJsonInitValues(ostream &output) const +{ + int i = 0; + deriv_node_temp_terms_t tef_terms; + for (init_values_t::const_iterator it = init_values.begin(); + it != init_values.end(); it++, i++) + { + output << "{\"name\": \"" << symbol_table.getName(it->first) << "\", " << "\"value\": \""; + it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}"; + if (i < init_values.size() - 1) + output << ", "; + } +} + InitValStatement::InitValStatement(const init_values_t &init_values_arg, const SymbolTable &symbol_table_arg, const bool &all_values_required_arg) : @@ -210,6 +234,14 @@ InitValStatement::writeOutput(ostream &output, const string &basename, bool mini writeInitValues(output); } +void +InitValStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"init_val\", \"vals\": ["; + writeJsonInitValues(output); + output << "]}"; +} + void InitValStatement::writeOutputPostInit(ostream &output) const { @@ -267,6 +299,14 @@ EndValStatement::writeOutput(ostream &output, const string &basename, bool minim writeInitValues(output); } +void +EndValStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"end_val\", \"vals\": ["; + writeJsonInitValues(output); + output << "]}"; +} + HistValStatement::HistValStatement(const hist_values_t &hist_values_arg, const SymbolTable &symbol_table_arg, const bool &all_values_required_arg) : @@ -375,6 +415,26 @@ HistValStatement::writeOutput(ostream &output, const string &basename, bool mini } } +void +HistValStatement::writeJsonOutput(ostream &output) const +{ + int i = 0; + deriv_node_temp_terms_t tef_terms; + output << "{\"statementName\": \"hist_val\", \"vals\": ["; + for (hist_values_t::const_iterator it = hist_values.begin(); + it != hist_values.end(); it++) + { + output << "{ \"name\": \"" << symbol_table.getName(it->first.first) << "\"" + << ", \"lag\": " << it->first.second + << ", \"value\": \""; + it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}"; + if (i < hist_values.size() - 1) + output << ", "; + } + output << "]}"; +} + InitvalFileStatement::InitvalFileStatement(const string &filename_arg) : filename(filename_arg) { diff --git a/NumericalInitialization.hh b/NumericalInitialization.hh index 2e34677b..e48cb9ee 100644 --- a/NumericalInitialization.hh +++ b/NumericalInitialization.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -43,6 +43,7 @@ public: virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeJuliaOutput(ostream &output, const string &basename); virtual void writeCOutput(ostream &output, const string &basename); + virtual void writeJsonOutput(ostream &output) const; //! Fill eval context with parameter value void fillEvalContext(eval_context_t &eval_context) const; }; @@ -69,6 +70,7 @@ public: void fillEvalContext(eval_context_t &eval_context) const; protected: void writeInitValues(ostream &output) const; + void writeJsonInitValues(ostream &output) const; }; class InitValStatement : public InitOrEndValStatement @@ -79,6 +81,7 @@ public: const bool &all_values_required_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; //! Writes initializations for oo_.exo_simul and oo_.exo_det_simul void writeOutputPostInit(ostream &output) const; }; @@ -92,6 +95,7 @@ public: //! Workaround for trac ticket #35 virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class HistValStatement : public Statement @@ -114,6 +118,7 @@ public: //! Workaround for trac ticket #157 virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class InitvalFileStatement : public Statement diff --git a/Statement.cc b/Statement.cc index 887603b6..ee18bbb8 100644 --- a/Statement.cc +++ b/Statement.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006-2015 Dynare Team + * Copyright (C) 2006-2017 Dynare Team * * This file is part of Dynare. * @@ -82,6 +82,10 @@ void Statement::writeJuliaOutput(ostream &output, const string &basename) { } +void Statement::writeJsonOutput(ostream &output) const +{ +} + void Statement::computingPass() { diff --git a/Statement.hh b/Statement.hh index 311260b0..0db8a3c8 100644 --- a/Statement.hh +++ b/Statement.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2006-2015 Dynare Team + * Copyright (C) 2006-2017 Dynare Team * * This file is part of Dynare. * @@ -144,6 +144,7 @@ public: virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const = 0; virtual void writeCOutput(ostream &output, const string &basename); virtual void writeJuliaOutput(ostream &output, const string &basename); + virtual void writeJsonOutput(ostream &output) const; }; class NativeStatement : public Statement diff --git a/SymbolTable.cc b/SymbolTable.cc index 17b63e95..84deb2a5 100644 --- a/SymbolTable.cc +++ b/SymbolTable.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -21,6 +21,7 @@ #include #include #include +#include #include "SymbolTable.hh" @@ -138,6 +139,17 @@ SymbolTable::freeze() throw (FrozenException) } } +void +SymbolTable::unfreeze() +{ + frozen = false; + endo_ids.clear(); + exo_ids.clear(); + exo_det_ids.clear(); + param_ids.clear(); + type_specific_ids.clear(); +} + void SymbolTable::changeType(int id, SymbolType newtype) throw (UnknownSymbolIDException, FrozenException) { @@ -950,3 +962,74 @@ SymbolTable::writeJuliaOutput(ostream &output) const throw (NotYetFrozenExceptio output << " ]" << endl; } } + +void +SymbolTable::writeJsonOutput(ostream &output) const +{/* + vector endos, exos, exo_dets, params; + for (int i = 0; i < size; i++) + { + switch (getType(i)) + { + case eEndogenous: + endos.push_back(i); + break; + case eExogenous: + exos.push_back(i); + break; + case eExogenousDet: + exo_dets.push_back(i); + break; + case eParameter: + params.push_back(i); + break; + default: + break; + } + } + */ + + if (!endo_ids.empty()) + { + output << "\"endogenous\":"; + writeJsonVarVector(output, endo_ids); + output << endl; + } + + if (!exo_ids.empty()) + { + output << ",\"exogenous\":"; + writeJsonVarVector(output, exo_ids); + output << endl; + } + + if (!exo_det_ids.empty()) + { + output << ",\"exogenous_deterministic\":"; + writeJsonVarVector(output, exo_det_ids); + output << endl; + } + + if (!param_ids.empty()) + { + output << ",\"parameters\":"; + writeJsonVarVector(output, param_ids); + cout << endl; + } +} + +void +SymbolTable::writeJsonVarVector(ostream &output, const vector &varvec) const +{ + output << "["; + for (int i = 0; i < varvec.size(); i++) + { + output << endl << "{" + << "\"name\":\" " << getName(varvec[i]) << "\", " + << "\"texName\":\" " << boost::replace_all_copy(getTeXName(varvec[i]), "\\", "\\\\") << "\", " + << "\"longName\":\" " << boost::replace_all_copy(getLongName(varvec[i]), "\\", "\\\\") << "\"}"; + if (i < varvec.size() - 1) + output << ", "; + } + output << endl << "]"; +} diff --git a/SymbolTable.hh b/SymbolTable.hh index c99dd462..370c5e77 100644 --- a/SymbolTable.hh +++ b/SymbolTable.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -192,7 +192,8 @@ private: int addLagAuxiliaryVarInternal(bool endo, int orig_symb_id, int orig_lead_lag, expr_t arg) throw (FrozenException); //! Factorized code for adding aux lead variables int addLeadAuxiliaryVarInternal(bool endo, int index, expr_t arg) throw (FrozenException); - + //! Factorized code for Json writing + void writeJsonVarVector(ostream &output, const vector &varvec) const; public: //! Add a symbol /*! Returns the symbol ID */ @@ -274,6 +275,9 @@ public: int getID(SymbolType type, int tsid) const throw (UnknownTypeSpecificIDException, NotYetFrozenException); //! Freeze symbol table void freeze() throw (FrozenException); + //! unreeze symbol table + //! Used after having written JSON files + void unfreeze(); //! Change the type of a symbol void changeType(int id, SymbolType newtype) throw (UnknownSymbolIDException, FrozenException); //! Get type specific ID (by symbol ID) @@ -294,6 +298,8 @@ public: inline int orig_endo_nbr() const throw (NotYetFrozenException); //! Write output of this class void writeOutput(ostream &output) const throw (NotYetFrozenException); + //! Write JSON Output + void writeJsonOutput(ostream &output) const; //! Write Julia output of this class void writeJuliaOutput(ostream &output) const throw (NotYetFrozenException); //! Write C output of this class From 96b35ff078c0ea59b85c682ca5f162d7f4d289ea Mon Sep 17 00:00:00 2001 From: Winant Pablo Date: Sun, 12 Feb 2017 12:54:58 +0100 Subject: [PATCH 02/18] FIX: JSON remove space before symbols + quote values --- NumericalInitialization.cc | 4 ++-- SymbolTable.cc | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/NumericalInitialization.cc b/NumericalInitialization.cc index 6e4dcd26..c9ebe608 100644 --- a/NumericalInitialization.cc +++ b/NumericalInitialization.cc @@ -66,9 +66,9 @@ InitParamStatement::writeJuliaOutput(ostream &output, const string &basename) void InitParamStatement::writeJsonOutput(ostream &output) const { - output << "{\"statementName\": \"param_init\", \"name\": \"" << symbol_table.getName(symb_id) << "\", " << "\"value\": "; + output << "{\"statementName\": \"param_init\", \"name\": \"" << symbol_table.getName(symb_id) << "\", " << "\"value\": \""; param_value->writeOutput(output); - output << "}"; + output << "\"}"; } void diff --git a/SymbolTable.cc b/SymbolTable.cc index 84deb2a5..04b46de0 100644 --- a/SymbolTable.cc +++ b/SymbolTable.cc @@ -1025,9 +1025,9 @@ SymbolTable::writeJsonVarVector(ostream &output, const vector &varvec) cons for (int i = 0; i < varvec.size(); i++) { output << endl << "{" - << "\"name\":\" " << getName(varvec[i]) << "\", " - << "\"texName\":\" " << boost::replace_all_copy(getTeXName(varvec[i]), "\\", "\\\\") << "\", " - << "\"longName\":\" " << boost::replace_all_copy(getLongName(varvec[i]), "\\", "\\\\") << "\"}"; + << "\"name\":\"" << getName(varvec[i]) << "\", " + << "\"texName\":\"" << boost::replace_all_copy(getTeXName(varvec[i]), "\\", "\\\\") << "\", " + << "\"longName\":\"" << boost::replace_all_copy(getLongName(varvec[i]), "\\", "\\\\") << "\"}"; if (i < varvec.size() - 1) output << ", "; } From 4486df9f8f3ec153f983a8ffb12b9c0eb65914ea Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Mon, 13 Feb 2017 12:33:12 +0100 Subject: [PATCH 03/18] preprocessor: bug fix for writing of parameter values. Closes #1394 --- NumericalInitialization.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/NumericalInitialization.cc b/NumericalInitialization.cc index c9ebe608..057b59d6 100644 --- a/NumericalInitialization.cc +++ b/NumericalInitialization.cc @@ -66,8 +66,9 @@ InitParamStatement::writeJuliaOutput(ostream &output, const string &basename) void InitParamStatement::writeJsonOutput(ostream &output) const { + deriv_node_temp_terms_t tef_terms; output << "{\"statementName\": \"param_init\", \"name\": \"" << symbol_table.getName(symb_id) << "\", " << "\"value\": \""; - param_value->writeOutput(output); + param_value->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); output << "\"}"; } From 58951045d96e57fe78956bbb6615823ce497497c Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Wed, 8 Feb 2017 18:29:57 +0100 Subject: [PATCH 04/18] preprocessor: JSON output for statements, #1387 --- ComputingTasks.cc | 1156 +++++++++++++++++++++++++++++++++++- ComputingTasks.hh | 77 ++- ModFile.cc | 23 +- NumericalInitialization.cc | 79 ++- NumericalInitialization.hh | 5 + ParsingDriver.cc | 2 +- Shocks.cc | 143 ++++- Shocks.hh | 8 +- Statement.cc | 121 ++++ Statement.hh | 4 + SymbolList.cc | 16 +- SymbolList.hh | 4 +- 12 files changed, 1601 insertions(+), 37 deletions(-) diff --git a/ComputingTasks.cc b/ComputingTasks.cc index f12c4086..db2ac624 100644 --- a/ComputingTasks.cc +++ b/ComputingTasks.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -50,6 +50,18 @@ SteadyStatement::writeOutput(ostream &output, const string &basename, bool minim output << "steady;" << endl; } +void +SteadyStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"steady\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + CheckStatement::CheckStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -68,6 +80,18 @@ CheckStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidatio mod_file_struct.check_present = true; } +void +CheckStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"check\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + ModelInfoStatement::ModelInfoStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -86,6 +110,18 @@ ModelInfoStatement::writeOutput(ostream &output, const string &basename, bool mi output << "model_info();" << endl; } +void +ModelInfoStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"model_info\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + SimulStatement::SimulStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -105,6 +141,18 @@ SimulStatement::writeOutput(ostream &output, const string &basename, bool minima << "perfect_foresight_solver;" << endl; } +void +SimulStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"simul\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + PerfectForesightSetupStatement::PerfectForesightSetupStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -117,6 +165,18 @@ PerfectForesightSetupStatement::writeOutput(ostream &output, const string &basen output << "perfect_foresight_setup;" << endl; } +void +PerfectForesightSetupStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"perfect_foresight_setup\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + PerfectForesightSolverStatement::PerfectForesightSolverStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -138,6 +198,18 @@ PerfectForesightSolverStatement::writeOutput(ostream &output, const string &base output << "perfect_foresight_solver;" << endl; } +void +PerfectForesightSolverStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"perfect_foresight_solver\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + PriorPosteriorFunctionStatement::PriorPosteriorFunctionStatement(const bool prior_func_arg, const OptionsList &options_list_arg) : prior_func(prior_func_arg), @@ -171,6 +243,21 @@ PriorPosteriorFunctionStatement::writeOutput(ostream &output, const string &base << "'" << type << "');" << endl; } +void +PriorPosteriorFunctionStatement::writeJsonOutput(ostream &output) const +{ + string type = "posterior"; + if (prior_func) + type = "prior"; + output << "{\"statementName\": \"prior_posterior_function\", \"type\": \"" << type << "\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + StochSimulStatement::StochSimulStatement(const SymbolList &symbol_list_arg, const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), @@ -227,6 +314,23 @@ StochSimulStatement::writeOutput(ostream &output, const string &basename, bool m output << "info = stoch_simul(var_list_);" << endl; } +void +StochSimulStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"stoch_simul\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + ForecastStatement::ForecastStatement(const SymbolList &symbol_list_arg, const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), @@ -242,6 +346,23 @@ ForecastStatement::writeOutput(ostream &output, const string &basename, bool min output << "[oo_.forecast,info] = dyn_forecast(var_list_,M_,options_,oo_,'simul');" << endl; } +void +ForecastStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"forecast\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + RamseyModelStatement::RamseyModelStatement(const SymbolList &symbol_list_arg, const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), @@ -299,7 +420,20 @@ RamseyModelStatement::writeOutput(ostream &output, const string &basename, bool options_list.writeOutput(output); } -RamseyConstraintsStatement::RamseyConstraintsStatement(const constraints_t &constraints_arg) : +void +RamseyModelStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"ramsey_model\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + +RamseyConstraintsStatement::RamseyConstraintsStatement(const SymbolTable &symbol_table_arg, const constraints_t &constraints_arg) : + symbol_table(symbol_table_arg), constraints(constraints_arg) { } @@ -345,6 +479,43 @@ RamseyConstraintsStatement::writeOutput(ostream &output, const string &basename, output << "};" << endl; } +void +RamseyConstraintsStatement::writeJsonOutput(ostream &output) const +{ + deriv_node_temp_terms_t tef_terms; + output << "{\"statementName\": \"ramsey_constraints\"" + << ", \"ramsey_model_constraints\": [" << endl; + for (RamseyConstraintsStatement::constraints_t::const_iterator it = constraints.begin(); it != constraints.end(); ++it) + { + if (it != constraints.begin()) + output << ", "; + output << "{\"constraint\": \"" << symbol_table.getName(it->endo) << " "; + switch(it->code) + { + case oLess: + output << '<'; + break; + case oGreater: + output << '>'; + break; + case oLessEqual: + output << "<="; + break; + case oGreaterEqual: + output << ">="; + break; + default: + cerr << "Ramsey constraints: this shouldn't happen." << endl; + exit(1); + } + output << " "; + it->expression->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}" << endl; + } + output << "]" << endl; + output << "}"; +} + // Statement * // RamseyConstraintsStatement::cloneAndReindexSymbIds(DataTree &dynamic_datatree, SymbolTable &orig_symbol_table) // { @@ -489,6 +660,28 @@ RamseyPolicyStatement::writeOutput(ostream &output, const string &basename, bool << "ramsey_policy(var_list_);" << endl; } +void +RamseyPolicyStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"ramsey_policy\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + output << ", "; + } + output << "\"ramsey_policy_list\": ["; + for (vector::const_iterator it = ramsey_policy_list.begin(); + it != ramsey_policy_list.end(); ++it) + { + if (it != ramsey_policy_list.begin()) + output << ","; + output << "\"" << *it << "\""; + } + output << "]" + << "}"; +} + DiscretionaryPolicyStatement::DiscretionaryPolicyStatement(const SymbolList &symbol_list_arg, const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), @@ -549,6 +742,23 @@ DiscretionaryPolicyStatement::writeOutput(ostream &output, const string &basenam output << "discretionary_policy(var_list_);" << endl; } +void +DiscretionaryPolicyStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"discretionary_policy\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + EstimationStatement::EstimationStatement(const SymbolList &symbol_list_arg, const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), @@ -654,6 +864,23 @@ EstimationStatement::writeOutput(ostream &output, const string &basename, bool m output << "oo_recursive_=dynare_estimation(var_list_);" << endl; } +void +EstimationStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"estimation\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + DynareSensitivityStatement::DynareSensitivityStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -690,6 +917,18 @@ DynareSensitivityStatement::writeOutput(ostream &output, const string &basename, output << "dynare_sensitivity(options_gsa);" << endl; } +void +DynareSensitivityStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"dynare_sensitivity\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + RplotStatement::RplotStatement(const SymbolList &symbol_list_arg) : symbol_list(symbol_list_arg) { @@ -702,6 +941,18 @@ RplotStatement::writeOutput(ostream &output, const string &basename, bool minima output << "rplot(var_list_);" << endl; } +void +RplotStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"rplot\""; + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + UnitRootVarsStatement::UnitRootVarsStatement(void) { } @@ -713,6 +964,14 @@ UnitRootVarsStatement::writeOutput(ostream &output, const string &basename, bool << "options_.steadystate.nocheck = 1;" << endl; } +void +UnitRootVarsStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"unit_root_vars\", " + << "\"diffuse_filter\": 1, " + << "\"steady_state.nocheck\": 1}"; +} + PeriodsStatement::PeriodsStatement(int periods_arg) : periods(periods_arg) { } @@ -723,6 +982,13 @@ PeriodsStatement::writeOutput(ostream &output, const string &basename, bool mini output << "options_.periods = " << periods << ";" << endl; } +void +PeriodsStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"periods\", " + << "\"periods\": " << periods << "}"; +} + DsampleStatement::DsampleStatement(int val1_arg) : val1(val1_arg), val2(-1) { } @@ -740,6 +1006,14 @@ DsampleStatement::writeOutput(ostream &output, const string &basename, bool mini output << "dsample(" << val1 << ", " << val2 << ");" << endl; } +void +DsampleStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"dsample\", " + << "\"value1\": " << val1 << ", " + << "\"value2\": " << val2 << "}"; +} + EstimatedParamsStatement::EstimatedParamsStatement(const vector &estim_params_list_arg, const SymbolTable &symbol_table_arg) : estim_params_list(estim_params_list_arg), @@ -870,6 +1144,55 @@ EstimatedParamsStatement::writeOutput(ostream &output, const string &basename, b } } +void +EstimatedParamsStatement::writeJsonOutput(ostream &output) const +{ + deriv_node_temp_terms_t tef_terms; + output << "{\"statementName\": \"estimated_params\", " + << "\"params\": ["; + for (vector::const_iterator it = estim_params_list.begin(); it != estim_params_list.end(); it++) + { + if (it != estim_params_list.begin()) + output << ", "; + output << "{"; + switch (it->type) + { + case 1: + output << "\"var\": \"" << it->name << "\""; + break; + case 2: + output << "\"param\": \"" << it->name << "\""; + break; + case 3: + output << "\"var1\": \"" << it->name << "\"," + << "\"var2\": \"" << it->name2 << "\""; + break; + } + + output << ", \"init_val\": \""; + it->init_val->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\", \"lower_bound\": \""; + it->low_bound->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\", \"upper_bound\": \""; + it->up_bound->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\", \"prior_distribution\": " + << it->prior + << ", \"mean\": \""; + it->mean->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\", \"std\": \""; + it->std->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\", \"p3\": \""; + it->p3->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\", \"p4\": \""; + it->p4->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\", \"jscale\": \""; + it->jscale->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}" << endl; + } + output << "]" + << "}"; +} + EstimatedParamsInitStatement::EstimatedParamsInitStatement(const vector &estim_params_list_arg, const SymbolTable &symbol_table_arg, const bool use_calibration_arg) : @@ -945,6 +1268,42 @@ EstimatedParamsInitStatement::writeOutput(ostream &output, const string &basenam } } +void +EstimatedParamsInitStatement::writeJsonOutput(ostream &output) const +{ + deriv_node_temp_terms_t tef_terms; + output << "{\"statementName\": \"estimated_params_init\""; + + if (use_calibration) + output << ", \"use_calibration_initialization\": 1"; + + output << ", \"params\": ["; + for (vector::const_iterator it = estim_params_list.begin(); it != estim_params_list.end(); it++) + { + if (it != estim_params_list.begin()) + output << ", "; + output << "{"; + switch (it->type) + { + case 1: + output << "\"var\": \"" << it->name << "\""; + break; + case 2: + output << "\"param\": \"" << it->name << "\""; + break; + case 3: + output << "\"var1\": \"" << it->name << "\"," + << "\"var2\": \"" << it->name2 << "\""; + break; + } + output << ", \"init_val\": \""; + it->init_val->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}"; + } + output << "]" + << "}"; +} + EstimatedParamsBoundsStatement::EstimatedParamsBoundsStatement(const vector &estim_params_list_arg, const SymbolTable &symbol_table_arg) : estim_params_list(estim_params_list_arg), @@ -1033,6 +1392,40 @@ EstimatedParamsBoundsStatement::writeOutput(ostream &output, const string &basen } } +void +EstimatedParamsBoundsStatement::writeJsonOutput(ostream &output) const +{ + deriv_node_temp_terms_t tef_terms; + output << "{\"statementName\": \"estimated_params_bounds\", " + << "\"params\": ["; + + for (vector::const_iterator it = estim_params_list.begin(); it != estim_params_list.end(); it++) + { + if (it != estim_params_list.begin()) + output << ", "; + output << "{"; + switch (it->type) + { + case 1: + output << "\"var\": \"" << it->name << "\""; + case 2: + output << "\"param\": \"" << it->name << "\""; + break; + case 3: + output << "\"var1\": \"" << it->name << "\"," + << "\"var2\": \"" << it->name2 << "\""; + break; + } + output << ", \"lower_bound\": "; + it->low_bound->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << ", \"upper_bound\": "; + it->up_bound->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "}"; + } + output << "]" + << "}"; +} + ObservationTrendsStatement::ObservationTrendsStatement(const trend_elements_t &trend_elements_arg, const SymbolTable &symbol_table_arg) : trend_elements(trend_elements_arg), @@ -1062,6 +1455,32 @@ ObservationTrendsStatement::writeOutput(ostream &output, const string &basename, } } +void +ObservationTrendsStatement::writeJsonOutput(ostream &output) const +{ + deriv_node_temp_terms_t tef_terms; + output << "{\"statementName\": \"observation_trends\", " + << "\"trends\" : {"; + bool printed = false; + for (trend_elements_t::const_iterator it = trend_elements.begin(); + it != trend_elements.end(); it++) + { + if (symbol_table.getType(it->first) == eEndogenous) + { + if (printed) + output << ", "; + output << "\"" << it->first << "\": \""; + it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"" << endl; + printed = true; + } + else + cerr << "Warning : Non-variable symbol used in observation_trends: " << it->first << endl; + } + output << "}" + << "}"; +} + OsrParamsStatement::OsrParamsStatement(const SymbolList &symbol_list_arg, const SymbolTable &symbol_table_arg) : symbol_list(symbol_list_arg), symbol_table(symbol_table_arg) @@ -1088,6 +1507,18 @@ OsrParamsStatement::writeOutput(ostream &output, const string &basename, bool mi output << "M_.osr.param_indices(" << ++i <<") = " << symbol_table.getTypeSpecificID(*it) + 1 << ";" << endl; } +void +OsrParamsStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"osr_params\""; + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + OsrStatement::OsrStatement(const SymbolList &symbol_list_arg, const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), @@ -1127,6 +1558,29 @@ OsrParamsBoundsStatement::writeOutput(ostream &output, const string &basename, b } } +void +OsrParamsBoundsStatement::writeJsonOutput(ostream &output) const +{ + deriv_node_temp_terms_t tef_terms; + output << "{\"statementName\": \"osr_params_bounds\"" + << ", \"bounds\": ["; + for (vector::const_iterator it = osr_params_list.begin(); + it != osr_params_list.end(); it++) + { + if (it != osr_params_list.begin()) + output << ", "; + output << "{\"parameter\": \"" << it->name << "\"," + << "\"bounds\": [\""; + it->low_bound->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\", \""; + it->up_bound->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"]" + << "}"; + } + output << "]" + << "}"; +} + void OsrStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) { @@ -1164,6 +1618,23 @@ OsrStatement::writeOutput(ostream &output, const string &basename, bool minimal_ output << "oo_.osr = osr(var_list_,M_.osr.param_names,M_.osr.variable_indices,M_.osr.variable_weights);" << endl; } +void +OsrStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"osr\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + OptimWeightsStatement::OptimWeightsStatement(const var_weights_t &var_weights_arg, const covar_weights_t &covar_weights_arg, const SymbolTable &symbol_table_arg) : @@ -1215,6 +1686,38 @@ OptimWeightsStatement::writeOutput(ostream &output, const string &basename, bool } } +void +OptimWeightsStatement::writeJsonOutput(ostream &output) const +{ + deriv_node_temp_terms_t tef_terms; + output << "{\"statementName\": \"optim_weights\", " + << "\"weights\": ["; + for (var_weights_t::const_iterator it = var_weights.begin(); + it != var_weights.end(); it++) + { + if (it != var_weights.begin()) + output << ", "; + output << "{\"name\": \"" << it->first << "\"" + << ", \"value\": \""; + it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}"; + } + + for (covar_weights_t::const_iterator it = covar_weights.begin(); + it != covar_weights.end(); it++) + { + if (it != covar_weights.begin() || !var_weights.empty()) + output << ", "; + output << "{\"name1\": \"" << it->first.first << "\"" + << ", \"name2\": \"" << it->first.second << "\"" + << ", \"value\": \""; + it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}"; + } + output << "]" + << "}"; +} + DynaSaveStatement::DynaSaveStatement(const SymbolList &symbol_list_arg, const string &filename_arg) : symbol_list(symbol_list_arg), @@ -1230,6 +1733,19 @@ DynaSaveStatement::writeOutput(ostream &output, const string &basename, bool min << "',var_list_);" << endl; } +void +DynaSaveStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"dynasave\", " + << "\"filename\": \"" << filename << "\""; + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + DynaTypeStatement::DynaTypeStatement(const SymbolList &symbol_list_arg, const string &filename_arg) : symbol_list(symbol_list_arg), @@ -1245,6 +1761,19 @@ DynaTypeStatement::writeOutput(ostream &output, const string &basename, bool min << "',var_list_);" << endl; } +void +DynaTypeStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"dynatype\", " + << "\"filename\": \"" << filename << "\""; + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + ModelComparisonStatement::ModelComparisonStatement(const filename_list_t &filename_list_arg, const OptionsList &options_list_arg) : filename_list(filename_list_arg), @@ -1269,6 +1798,34 @@ ModelComparisonStatement::writeOutput(ostream &output, const string &basename, b output << "oo_ = model_comparison(ModelNames_,ModelPriors_,oo_,options_,M_.fname);" << endl; } +void +ModelComparisonStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"model_comparison\""; + if (!filename_list.empty()) + output << ", \"filename_list\": {"; + + for (filename_list_t::const_iterator it = filename_list.begin(); + it != filename_list.end(); it++) + { + if (it != filename_list.begin()) + output << ", "; + output << "\"name\": \"" << it->first << "\"" + << "\"prior\": \"" << it->second << "\""; + } + + if (!filename_list.empty()) + output << "}"; + + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + + output << "}"; +} + PlannerObjectiveStatement::PlannerObjectiveStatement(StaticModel *model_tree_arg) : model_tree(model_tree_arg) { @@ -1311,6 +1868,14 @@ PlannerObjectiveStatement::writeOutput(ostream &output, const string &basename, model_tree->writeStaticFile(basename + "_objective", false, false, false, false); } +void +PlannerObjectiveStatement::writeJsonOutput(ostream &output) const +{ + cerr << "ERROR: writeJsonOutput not yet implemented for Planner Objective Statement" << endl; + exit(EXIT_FAILURE); + // model_tree->writeStaticJsonFile(basename + "_objective", false, false, false, false); +} + BVARDensityStatement::BVARDensityStatement(int maxnlags_arg, const OptionsList &options_list_arg) : maxnlags(maxnlags_arg), options_list(options_list_arg) @@ -1330,6 +1895,18 @@ BVARDensityStatement::writeOutput(ostream &output, const string &basename, bool output << "bvar_density(" << maxnlags << ");" << endl; } +void +BVARDensityStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"bvar_density\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + BVARForecastStatement::BVARForecastStatement(int nlags_arg, const OptionsList &options_list_arg) : nlags(nlags_arg), options_list(options_list_arg) @@ -1349,6 +1926,18 @@ BVARForecastStatement::writeOutput(ostream &output, const string &basename, bool output << "bvar_forecast(" << nlags << ");" << endl; } +void +BVARForecastStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"bvar_forecast\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + SBVARStatement::SBVARStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -1367,6 +1956,18 @@ SBVARStatement::writeOutput(ostream &output, const string &basename, bool minima output << "sbvar(M_,options_);" << endl; } +void +SBVARStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"sbvar\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + MSSBVAREstimationStatement::MSSBVAREstimationStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -1396,6 +1997,18 @@ MSSBVAREstimationStatement::writeOutput(ostream &output, const string &basename, output << "[options_, oo_] = ms_estimation(M_, options_, oo_);" << endl; } +void +MSSBVAREstimationStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"ms_sbvar_estimation\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + MSSBVARSimulationStatement::MSSBVARSimulationStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -1424,6 +2037,18 @@ MSSBVARSimulationStatement::writeOutput(ostream &output, const string &basename, output << "[options_, oo_] = ms_simulation(M_, options_, oo_);" << endl; } +void +MSSBVARSimulationStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"ms_sbvar_simulation\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + MSSBVARComputeMDDStatement::MSSBVARComputeMDDStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -1443,6 +2068,18 @@ MSSBVARComputeMDDStatement::writeOutput(ostream &output, const string &basename, output << "[options_, oo_] = ms_compute_mdd(M_, options_, oo_);" << endl; } +void +MSSBVARComputeMDDStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"ms_sbvar_compute_mdd\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + MSSBVARComputeProbabilitiesStatement::MSSBVARComputeProbabilitiesStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -1470,6 +2107,18 @@ MSSBVARComputeProbabilitiesStatement::writeOutput(ostream &output, const string output << "[options_, oo_] = ms_compute_probabilities(M_, options_, oo_);" << endl; } +void +MSSBVARComputeProbabilitiesStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"ms_sbvar_compute_probabilities\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + MSSBVARIrfStatement::MSSBVARIrfStatement(const SymbolList &symbol_list_arg, const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), @@ -1517,6 +2166,23 @@ MSSBVARIrfStatement::writeOutput(ostream &output, const string &basename, bool m output << "[options_, oo_] = ms_irf(var_list_,M_, options_, oo_);" << endl; } +void +MSSBVARIrfStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"ms_sbvar_irf\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + MSSBVARForecastStatement::MSSBVARForecastStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -1543,6 +2209,18 @@ MSSBVARForecastStatement::writeOutput(ostream &output, const string &basename, b output << "[options_, oo_] = ms_forecast(M_, options_, oo_);" << endl; } +void +MSSBVARForecastStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"ms_sbvar_forecast\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + MSSBVARVarianceDecompositionStatement::MSSBVARVarianceDecompositionStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -1587,6 +2265,18 @@ MSSBVARVarianceDecompositionStatement::writeOutput(ostream &output, const string output << "[options_, oo_] = ms_variance_decomposition(M_, options_, oo_);" << endl; } +void +MSSBVARVarianceDecompositionStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"ms_sbvar_variance_decomposition\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + IdentificationStatement::IdentificationStatement(const OptionsList &options_list_arg) { options_list = options_list_arg; @@ -1626,6 +2316,18 @@ IdentificationStatement::writeOutput(ostream &output, const string &basename, bo output << "dynare_identification(options_ident);" << endl; } +void +IdentificationStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"identification\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + WriteLatexDynamicModelStatement::WriteLatexDynamicModelStatement(const DynamicModel &dynamic_model_arg) : dynamic_model(dynamic_model_arg) { @@ -1637,6 +2339,12 @@ WriteLatexDynamicModelStatement::writeOutput(ostream &output, const string &base dynamic_model.writeLatexFile(basename); } +void +WriteLatexDynamicModelStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"write_latex_dynamic_model\"}"; +} + WriteLatexStaticModelStatement::WriteLatexStaticModelStatement(const StaticModel &static_model_arg) : static_model(static_model_arg) { @@ -1648,6 +2356,12 @@ WriteLatexStaticModelStatement::writeOutput(ostream &output, const string &basen static_model.writeLatexFile(basename); } +void +WriteLatexStaticModelStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"write_latex_static_model\"}"; +} + WriteLatexOriginalModelStatement::WriteLatexOriginalModelStatement(const DynamicModel &original_model_arg) : original_model(original_model_arg) { @@ -1659,6 +2373,12 @@ WriteLatexOriginalModelStatement::writeOutput(ostream &output, const string &bas original_model.writeLatexOriginalFile(basename); } +void +WriteLatexOriginalModelStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"write_latex_original_model\"}"; +} + ShockDecompositionStatement::ShockDecompositionStatement(const SymbolList &symbol_list_arg, const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), @@ -1674,6 +2394,23 @@ ShockDecompositionStatement::writeOutput(ostream &output, const string &basename output << "oo_ = shock_decomposition(M_,oo_,options_,var_list_,bayestopt_,estim_params_);" << endl; } +void +ShockDecompositionStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"shock_decomposition\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + ConditionalForecastStatement::ConditionalForecastStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -1686,6 +2423,18 @@ ConditionalForecastStatement::writeOutput(ostream &output, const string &basenam output << "imcforecast(constrained_paths_, constrained_vars_, options_cond_fcst_);" << endl; } +void +ConditionalForecastStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"conditional_forecast\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + PlotConditionalForecastStatement::PlotConditionalForecastStatement(int periods_arg, const SymbolList &symbol_list_arg) : periods(periods_arg), symbol_list(symbol_list_arg) @@ -1702,6 +2451,19 @@ PlotConditionalForecastStatement::writeOutput(ostream &output, const string &bas output << "plot_icforecast(var_list_, " << periods << ",options_);" << endl; } +void +PlotConditionalForecastStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"plot_conditional_forecast\", " + << "\"periods\": " << periods; + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + SvarIdentificationStatement::SvarIdentificationStatement(const svar_identification_restrictions_t &restrictions_arg, const bool &upper_cholesky_present_arg, const bool &lower_cholesky_present_arg, @@ -1812,6 +2574,42 @@ SvarIdentificationStatement::writeOutput(ostream &output, const string &basename } } +void +SvarIdentificationStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"svar_identification\""; + + if (upper_cholesky_present) + output << ", \"upper_cholesky\": 1"; + + if (lower_cholesky_present) + output << ", \"lower_cholesky\": 1"; + + if (constants_exclusion_present) + output << ", \"constants_exclusion\": 1"; + + if (!upper_cholesky_present && !lower_cholesky_present) + { + output << ", \"nlags\": " << getMaxLag() + << ", \"restrictions\": ["; + + for (svar_identification_restrictions_t::const_iterator it = restrictions.begin(); it != restrictions.end(); it++) + { + if (it != restrictions.begin()) + output << ", "; + output << "{" + << "\"equation_number\": " << it->equation << ", " + << "\"restriction_number\": " << it->restriction_nbr << ", " + << "\"variable\": " << symbol_table.getName(it->variable) << ", " + << "\"expression\": \""; + it->value->writeOutput(output); + output << "\"}"; + } + output << "]"; + } + output << "}"; +} + MarkovSwitchingStatement::MarkovSwitchingStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -2051,6 +2849,33 @@ MarkovSwitchingStatement::writeCOutput(ostream &output, const string &basename) << " chain, number_of_regimes, number_of_lags, number_of_lags_was_passed, parameters, duration, restriction_map));" << endl; } +void +MarkovSwitchingStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"markov_switching\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + + if (!restriction_map.empty()) + output << ", {"; + for (map, double >::const_iterator it = restriction_map.begin(); + it != restriction_map.end(); it++) + { + if (it != restriction_map.begin()) + output << ", "; + output << "{\"current_period_regime\": " << it->first.first + << ", \"next_period_regime\": " << it->first.second + << ", \"transition_probability\": "<< it->second + << "}"; + } + if (!restriction_map.empty()) + output << "}"; + output << "}"; +} + SvarStatement::SvarStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -2115,6 +2940,18 @@ SvarStatement::writeOutput(ostream &output, const string &basename, bool minimal output << "'ALL';" << endl; } +void +SvarStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"svar\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + SvarGlobalIdentificationCheckStatement::SvarGlobalIdentificationCheckStatement(void) { } @@ -2125,6 +2962,12 @@ SvarGlobalIdentificationCheckStatement::writeOutput(ostream &output, const strin output << "svar_global_identification_check(options_);" << std::endl; } +void +SvarGlobalIdentificationCheckStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"svar_global_identification\"}"; +} + SetTimeStatement::SetTimeStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -2136,6 +2979,18 @@ SetTimeStatement::writeOutput(ostream &output, const string &basename, bool mini options_list.writeOutput(output); } +void +SetTimeStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"set_time\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + EstimationDataStatement::EstimationDataStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -2175,6 +3030,18 @@ EstimationDataStatement::writeOutput(ostream &output, const string &basename, bo options_list.writeOutput(output, "options_.dataset"); } +void +EstimationDataStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"estimation_data\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + SubsamplesStatement::SubsamplesStatement(const string &name1_arg, const string &name2_arg, const subsample_declaration_map_t subsample_declaration_map_arg, @@ -2248,6 +3115,30 @@ SubsamplesStatement::writeOutput(ostream &output, const string &basename, bool m << endl; } +void +SubsamplesStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"subsamples\"" + << ", \"name1\": \"" << name1 << "\""; + if (!name2.empty()) + output << ", \"name2\": \"" << name2 << "\""; + + output << ", \"declarations\": {"; + for (subsample_declaration_map_t::const_iterator it = subsample_declaration_map.begin(); + it != subsample_declaration_map.end(); it++) + { + if (it != subsample_declaration_map.begin()) + output << ","; + output << "{" + << "\"range_index\": \"" << it->first << "\"" + << ", \"date1\": \"" << it->second.first << "\"" + << ", \"date2\": \"" << it->second.second << "\"" + << "}"; + } + output << "}" + << "}"; +} + SubsamplesEqualStatement::SubsamplesEqualStatement(const string &to_name1_arg, const string &to_name2_arg, const string &from_name1_arg, @@ -2310,6 +3201,19 @@ SubsamplesEqualStatement::writeOutput(ostream &output, const string &basename, b << endl; } +void +SubsamplesEqualStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"subsamples_equal\"" + << ", \"to_name1\": \"" << to_name1 << "\""; + if (!to_name2.empty()) + output << ", \"to_name2\": \"" << to_name2 << "\""; + output << ", \"from_name1\": \"" << from_name1 << "\""; + if (!from_name2.empty()) + output << ", \"from_name2\": \"" << from_name2 << "\""; + output << "}"; +} + JointPriorStatement::JointPriorStatement(const vector joint_parameters_arg, const PriorDistributions &prior_shape_arg, const OptionsList &options_list_arg) : @@ -2416,6 +3320,58 @@ JointPriorStatement::writeOutputHelper(ostream &output, const string &field, con output << "};" << endl; } +void +JointPriorStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"joint_prior\"" + << ", \"key\": ["; + for (vector::const_iterator it = joint_parameters.begin() ; it != joint_parameters.end(); it++) + { + if (it != joint_parameters.begin()) + output << ", "; + output << "\"" << *it << "\""; + } + output << "]"; + + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + + output << ", \"shape\": "; + switch(prior_shape) + { + case eBeta: + output << "\"beta\""; + break; + case eGamma: + output << "\"gamma\""; + break; + case eNormal: + output << "\"normal\""; + break; + case eInvGamma: + output << "\"inv_gamma\""; + break; + case eUniform: + output << "\"uniform\""; + break; + case eInvGamma2: + output << "\"inv_gamma2\""; + break; + case eDirichlet: + output << "\"dirichlet\""; + break; + case eWeibull: + output << "\"weibull\""; + break; + case eNoShape: + cerr << "Impossible case." << endl; + exit(EXIT_FAILURE); + } + output << "}"; +} BasicPriorStatement::~BasicPriorStatement() { @@ -2537,6 +3493,27 @@ BasicPriorStatement::writePriorOutput(ostream &output, string &lhs_field, const writeCommonOutput(output, lhs_field); } +void +BasicPriorStatement::writeJsonPriorOutput(ostream &output) const +{ + output << ", \"name\": \"" << name << "\"" + << ", \"subsample\": \"" << subsample_name << "\"" + << ", "; + writeJsonShape(output); + if (variance != NULL) + { + deriv_node_temp_terms_t tef_terms; + output << ", \"variance\": \""; + variance->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\""; + } + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } +} + void BasicPriorStatement::writeCVarianceOption(ostream &output) const { @@ -2610,6 +3587,41 @@ BasicPriorStatement::writeCShape(ostream &output) const } } +void +BasicPriorStatement::writeJsonShape(ostream &output) const +{ + output << "\"shape\": "; + switch (prior_shape) + { + case eBeta: + output << "\"beta\""; + break; + case eGamma: + output << "\"gamma\""; + break; + case eNormal: + output << "\"normal\""; + break; + case eInvGamma: + output << "\"inv_gamma\""; + break; + case eUniform: + output << "\"uniform\""; + break; + case eInvGamma2: + output << "\"inv_gamma2\""; + break; + case eDirichlet: + output << "\"dirichlet\""; + break; + case eWeibull: + output << "\"weibull\""; + break; + case eNoShape: + assert(prior_shape != eNoShape); + } +} + PriorStatement::PriorStatement(const string &name_arg, const string &subsample_name_arg, const PriorDistributions &prior_shape_arg, @@ -2629,6 +3641,14 @@ PriorStatement::writeOutput(ostream &output, const string &basename, bool minima writePriorOutput(output, lhs_field, ""); } +void +PriorStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"prior\""; + writeJsonPriorOutput(output); + output << "}"; +} + void PriorStatement::writeCOutput(ostream &output, const string &basename) { @@ -2669,6 +3689,14 @@ StdPriorStatement::writeOutput(ostream &output, const string &basename, bool min writePriorOutput(output, lhs_field, ""); } +void +StdPriorStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"std_prior\""; + writeJsonPriorOutput(output); + output << "}"; +} + void StdPriorStatement::writeCOutput(ostream &output, const string &basename) { @@ -2734,6 +3762,15 @@ CorrPriorStatement::writeOutput(ostream &output, const string &basename, bool mi writePriorOutput(output, lhs_field, name1); } +void +CorrPriorStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"corr_prior\"" + << ", \"name2\": \"" << name1 << "\""; + writeJsonPriorOutput(output); + output << "}"; +} + void CorrPriorStatement::writeCOutput(ostream &output, const string &basename) { @@ -2869,6 +3906,21 @@ PriorEqualStatement::writeOutput(ostream &output, const string &basename, bool m output << lhs_field << " = " << rhs_field << ";" << endl; } +void +PriorEqualStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"prior_equal\"" + << ", \"to_name1\": \"" << to_name1 << "\""; + if (to_declaration_type == "corr") + output << ", \"to_name2\": \"" << to_name2 << "\""; + output << ", \"to_subsample\": \"" << to_subsample_name << "\"" + << ", \"from_name1\": \"" << from_name1 << "\""; + if (to_declaration_type == "corr") + output << ", \"from_name2\": \"" << from_name2 << "\""; + output << ", \"from_subsample\": \"" << from_subsample_name << "\"" + << "}"; +} + BasicOptionsStatement::~BasicOptionsStatement() { } @@ -2946,6 +3998,19 @@ BasicOptionsStatement::writeOptionsOutput(ostream &output, string &lhs_field, co writeCommonOutput(output, lhs_field); } +void +BasicOptionsStatement::writeJsonOptionsOutput(ostream &output) const +{ + output << ", \"name\": \"" << name << "\""; + if (!subsample_name.empty()) + output << ", \"subsample_name\": \"" << subsample_name << "\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } +} + OptionsStatement::OptionsStatement(const string &name_arg, const string &subsample_name_arg, const OptionsList &options_list_arg) : @@ -2963,6 +4028,14 @@ OptionsStatement::writeOutput(ostream &output, const string &basename, bool mini writeOptionsOutput(output, lhs_field, ""); } +void +OptionsStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"options\""; + writeJsonOptionsOutput(output); + output << "}"; +} + void OptionsStatement::writeCOutput(ostream &output, const string &basename) { @@ -2994,6 +4067,14 @@ StdOptionsStatement::writeOutput(ostream &output, const string &basename, bool m writeOptionsOutput(output, lhs_field, ""); } +void +StdOptionsStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"std_options\""; + writeJsonOptionsOutput(output); + output << "}"; +} + void StdOptionsStatement::writeCOutput(ostream &output, const string &basename) { @@ -3051,6 +4132,15 @@ CorrOptionsStatement::writeOutput(ostream &output, const string &basename, bool writeOptionsOutput(output, lhs_field, name1); } +void +CorrOptionsStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"corr_options\"" + << ", \"name2\": \"" << name1 << "\""; + writeJsonOptionsOutput(output); + output << "}"; +} + void CorrOptionsStatement::writeCOutput(ostream &output, const string &basename) { @@ -3110,6 +4200,21 @@ OptionsEqualStatement::checkPass(ModFileStructure &mod_file_struct, WarningConso } } +void +OptionsEqualStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"options_equal\"" + << ", \"to_name1\": \"" << to_name1 << "\""; + if (to_declaration_type == "corr") + output << ", \"to_name2\": \"" << to_name2 << "\""; + output << ", \"to_subsample\": \"" << to_subsample_name << "\"" + << ", \"from_name1\": \"" << from_name1 << "\""; + if (to_declaration_type == "corr") + output << ", \"from_name2\": \"" << from_name2 << "\""; + output << ", \"from_subsample\": \"" << from_subsample_name << "\"" + << "}"; +} + void OptionsEqualStatement::get_base_name(const SymbolType symb_type, string &lhs_field) const { @@ -3203,6 +4308,23 @@ CalibSmootherStatement::writeOutput(ostream &output, const string &basename, boo output << "[oo_,options_,bayestopt_]=evaluate_smoother('calibration',var_list_,M_,oo_,options_,bayestopt_,estim_params_);" << endl; } +void +CalibSmootherStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"calib_smoother\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + if (!symbol_list.empty()) + { + output << ", "; + symbol_list.writeJsonOutput(output); + } + output << "}"; +} + ExtendedPathStatement::ExtendedPathStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -3239,6 +4361,18 @@ ExtendedPathStatement::writeOutput(ostream &output, const string &basename, bool << ", [], options_, M_, oo_);" << endl; } +void +ExtendedPathStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"extended_path\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} + ModelDiagnosticsStatement::ModelDiagnosticsStatement() { } @@ -3249,6 +4383,12 @@ ModelDiagnosticsStatement::writeOutput(ostream &output, const string &basename, output << "model_diagnostics(M_,options_,oo_);" << endl; } +void +ModelDiagnosticsStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"model_diagnostics\"}"; +} + Smoother2histvalStatement::Smoother2histvalStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -3260,3 +4400,15 @@ Smoother2histvalStatement::writeOutput(ostream &output, const string &basename, options_list.writeOutput(output, "options_smoother2histval"); output << "smoother2histval(options_smoother2histval);" << endl; } + +void +Smoother2histvalStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"smoother_2_histval\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + output << "}"; +} diff --git a/ComputingTasks.hh b/ComputingTasks.hh index a62a02b3..49dcdbe8 100644 --- a/ComputingTasks.hh +++ b/ComputingTasks.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -36,6 +36,7 @@ public: SteadyStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class CheckStatement : public Statement @@ -46,6 +47,7 @@ public: CheckStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class SimulStatement : public Statement @@ -56,6 +58,7 @@ public: SimulStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class PerfectForesightSetupStatement : public Statement @@ -65,6 +68,7 @@ private: public: PerfectForesightSetupStatement(const OptionsList &options_list_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class PerfectForesightSolverStatement : public Statement @@ -75,6 +79,7 @@ public: PerfectForesightSolverStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class PriorPosteriorFunctionStatement : public Statement @@ -86,6 +91,7 @@ public: PriorPosteriorFunctionStatement(const bool prior_func_arg, const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class ModelInfoStatement : public Statement @@ -96,6 +102,7 @@ public: ModelInfoStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class StochSimulStatement : public Statement @@ -108,6 +115,7 @@ public: const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class ForecastStatement : public Statement @@ -119,6 +127,7 @@ public: ForecastStatement(const SymbolList &symbol_list_arg, const OptionsList &options_list_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class RamseyModelStatement : public Statement @@ -131,6 +140,7 @@ public: const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class RamseyConstraintsStatement : public Statement @@ -143,11 +153,13 @@ public: }; typedef vector constraints_t; private: + const SymbolTable &symbol_table; const constraints_t constraints; public: - RamseyConstraintsStatement(const constraints_t &constraints_arg); + RamseyConstraintsStatement(const SymbolTable &symbol_table_arg, const constraints_t &constraints_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; // virtual Statement *cloneAndReindexSymbIds(DataTree &dynamic_datatree, SymbolTable &orig_symbol_table); }; @@ -164,6 +176,7 @@ public: virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); void checkRamseyPolicyList(); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class DiscretionaryPolicyStatement : public Statement @@ -176,6 +189,7 @@ public: const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class RplotStatement : public Statement @@ -185,6 +199,7 @@ private: public: RplotStatement(const SymbolList &symbol_list_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class UnitRootVarsStatement : public Statement @@ -192,6 +207,7 @@ class UnitRootVarsStatement : public Statement public: UnitRootVarsStatement(void); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class PeriodsStatement : public Statement @@ -201,6 +217,7 @@ private: public: PeriodsStatement(int periods_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class DsampleStatement : public Statement @@ -211,6 +228,7 @@ public: DsampleStatement(int val1_arg); DsampleStatement(int val1_arg, int val2_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class EstimationStatement : public Statement @@ -223,6 +241,7 @@ public: const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class DynareSensitivityStatement : public Statement @@ -233,6 +252,7 @@ public: DynareSensitivityStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class ObservationTrendsStatement : public Statement @@ -246,6 +266,7 @@ public: ObservationTrendsStatement(const trend_elements_t &trend_elements_arg, const SymbolTable &symbol_table_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class OsrParamsStatement : public Statement @@ -257,6 +278,7 @@ public: OsrParamsStatement(const SymbolList &symbol_list_arg, const SymbolTable &symbol_table_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class OsrStatement : public Statement @@ -269,6 +291,7 @@ public: const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; //! Temporary structure used when parsing estimation_params* statements @@ -295,6 +318,7 @@ public: OsrParamsBoundsStatement(const vector &osr_params_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class DynaTypeStatement : public Statement @@ -306,6 +330,7 @@ public: DynaTypeStatement(const SymbolList &symbol_list_arg, const string &filename_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class DynaSaveStatement : public Statement @@ -317,6 +342,7 @@ public: DynaSaveStatement(const SymbolList &symbol_list_arg, const string &filename_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class ModelComparisonStatement : public Statement @@ -330,6 +356,7 @@ public: ModelComparisonStatement(const filename_list_t &filename_list_arg, const OptionsList &options_list_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; //! Temporary structure used when parsing estimation_params* statements @@ -369,6 +396,7 @@ public: const SymbolTable &symbol_table_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class EstimatedParamsInitStatement : public Statement @@ -383,6 +411,7 @@ public: const bool use_calibration_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class EstimatedParamsBoundsStatement : public Statement @@ -394,6 +423,7 @@ public: EstimatedParamsBoundsStatement(const vector &estim_params_list_arg, const SymbolTable &symbol_table_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class OptimWeightsStatement : public Statement @@ -411,6 +441,7 @@ public: const SymbolTable &symbol_table_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; /*! \todo Make model_tree a member instead of a pointer */ @@ -430,6 +461,7 @@ public: /*! \todo allow for the possibility of disabling temporary terms */ virtual void computingPass(); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; //! Return the Planner Objective StaticModel *getPlannerObjective() const; }; @@ -443,6 +475,7 @@ public: BVARDensityStatement(int maxnlags_arg, const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class BVARForecastStatement : public Statement @@ -454,6 +487,7 @@ public: BVARForecastStatement(int nlags_arg, const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class SBVARStatement : public Statement @@ -464,6 +498,7 @@ public: SBVARStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class MSSBVAREstimationStatement : public Statement @@ -474,6 +509,7 @@ public: MSSBVAREstimationStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class MSSBVARSimulationStatement : public Statement @@ -484,6 +520,7 @@ public: MSSBVARSimulationStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class MSSBVARComputeMDDStatement : public Statement @@ -494,6 +531,7 @@ public: MSSBVARComputeMDDStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class MSSBVARComputeProbabilitiesStatement : public Statement @@ -504,6 +542,7 @@ public: MSSBVARComputeProbabilitiesStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class MSSBVARIrfStatement : public Statement @@ -516,6 +555,7 @@ public: const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class MSSBVARForecastStatement : public Statement @@ -526,6 +566,7 @@ public: MSSBVARForecastStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class MSSBVARVarianceDecompositionStatement : public Statement @@ -536,6 +577,7 @@ public: MSSBVARVarianceDecompositionStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class IdentificationStatement : public Statement @@ -546,6 +588,7 @@ public: IdentificationStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class WriteLatexDynamicModelStatement : public Statement @@ -555,6 +598,7 @@ private: public: WriteLatexDynamicModelStatement(const DynamicModel &dynamic_model_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class WriteLatexStaticModelStatement : public Statement @@ -564,6 +608,7 @@ private: public: WriteLatexStaticModelStatement(const StaticModel &static_model_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class WriteLatexOriginalModelStatement : public Statement @@ -573,6 +618,7 @@ private: public: WriteLatexOriginalModelStatement(const DynamicModel &original_model_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class ShockDecompositionStatement : public Statement @@ -584,6 +630,7 @@ public: ShockDecompositionStatement(const SymbolList &symbol_list_arg, const OptionsList &options_list_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class ConditionalForecastStatement : public Statement @@ -593,6 +640,7 @@ private: public: ConditionalForecastStatement(const OptionsList &options_list_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class PlotConditionalForecastStatement : public Statement @@ -604,6 +652,7 @@ private: public: PlotConditionalForecastStatement(int periods_arg, const SymbolList &symbol_list_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class CalibSmootherStatement : public Statement @@ -616,6 +665,7 @@ public: const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class ExtendedPathStatement : public Statement @@ -626,6 +676,7 @@ public: ExtendedPathStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class SvarIdentificationStatement : public Statement @@ -657,6 +708,7 @@ public: const SymbolTable &symbol_table_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class MarkovSwitchingStatement : public Statement @@ -669,6 +721,7 @@ public: virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeCOutput(ostream &output, const string &basename); + virtual void writeJsonOutput(ostream &output) const; }; class SvarStatement : public Statement @@ -679,6 +732,7 @@ public: SvarStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class SvarGlobalIdentificationCheckStatement : public Statement @@ -686,6 +740,7 @@ class SvarGlobalIdentificationCheckStatement : public Statement public: SvarGlobalIdentificationCheckStatement(); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class SetTimeStatement : public Statement @@ -695,6 +750,7 @@ private: public: SetTimeStatement(const OptionsList &options_list_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class EstimationDataStatement : public Statement @@ -705,6 +761,7 @@ public: EstimationDataStatement(const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class SubsamplesStatement : public Statement @@ -724,6 +781,7 @@ public: const SymbolTable &symbol_table_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class SubsamplesEqualStatement : public Statement @@ -741,6 +799,7 @@ public: const string &from_name2_arg, const SymbolTable &symbol_table_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class JointPriorStatement : public Statement @@ -756,6 +815,7 @@ public: virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; void writeOutputHelper(ostream &output, const string &field, const string &lhs_field) const; + virtual void writeJsonOutput(ostream &output) const; }; @@ -788,6 +848,8 @@ protected: void writeCShape(ostream &output) const; void writeCVarianceOption(ostream &output) const; void writeCDomain(ostream &output) const; + void writeJsonShape(ostream &output) const; + void writeJsonPriorOutput(ostream &output) const; }; class PriorStatement : public BasicPriorStatement @@ -800,6 +862,7 @@ public: const OptionsList &options_list_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeCOutput(ostream &output, const string &basename); + virtual void writeJsonOutput(ostream &output) const; }; class StdPriorStatement : public BasicPriorStatement @@ -815,6 +878,7 @@ public: const SymbolTable &symbol_table_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeCOutput(ostream &output, const string &basename); + virtual void writeJsonOutput(ostream &output) const; }; class CorrPriorStatement : public BasicPriorStatement @@ -833,6 +897,7 @@ public: virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeCOutput(ostream &output, const string &basename); + virtual void writeJsonOutput(ostream &output) const; }; class PriorEqualStatement : public Statement @@ -860,6 +925,7 @@ public: void get_base_name(const SymbolType symb_type, string &lhs_field) const; virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class BasicOptionsStatement : public Statement @@ -882,6 +948,7 @@ protected: void writeOptionsIndex(ostream &output, const string &lhs_field) const; void writeOutputHelper(ostream &output, const string &field, const string &lhs_field) const; void writeCOutputHelper(ostream &output, const string &field) const; + void writeJsonOptionsOutput(ostream &output) const; }; class OptionsStatement : public BasicOptionsStatement @@ -890,6 +957,7 @@ public: OptionsStatement(const string &name_arg, const string &subsample_name_arg, const OptionsList &options_list_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeCOutput(ostream &output, const string &basename); + virtual void writeJsonOutput(ostream &output) const; }; class StdOptionsStatement : public BasicOptionsStatement @@ -903,6 +971,7 @@ public: const SymbolTable &symbol_table_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeCOutput(ostream &output, const string &basename); + virtual void writeJsonOutput(ostream &output) const; }; class CorrOptionsStatement : public BasicOptionsStatement @@ -918,6 +987,7 @@ public: virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeCOutput(ostream &output, const string &basename); + virtual void writeJsonOutput(ostream &output) const; }; class OptionsEqualStatement : public Statement @@ -945,6 +1015,7 @@ public: void get_base_name(const SymbolType symb_type, string &lhs_field) const; virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class ModelDiagnosticsStatement : public Statement @@ -952,6 +1023,7 @@ class ModelDiagnosticsStatement : public Statement public: ModelDiagnosticsStatement(); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class Smoother2histvalStatement : public Statement @@ -961,6 +1033,7 @@ private: public: Smoother2histvalStatement(const OptionsList &options_list_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; #endif diff --git a/ModFile.cc b/ModFile.cc index d2698873..78ae952a 100644 --- a/ModFile.cc +++ b/ModFile.cc @@ -1259,29 +1259,12 @@ ModFile::writeJsonOutput(const string &basename, JsonFileOutputType json_output_ if (!statements.empty()) { output << ",\"statements\": ["; - bool printed_statement = false; for (vector::const_iterator it = statements.begin(); - it != statements.end();) + it != statements.end(); it++) { + if (it != statements.begin()) + output << ", " << endl; (*it)->writeJsonOutput(output); - - if (dynamic_cast(*it) != NULL || - dynamic_cast(*it) != NULL || - dynamic_cast(*it) != NULL || - dynamic_cast(*it) != NULL) - printed_statement = true; - - if (++it == statements.end()) - break; - - // tests to see if the next statement will be one for which we support writing JSON files - // to be deleted once we support all statements - if (printed_statement && - (dynamic_cast(*it) != NULL || - dynamic_cast(*it) != NULL || - dynamic_cast(*it) != NULL || - dynamic_cast(*it) != NULL)) - output << "," << endl; } output << "]" << endl; } diff --git a/NumericalInitialization.cc b/NumericalInitialization.cc index 057b59d6..22c013b3 100644 --- a/NumericalInitialization.cc +++ b/NumericalInitialization.cc @@ -177,16 +177,15 @@ InitOrEndValStatement::writeInitValues(ostream &output) const void InitOrEndValStatement::writeJsonInitValues(ostream &output) const { - int i = 0; deriv_node_temp_terms_t tef_terms; for (init_values_t::const_iterator it = init_values.begin(); - it != init_values.end(); it++, i++) + it != init_values.end(); it++) { + if (it != init_values.begin()) + output << ", "; output << "{\"name\": \"" << symbol_table.getName(it->first) << "\", " << "\"value\": \""; it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); output << "\"}"; - if (i < init_values.size() - 1) - output << ", "; } } @@ -419,19 +418,18 @@ HistValStatement::writeOutput(ostream &output, const string &basename, bool mini void HistValStatement::writeJsonOutput(ostream &output) const { - int i = 0; deriv_node_temp_terms_t tef_terms; output << "{\"statementName\": \"hist_val\", \"vals\": ["; for (hist_values_t::const_iterator it = hist_values.begin(); it != hist_values.end(); it++) { + if (it != hist_values.begin()) + output << ", "; output << "{ \"name\": \"" << symbol_table.getName(it->first.first) << "\"" << ", \"lag\": " << it->first.second << ", \"value\": \""; it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); output << "\"}"; - if (i < hist_values.size() - 1) - output << ", "; } output << "]}"; } @@ -451,6 +449,14 @@ InitvalFileStatement::writeOutput(ostream &output, const string &basename, bool << "initvalf('" << filename << "');" << endl; } +void +InitvalFileStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"init_val_file\"" + << ", \"filename\": \"" << filename << "\"" + << "}"; +} + HistvalFileStatement::HistvalFileStatement(const string &filename_arg) : filename(filename_arg) { @@ -462,6 +468,14 @@ HistvalFileStatement::writeOutput(ostream &output, const string &basename, bool output << "histvalf('" << filename << "');" << endl; } +void +HistvalFileStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"hist_val_file\"" + << ", \"filename\": \"" << filename << "\"" + << "}"; +} + HomotopyStatement::HomotopyStatement(const homotopy_values_t &homotopy_values_arg, const SymbolTable &symbol_table_arg) : homotopy_values(homotopy_values_arg), @@ -498,6 +512,31 @@ HomotopyStatement::writeOutput(ostream &output, const string &basename, bool min } } +void +HomotopyStatement::writeJsonOutput(ostream &output) const +{ + deriv_node_temp_terms_t tef_terms; + output << "{\"statementName\": \"homotopy\", " + << "\"values\": ["; + for (homotopy_values_t::const_iterator it = homotopy_values.begin(); + it != homotopy_values.end(); it++) + { + if (it != homotopy_values.begin()) + output << ", "; + output << "{\"name\": \"" << symbol_table.getName(it->first) << "\"" + << ", \"initial_value\": \""; + if (it->second.first != NULL) + it->second.first->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + else + output << "NaN"; + output << "\", \"final_value\": \""; + it->second.second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}"; + } + output << "]" + << "}"; +} + SaveParamsAndSteadyStateStatement::SaveParamsAndSteadyStateStatement(const string &filename_arg) : filename(filename_arg) { @@ -509,6 +548,14 @@ SaveParamsAndSteadyStateStatement::writeOutput(ostream &output, const string &ba output << "save_params_and_steady_state('" << filename << "');" << endl; } +void +SaveParamsAndSteadyStateStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"save_params_and_steady_state\"" + << ", \"filename\": \"" << filename << "\"" + << "}"; +} + LoadParamsAndSteadyStateStatement::LoadParamsAndSteadyStateStatement(const string &filename, const SymbolTable &symbol_table_arg, WarningConsolidation &warnings) : @@ -574,6 +621,24 @@ LoadParamsAndSteadyStateStatement::writeOutput(ostream &output, const string &ba } } +void +LoadParamsAndSteadyStateStatement::writeJsonOutput(ostream &output) const +{ + deriv_node_temp_terms_t tef_terms; + output << "{\"statementName\": \"load_params_and_steady_state\"" + << "\"values\": ["; + for (map::const_iterator it = content.begin(); + it != content.end(); it++) + { + if (it != content.begin()) + output << ", "; + output << "{\"name\": \"" << symbol_table.getName(it->first) << "\"" + << ", \"value\": \"" << it->second << "\"}"; + } + output << "]" + << "}"; +} + void LoadParamsAndSteadyStateStatement::fillEvalContext(eval_context_t &eval_context) const { diff --git a/NumericalInitialization.hh b/NumericalInitialization.hh index e48cb9ee..58a7e6e0 100644 --- a/NumericalInitialization.hh +++ b/NumericalInitialization.hh @@ -128,6 +128,7 @@ private: public: InitvalFileStatement(const string &filename_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class HistvalFileStatement : public Statement @@ -137,6 +138,7 @@ private: public: HistvalFileStatement(const string &filename_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class HomotopyStatement : public Statement @@ -152,6 +154,7 @@ public: HomotopyStatement(const homotopy_values_t &homotopy_values_arg, const SymbolTable &symbol_table_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class SaveParamsAndSteadyStateStatement : public Statement @@ -161,6 +164,7 @@ private: public: SaveParamsAndSteadyStateStatement(const string &filename_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class LoadParamsAndSteadyStateStatement : public Statement @@ -177,6 +181,7 @@ public: virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; //! Fill eval context with parameters/variables values void fillEvalContext(eval_context_t &eval_context) const; + virtual void writeJsonOutput(ostream &output) const; }; #endif diff --git a/ParsingDriver.cc b/ParsingDriver.cc index 23e2018c..3129df07 100644 --- a/ParsingDriver.cc +++ b/ParsingDriver.cc @@ -2934,7 +2934,7 @@ ParsingDriver::prior_posterior_function(bool prior_func) void ParsingDriver::add_ramsey_constraints_statement() { - mod_file->addStatement(new RamseyConstraintsStatement(ramsey_constraints)); + mod_file->addStatement(new RamseyConstraintsStatement(mod_file->symbol_table, ramsey_constraints)); ramsey_constraints.clear(); } diff --git a/Shocks.cc b/Shocks.cc index af402624..95391092 100644 --- a/Shocks.cc +++ b/Shocks.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -67,6 +67,34 @@ AbstractShocksStatement::writeDetShocks(ostream &output) const output << "M_.exo_det_length = " << exo_det_length << ";\n"; } +void +AbstractShocksStatement::writeJsonDetShocks(ostream &output) const +{ + deriv_node_temp_terms_t tef_terms; + output << "\"deterministic_shocks\": ["; + for (det_shocks_t::const_iterator it = det_shocks.begin(); + it != det_shocks.end(); it++) + { + if (it != det_shocks.begin()) + output << ", "; + output << "{\"var\": \"" << symbol_table.getName(it->first) << "\", " + << "\"values\": ["; + for (vector::const_iterator it1 = it->second.begin(); + it1 != it->second.end(); it1++) + { + if (it1 != it->second.begin()) + output << ", "; + output << "{\"period1\": " << it1->period1 << ", " + << "\"period2\": " << it1->period2 << ", " + << "\"value\": \""; + it1->value->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}"; + } + output << "]}"; + } + output << "]"; +} + ShocksStatement::ShocksStatement(bool overwrite_arg, const det_shocks_t &det_shocks_arg, const var_and_std_shocks_t &var_shocks_arg, @@ -123,6 +151,73 @@ ShocksStatement::writeOutput(ostream &output, const string &basename, bool minim output << "M_.sigma_e_is_diagonal = 1;" << endl; } + +void +ShocksStatement::writeJsonOutput(ostream &output) const +{ + deriv_node_temp_terms_t tef_terms; + output << "{\"statementName\": \"shocks\"" + << ", \"overwrite\": "; + if (overwrite) + output << "true"; + else + output << "false"; + if (!det_shocks.empty()) + { + output << ", "; + writeJsonDetShocks(output); + } + output<< ", \"variance\": ["; + for (var_and_std_shocks_t::const_iterator it = var_shocks.begin(); it != var_shocks.end(); it++) + { + if (it != var_shocks.begin()) + output << ", "; + output << "{\"name\": \"" << symbol_table.getName(it->first) << "\", " + << "\"variance\": \""; + it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}"; + } + output << "]" + << ", \"stderr\": ["; + for (var_and_std_shocks_t::const_iterator it = std_shocks.begin(); it != std_shocks.end(); it++) + { + if (it != std_shocks.begin()) + output << ", "; + output << "{\"name\": \"" << symbol_table.getName(it->first) << "\", " + << "\"stderr\": \""; + it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}"; + } + output << "]" + << ", \"covariance\": ["; + for (covar_and_corr_shocks_t::const_iterator it = covar_shocks.begin(); it != covar_shocks.end(); it++) + { + if (it != covar_shocks.begin()) + output << ", "; + output << "{" + << "\"name\": \"" << symbol_table.getName(it->first.first) << "\", " + << "\"name2\": \"" << symbol_table.getName(it->first.second) << "\", " + << "\"covariance\": \""; + it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}"; + } + output << "]" + << ", \"correlation\": ["; + for (covar_and_corr_shocks_t::const_iterator it = corr_shocks.begin(); it != corr_shocks.end(); it++) + { + if (it != corr_shocks.begin()) + output << ", "; + output << "{" + << "\"name\": \"" << symbol_table.getName(it->first.first) << "\", " + << "\"name2\": \"" << symbol_table.getName(it->first.second) << "\", " + << "\"correlation\": \""; + it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + output << "\"}"; + } + output << "]" + << "}"; +} + void ShocksStatement::writeVarOrStdShock(ostream &output, var_and_std_shocks_t::const_iterator &it, bool stddev) const @@ -430,6 +525,26 @@ MomentCalibration::writeOutput(ostream &output, const string &basename, bool min output << "};" << endl; } +void +MomentCalibration::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"moment_calibration\"" + << ", \"moment_calibration_criteria\": ["; + for (constraints_t::const_iterator it = constraints.begin(); it != constraints.end(); it++) + { + if (it != constraints.begin()) + output << ", "; + output << "{\"endogenous1\": \"" << symbol_table.getName(it->endo1) << "\"" + << ", \"endogenous2\": \"" << symbol_table.getName(it->endo2) << "\"" + << ", \"lags\": \"" << it->lags << "\"" + << ", \"lower_bound\": \"" << it->lower_bound << "\"" + << ", \"upper_bound\": \"" << it->upper_bound << "\"" + << "}"; + } + output << "]" + << "}"; +} + IrfCalibration::IrfCalibration(const constraints_t &constraints_arg, const SymbolTable &symbol_table_arg, const OptionsList &options_list_arg) @@ -455,6 +570,32 @@ IrfCalibration::writeOutput(ostream &output, const string &basename, bool minima output << "};" << endl; } +void +IrfCalibration::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"irf_calibration\""; + if (options_list.getNumberOfOptions()) + { + output << ", "; + options_list.writeJsonOutput(output); + } + + output << ", \"irf_restrictions\": ["; + for (constraints_t::const_iterator it = constraints.begin(); it != constraints.end(); it++) + { + if (it != constraints.begin()) + output << ", "; + output << "{\"endogenous\": \"" << symbol_table.getName(it->endo) << "\"" + << ", \"exogenous\": \"" << symbol_table.getName(it->exo) << "\"" + << ", \"periods\": \"" << it->periods << "\"" + << ", \"lower_bound\": \"" << it->lower_bound << "\"" + << ", \"upper_bound\": \"" << it->upper_bound << "\"" + << "}"; + } + output << "]" + << "}"; +} + ShockGroupsStatement::ShockGroupsStatement(const group_t &shock_groups_arg, const string &name_arg) : shock_groups(shock_groups_arg), name(name_arg) { diff --git a/Shocks.hh b/Shocks.hh index f89e1fba..76f49ffe 100644 --- a/Shocks.hh +++ b/Shocks.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -50,6 +50,7 @@ protected: const det_shocks_t det_shocks; const SymbolTable &symbol_table; void writeDetShocks(ostream &output) const; + void writeJsonDetShocks(ostream &output) const; AbstractShocksStatement(bool mshocks_arg, bool overwrite_arg, const det_shocks_t &det_shocks_arg, @@ -77,8 +78,9 @@ public: const covar_and_corr_shocks_t &covar_shocks_arg, const covar_and_corr_shocks_t &corr_shocks_arg, const SymbolTable &symbol_table_arg); - virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); + virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class MShocksStatement : public AbstractShocksStatement @@ -120,6 +122,7 @@ public: MomentCalibration(const constraints_t &constraints_arg, const SymbolTable &symbol_table_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class IrfCalibration : public Statement @@ -141,6 +144,7 @@ public: const SymbolTable &symbol_table_arg, const OptionsList &options_list_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class ShockGroupsStatement : public Statement diff --git a/Statement.cc b/Statement.cc index ee18bbb8..82ced981 100644 --- a/Statement.cc +++ b/Statement.cc @@ -109,6 +109,14 @@ NativeStatement::writeOutput(ostream &output, const string &basename, bool minim output << ns << endl; } +void +NativeStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"native\"" + << ", \"string\": \"" << native_statement << "\"" + << "}"; +} + VerbatimStatement::VerbatimStatement(const string &verbatim_statement_arg) : verbatim_statement(verbatim_statement_arg) { @@ -120,6 +128,14 @@ VerbatimStatement::writeOutput(ostream &output, const string &basename, bool min output << verbatim_statement << endl; } +void +VerbatimStatement::writeJsonOutput(ostream &output) const +{ + output << "{\"statementName\": \"verbatim\"" + << ", \"string\": \"" << verbatim_statement << "\"" + << "}"; +} + void OptionsList::writeOutput(ostream &output) const { @@ -213,6 +229,100 @@ OptionsList::writeOutput(ostream &output, const string &option_group) const } } +void +OptionsList::writeJsonOutput(ostream &output) const +{ + if (getNumberOfOptions() == 0) + return; + + output << "\"options\": {"; + for (num_options_t::const_iterator it = num_options.begin(); + it != num_options.end();) + { + output << "\""<< it->first << "\": " << it->second; + it++; + if (it != num_options.end() || + !(paired_num_options.empty() && + string_options.empty() && + date_options.empty() && + symbol_list_options.empty() && + vector_int_options.empty())) + output << ", "; + } + + for (paired_num_options_t::const_iterator it = paired_num_options.begin(); + it != paired_num_options.end();) + { + output << "\""<< it->first << "\": [" << it->second.first << " " << it->second.second << "]"; + it++; + if (it != paired_num_options.end() || + !(string_options.empty() && + date_options.empty() && + symbol_list_options.empty() && + vector_int_options.empty())) + output << ", "; + } + + for (string_options_t::const_iterator it = string_options.begin(); + it != string_options.end();) + { + output << "\""<< it->first << "\": \"" << it->second << "\""; + it++; + if (it != string_options.end() || + !(date_options.empty() && + symbol_list_options.empty() && + vector_int_options.empty())) + output << ", "; + } + + for (date_options_t::const_iterator it = date_options.begin(); + it != date_options.end();) + { + output << "\""<< it->first << "\": \"" << it->second << "\""; + it++; + if (it != date_options.end() || + !(symbol_list_options.empty() && + vector_int_options.empty())) + output << ", "; + } + + for (symbol_list_options_t::const_iterator it = symbol_list_options.begin(); + it != symbol_list_options.end(); it++) + { + output << "\""<< it->first << "\":"; + it->second.writeJsonOutput(output); + it++; + if (it != symbol_list_options.end() || + !vector_int_options.empty()) + output << ", "; + } + + for (vec_int_options_t::const_iterator it = vector_int_options.begin(); + it != vector_int_options.end();) + { + output << "\""<< it->first << "\": ["; + if (it->second.size() > 1) + { + for (vector::const_iterator viit = it->second.begin(); + viit != it->second.end();) + { + output << *viit; + viit++; + if (viit != it->second.end()) + output << ", "; + } + } + else + output << it->second.front() << endl; + output << "]"; + it++; + if (it != vector_int_options.end()) + output << ", "; + } + + output << "}"; +} + void OptionsList::clear() { @@ -223,3 +333,14 @@ OptionsList::clear() symbol_list_options.clear(); vector_int_options.clear(); } + +int +OptionsList::getNumberOfOptions() const +{ + return num_options.size() + + paired_num_options.size() + + string_options.size() + + date_options.size() + + symbol_list_options.size() + + vector_int_options.size(); +} diff --git a/Statement.hh b/Statement.hh index 0db8a3c8..54f13a76 100644 --- a/Statement.hh +++ b/Statement.hh @@ -154,6 +154,7 @@ private: public: NativeStatement(const string &native_statement_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class VerbatimStatement : public Statement @@ -163,6 +164,7 @@ private: public: VerbatimStatement(const string &verbatim_statement_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; + virtual void writeJsonOutput(ostream &output) const; }; class OptionsList @@ -180,8 +182,10 @@ public: date_options_t date_options; symbol_list_options_t symbol_list_options; vec_int_options_t vector_int_options; + int getNumberOfOptions() const; void writeOutput(ostream &output) const; void writeOutput(ostream &output, const string &option_group) const; + void writeJsonOutput(ostream &output) const; void clear(); }; diff --git a/SymbolList.cc b/SymbolList.cc index dca1410e..d729f447 100644 --- a/SymbolList.cc +++ b/SymbolList.cc @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2014 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -39,6 +39,20 @@ SymbolList::writeOutput(const string &varname, ostream &output) const output << ");" << endl; } +void +SymbolList::writeJsonOutput(ostream &output) const +{ + output << "\"symbol_list\": ["; + for (vector::const_iterator it = symbols.begin(); + it != symbols.end(); ++it) + { + if (it != symbols.begin()) + output << ","; + output << "\"" << *it << "\""; + } + output << "]"; +} + void SymbolList::clear() { diff --git a/SymbolList.hh b/SymbolList.hh index 82f0b794..8ad5f9d2 100644 --- a/SymbolList.hh +++ b/SymbolList.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2011 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -39,6 +39,8 @@ public: //! Output content in Matlab format /*! Creates a string array for Matlab, stored in variable "varname" */ void writeOutput(const string &varname, ostream &output) const; + //! Write JSON output + void writeJsonOutput(ostream &output) const; //! Clears all content void clear(); //! Get a copy of the string vector From 915bea91a101ba009f30387d02cc3c1cbd0d9698 Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Mon, 20 Feb 2017 12:18:11 +0100 Subject: [PATCH 05/18] preprocessor: output JSON after different steps, write static, dynamic, params derivs files in JSON. #1387 --- ComputingTasks.cc | 36 ++-- DynamicModel.cc | 302 +++++++++++++++++++++++++++++- DynamicModel.hh | 6 + DynareMain.cc | 29 ++- DynareMain2.cc | 17 +- ExprNode.cc | 350 +++++++++++++++++++++++++++++++---- ExprNode.hh | 52 ++++-- ExtendedPreprocessorTypes.hh | 9 + ModFile.cc | 141 +++++++++++++- ModFile.hh | 5 +- ModelTree.cc | 177 ++++++++++++++++-- ModelTree.hh | 6 +- NumericalInitialization.cc | 10 +- Shocks.cc | 10 +- StaticModel.cc | 284 ++++++++++++++++++++++++++++ StaticModel.hh | 8 +- SymbolTable.cc | 2 +- 17 files changed, 1328 insertions(+), 116 deletions(-) diff --git a/ComputingTasks.cc b/ComputingTasks.cc index db2ac624..f750b9b6 100644 --- a/ComputingTasks.cc +++ b/ComputingTasks.cc @@ -509,7 +509,7 @@ RamseyConstraintsStatement::writeJsonOutput(ostream &output) const exit(1); } output << " "; - it->expression->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->expression->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}" << endl; } output << "]" << endl; @@ -1170,23 +1170,23 @@ EstimatedParamsStatement::writeJsonOutput(ostream &output) const } output << ", \"init_val\": \""; - it->init_val->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->init_val->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\", \"lower_bound\": \""; - it->low_bound->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->low_bound->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\", \"upper_bound\": \""; - it->up_bound->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->up_bound->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\", \"prior_distribution\": " << it->prior << ", \"mean\": \""; - it->mean->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->mean->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\", \"std\": \""; - it->std->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->std->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\", \"p3\": \""; - it->p3->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->p3->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\", \"p4\": \""; - it->p4->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->p4->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\", \"jscale\": \""; - it->jscale->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->jscale->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}" << endl; } output << "]" @@ -1297,7 +1297,7 @@ EstimatedParamsInitStatement::writeJsonOutput(ostream &output) const break; } output << ", \"init_val\": \""; - it->init_val->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->init_val->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}"; } output << "]" @@ -1417,9 +1417,9 @@ EstimatedParamsBoundsStatement::writeJsonOutput(ostream &output) const break; } output << ", \"lower_bound\": "; - it->low_bound->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->low_bound->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << ", \"upper_bound\": "; - it->up_bound->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->up_bound->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "}"; } output << "]" @@ -1470,7 +1470,7 @@ ObservationTrendsStatement::writeJsonOutput(ostream &output) const if (printed) output << ", "; output << "\"" << it->first << "\": \""; - it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->second->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"" << endl; printed = true; } @@ -1571,9 +1571,9 @@ OsrParamsBoundsStatement::writeJsonOutput(ostream &output) const output << ", "; output << "{\"parameter\": \"" << it->name << "\"," << "\"bounds\": [\""; - it->low_bound->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->low_bound->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\", \""; - it->up_bound->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->up_bound->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"]" << "}"; } @@ -1699,7 +1699,7 @@ OptimWeightsStatement::writeJsonOutput(ostream &output) const output << ", "; output << "{\"name\": \"" << it->first << "\"" << ", \"value\": \""; - it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->second->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}"; } @@ -1711,7 +1711,7 @@ OptimWeightsStatement::writeJsonOutput(ostream &output) const output << "{\"name1\": \"" << it->first.first << "\"" << ", \"name2\": \"" << it->first.second << "\"" << ", \"value\": \""; - it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->second->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}"; } output << "]" @@ -3504,7 +3504,7 @@ BasicPriorStatement::writeJsonPriorOutput(ostream &output) const { deriv_node_temp_terms_t tef_terms; output << ", \"variance\": \""; - variance->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + variance->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\""; } if (options_list.getNumberOfOptions()) diff --git a/DynamicModel.cc b/DynamicModel.cc index 704592da..edcc5f3a 100644 --- a/DynamicModel.cc +++ b/DynamicModel.cc @@ -5341,5 +5341,305 @@ DynamicModel::writeCCOutput(ostream &output, const string &basename, bool block_ void DynamicModel::writeJsonOutput(ostream &output) const { - writeJsonModelEquations(output); + writeJsonModelEquations(output, false); +} + +void +DynamicModel::writeJsonComputingPassOutput(ostream &output) const +{ + 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 third_derivatives_output; // Used for storing third order derivatives equations + + deriv_node_temp_terms_t tef_terms; + temporary_terms_t temp_term_empty; + temporary_terms_t temp_term_union = temporary_terms_res; + temporary_terms_t temp_term_union_m_1; + + string concat = ""; + int hessianColsNbr = dynJacobianColsNbr * dynJacobianColsNbr; + + writeJsonModelLocalVariables(model_local_vars_output, tef_terms); + + writeJsonTemporaryTerms(temporary_terms_res, temp_term_union_m_1, model_output, tef_terms, concat); + + writeJsonModelEquations(model_output, true); + + // Writing Jacobian + temp_term_union_m_1 = temp_term_union; + temp_term_union.insert(temporary_terms_g1.begin(), temporary_terms_g1.end()); + concat = "jacobian"; + writeJsonTemporaryTerms(temp_term_union, temp_term_union_m_1, jacobian_output, tef_terms, concat); + jacobian_output << ", \"jacobian\": {" + << " \"nrows\": " << equations.size() + << ", \"ncols\": " << dynJacobianColsNbr + << ", \"entries\": ["; + for (first_derivatives_t::const_iterator it = first_derivatives.begin(); + it != first_derivatives.end(); it++) + { + if (it != first_derivatives.begin()) + jacobian_output << ", "; + + int eq = it->first.first; + string var = symbol_table.getName(getSymbIDByDerivID(it->first.second)); + int lag = getLagByDerivID(it->first.second); + expr_t d1 = it->second; + + jacobian_output << "{\"eq\": " << eq + << ", \"var\": \"" << var << "\"" + << ", \"lag\": " << lag + << ", \"val\": \""; + d1->writeJsonOutput(jacobian_output, temp_term_union, tef_terms); + jacobian_output << "\"}" << endl; + } + jacobian_output << "]}"; + + // Writing Hessian + temp_term_union_m_1 = temp_term_union; + temp_term_union.insert(temporary_terms_g2.begin(), temporary_terms_g2.end()); + concat = "hessian"; + writeJsonTemporaryTerms(temp_term_union, temp_term_union_m_1, hessian_output, tef_terms, concat); + hessian_output << ", \"hessian\": {" + << " \"nrows\": " << equations.size() + << ", \"ncols\": " << hessianColsNbr + << ", \"entries\": ["; + for (second_derivatives_t::const_iterator it = second_derivatives.begin(); + it != second_derivatives.end(); it++) + { + if (it != second_derivatives.begin()) + hessian_output << ", "; + + int eq = it->first.first; + string var1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); + int lag1 = getLagByDerivID(it->first.second.first); + string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); + int lag2 = getLagByDerivID(it->first.second.second); + expr_t d2 = it->second; + + hessian_output << "{\"eq\": " << eq + << ", \"var1\": \"" << var1 << "\"" + << ", \"lag1\": " << lag1 + << ", \"var2\": \"" << var2 << "\"" + << ", \"lag2\": " << lag2 + << ", \"val\": \""; + d2->writeJsonOutput(hessian_output, temp_term_union, tef_terms); + hessian_output << "\"}" << endl; + } + hessian_output << "]}"; + + // Writing third derivatives + temp_term_union_m_1 = temp_term_union; + temp_term_union.insert(temporary_terms_g3.begin(), temporary_terms_g3.end()); + concat = "third_derivatives"; + writeJsonTemporaryTerms(temp_term_union, temp_term_union_m_1, third_derivatives_output, tef_terms, concat); + third_derivatives_output << ", \"third_derivative\": {" + << " \"nrows\": " << equations.size() + << ", \"ncols\": " << hessianColsNbr * dynJacobianColsNbr + << ", \"entries\": ["; + for (third_derivatives_t::const_iterator it = third_derivatives.begin(); + it != third_derivatives.end(); it++) + { + if (it != third_derivatives.begin()) + third_derivatives_output << ", "; + + int eq = it->first.first; + string var1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); + int lag1 = getLagByDerivID(it->first.second.first); + string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.first)); + int lag2 = getLagByDerivID(it->first.second.second.first); + string var3 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); + int lag3 = getLagByDerivID(it->first.second.second.second); + expr_t d3 = it->second; + + third_derivatives_output << "{\"eq\": " << eq + << ", \"var1\": \"" << var1 << "\"" + << ", \"lag1\": " << lag1 + << ", \"var2\": \"" << var2 << "\"" + << ", \"lag2\": " << lag2 + << ", \"var3\": \"" << var3 << "\"" + << ", \"lag3\": " << lag3 + << ", \"val\": \""; + d3->writeJsonOutput(third_derivatives_output, temp_term_union, tef_terms); + third_derivatives_output << "\"}" << endl; + } + third_derivatives_output << "]}"; + + output << "\"dynamic_model_derivatives\": {" + << model_local_vars_output.str() + << ", " << model_output.str() + << ", " << jacobian_output.str() + << ", " << hessian_output.str() + << ", " << third_derivatives_output.str() + << "}"; +} + +void +DynamicModel::writeJsonParamsDerivativesFile(ostream &output) const +{ + if (!residuals_params_derivatives.size() + && !residuals_params_second_derivatives.size() + && !jacobian_params_derivatives.size() + && !jacobian_params_second_derivatives.size() + && !hessian_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 + + deriv_node_temp_terms_t tef_terms; + writeJsonModelLocalVariables(model_local_vars_output, tef_terms); + + temporary_terms_t temp_terms_empty; + string concat = "all"; + writeJsonTemporaryTerms(params_derivs_temporary_terms, temp_terms_empty, model_output, tef_terms, concat); + jacobian_output << "\"deriv_wrt_params\": {" + << " \"neqs\": " << equations.size() + << ", \"nparamcols\": " << symbol_table.param_nbr() + << ", \"entries\": ["; + for (first_derivatives_t::const_iterator it = residuals_params_derivatives.begin(); + it != residuals_params_derivatives.end(); it++) + { + if (it != residuals_params_derivatives.begin()) + jacobian_output << ", "; + + int eq = it->first.first; + string param = symbol_table.getName(getSymbIDByDerivID(it->first.second)); + expr_t d1 = it->second; + + jacobian_output << "{\"eq\": " << eq + << ", \"param\": \"" << param << "\"" + << ", \"val\": \""; + d1->writeJsonOutput(jacobian_output, params_derivs_temporary_terms, tef_terms); + jacobian_output << "\"}" << endl; + } + jacobian_output << "]}"; + hessian_output << "\"deriv_jacobian_wrt_params\": {" + << " \"neqs\": " << equations.size() + << ", \"nvarcols\": " << dynJacobianColsNbr + << ", \"nparamcols\": " << symbol_table.param_nbr() + << ", \"entries\": ["; + for (second_derivatives_t::const_iterator it = jacobian_params_derivatives.begin(); + it != jacobian_params_derivatives.end(); it++) + { + if (it != jacobian_params_derivatives.begin()) + hessian_output << ", "; + + int eq = it->first.first; + string var = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); + int lag = getLagByDerivID(it->first.second.first); + string param = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); + expr_t d2 = it->second; + + hessian_output << "{\"eq\": " << eq + << ", \"var\": \"" << var << "\"" + << ", \"lag\": " << lag + << ", \"param\": \"" << param << "\"" + << ", \"val\": \""; + d2->writeJsonOutput(hessian_output, params_derivs_temporary_terms, tef_terms); + hessian_output << "\"}" << endl; + } + hessian_output << "]}"; + + hessian1_output << "\"second_deriv_residuals_wrt_params\": {" + << " \"nrows\": " << equations.size() + << ", \"nparam1cols\": " << symbol_table.param_nbr() + << ", \"nparam2cols\": " << symbol_table.param_nbr() + << ", \"entries\": ["; + for (second_derivatives_t::const_iterator it = residuals_params_second_derivatives.begin(); + it != residuals_params_second_derivatives.end(); ++it) + { + if (it != residuals_params_second_derivatives.begin()) + hessian1_output << ", "; + + int eq = it->first.first; + string param1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); + string param2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); + expr_t d2 = it->second; + + hessian1_output << "{\"eq\": " << eq + << ", \"param1\": \"" << param1 << "\"" + << ", \"param2\": \"" << param2 << "\"" + << ", \"val\": \""; + d2->writeJsonOutput(hessian1_output, params_derivs_temporary_terms, tef_terms); + hessian1_output << "\"}" << endl; + } + hessian1_output << "]}"; + third_derivs_output << "\"second_deriv_jacobian_wrt_params\": {" + << " \"neqs\": " << equations.size() + << ", \"nvarcols\": " << dynJacobianColsNbr + << ", \"nparam1cols\": " << symbol_table.param_nbr() + << ", \"nparam2cols\": " << symbol_table.param_nbr() + << ", \"entries\": ["; + for (third_derivatives_t::const_iterator it = jacobian_params_second_derivatives.begin(); + it != jacobian_params_second_derivatives.end(); ++it) + { + if (it != jacobian_params_second_derivatives.begin()) + third_derivs_output << ", "; + + int eq = it->first.first; + string var = symbol_table.getName(it->first.second.first); + int lag = getLagByDerivID(it->first.second.first); + string param1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.first)); + string param2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); + expr_t d2 = it->second; + + third_derivs_output << "{\"eq\": " << eq + << ", \"var\": \"" << var << "\"" + << ", \"lag\": " << lag + << ", \"param1\": \"" << param1 << "\"" + << ", \"param2\": \"" << param2 << "\"" + << ", \"val\": \""; + d2->writeJsonOutput(third_derivs_output, params_derivs_temporary_terms, tef_terms); + third_derivs_output << "\"}" << endl; + } + third_derivs_output << "]}" << endl; + + third_derivs1_output << "\"derivative_hessian_wrt_params\": {" + << " \"neqs\": " << equations.size() + << ", \"nvar1cols\": " << dynJacobianColsNbr + << ", \"nvar2cols\": " << dynJacobianColsNbr + << ", \"nparamcols\": " << symbol_table.param_nbr() + << ", \"entries\": ["; + for (third_derivatives_t::const_iterator it = hessian_params_derivatives.begin(); + it != hessian_params_derivatives.end(); ++it) + { + if (it != hessian_params_derivatives.begin()) + third_derivs1_output << ", "; + + int eq = it->first.first; + string var1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); + int lag1 = getLagByDerivID(it->first.second.first); + string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.first)); + int lag2 = getLagByDerivID(it->first.second.second.first); + string param = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); + expr_t d2 = it->second; + + third_derivs1_output << "{\"eq\": " << eq + << ", \"var1\": \"" << var1 << "\"" + << ", \"lag1\": " << lag1 + << ", \"var2\": \"" << var2 << "\"" + << ", \"lag2\": " << lag2 + << ", \"param1\": \"" << param << "\"" + << ", \"val\": \""; + d2->writeJsonOutput(third_derivs1_output, params_derivs_temporary_terms, tef_terms); + third_derivs1_output << "\"}" << endl; + } + third_derivs1_output << "]}" << endl; + + output << "\"dynamic_model_params_derivatives\": {" + << model_local_vars_output.str() + << ", " << model_output.str() + << ", " << jacobian_output.str() + << ", " << hessian_output.str() + << ", " << hessian1_output.str() + << ", " << third_derivs_output.str() + << ", " << third_derivs1_output.str() + << "}"; } diff --git a/DynamicModel.hh b/DynamicModel.hh index e79ac7f4..87e41e38 100644 --- a/DynamicModel.hh +++ b/DynamicModel.hh @@ -220,6 +220,12 @@ public: //! Write JSON Output void writeJsonOutput(ostream &output) const; + //! Write JSON Output representation of dynamic model after computing pass + void writeJsonComputingPassOutput(ostream &output) const; + + //! Write JSON prams derivatives file + void writeJsonParamsDerivativesFile(ostream &output) const; + //! Return true if the hessian is equal to zero inline bool checkHessianZero() const; diff --git a/DynareMain.cc b/DynareMain.cc index c5650926..cd62325c 100644 --- a/DynareMain.cc +++ b/DynareMain.cc @@ -45,7 +45,7 @@ void main2(stringstream &in, string &basename, bool debug, bool clear_all, bool #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) , bool cygwin, bool msvc, bool mingw #endif - , bool json, JsonFileOutputType json_output_mode + , JsonOutputPointType json, JsonFileOutputType json_output_mode ); void main1(char *modfile, string &basename, bool debug, bool save_macro, string &save_macro_file, @@ -62,7 +62,7 @@ usage() #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) << " [cygwin] [msvc] [mingw]" #endif - << "[json] [jsonstdout]" + << "[json=parse|check|transform|compute] [jsonstdout]" << endl; exit(EXIT_FAILURE); } @@ -115,7 +115,7 @@ main(int argc, char **argv) map defines; vector path; FileOutputType output_mode = none; - bool json = false; + JsonOutputPointType json = nojson; JsonFileOutputType json_output_mode = file; LanguageOutputType language = matlab; @@ -297,8 +297,27 @@ main(int argc, char **argv) } else if (!strcmp(argv[arg], "jsonstdout")) json_output_mode = standardout; - else if (!strcmp(argv[arg], "json")) - json = true; + else if (strlen(argv[arg]) >= 4 && !strncmp(argv[arg], "json", 4)) + { + if (strlen(argv[arg]) <= 5 || argv[arg][4] != '=') + { + cerr << "Incorrect syntax for json option" << endl; + usage(); + } + if (strlen(argv[arg]) == 10 && !strncmp(argv[arg] + 5, "parse", 5)) + json = parsing; + else if (strlen(argv[arg]) == 10 && !strncmp(argv[arg] + 5, "check", 5)) + json = checkpass; + else if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 5, "transform", 9)) + json = transformpass; + else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 5, "compute", 7)) + json = computingpass; + else + { + cerr << "Incorrect syntax for json option" << endl; + usage(); + } + } else { cerr << "Unknown option: " << argv[arg] << endl; diff --git a/DynareMain2.cc b/DynareMain2.cc index 3bbc4b4f..bc2d34ff 100644 --- a/DynareMain2.cc +++ b/DynareMain2.cc @@ -34,32 +34,33 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) , bool cygwin, bool msvc, bool mingw #endif - , bool json, JsonFileOutputType json_output_mode + , JsonOutputPointType json, JsonFileOutputType json_output_mode ) { ParsingDriver p(warnings, nostrict); // Do parsing and construct internal representation of mod file ModFile *mod_file = p.parse(in, debug); - if (json) - { - mod_file->symbol_table.freeze(); - mod_file->writeJsonOutput(basename, json_output_mode); - mod_file->symbol_table.unfreeze(); - cout << "JSON file written after Parsing step." << endl; - } + if (json == parsing) + mod_file->writeJsonOutput(basename, json, json_output_mode); // Run checking pass mod_file->checkPass(nostrict); + if (json == checkpass) + mod_file->writeJsonOutput(basename, json, json_output_mode); // Perform transformations on the model (creation of auxiliary vars and equations) mod_file->transformPass(nostrict); + if (json == transformpass) + mod_file->writeJsonOutput(basename, json, json_output_mode); // Evaluate parameters initialization, initval, endval and pounds mod_file->evalAllExpressions(warn_uninit); // Do computations mod_file->computingPass(no_tmp_terms, output_mode, compute_xrefs, params_derivs_order); + if (json == computingpass) + mod_file->writeJsonOutput(basename, json, json_output_mode); // Write outputs if (output_mode != none) diff --git a/ExprNode.cc b/ExprNode.cc index ccba75c2..b5b9d4dd 100644 --- a/ExprNode.cc +++ b/ExprNode.cc @@ -73,6 +73,13 @@ ExprNode::precedence(ExprNodeOutputType output_type, const temporary_terms_t &te return 100; } +int +ExprNode::precedenceJson(const temporary_terms_t &temporary_terms) const +{ + // For a constant, a variable, or a unary op, the precedence is maximal + return 100; +} + int ExprNode::cost(int cost, bool is_matlab) const { @@ -185,6 +192,14 @@ ExprNode::writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output // Nothing to do } +void +ExprNode::writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + // Nothing to do +} + void ExprNode::compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, @@ -323,7 +338,7 @@ NumConstNode::writeOutput(ostream &output, ExprNodeOutputType output_type, } void -NumConstNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, +NumConstNode::writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const { @@ -624,10 +639,17 @@ VariableNode::containsExternalFunction() const } void -VariableNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, +VariableNode::writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const { + temporary_terms_t::const_iterator it = temporary_terms.find(const_cast(this)); + if (it != temporary_terms.end()) + { + output << "T" << idx; + return; + } + output << datatree.symbol_table.getName(symb_id); if (lag != 0) output << "(" << lag << ")"; @@ -1869,13 +1891,20 @@ UnaryOpNode::containsExternalFunction() const } void -UnaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, +UnaryOpNode::writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const { + temporary_terms_t::const_iterator it = temporary_terms.find(const_cast(this)); + if (it != temporary_terms.end()) + { + output << "T" << idx; + return; + } + // Always put parenthesis around uminus nodes if (op_code == oUminus) - output << LEFT_PAR(output_type); + output << "("; switch (op_code) { @@ -1938,7 +1967,7 @@ UnaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, break; case oSteadyState: output << "("; - arg->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + arg->writeJsonOutput(output, temporary_terms, tef_terms); output << ")"; return; case oSteadyStateParamDeriv: @@ -1949,7 +1978,6 @@ UnaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, assert(datatree.symbol_table.getType(param1_symb_id) == eParameter); int tsid_endo = datatree.symbol_table.getTypeSpecificID(varg->symb_id); int tsid_param = datatree.symbol_table.getTypeSpecificID(param1_symb_id); - assert(IS_MATLAB(output_type)); output << "ss_param_deriv(" << tsid_endo+1 << "," << tsid_param+1 << ")"; } return; @@ -1963,7 +1991,6 @@ UnaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, int tsid_endo = datatree.symbol_table.getTypeSpecificID(varg->symb_id); int tsid_param1 = datatree.symbol_table.getTypeSpecificID(param1_symb_id); int tsid_param2 = datatree.symbol_table.getTypeSpecificID(param2_symb_id); - assert(IS_MATLAB(output_type)); output << "ss_param_2nd_deriv(" << tsid_endo+1 << "," << tsid_param1+1 << "," << tsid_param2+1 << ")"; } @@ -1984,23 +2011,21 @@ UnaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, */ if (op_code != oUminus || (op_code == oUminus - && arg->precedence(output_type, temporary_terms) < precedence(output_type, temporary_terms))) + && arg->precedenceJson(temporary_terms) < precedenceJson(temporary_terms))) { - output << LEFT_PAR(output_type); - if (op_code == oSign && (output_type == oCDynamicModel || output_type == oCStaticModel)) - output << "1.0,"; + output << "("; close_parenthesis = true; } // Write argument - arg->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + arg->writeJsonOutput(output, temporary_terms, tef_terms); if (close_parenthesis) - output << RIGHT_PAR(output_type); + output << ")"; // Close parenthesis for uminus if (op_code == oUminus) - output << RIGHT_PAR(output_type); + output << ")"; } void @@ -2197,6 +2222,14 @@ UnaryOpNode::writeExternalFunctionOutput(ostream &output, ExprNodeOutputType out arg->writeExternalFunctionOutput(output, output_type, temporary_terms, tef_terms); } +void +UnaryOpNode::writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + arg->writeJsonExternalFunctionOutput(efout, temporary_terms, tef_terms); +} + void UnaryOpNode::compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, @@ -2963,6 +2996,43 @@ BinaryOpNode::precedence(ExprNodeOutputType output_type, const temporary_terms_t exit(EXIT_FAILURE); } +int +BinaryOpNode::precedenceJson(const temporary_terms_t &temporary_terms) const +{ + temporary_terms_t::const_iterator it = temporary_terms.find(const_cast(this)); + // A temporary term behaves as a variable + if (it != temporary_terms.end()) + return 100; + + switch (op_code) + { + case oEqual: + return 0; + case oEqualEqual: + case oDifferent: + return 1; + case oLessEqual: + case oGreaterEqual: + case oLess: + case oGreater: + return 2; + case oPlus: + case oMinus: + return 3; + case oTimes: + case oDivide: + return 4; + case oPower: + case oPowerDeriv: + return 5; + case oMin: + case oMax: + return 100; + } + // Suppress GCC warning + exit(EXIT_FAILURE); +} + int BinaryOpNode::cost(const map &temp_terms_map, bool is_matlab) const { @@ -3226,10 +3296,18 @@ BinaryOpNode::containsExternalFunction() const } void -BinaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, +BinaryOpNode::writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const { + // If current node is a temporary term + temporary_terms_t::const_iterator it = temporary_terms.find(const_cast(this)); + if (it != temporary_terms.end()) + { + output << "T" << idx; + return; + } + if (op_code == oMax || op_code == oMin) { switch (op_code) @@ -3243,32 +3321,32 @@ BinaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, default: ; } - arg1->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + arg1->writeJsonOutput(output, temporary_terms, tef_terms); output << ","; - arg2->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + arg2->writeJsonOutput(output, temporary_terms, tef_terms); output << ")"; return; } - int prec = precedence(output_type, temporary_terms); + int prec = precedenceJson(temporary_terms); bool close_parenthesis = false; // If left argument has a lower precedence, or if current and left argument are both power operators, // add parenthesis around left argument BinaryOpNode *barg1 = dynamic_cast(arg1); - if (arg1->precedence(output_type, temporary_terms) < prec + if (arg1->precedenceJson(temporary_terms) < prec || (op_code == oPower && barg1 != NULL && barg1->op_code == oPower)) { - output << LEFT_PAR(output_type); + output << "("; close_parenthesis = true; } // Write left argument - arg1->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + arg1->writeJsonOutput(output, temporary_terms, tef_terms); if (close_parenthesis) - output << RIGHT_PAR(output_type); + output << ")"; // Write current operator symbol switch (op_code) @@ -3321,21 +3399,21 @@ BinaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, - it is a minus operator with same precedence than current operator - it is a divide operator with same precedence than current operator */ BinaryOpNode *barg2 = dynamic_cast(arg2); - int arg2_prec = arg2->precedence(output_type, temporary_terms); + int arg2_prec = arg2->precedenceJson(temporary_terms); if (arg2_prec < prec - || (op_code == oPower && barg2 != NULL && barg2->op_code == oPower && !IS_LATEX(output_type)) + || (op_code == oPower && barg2 != NULL && barg2->op_code == oPower) || (op_code == oMinus && arg2_prec == prec) - || (op_code == oDivide && arg2_prec == prec && !IS_LATEX(output_type))) + || (op_code == oDivide && arg2_prec == prec)) { - output << LEFT_PAR(output_type); + output << "("; close_parenthesis = true; } // Write right argument - arg2->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + arg2->writeJsonOutput(output, temporary_terms, tef_terms); if (close_parenthesis) - output << RIGHT_PAR(output_type); + output << ")"; } void @@ -3527,6 +3605,15 @@ BinaryOpNode::writeExternalFunctionOutput(ostream &output, ExprNodeOutputType ou arg2->writeExternalFunctionOutput(output, output_type, temporary_terms, tef_terms); } +void +BinaryOpNode::writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + arg1->writeJsonExternalFunctionOutput(efout, temporary_terms, tef_terms); + arg2->writeJsonExternalFunctionOutput(efout, temporary_terms, tef_terms); +} + void BinaryOpNode::compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, @@ -4478,10 +4565,18 @@ TrinaryOpNode::containsExternalFunction() const } void -TrinaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, +TrinaryOpNode::writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const { + // If current node is a temporary term + temporary_terms_t::const_iterator it = temporary_terms.find(const_cast(this)); + if (it != temporary_terms.end()) + { + output << "T" << idx; + return; + } + switch (op_code) { case oNormcdf: @@ -4492,11 +4587,11 @@ TrinaryOpNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, break; } - arg1->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + arg1->writeJsonOutput(output, temporary_terms, tef_terms); output << ","; - arg2->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + arg2->writeJsonOutput(output, temporary_terms, tef_terms); output << ","; - arg3->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + arg3->writeJsonOutput(output, temporary_terms, tef_terms); output << ")"; } @@ -4576,6 +4671,16 @@ TrinaryOpNode::writeExternalFunctionOutput(ostream &output, ExprNodeOutputType o arg3->writeExternalFunctionOutput(output, output_type, temporary_terms, tef_terms); } +void +TrinaryOpNode::writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + arg1->writeJsonExternalFunctionOutput(efout, temporary_terms, tef_terms); + arg2->writeJsonExternalFunctionOutput(efout, temporary_terms, tef_terms); + arg3->writeJsonExternalFunctionOutput(efout, temporary_terms, tef_terms); +} + void TrinaryOpNode::compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, @@ -5181,7 +5286,7 @@ AbstractExternalFunctionNode::writeExternalFunctionArguments(ostream &output, Ex } void -AbstractExternalFunctionNode::writeJsonExternalFunctionArguments(ostream &output, ExprNodeOutputType output_type, +AbstractExternalFunctionNode::writeJsonExternalFunctionArguments(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const { @@ -5191,7 +5296,7 @@ AbstractExternalFunctionNode::writeJsonExternalFunctionArguments(ostream &output if (it != arguments.begin()) output << ","; - (*it)->writeJsonOutput(output, output_type, temporary_terms, tef_terms); + (*it)->writeJsonOutput(output, temporary_terms, tef_terms); } } @@ -5359,12 +5464,19 @@ ExternalFunctionNode::compileExternalFunctionOutput(ostream &CompileCode, unsign } void -ExternalFunctionNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, +ExternalFunctionNode::writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const { + temporary_terms_t::const_iterator it = temporary_terms.find(const_cast(this)); + if (it != temporary_terms.end()) + { + output << "T" << idx; + return; + } + output << datatree.symbol_table.getName(symb_id) << "("; - writeJsonExternalFunctionArguments(output, output_type, temporary_terms, tef_terms); + writeJsonExternalFunctionArguments(output, temporary_terms, tef_terms); output << ")"; } @@ -5477,6 +5589,42 @@ ExternalFunctionNode::writeExternalFunctionOutput(ostream &output, ExprNodeOutpu } } +void +ExternalFunctionNode::writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + int first_deriv_symb_id = datatree.external_functions_table.getFirstDerivSymbID(symb_id); + assert(first_deriv_symb_id != eExtFunSetButNoNameProvided); + + for (vector::const_iterator it = arguments.begin(); + it != arguments.end(); it++) + (*it)->writeJsonExternalFunctionOutput(efout, temporary_terms, tef_terms); + + if (!alreadyWrittenAsTefTerm(symb_id, tef_terms)) + { + tef_terms[make_pair(symb_id, arguments)] = (int) tef_terms.size(); + int indx = getIndxInTefTerms(symb_id, tef_terms); + int second_deriv_symb_id = datatree.external_functions_table.getSecondDerivSymbID(symb_id); + assert(second_deriv_symb_id != eExtFunSetButNoNameProvided); + + stringstream ef; + ef << "{\"external_function\": {" + << "\"output\": \"TEF_" << indx << "\""; + + if (symb_id == first_deriv_symb_id) + ef << ", \"output_d\": \"TEFD_" << indx << "\""; + + if (symb_id == second_deriv_symb_id) + ef << ", \"output_dd\": \"TEFDD_" << indx << "\""; + + ef << ", \"function\": \"" << datatree.symbol_table.getName(symb_id) << "("; + writeJsonExternalFunctionArguments(ef, temporary_terms, tef_terms); + ef << ")\"}}"; + efout.push_back(ef.str()); + } +} + expr_t ExternalFunctionNode::toStatic(DataTree &static_datatree) const { @@ -5559,10 +5707,31 @@ FirstDerivExternalFunctionNode::composeDerivatives(const vector &dargs) } void -FirstDerivExternalFunctionNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, +FirstDerivExternalFunctionNode::writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const { + // If current node is a temporary term + temporary_terms_t::const_iterator it = temporary_terms.find(const_cast(this)); + if (it != temporary_terms.end()) + { + output << "T" << idx; + return; + } + + const int first_deriv_symb_id = datatree.external_functions_table.getFirstDerivSymbID(symb_id); + assert(first_deriv_symb_id != eExtFunSetButNoNameProvided); + + const int tmpIndx = inputIndex - 1; + + if (first_deriv_symb_id == symb_id) + output << "TEFD_" << getIndxInTefTerms(symb_id, tef_terms) + << "[" << tmpIndx << "]"; + else if (first_deriv_symb_id == eExtFunNotSet) + output << "TEFD_fdd_" << getIndxInTefTerms(symb_id, tef_terms) << "_" << inputIndex; + else + output << "TEFD_def_" << getIndxInTefTerms(first_deriv_symb_id, tef_terms) + << "[" << tmpIndx << "]"; } void @@ -5752,6 +5921,47 @@ FirstDerivExternalFunctionNode::writeExternalFunctionOutput(ostream &output, Exp } } +void +FirstDerivExternalFunctionNode::writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + int first_deriv_symb_id = datatree.external_functions_table.getFirstDerivSymbID(symb_id); + assert(first_deriv_symb_id != eExtFunSetButNoNameProvided); + + /* For a node with derivs provided by the user function, call the method + on the non-derived node */ + if (first_deriv_symb_id == symb_id) + { + expr_t parent = datatree.AddExternalFunction(symb_id, arguments); + parent->writeJsonExternalFunctionOutput(efout, temporary_terms, tef_terms); + return; + } + + if (alreadyWrittenAsTefTerm(first_deriv_symb_id, tef_terms)) + return; + + stringstream ef; + if (first_deriv_symb_id == eExtFunNotSet) + ef << "{\"first_deriv_external_function\": {" + << "\"output\": \"TEFD_fdd_" << getIndxInTefTerms(symb_id, tef_terms) << "_" << inputIndex << "\"" + << ", \"analytic_derivative\": false" + << ", \"wrt\": " << inputIndex + << ", \"function\": \"" << datatree.symbol_table.getName(symb_id) << "("; + else + { + tef_terms[make_pair(first_deriv_symb_id, arguments)] = (int) tef_terms.size(); + ef << "{\"first_deriv_external_function\": {" + << "\"output\": \"TEFD_def_" << getIndxInTefTerms(first_deriv_symb_id, tef_terms) + << ", \"analytic_derivative\": true" + << ", \"function\": \"" << datatree.symbol_table.getName(first_deriv_symb_id) << "("; + } + + writeJsonExternalFunctionArguments(ef, temporary_terms, tef_terms); + ef << ")\"}}"; + efout.push_back(ef.str()); +} + void FirstDerivExternalFunctionNode::compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, @@ -5878,10 +6088,32 @@ SecondDerivExternalFunctionNode::composeDerivatives(const vector &dargs) } void -SecondDerivExternalFunctionNode::writeJsonOutput(ostream &output, ExprNodeOutputType output_type, +SecondDerivExternalFunctionNode::writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const { + // If current node is a temporary term + temporary_terms_t::const_iterator it = temporary_terms.find(const_cast(this)); + if (it != temporary_terms.end()) + { + output << "T" << idx; + return; + } + + const int second_deriv_symb_id = datatree.external_functions_table.getSecondDerivSymbID(symb_id); + assert(second_deriv_symb_id != eExtFunSetButNoNameProvided); + + const int tmpIndex1 = inputIndex1 - 1; + const int tmpIndex2 = inputIndex2 - 1; + + if (second_deriv_symb_id == symb_id) + output << "TEFDD_" << getIndxInTefTerms(symb_id, tef_terms) + << "[" << tmpIndex1 << "," << tmpIndex2 << "]"; + else if (second_deriv_symb_id == eExtFunNotSet) + output << "TEFDD_fdd_" << getIndxInTefTerms(symb_id, tef_terms) << "_" << inputIndex1 << "_" << inputIndex2; + else + output << "TEFDD_def_" << getIndxInTefTerms(second_deriv_symb_id, tef_terms) + << "[" << tmpIndex1 << "," << tmpIndex2 << "]"; } void @@ -6048,6 +6280,48 @@ SecondDerivExternalFunctionNode::writeExternalFunctionOutput(ostream &output, Ex } } +void +SecondDerivExternalFunctionNode::writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const +{ + int second_deriv_symb_id = datatree.external_functions_table.getSecondDerivSymbID(symb_id); + assert(second_deriv_symb_id != eExtFunSetButNoNameProvided); + + /* For a node with derivs provided by the user function, call the method + on the non-derived node */ + if (second_deriv_symb_id == symb_id) + { + expr_t parent = datatree.AddExternalFunction(symb_id, arguments); + parent->writeJsonExternalFunctionOutput(efout, temporary_terms, tef_terms); + return; + } + + if (alreadyWrittenAsTefTerm(second_deriv_symb_id, tef_terms)) + return; + + stringstream ef; + if (second_deriv_symb_id == eExtFunNotSet) + ef << "{\"second_deriv_external_function\": {" + << "\"output\": \"TEFDD_fdd_" << getIndxInTefTerms(symb_id, tef_terms) << "_" << inputIndex1 << "_" << inputIndex2 << "\"" + << ", \"analytic_derivative\": false" + << ", \"wrt1\": " << inputIndex1 + << ", \"wrt2\": " << inputIndex2 + << ", \"function\": \"" << datatree.symbol_table.getName(symb_id) << "("; + else + { + tef_terms[make_pair(second_deriv_symb_id, arguments)] = (int) tef_terms.size(); + ef << "{\"second_deriv_external_function\": {" + << "\"output\": \"TEFDD_def_" << getIndxInTefTerms(second_deriv_symb_id, tef_terms) + << ", \"analytic_derivative\": true" + << ", \"function\": \"" << datatree.symbol_table.getName(second_deriv_symb_id) << "("; + } + + writeJsonExternalFunctionArguments(ef, temporary_terms, tef_terms); + ef << ")\"}}" << endl; + efout.push_back(ef.str()); +} + expr_t SecondDerivExternalFunctionNode::cloneDynamic(DataTree &dynamic_datatree) const { diff --git a/ExprNode.hh b/ExprNode.hh index 32654071..e4e5d9bc 100644 --- a/ExprNode.hh +++ b/ExprNode.hh @@ -222,13 +222,21 @@ public: void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms) const; //! Writes output of node in JSON syntax - virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; + virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) 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, 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 &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) 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, @@ -481,7 +489,7 @@ public: }; virtual void prepareForDerivation(); virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; - virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void collectDynamicVariables(SymbolType type_arg, set > &result) const; virtual void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const; @@ -531,7 +539,7 @@ public: VariableNode(DataTree &datatree_arg, int symb_id_arg, int lag_arg); virtual void prepareForDerivation(); virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; - virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void collectDynamicVariables(SymbolType type_arg, set > &result) const; virtual void computeTemporaryTerms(map &reference_count, @@ -607,11 +615,14 @@ public: map &temp_terms_map, bool is_matlab, NodeTreeReference tr) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; - virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) 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, @@ -690,16 +701,20 @@ public: BinaryOpNode(DataTree &datatree_arg, const expr_t arg1_arg, BinaryOpcode op_code_arg, const expr_t arg2_arg, int powerDerivOrder); virtual void prepareForDerivation(); + virtual int precedenceJson(const temporary_terms_t &temporary_terms) const; virtual int precedence(ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms) const; virtual void computeTemporaryTerms(map > &reference_count, map &temp_terms_map, bool is_matlab, NodeTreeReference tr) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; - virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) 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, @@ -801,11 +816,14 @@ public: map &temp_terms_map, bool is_matlab, NodeTreeReference tr) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; - virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual bool containsExternalFunction() const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) 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, @@ -872,7 +890,7 @@ protected: int getIndxInTefTerms(int the_symb_id, deriv_node_temp_terms_t &tef_terms) const throw (UnknownFunctionNameAndArgs); //! Helper function to write output arguments of any given external function void writeExternalFunctionArguments(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; - void writeJsonExternalFunctionArguments(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + void writeJsonExternalFunctionArguments(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; public: AbstractExternalFunctionNode(DataTree &datatree_arg, int symb_id_arg, const vector &arguments_arg); @@ -881,11 +899,14 @@ public: map &temp_terms_map, bool is_matlab, NodeTreeReference tr) const = 0; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; - virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; + virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; virtual bool containsExternalFunction() const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; + virtual void writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const = 0; 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, @@ -948,10 +969,13 @@ public: map &temp_terms_map, bool is_matlab, NodeTreeReference tr) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; - virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) 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, @@ -989,7 +1013,7 @@ public: vector< vector > &v_temporary_terms, int equation) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; - virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; 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, @@ -997,6 +1021,9 @@ public: virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) 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, @@ -1029,7 +1056,7 @@ public: vector< vector > &v_temporary_terms, int equation) const; virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; - virtual void writeJsonOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; 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, @@ -1037,6 +1064,9 @@ public: virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const; + virtual void writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) 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, diff --git a/ExtendedPreprocessorTypes.hh b/ExtendedPreprocessorTypes.hh index 1388cafc..26c8ac19 100644 --- a/ExtendedPreprocessorTypes.hh +++ b/ExtendedPreprocessorTypes.hh @@ -44,4 +44,13 @@ enum JsonFileOutputType file, // output JSON files to file standardout, // output JSON files to stdout }; + +enum 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 + }; #endif diff --git a/ModFile.cc b/ModFile.cc index 78ae952a..4cf0ba1b 100644 --- a/ModFile.cc +++ b/ModFile.cc @@ -1248,7 +1248,44 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output) } void -ModFile::writeJsonOutput(const string &basename, JsonFileOutputType json_output_mode) const +ModFile::writeJsonOutput(const string &basename, JsonOutputPointType json, JsonFileOutputType json_output_mode) +{ + if (json == nojson) + return; + + if (json == parsing || json == checkpass) + symbol_table.freeze(); + + writeJsonOutputParsingCheck(basename, json_output_mode); + + if (json == parsing || json == checkpass) + symbol_table.unfreeze(); + + if (json == computingpass) + writeJsonComputingPassOutput(basename, json_output_mode); + + switch (json) + { + case parsing: + cout << "JSON written after Parsing step." << endl; + break; + case checkpass: + cout << "JSON written after Check step." << endl; + break; + case transformpass: + cout << "JSON written after Transform step." << endl; + break; + case computingpass: + cout << "JSON written after Computing step." << endl; + break; + case nojson: + cerr << "ModFile::writeJsonOutput: should not arrive here." << endl; + exit(EXIT_FAILURE); + } +} + +void +ModFile::writeJsonOutputParsingCheck(const string &basename, JsonFileOutputType json_output_mode) const { ostringstream output; output << "{" << endl; @@ -1298,3 +1335,105 @@ ModFile::writeJsonOutput(const string &basename, JsonFileOutputType json_output_ jsonOutputFile.close(); } } + +void +ModFile::writeJsonComputingPassOutput(const string &basename, JsonFileOutputType json_output_mode) const +{ + ostringstream static_output; + static_output << "{"; + static_model.writeJsonComputingPassOutput(static_output); + static_output << "}" << endl; + + ostringstream dynamic_output; + dynamic_output << "{"; + dynamic_model.writeJsonComputingPassOutput(dynamic_output); + dynamic_output << "}" << endl; + + ostringstream tmp_out, static_paramsd_output; + tmp_out << ""; + static_paramsd_output << ""; + static_model.writeJsonParamsDerivativesFile(tmp_out); + if (!tmp_out.str().empty()) + static_paramsd_output << "{" << tmp_out.str() << "}" << endl; + + ostringstream tmp1_out, dynamic_paramsd_output; + tmp1_out << ""; + dynamic_paramsd_output << ""; + dynamic_model.writeJsonParamsDerivativesFile(tmp1_out); + if (!tmp1_out.str().empty()) + dynamic_paramsd_output << "{" << tmp1_out.str() << "}" << endl; + + if (json_output_mode == standardout) + { + cout << static_output.str() << endl; + cout << dynamic_output.str() << endl; + if (!dynamic_paramsd_output.str().empty()) + cout << dynamic_paramsd_output.str() << endl; + if (!static_paramsd_output.str().empty()) + cout << static_paramsd_output.str() << endl; + } + else + { + if (basename.empty()) + { + cerr << "ERROR: Missing file name" << endl; + exit(EXIT_FAILURE); + } + + string fname_static, fname_dynamic; + fname_static = basename + "_static.json"; + fname_dynamic = basename + "_dynamic.json"; + + ofstream jsonOutputFileStatic, jsonOutputFileDynamic; + jsonOutputFileStatic.open(fname_static.c_str(), ios::out | ios::binary); + if (!jsonOutputFileStatic.is_open()) + { + cerr << "ERROR: Can't open file " << fname_static << " for writing" << endl; + exit(EXIT_FAILURE); + } + + jsonOutputFileDynamic.open(fname_dynamic.c_str(), ios::out | ios::binary); + if (!jsonOutputFileDynamic.is_open()) + { + cerr << "ERROR: Can't open file " << fname_dynamic << " for writing" << endl; + exit(EXIT_FAILURE); + } + + jsonOutputFileStatic << static_output.str(); + jsonOutputFileStatic.close(); + jsonOutputFileDynamic << dynamic_output.str(); + jsonOutputFileDynamic.close(); + + if (!static_paramsd_output.str().empty()) + { + string fname_static_params; + fname_static_params = basename + "_static_params_derivs.json"; + ofstream jsonOutputFileStaticParamsDerivs; + jsonOutputFileStaticParamsDerivs.open(fname_static_params.c_str(), ios::out | ios::binary); + if (!jsonOutputFileStaticParamsDerivs.is_open()) + { + cerr << "ERROR: Can't open file " << fname_static_params << " for writing" << endl; + exit(EXIT_FAILURE); + } + + jsonOutputFileStaticParamsDerivs << static_paramsd_output.str(); + jsonOutputFileStaticParamsDerivs.close(); + } + + if (!dynamic_paramsd_output.str().empty()) + { + string fname_dynamic_params; + fname_dynamic_params = basename + "_params_derivs.json"; + ofstream jsonOutputFileDynamicParamsDerivs; + jsonOutputFileDynamicParamsDerivs.open(fname_dynamic_params.c_str(), ios::out | ios::binary); + if (!jsonOutputFileDynamicParamsDerivs.is_open()) + { + cerr << "ERROR: Can't open file " << fname_dynamic_params << " for writing" << endl; + exit(EXIT_FAILURE); + } + + jsonOutputFileDynamicParamsDerivs << dynamic_paramsd_output.str(); + jsonOutputFileDynamicParamsDerivs.close(); + } + } +} diff --git a/ModFile.hh b/ModFile.hh index b83f984d..684d592e 100644 --- a/ModFile.hh +++ b/ModFile.hh @@ -117,6 +117,9 @@ private: ModFileStructure mod_file_struct; //! Warnings Encountered WarningConsolidation &warnings; + //! Functions used in writing of JSON outut. See writeJsonOutput + void writeJsonOutputParsingCheck(const string &basename, JsonFileOutputType json_output_mode) const; + void writeJsonComputingPassOutput(const string &basename, JsonFileOutputType json_output_mode) const; public: //! Add a statement @@ -171,7 +174,7 @@ public: //! Initially created to enable Julia to work with .mod files //! Potentially outputs ModFile after the various parts of processing (parsing, checkPass, transformPass, computingPass) //! Allows user of other host language platforms (python, fortran, etc) to provide support for dynare .mod files - void writeJsonOutput(const string &basename, JsonFileOutputType json_output_mode) const; + void writeJsonOutput(const string &basename, JsonOutputPointType json, JsonFileOutputType json_output_mode); }; #endif // ! MOD_FILE_HH diff --git a/ModelTree.cc b/ModelTree.cc index 444aec2b..3e2b7395 100644 --- a/ModelTree.cc +++ b/ModelTree.cc @@ -1292,6 +1292,59 @@ ModelTree::writeTemporaryTerms(const temporary_terms_t &tt, const temporary_term } } +void +ModelTree::writeJsonTemporaryTerms(const temporary_terms_t &tt, const temporary_terms_t &ttm1, ostream &output, + deriv_node_temp_terms_t &tef_terms, string &concat) const +{ + // Local var used to keep track of temp nodes already written + bool wrote_term = false; + temporary_terms_t tt2 = ttm1; + + output << "\"external_functions_temporary_terms_" << concat << "\": ["; + for (temporary_terms_t::const_iterator it = tt.begin(); + it != tt.end(); it++) + if (ttm1.find(*it) == ttm1.end()) + { + if (dynamic_cast(*it) != NULL) + { + if (wrote_term) + output << ", "; + vector efout; + (*it)->writeJsonExternalFunctionOutput(efout, tt2, tef_terms); + for (vector::const_iterator it1 = efout.begin(); it1 != efout.end(); it1++) + { + if (it1 != efout.begin()) + output << ", "; + output << *it1; + } + wrote_term = true; + } + tt2.insert(*it); + } + + tt2 = ttm1; + wrote_term = false; + output << "]" + << ", \"temporary_terms_" << concat << "\": ["; + for (temporary_terms_t::const_iterator it = tt.begin(); + it != tt.end(); it++) + if (ttm1.find(*it) == ttm1.end()) + { + if (wrote_term) + output << ", "; + output << "{\"temporary_term\": \""; + (*it)->writeJsonOutput(output, tt, tef_terms); + output << " = "; + (*it)->writeJsonOutput(output, tt2, tef_terms); + output << "\"}" << endl; + wrote_term = true; + + // Insert current node into tt2 + tt2.insert(*it); + } + output << "]"; +} + void ModelTree::fixNestedParenthesis(ostringstream &output, map &tmp_paren_vars, bool &message_printed) const { @@ -1481,6 +1534,51 @@ ModelTree::writeModelLocalVariables(ostream &output, ExprNodeOutputType output_t } } +void +ModelTree::writeJsonModelLocalVariables(ostream &output, deriv_node_temp_terms_t &tef_terms) const +{ + /* Collect all model local variables appearing in equations, and print only + them. Printing unused model local variables can lead to a crash (see + ticket #101). */ + set used_local_vars; + + // Use an empty set for the temporary terms + const temporary_terms_t tt; + + for (size_t i = 0; i < equations.size(); i++) + equations[i]->collectVariables(eModelLocalVariable, used_local_vars); + + output << "\"external_functions_model_local_variables\": ["; + for (set::const_iterator it = used_local_vars.begin(); + it != used_local_vars.end(); ++it) + { + vector efout; + expr_t value = local_variables_table.find(*it)->second; + value->writeJsonExternalFunctionOutput(efout, tt, tef_terms); + for (vector::const_iterator it1 = efout.begin(); it1 != efout.end(); it1++) + { + if (it1 != efout.begin()) + output << ", "; + output << *it1; + } + } + output << "]" + << ", \"model_local_variables\": ["; + for (set::const_iterator it = used_local_vars.begin(); + it != used_local_vars.end(); ++it) + { + int id = *it; + expr_t value = local_variables_table.find(id)->second; + + /* We append underscores to avoid name clashes with "g1" or "oo_" (see + also VariableNode::writeOutput) */ + output << "{\"" << symbol_table.getName(id) << "__ = "; + value->writeJsonOutput(output, tt, tef_terms); + output << "\"}" << endl; + } + output << "]"; +} + void ModelTree::writeModelEquations(ostream &output, ExprNodeOutputType output_type) const { @@ -1920,37 +2018,76 @@ bool ModelTree::isNonstationary(int symb_id) const } void -ModelTree::writeJsonModelEquations(ostream &output) const +ModelTree::writeJsonModelEquations(ostream &output, bool residuals) const { deriv_node_temp_terms_t tef_terms; vector > eqtags; - output << endl << ",\"model\":[" << endl; + temporary_terms_t tt_empty; + if (residuals) + output << endl << ",\"residuals\":[" << endl; + else + output << endl << ",\"model\":[" << endl; for (int eq = 0; eq < (int) equations.size(); eq++) { - output << "{ \"equation\": \""; - equations[eq]->writeJsonOutput(output, oMatlabDynamicModel, temporary_terms, tef_terms); - output << "\", \"line\": " << equations_lineno[eq]; - for (vector > >::const_iterator it = equation_tags.begin(); - it != equation_tags.end(); it++) - if (it->first == eq) - eqtags.push_back(it->second); + if (eq > 0) + output << ", "; - if (!eqtags.empty()) + if (residuals) { - output << ", \"tags\": {"; - int i = 0; - for (vector >:: const_iterator it = eqtags.begin(); it != eqtags.end(); it++, i++) + BinaryOpNode *eq_node = equations[eq]; + expr_t lhs = eq_node->get_arg1(); + expr_t rhs = eq_node->get_arg2(); + + output << "{\"residual\": {" + << "\"lhs\": \""; + lhs->writeJsonOutput(output, temporary_terms, tef_terms); + output << "\""; + + output << ", \"rhs\": \""; + rhs->writeJsonOutput(output, temporary_terms, tef_terms); + output << "\""; + try + { + // Test if the right hand side of the equation is empty. + if (rhs->eval(eval_context_t()) != 0) + { + output << ", \"rhs\": \""; + rhs->writeJsonOutput(output, temporary_terms, tef_terms); + output << "\""; + } + } + catch (ExprNode::EvalException &e) { - if (i != 0) - output << ", "; - output << "\"" << it->first << "\": \"" << it->second << "\""; } output << "}"; - eqtags.clear(); } - output << "}"; - if (eq < (int) equations.size() - 1) - output << "," << endl; + else + { + output << "{\"equation\": \""; + equations[eq]->writeJsonOutput(output, tt_empty, tef_terms); + output << "\"" + << ", \"line\": " << equations_lineno[eq]; + + for (vector > >::const_iterator it = equation_tags.begin(); + it != equation_tags.end(); it++) + if (it->first == eq) + eqtags.push_back(it->second); + + if (!eqtags.empty()) + { + output << ", \"tags\": {"; + int i = 0; + for (vector >:: const_iterator it = eqtags.begin(); it != eqtags.end(); it++, i++) + { + if (i != 0) + output << ", "; + output << "\"" << it->first << "\": \"" << it->second << "\""; + } + output << "}"; + eqtags.clear(); + } + } + output << "}" << endl; } output << endl << "]" << endl; } diff --git a/ModelTree.hh b/ModelTree.hh index d74598d8..ac6bfca8 100644 --- a/ModelTree.hh +++ b/ModelTree.hh @@ -186,6 +186,7 @@ protected: void computeParamsDerivativesTemporaryTerms(); //! Writes temporary terms void writeTemporaryTerms(const temporary_terms_t &tt, const temporary_terms_t &ttm1, ostream &output, ExprNodeOutputType output_type, deriv_node_temp_terms_t &tef_terms) const; + void writeJsonTemporaryTerms(const temporary_terms_t &tt, const temporary_terms_t &ttm1, ostream &output, deriv_node_temp_terms_t &tef_terms, string &concat) const; //! Compiles temporary terms void compileTemporaryTerms(ostream &code_file, unsigned int &instruction_number, const temporary_terms_t &tt, map_idx_t map_idx, bool dynamic, bool steady_dynamic) const; //! Adds informations for simulation in a binary file @@ -200,7 +201,10 @@ protected: //! Writes model equations void writeModelEquations(ostream &output, ExprNodeOutputType output_type) const; //! Writes JSON model equations - void writeJsonModelEquations(ostream &output) const; + //! if residuals = true, we are writing the dynamic/static model. + //! Otherwise, just the model equations (with line numbers, no tmp terms) + void writeJsonModelEquations(ostream &output, bool residuals) const; + void writeJsonModelLocalVariables(ostream &output, deriv_node_temp_terms_t &tef_terms) const; //! Compiles model equations void compileModelEquations(ostream &code_file, unsigned int &instruction_number, const temporary_terms_t &tt, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic) const; diff --git a/NumericalInitialization.cc b/NumericalInitialization.cc index 22c013b3..59ef96ad 100644 --- a/NumericalInitialization.cc +++ b/NumericalInitialization.cc @@ -68,7 +68,7 @@ InitParamStatement::writeJsonOutput(ostream &output) const { deriv_node_temp_terms_t tef_terms; output << "{\"statementName\": \"param_init\", \"name\": \"" << symbol_table.getName(symb_id) << "\", " << "\"value\": \""; - param_value->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + param_value->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}"; } @@ -184,7 +184,7 @@ InitOrEndValStatement::writeJsonInitValues(ostream &output) const if (it != init_values.begin()) output << ", "; output << "{\"name\": \"" << symbol_table.getName(it->first) << "\", " << "\"value\": \""; - it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->second->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}"; } } @@ -428,7 +428,7 @@ HistValStatement::writeJsonOutput(ostream &output) const output << "{ \"name\": \"" << symbol_table.getName(it->first.first) << "\"" << ", \"lag\": " << it->first.second << ", \"value\": \""; - it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->second->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}"; } output << "]}"; @@ -526,11 +526,11 @@ HomotopyStatement::writeJsonOutput(ostream &output) const output << "{\"name\": \"" << symbol_table.getName(it->first) << "\"" << ", \"initial_value\": \""; if (it->second.first != NULL) - it->second.first->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->second.first->writeJsonOutput(output, temporary_terms_t(), tef_terms); else output << "NaN"; output << "\", \"final_value\": \""; - it->second.second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->second.second->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}"; } output << "]" diff --git a/Shocks.cc b/Shocks.cc index 95391092..4835b370 100644 --- a/Shocks.cc +++ b/Shocks.cc @@ -87,7 +87,7 @@ AbstractShocksStatement::writeJsonDetShocks(ostream &output) const output << "{\"period1\": " << it1->period1 << ", " << "\"period2\": " << it1->period2 << ", " << "\"value\": \""; - it1->value->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it1->value->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}"; } output << "]}"; @@ -174,7 +174,7 @@ ShocksStatement::writeJsonOutput(ostream &output) const output << ", "; output << "{\"name\": \"" << symbol_table.getName(it->first) << "\", " << "\"variance\": \""; - it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->second->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}"; } output << "]" @@ -185,7 +185,7 @@ ShocksStatement::writeJsonOutput(ostream &output) const output << ", "; output << "{\"name\": \"" << symbol_table.getName(it->first) << "\", " << "\"stderr\": \""; - it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->second->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}"; } output << "]" @@ -198,7 +198,7 @@ ShocksStatement::writeJsonOutput(ostream &output) const << "\"name\": \"" << symbol_table.getName(it->first.first) << "\", " << "\"name2\": \"" << symbol_table.getName(it->first.second) << "\", " << "\"covariance\": \""; - it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->second->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}"; } output << "]" @@ -211,7 +211,7 @@ ShocksStatement::writeJsonOutput(ostream &output) const << "\"name\": \"" << symbol_table.getName(it->first.first) << "\", " << "\"name2\": \"" << symbol_table.getName(it->first.second) << "\", " << "\"correlation\": \""; - it->second->writeJsonOutput(output, oMatlabOutsideModel, temporary_terms_t(), tef_terms); + it->second->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}"; } output << "]" diff --git a/StaticModel.cc b/StaticModel.cc index a7652f9b..4516a886 100644 --- a/StaticModel.cc +++ b/StaticModel.cc @@ -2414,3 +2414,287 @@ StaticModel::writeParamsDerivativesFile(const string &basename, bool julia) cons paramsDerivsFile.close(); } + +void +StaticModel::writeJsonComputingPassOutput(ostream &output) const +{ + ostringstream model_local_vars_output; // Used for storing model local vars + ostringstream model_output; // Used for storing model + ostringstream jacobian_output; // Used for storing jacobian equations + ostringstream hessian_output; // Used for storing Hessian equations + ostringstream third_derivatives_output; // Used for storing third order derivatives equations + + deriv_node_temp_terms_t tef_terms; + temporary_terms_t temp_term_empty; + temporary_terms_t temp_term_union = temporary_terms_res; + temporary_terms_t temp_term_union_m_1; + + string concat = ""; + + writeJsonModelLocalVariables(model_local_vars_output, tef_terms); + + writeJsonTemporaryTerms(temporary_terms_res, temp_term_union_m_1, model_output, tef_terms, concat); + + writeJsonModelEquations(model_output, true); + + int nrows = equations.size(); + int JacobianColsNbr = symbol_table.endo_nbr(); + int hessianColsNbr = JacobianColsNbr*JacobianColsNbr; + + // Write Jacobian w.r. to endogenous only + temp_term_union_m_1 = temp_term_union; + temp_term_union.insert(temporary_terms_g1.begin(), temporary_terms_g1.end()); + concat = "jacobian"; + writeJsonTemporaryTerms(temp_term_union, temp_term_union_m_1, jacobian_output, tef_terms, concat); + jacobian_output << ", \"jacobian\": {" + << " \"nrows\": " << nrows + << ", \"ncols\": " << JacobianColsNbr + << ", \"entries\": ["; + for (first_derivatives_t::const_iterator it = first_derivatives.begin(); + it != first_derivatives.end(); it++) + { + if (it != first_derivatives.begin()) + jacobian_output << ", "; + + int eq = it->first.first; + string var = symbol_table.getName(getSymbIDByDerivID(it->first.second)); + expr_t d1 = it->second; + + jacobian_output << "{\"eq\": " << eq + << ", \"var\": \"" << var << "\"" + << ", \"val\": \""; + d1->writeJsonOutput(jacobian_output, temp_term_union, tef_terms); + jacobian_output << "\"}" << endl; + } + jacobian_output << "]}"; + + int g2ncols = symbol_table.endo_nbr() * symbol_table.endo_nbr(); + // Write Hessian w.r. to endogenous only (only if 2nd order derivatives have been computed) + temp_term_union_m_1 = temp_term_union; + temp_term_union.insert(temporary_terms_g2.begin(), temporary_terms_g2.end()); + concat = "hessian"; + writeJsonTemporaryTerms(temp_term_union, temp_term_union_m_1, hessian_output, tef_terms, concat); + hessian_output << ", \"hessian\": {" + << " \"nrows\": " << equations.size() + << ", \"ncols\": " << g2ncols + << ", \"entries\": ["; + for (second_derivatives_t::const_iterator it = second_derivatives.begin(); + it != second_derivatives.end(); it++) + { + if (it != second_derivatives.begin()) + hessian_output << ", "; + + int eq = it->first.first; + string var1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); + string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); + expr_t d2 = it->second; + + hessian_output << "{\"eq\": " << eq + << ", \"var1\": \"" << var1 << "\"" + << ", \"var2\": \"" << var2 << "\"" + << ", \"val\": \""; + d2->writeJsonOutput(hessian_output, temp_term_union, tef_terms); + hessian_output << "\"}" << endl; + } + hessian_output << "]}"; + + // Writing third derivatives + temp_term_union_m_1 = temp_term_union; + temp_term_union.insert(temporary_terms_g3.begin(), temporary_terms_g3.end()); + concat = "third_derivatives"; + writeJsonTemporaryTerms(temp_term_union, temp_term_union_m_1, third_derivatives_output, tef_terms, concat); + third_derivatives_output << ", \"third_derivative\": {" + << " \"nrows\": " << equations.size() + << ", \"ncols\": " << hessianColsNbr * JacobianColsNbr + << ", \"entries\": ["; + for (third_derivatives_t::const_iterator it = third_derivatives.begin(); + it != third_derivatives.end(); it++) + { + if (it != third_derivatives.begin()) + third_derivatives_output << ", "; + + int eq = it->first.first; + string var1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); + string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.first)); + string var3 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); + expr_t d3 = it->second; + + third_derivatives_output << "{\"eq\": " << eq + << ", \"var1\": \"" << var1 << "\"" + << ", \"var2\": \"" << var2 << "\"" + << ", \"var3\": \"" << var3 << "\"" + << ", \"val\": \""; + d3->writeJsonOutput(third_derivatives_output, temp_term_union, tef_terms); + third_derivatives_output << "\"}" << endl; + } + third_derivatives_output << "]}"; + + output << "\"static_model_derivatives\": {" + << model_local_vars_output.str() + << ", " << model_output.str() + << ", " << jacobian_output.str() + << ", " << hessian_output.str() + << ", " << third_derivatives_output.str() + << "}"; +} + +void +StaticModel::writeJsonParamsDerivativesFile(ostream &output) const +{ + if (!residuals_params_derivatives.size() + && !residuals_params_second_derivatives.size() + && !jacobian_params_derivatives.size() + && !jacobian_params_second_derivatives.size() + && !hessian_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 + + deriv_node_temp_terms_t tef_terms; + writeJsonModelLocalVariables(model_local_vars_output, tef_terms); + + temporary_terms_t temp_terms_empty; + string concat = "all"; + writeJsonTemporaryTerms(params_derivs_temporary_terms, temp_terms_empty, model_output, tef_terms, concat); + jacobian_output << "\"deriv_wrt_params\": {" + << " \"neqs\": " << equations.size() + << ", \"nparamcols\": " << symbol_table.param_nbr() + << ", \"entries\": ["; + for (first_derivatives_t::const_iterator it = residuals_params_derivatives.begin(); + it != residuals_params_derivatives.end(); it++) + { + if (it != residuals_params_derivatives.begin()) + jacobian_output << ", "; + + int eq = it->first.first; + string param = symbol_table.getName(getSymbIDByDerivID(it->first.second)); + expr_t d1 = it->second; + + jacobian_output << "{\"eq\": " << eq + << ", \"param\": \"" << param << "\"" + << ", \"val\": \""; + d1->writeJsonOutput(jacobian_output, params_derivs_temporary_terms, tef_terms); + jacobian_output << "\"}" << endl; + } + jacobian_output << "]}"; + hessian_output << "\"deriv_jacobian_wrt_params\": {" + << " \"neqs\": " << equations.size() + << ", \"nvarcols\": " << symbol_table.endo_nbr() + << ", \"nparamcols\": " << symbol_table.param_nbr() + << ", \"entries\": ["; + for (second_derivatives_t::const_iterator it = jacobian_params_derivatives.begin(); + it != jacobian_params_derivatives.end(); it++) + { + if (it != jacobian_params_derivatives.begin()) + hessian_output << ", "; + + int eq = it->first.first; + string var = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); + string param = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); + expr_t d2 = it->second; + + hessian_output << "{\"eq\": " << eq + << ", \"var\": \"" << var << "\"" + << ", \"param\": \"" << param << "\"" + << ", \"val\": \""; + d2->writeJsonOutput(hessian_output, params_derivs_temporary_terms, tef_terms); + hessian_output << "\"}" << endl; + } + hessian_output << "]}"; + + hessian1_output << "\"second_deriv_residuals_wrt_params\": {" + << " \"nrows\": " << equations.size() + << ", \"nparam1cols\": " << symbol_table.param_nbr() + << ", \"nparam2cols\": " << symbol_table.param_nbr() + << ", \"entries\": ["; + for (second_derivatives_t::const_iterator it = residuals_params_second_derivatives.begin(); + it != residuals_params_second_derivatives.end(); ++it) + { + if (it != residuals_params_second_derivatives.begin()) + hessian1_output << ", "; + + int eq = it->first.first; + string param1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); + string param2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); + expr_t d2 = it->second; + + hessian1_output << "{\"eq\": " << eq + << ", \"param1\": \"" << param1 << "\"" + << ", \"param2\": \"" << param2 << "\"" + << ", \"val\": \""; + d2->writeJsonOutput(hessian1_output, params_derivs_temporary_terms, tef_terms); + hessian1_output << "\"}" << endl; + } + hessian1_output << "]}"; + third_derivs_output << "\"second_deriv_jacobian_wrt_params\": {" + << " \"neqs\": " << equations.size() + << ", \"nvarcols\": " << symbol_table.endo_nbr() + << ", \"nparam1cols\": " << symbol_table.param_nbr() + << ", \"nparam2cols\": " << symbol_table.param_nbr() + << ", \"entries\": ["; + for (third_derivatives_t::const_iterator it = jacobian_params_second_derivatives.begin(); + it != jacobian_params_second_derivatives.end(); ++it) + { + if (it != jacobian_params_second_derivatives.begin()) + third_derivs_output << ", "; + + int eq = it->first.first; + string var = symbol_table.getName(it->first.second.first); + string param1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.first)); + string param2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); + expr_t d2 = it->second; + + third_derivs_output << "{\"eq\": " << eq + << ", \"var\": \"" << var << "\"" + << ", \"param1\": \"" << param1 << "\"" + << ", \"param2\": \"" << param2 << "\"" + << ", \"val\": \""; + d2->writeJsonOutput(third_derivs_output, params_derivs_temporary_terms, tef_terms); + third_derivs_output << "\"}" << endl; + } + third_derivs_output << "]}" << endl; + + third_derivs1_output << "\"derivative_hessian_wrt_params\": {" + << " \"neqs\": " << equations.size() + << ", \"nvar1cols\": " << symbol_table.endo_nbr() + << ", \"nvar2cols\": " << symbol_table.endo_nbr() + << ", \"nparamcols\": " << symbol_table.param_nbr() + << ", \"entries\": ["; + for (third_derivatives_t::const_iterator it = hessian_params_derivatives.begin(); + it != hessian_params_derivatives.end(); ++it) + { + if (it != hessian_params_derivatives.begin()) + third_derivs1_output << ", "; + + int eq = it->first.first; + string var1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); + string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.first)); + string param = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); + expr_t d2 = it->second; + + third_derivs1_output << "{\"eq\": " << eq + << ", \"var1\": \"" << var1 << "\"" + << ", \"var2\": \"" << var2 << "\"" + << ", \"param1\": \"" << param << "\"" + << ", \"val\": \""; + d2->writeJsonOutput(third_derivs1_output, params_derivs_temporary_terms, tef_terms); + third_derivs1_output << "\"}" << endl; + } + third_derivs1_output << "]}" << endl; + + output << "\"static_model_params_derivatives\": {" + << model_local_vars_output.str() + << ", " << model_output.str() + << ", " << jacobian_output.str() + << ", " << hessian_output.str() + << ", " << hessian1_output.str() + << ", " << third_derivs_output.str() + << ", " << third_derivs1_output.str() + << "}"; +} diff --git a/StaticModel.hh b/StaticModel.hh index bf6cad6f..04d41e14 100644 --- a/StaticModel.hh +++ b/StaticModel.hh @@ -1,5 +1,5 @@ /* - * Copyright (C) 2003-2016 Dynare Team + * Copyright (C) 2003-2017 Dynare Team * * This file is part of Dynare. * @@ -173,6 +173,12 @@ public: //! Writes static model file void writeStaticFile(const string &basename, bool block, bool bytecode, bool use_dll, bool julia) const; + //! Write JSON representation of static model + void writeJsonComputingPassOutput(ostream &output) const; + + //! Writes file containing static parameters derivatives + void writeJsonParamsDerivativesFile(ostream &output) const; + //! Writes file containing static parameters derivatives void writeParamsDerivativesFile(const string &basename, bool julia) const; diff --git a/SymbolTable.cc b/SymbolTable.cc index 04b46de0..d6150183 100644 --- a/SymbolTable.cc +++ b/SymbolTable.cc @@ -1022,7 +1022,7 @@ void SymbolTable::writeJsonVarVector(ostream &output, const vector &varvec) const { output << "["; - for (int i = 0; i < varvec.size(); i++) + for (size_t i = 0; i < varvec.size(); i++) { output << endl << "{" << "\"name\":\"" << getName(varvec[i]) << "\", " From 236f1ca7d029691ed2b8acf243681aa9d0e2153c Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Mon, 27 Feb 2017 12:23:39 +0100 Subject: [PATCH 06/18] preprocessor: fix JSON bugs. #1387 --- ComputingTasks.cc | 2 +- ExprNode.cc | 24 ++++++++++++------------ ModelTree.cc | 8 ++++++-- 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/ComputingTasks.cc b/ComputingTasks.cc index f750b9b6..ae5a6f22 100644 --- a/ComputingTasks.cc +++ b/ComputingTasks.cc @@ -2600,7 +2600,7 @@ SvarIdentificationStatement::writeJsonOutput(ostream &output) const output << "{" << "\"equation_number\": " << it->equation << ", " << "\"restriction_number\": " << it->restriction_nbr << ", " - << "\"variable\": " << symbol_table.getName(it->variable) << ", " + << "\"variable\": \"" << symbol_table.getName(it->variable) << "\", " << "\"expression\": \""; it->value->writeOutput(output); output << "\"}"; diff --git a/ExprNode.cc b/ExprNode.cc index b5b9d4dd..5cc0298b 100644 --- a/ExprNode.cc +++ b/ExprNode.cc @@ -5610,15 +5610,15 @@ ExternalFunctionNode::writeJsonExternalFunctionOutput(vector &efout, stringstream ef; ef << "{\"external_function\": {" - << "\"output\": \"TEF_" << indx << "\""; + << "\"external_function_term\": \"TEF_" << indx << "\""; if (symb_id == first_deriv_symb_id) - ef << ", \"output_d\": \"TEFD_" << indx << "\""; + ef << ", \"external_function_term_d\": \"TEFD_" << indx << "\""; if (symb_id == second_deriv_symb_id) - ef << ", \"output_dd\": \"TEFDD_" << indx << "\""; + ef << ", \"external_function_term_dd\": \"TEFDD_" << indx << "\""; - ef << ", \"function\": \"" << datatree.symbol_table.getName(symb_id) << "("; + ef << ", \"value\": \"" << datatree.symbol_table.getName(symb_id) << "("; writeJsonExternalFunctionArguments(ef, temporary_terms, tef_terms); ef << ")\"}}"; efout.push_back(ef.str()); @@ -5944,17 +5944,17 @@ FirstDerivExternalFunctionNode::writeJsonExternalFunctionOutput(vector & stringstream ef; if (first_deriv_symb_id == eExtFunNotSet) ef << "{\"first_deriv_external_function\": {" - << "\"output\": \"TEFD_fdd_" << getIndxInTefTerms(symb_id, tef_terms) << "_" << inputIndex << "\"" + << "\"external_function_term\": \"TEFD_fdd_" << getIndxInTefTerms(symb_id, tef_terms) << "_" << inputIndex << "\"" << ", \"analytic_derivative\": false" << ", \"wrt\": " << inputIndex - << ", \"function\": \"" << datatree.symbol_table.getName(symb_id) << "("; + << ", \"value\": \"" << datatree.symbol_table.getName(symb_id) << "("; else { tef_terms[make_pair(first_deriv_symb_id, arguments)] = (int) tef_terms.size(); ef << "{\"first_deriv_external_function\": {" - << "\"output\": \"TEFD_def_" << getIndxInTefTerms(first_deriv_symb_id, tef_terms) + << "\"external_function_term\": \"TEFD_def_" << getIndxInTefTerms(first_deriv_symb_id, tef_terms) << "\"" << ", \"analytic_derivative\": true" - << ", \"function\": \"" << datatree.symbol_table.getName(first_deriv_symb_id) << "("; + << ", \"value\": \"" << datatree.symbol_table.getName(first_deriv_symb_id) << "("; } writeJsonExternalFunctionArguments(ef, temporary_terms, tef_terms); @@ -6303,18 +6303,18 @@ SecondDerivExternalFunctionNode::writeJsonExternalFunctionOutput(vector stringstream ef; if (second_deriv_symb_id == eExtFunNotSet) ef << "{\"second_deriv_external_function\": {" - << "\"output\": \"TEFDD_fdd_" << getIndxInTefTerms(symb_id, tef_terms) << "_" << inputIndex1 << "_" << inputIndex2 << "\"" + << "\"external_function_term\": \"TEFDD_fdd_" << getIndxInTefTerms(symb_id, tef_terms) << "_" << inputIndex1 << "_" << inputIndex2 << "\"" << ", \"analytic_derivative\": false" << ", \"wrt1\": " << inputIndex1 << ", \"wrt2\": " << inputIndex2 - << ", \"function\": \"" << datatree.symbol_table.getName(symb_id) << "("; + << ", \"value\": \"" << datatree.symbol_table.getName(symb_id) << "("; else { tef_terms[make_pair(second_deriv_symb_id, arguments)] = (int) tef_terms.size(); ef << "{\"second_deriv_external_function\": {" - << "\"output\": \"TEFDD_def_" << getIndxInTefTerms(second_deriv_symb_id, tef_terms) + << "\"external_function_term\": \"TEFDD_def_" << getIndxInTefTerms(second_deriv_symb_id, tef_terms) << "\"" << ", \"analytic_derivative\": true" - << ", \"function\": \"" << datatree.symbol_table.getName(second_deriv_symb_id) << "("; + << ", \"value\": \"" << datatree.symbol_table.getName(second_deriv_symb_id) << "("; } writeJsonExternalFunctionArguments(ef, temporary_terms, tef_terms); diff --git a/ModelTree.cc b/ModelTree.cc index 3e2b7395..a2cc7df3 100644 --- a/ModelTree.cc +++ b/ModelTree.cc @@ -1334,7 +1334,8 @@ ModelTree::writeJsonTemporaryTerms(const temporary_terms_t &tt, const temporary_ output << ", "; output << "{\"temporary_term\": \""; (*it)->writeJsonOutput(output, tt, tef_terms); - output << " = "; + output << "\"" + << ", \"value\": \""; (*it)->writeJsonOutput(output, tt2, tef_terms); output << "\"}" << endl; wrote_term = true; @@ -1567,12 +1568,15 @@ ModelTree::writeJsonModelLocalVariables(ostream &output, deriv_node_temp_terms_t for (set::const_iterator it = used_local_vars.begin(); it != used_local_vars.end(); ++it) { + if (it != used_local_vars.begin()) + output << ", "; int id = *it; expr_t value = local_variables_table.find(id)->second; /* We append underscores to avoid name clashes with "g1" or "oo_" (see also VariableNode::writeOutput) */ - output << "{\"" << symbol_table.getName(id) << "__ = "; + output << "{\"variable\": \"" << symbol_table.getName(id) << "__\"" + << ", \"value\": \""; value->writeJsonOutput(output, tt, tef_terms); output << "\"}" << endl; } From 301c9691d99042903f3b25a15521efc74b34414d Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Mon, 27 Feb 2017 15:40:34 +0100 Subject: [PATCH 07/18] preprocessor: JSON output aesthetic fixes, support planner objective. #1387 --- ComputingTasks.cc | 18 ++++++++----- ComputingTasks.hh | 1 + DynamicModel.cc | 2 +- ModFile.cc | 4 +-- ModelTree.cc | 4 +-- StaticModel.cc | 8 +++++- StaticModel.hh | 3 +++ SymbolTable.cc | 68 +++++++++++------------------------------------ 8 files changed, 43 insertions(+), 65 deletions(-) diff --git a/ComputingTasks.cc b/ComputingTasks.cc index ae5a6f22..8240e9fc 100644 --- a/ComputingTasks.cc +++ b/ComputingTasks.cc @@ -668,9 +668,8 @@ RamseyPolicyStatement::writeJsonOutput(ostream &output) const { output << ", "; options_list.writeJsonOutput(output); - output << ", "; } - output << "\"ramsey_policy_list\": ["; + output << ", \"ramsey_policy_list\": ["; for (vector::const_iterator it = ramsey_policy_list.begin(); it != ramsey_policy_list.end(); ++it) { @@ -1827,7 +1826,8 @@ ModelComparisonStatement::writeJsonOutput(ostream &output) const } PlannerObjectiveStatement::PlannerObjectiveStatement(StaticModel *model_tree_arg) : - model_tree(model_tree_arg) + model_tree(model_tree_arg), + computing_pass_called(false) { } @@ -1860,6 +1860,7 @@ void PlannerObjectiveStatement::computingPass() { model_tree->computingPass(eval_context_t(), false, true, true, none, false, false); + computing_pass_called = true; } void @@ -1871,9 +1872,14 @@ PlannerObjectiveStatement::writeOutput(ostream &output, const string &basename, void PlannerObjectiveStatement::writeJsonOutput(ostream &output) const { - cerr << "ERROR: writeJsonOutput not yet implemented for Planner Objective Statement" << endl; - exit(EXIT_FAILURE); - // model_tree->writeStaticJsonFile(basename + "_objective", false, false, false, false); + output << "{\"statementName\": \"planner_objective\"" + << ", "; + if (computing_pass_called) + model_tree->writeJsonComputingPassOutput(output); + else + model_tree->writeJsonOutput(output); + + output << "}"; } BVARDensityStatement::BVARDensityStatement(int maxnlags_arg, const OptionsList &options_list_arg) : diff --git a/ComputingTasks.hh b/ComputingTasks.hh index 49dcdbe8..6cec3e38 100644 --- a/ComputingTasks.hh +++ b/ComputingTasks.hh @@ -449,6 +449,7 @@ class PlannerObjectiveStatement : public Statement { private: StaticModel *model_tree; + bool computing_pass_called; public: //! Constructor /*! \param model_tree_arg the model tree used to store the objective function. diff --git a/DynamicModel.cc b/DynamicModel.cc index edcc5f3a..1c35f3cb 100644 --- a/DynamicModel.cc +++ b/DynamicModel.cc @@ -5364,7 +5364,7 @@ DynamicModel::writeJsonComputingPassOutput(ostream &output) const writeJsonModelLocalVariables(model_local_vars_output, tef_terms); writeJsonTemporaryTerms(temporary_terms_res, temp_term_union_m_1, model_output, tef_terms, concat); - + model_output << ", "; writeJsonModelEquations(model_output, true); // Writing Jacobian diff --git a/ModFile.cc b/ModFile.cc index 4cf0ba1b..4228a393 100644 --- a/ModFile.cc +++ b/ModFile.cc @@ -1291,11 +1291,12 @@ ModFile::writeJsonOutputParsingCheck(const string &basename, JsonFileOutputType output << "{" << endl; symbol_table.writeJsonOutput(output); + output << ", "; dynamic_model.writeJsonOutput(output); if (!statements.empty()) { - output << ",\"statements\": ["; + output << ", \"statements\": ["; for (vector::const_iterator it = statements.begin(); it != statements.end(); it++) { @@ -1305,7 +1306,6 @@ ModFile::writeJsonOutputParsingCheck(const string &basename, JsonFileOutputType } output << "]" << endl; } - output << "}" << endl; if (json_output_mode == standardout) diff --git a/ModelTree.cc b/ModelTree.cc index a2cc7df3..02b4c93d 100644 --- a/ModelTree.cc +++ b/ModelTree.cc @@ -2028,9 +2028,9 @@ ModelTree::writeJsonModelEquations(ostream &output, bool residuals) const vector > eqtags; temporary_terms_t tt_empty; if (residuals) - output << endl << ",\"residuals\":[" << endl; + output << endl << "\"residuals\":[" << endl; else - output << endl << ",\"model\":[" << endl; + output << endl << "\"model\":[" << endl; for (int eq = 0; eq < (int) equations.size(); eq++) { if (eq > 0) diff --git a/StaticModel.cc b/StaticModel.cc index 4516a886..71e631ee 100644 --- a/StaticModel.cc +++ b/StaticModel.cc @@ -2415,6 +2415,12 @@ StaticModel::writeParamsDerivativesFile(const string &basename, bool julia) cons paramsDerivsFile.close(); } +void +StaticModel::writeJsonOutput(ostream &output) const +{ + writeJsonModelEquations(output, false); +} + void StaticModel::writeJsonComputingPassOutput(ostream &output) const { @@ -2434,7 +2440,7 @@ StaticModel::writeJsonComputingPassOutput(ostream &output) const writeJsonModelLocalVariables(model_local_vars_output, tef_terms); writeJsonTemporaryTerms(temporary_terms_res, temp_term_union_m_1, model_output, tef_terms, concat); - + model_output << ", "; writeJsonModelEquations(model_output, true); int nrows = equations.size(); diff --git a/StaticModel.hh b/StaticModel.hh index 04d41e14..75ab0b3f 100644 --- a/StaticModel.hh +++ b/StaticModel.hh @@ -173,6 +173,9 @@ public: //! Writes static model file void writeStaticFile(const string &basename, bool block, bool bytecode, bool use_dll, bool julia) const; + //! Write JSON Output (used by PlannerObjectiveStatement) + void writeJsonOutput(ostream &output) const; + //! Write JSON representation of static model void writeJsonComputingPassOutput(ostream &output) const; diff --git a/SymbolTable.cc b/SymbolTable.cc index d6150183..9db683db 100644 --- a/SymbolTable.cc +++ b/SymbolTable.cc @@ -965,57 +965,18 @@ SymbolTable::writeJuliaOutput(ostream &output) const throw (NotYetFrozenExceptio void SymbolTable::writeJsonOutput(ostream &output) const -{/* - vector endos, exos, exo_dets, params; - for (int i = 0; i < size; i++) - { - switch (getType(i)) - { - case eEndogenous: - endos.push_back(i); - break; - case eExogenous: - exos.push_back(i); - break; - case eExogenousDet: - exo_dets.push_back(i); - break; - case eParameter: - params.push_back(i); - break; - default: - break; - } - } - */ +{ + output << "\"endogenous\": "; + writeJsonVarVector(output, endo_ids); - if (!endo_ids.empty()) - { - output << "\"endogenous\":"; - writeJsonVarVector(output, endo_ids); - output << endl; - } + output << ", \"exogenous\":" ; + writeJsonVarVector(output, exo_ids); - if (!exo_ids.empty()) - { - output << ",\"exogenous\":"; - writeJsonVarVector(output, exo_ids); - output << endl; - } + output << ", \"exogenous_deterministic\": "; + writeJsonVarVector(output, exo_det_ids); - if (!exo_det_ids.empty()) - { - output << ",\"exogenous_deterministic\":"; - writeJsonVarVector(output, exo_det_ids); - output << endl; - } - - if (!param_ids.empty()) - { - output << ",\"parameters\":"; - writeJsonVarVector(output, param_ids); - cout << endl; - } + output << ", \"parameters\": "; + writeJsonVarVector(output, param_ids); } void @@ -1024,12 +985,13 @@ SymbolTable::writeJsonVarVector(ostream &output, const vector &varvec) cons output << "["; for (size_t i = 0; i < varvec.size(); i++) { - output << endl << "{" + if (i != 0) + output << ", "; + output << "{" << "\"name\":\"" << getName(varvec[i]) << "\", " << "\"texName\":\"" << boost::replace_all_copy(getTeXName(varvec[i]), "\\", "\\\\") << "\", " - << "\"longName\":\"" << boost::replace_all_copy(getLongName(varvec[i]), "\\", "\\\\") << "\"}"; - if (i < varvec.size() - 1) - output << ", "; + << "\"longName\":\"" << boost::replace_all_copy(getLongName(varvec[i]), "\\", "\\\\") << "\"}" + << endl; } - output << endl << "]"; + output << "]" << endl; } From 32a08f8db06857688a2aaf1fb95be515599ef3af Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Tue, 28 Feb 2017 14:34:22 +0100 Subject: [PATCH 08/18] preprocessor: add onlyjson option to allow exit upon writing of JSON output. #1387 --- DynareMain.cc | 9 ++++++--- DynareMain2.cc | 10 +++++----- ModFile.cc | 5 ++++- ModFile.hh | 2 +- 4 files changed, 16 insertions(+), 10 deletions(-) diff --git a/DynareMain.cc b/DynareMain.cc index cd62325c..3aa0aa3f 100644 --- a/DynareMain.cc +++ b/DynareMain.cc @@ -45,7 +45,7 @@ void main2(stringstream &in, string &basename, bool debug, bool clear_all, bool #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) , bool cygwin, bool msvc, bool mingw #endif - , JsonOutputPointType json, JsonFileOutputType json_output_mode + , JsonOutputPointType json, JsonFileOutputType json_output_mode, bool onlyjson ); void main1(char *modfile, string &basename, bool debug, bool save_macro, string &save_macro_file, @@ -62,7 +62,7 @@ usage() #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) << " [cygwin] [msvc] [mingw]" #endif - << "[json=parse|check|transform|compute] [jsonstdout]" + << "[json=parse|check|transform|compute] [jsonstdout] [onlyjson]" << endl; exit(EXIT_FAILURE); } @@ -117,6 +117,7 @@ main(int argc, char **argv) FileOutputType output_mode = none; JsonOutputPointType json = nojson; JsonFileOutputType json_output_mode = file; + bool onlyjson = false; LanguageOutputType language = matlab; // Parse options @@ -297,6 +298,8 @@ main(int argc, char **argv) } else if (!strcmp(argv[arg], "jsonstdout")) json_output_mode = standardout; + else if (!strcmp(argv[arg], "onlyjson")) + onlyjson = true; else if (strlen(argv[arg]) >= 4 && !strncmp(argv[arg], "json", 4)) { if (strlen(argv[arg]) <= 5 || argv[arg][4] != '=') @@ -364,7 +367,7 @@ main(int argc, char **argv) #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) , cygwin, msvc, mingw #endif - , json, json_output_mode + , json, json_output_mode, onlyjson ); return EXIT_SUCCESS; diff --git a/DynareMain2.cc b/DynareMain2.cc index bc2d34ff..5139cd3d 100644 --- a/DynareMain2.cc +++ b/DynareMain2.cc @@ -34,7 +34,7 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) , bool cygwin, bool msvc, bool mingw #endif - , JsonOutputPointType json, JsonFileOutputType json_output_mode + , JsonOutputPointType json, JsonFileOutputType json_output_mode, bool onlyjson ) { ParsingDriver p(warnings, nostrict); @@ -42,17 +42,17 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear // Do parsing and construct internal representation of mod file ModFile *mod_file = p.parse(in, debug); if (json == parsing) - mod_file->writeJsonOutput(basename, json, json_output_mode); + mod_file->writeJsonOutput(basename, json, json_output_mode, onlyjson); // Run checking pass mod_file->checkPass(nostrict); if (json == checkpass) - mod_file->writeJsonOutput(basename, json, json_output_mode); + mod_file->writeJsonOutput(basename, json, json_output_mode, onlyjson); // Perform transformations on the model (creation of auxiliary vars and equations) mod_file->transformPass(nostrict); if (json == transformpass) - mod_file->writeJsonOutput(basename, json, json_output_mode); + mod_file->writeJsonOutput(basename, json, json_output_mode, onlyjson); // Evaluate parameters initialization, initval, endval and pounds mod_file->evalAllExpressions(warn_uninit); @@ -60,7 +60,7 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear // Do computations mod_file->computingPass(no_tmp_terms, output_mode, compute_xrefs, params_derivs_order); if (json == computingpass) - mod_file->writeJsonOutput(basename, json, json_output_mode); + mod_file->writeJsonOutput(basename, json, json_output_mode, onlyjson); // Write outputs if (output_mode != none) diff --git a/ModFile.cc b/ModFile.cc index 4228a393..32cb70bf 100644 --- a/ModFile.cc +++ b/ModFile.cc @@ -1248,7 +1248,7 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output) } void -ModFile::writeJsonOutput(const string &basename, JsonOutputPointType json, JsonFileOutputType json_output_mode) +ModFile::writeJsonOutput(const string &basename, JsonOutputPointType json, JsonFileOutputType json_output_mode, bool onlyjson) { if (json == nojson) return; @@ -1282,6 +1282,9 @@ ModFile::writeJsonOutput(const string &basename, JsonOutputPointType json, JsonF cerr << "ModFile::writeJsonOutput: should not arrive here." << endl; exit(EXIT_FAILURE); } + + if (onlyjson) + exit(EXIT_SUCCESS); } void diff --git a/ModFile.hh b/ModFile.hh index 684d592e..385e97b6 100644 --- a/ModFile.hh +++ b/ModFile.hh @@ -174,7 +174,7 @@ public: //! Initially created to enable Julia to work with .mod files //! Potentially outputs ModFile after the various parts of processing (parsing, checkPass, transformPass, computingPass) //! Allows user of other host language platforms (python, fortran, etc) to provide support for dynare .mod files - void writeJsonOutput(const string &basename, JsonOutputPointType json, JsonFileOutputType json_output_mode); + void writeJsonOutput(const string &basename, JsonOutputPointType json, JsonFileOutputType json_output_mode, bool onlyjson); }; #endif // ! MOD_FILE_HH From 5fbadbadd361da568223057e9fb64e931c2fcb3d Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Thu, 2 Mar 2017 17:32:50 +0100 Subject: [PATCH 09/18] preprocessor: make JSON output start counting at 1 instead of 0. #1387 --- DynamicModel.cc | 16 ++++++++-------- StaticModel.cc | 16 ++++++++-------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/DynamicModel.cc b/DynamicModel.cc index 1c35f3cb..a665a577 100644 --- a/DynamicModel.cc +++ b/DynamicModel.cc @@ -5387,7 +5387,7 @@ DynamicModel::writeJsonComputingPassOutput(ostream &output) const int lag = getLagByDerivID(it->first.second); expr_t d1 = it->second; - jacobian_output << "{\"eq\": " << eq + jacobian_output << "{\"eq\": " << eq + 1 << ", \"var\": \"" << var << "\"" << ", \"lag\": " << lag << ", \"val\": \""; @@ -5418,7 +5418,7 @@ DynamicModel::writeJsonComputingPassOutput(ostream &output) const int lag2 = getLagByDerivID(it->first.second.second); expr_t d2 = it->second; - hessian_output << "{\"eq\": " << eq + hessian_output << "{\"eq\": " << eq + 1 << ", \"var1\": \"" << var1 << "\"" << ", \"lag1\": " << lag1 << ", \"var2\": \"" << var2 << "\"" @@ -5453,7 +5453,7 @@ DynamicModel::writeJsonComputingPassOutput(ostream &output) const int lag3 = getLagByDerivID(it->first.second.second.second); expr_t d3 = it->second; - third_derivatives_output << "{\"eq\": " << eq + third_derivatives_output << "{\"eq\": " << eq + 1 << ", \"var1\": \"" << var1 << "\"" << ", \"lag1\": " << lag1 << ", \"var2\": \"" << var2 << "\"" @@ -5513,7 +5513,7 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output) const string param = symbol_table.getName(getSymbIDByDerivID(it->first.second)); expr_t d1 = it->second; - jacobian_output << "{\"eq\": " << eq + jacobian_output << "{\"eq\": " << eq + 1 << ", \"param\": \"" << param << "\"" << ", \"val\": \""; d1->writeJsonOutput(jacobian_output, params_derivs_temporary_terms, tef_terms); @@ -5537,7 +5537,7 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output) const string param = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); expr_t d2 = it->second; - hessian_output << "{\"eq\": " << eq + hessian_output << "{\"eq\": " << eq + 1 << ", \"var\": \"" << var << "\"" << ", \"lag\": " << lag << ", \"param\": \"" << param << "\"" @@ -5563,7 +5563,7 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output) const string param2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); expr_t d2 = it->second; - hessian1_output << "{\"eq\": " << eq + hessian1_output << "{\"eq\": " << eq + 1 << ", \"param1\": \"" << param1 << "\"" << ", \"param2\": \"" << param2 << "\"" << ", \"val\": \""; @@ -5590,7 +5590,7 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output) const string param2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); expr_t d2 = it->second; - third_derivs_output << "{\"eq\": " << eq + third_derivs_output << "{\"eq\": " << eq + 1 << ", \"var\": \"" << var << "\"" << ", \"lag\": " << lag << ", \"param1\": \"" << param1 << "\"" @@ -5621,7 +5621,7 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output) const string param = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); expr_t d2 = it->second; - third_derivs1_output << "{\"eq\": " << eq + third_derivs1_output << "{\"eq\": " << eq + 1 << ", \"var1\": \"" << var1 << "\"" << ", \"lag1\": " << lag1 << ", \"var2\": \"" << var2 << "\"" diff --git a/StaticModel.cc b/StaticModel.cc index 71e631ee..e3823167 100644 --- a/StaticModel.cc +++ b/StaticModel.cc @@ -2466,7 +2466,7 @@ StaticModel::writeJsonComputingPassOutput(ostream &output) const string var = symbol_table.getName(getSymbIDByDerivID(it->first.second)); expr_t d1 = it->second; - jacobian_output << "{\"eq\": " << eq + jacobian_output << "{\"eq\": " << eq + 1 << ", \"var\": \"" << var << "\"" << ", \"val\": \""; d1->writeJsonOutput(jacobian_output, temp_term_union, tef_terms); @@ -2495,7 +2495,7 @@ StaticModel::writeJsonComputingPassOutput(ostream &output) const string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); expr_t d2 = it->second; - hessian_output << "{\"eq\": " << eq + hessian_output << "{\"eq\": " << eq + 1 << ", \"var1\": \"" << var1 << "\"" << ", \"var2\": \"" << var2 << "\"" << ", \"val\": \""; @@ -2525,7 +2525,7 @@ StaticModel::writeJsonComputingPassOutput(ostream &output) const string var3 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); expr_t d3 = it->second; - third_derivatives_output << "{\"eq\": " << eq + third_derivatives_output << "{\"eq\": " << eq + 1 << ", \"var1\": \"" << var1 << "\"" << ", \"var2\": \"" << var2 << "\"" << ", \"var3\": \"" << var3 << "\"" @@ -2582,7 +2582,7 @@ StaticModel::writeJsonParamsDerivativesFile(ostream &output) const string param = symbol_table.getName(getSymbIDByDerivID(it->first.second)); expr_t d1 = it->second; - jacobian_output << "{\"eq\": " << eq + jacobian_output << "{\"eq\": " << eq + 1 << ", \"param\": \"" << param << "\"" << ", \"val\": \""; d1->writeJsonOutput(jacobian_output, params_derivs_temporary_terms, tef_terms); @@ -2605,7 +2605,7 @@ StaticModel::writeJsonParamsDerivativesFile(ostream &output) const string param = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); expr_t d2 = it->second; - hessian_output << "{\"eq\": " << eq + hessian_output << "{\"eq\": " << eq + 1 << ", \"var\": \"" << var << "\"" << ", \"param\": \"" << param << "\"" << ", \"val\": \""; @@ -2630,7 +2630,7 @@ StaticModel::writeJsonParamsDerivativesFile(ostream &output) const string param2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); expr_t d2 = it->second; - hessian1_output << "{\"eq\": " << eq + hessian1_output << "{\"eq\": " << eq + 1 << ", \"param1\": \"" << param1 << "\"" << ", \"param2\": \"" << param2 << "\"" << ", \"val\": \""; @@ -2656,7 +2656,7 @@ StaticModel::writeJsonParamsDerivativesFile(ostream &output) const string param2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); expr_t d2 = it->second; - third_derivs_output << "{\"eq\": " << eq + third_derivs_output << "{\"eq\": " << eq + 1 << ", \"var\": \"" << var << "\"" << ", \"param1\": \"" << param1 << "\"" << ", \"param2\": \"" << param2 << "\"" @@ -2684,7 +2684,7 @@ StaticModel::writeJsonParamsDerivativesFile(ostream &output) const string param = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); expr_t d2 = it->second; - third_derivs1_output << "{\"eq\": " << eq + third_derivs1_output << "{\"eq\": " << eq + 1 << ", \"var1\": \"" << var1 << "\"" << ", \"var2\": \"" << var2 << "\"" << ", \"param1\": \"" << param << "\"" From 746f88eb6eb321e76b8dac8de4764c0a049c4823 Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Thu, 2 Mar 2017 18:34:18 +0100 Subject: [PATCH 10/18] preprocessor: create two different static and dynamic files with the option jsonprintderivdetail. #1387 --- ComputingTasks.cc | 2 +- DynamicModel.cc | 216 +++++++++++++++++++++++++++++++--------------- DynamicModel.hh | 4 +- DynareMain.cc | 9 +- DynareMain2.cc | 4 +- ModFile.cc | 138 +++++++++++++++++------------ ModFile.hh | 6 +- StaticModel.cc | 189 +++++++++++++++++++++++++++++----------- StaticModel.hh | 4 +- 9 files changed, 388 insertions(+), 184 deletions(-) diff --git a/ComputingTasks.cc b/ComputingTasks.cc index bc9aa02a..7eccf256 100644 --- a/ComputingTasks.cc +++ b/ComputingTasks.cc @@ -1866,7 +1866,7 @@ PlannerObjectiveStatement::writeJsonOutput(ostream &output) const output << "{\"statementName\": \"planner_objective\"" << ", "; if (computing_pass_called) - model_tree->writeJsonComputingPassOutput(output); + model_tree->writeJsonComputingPassOutput(output, false); else model_tree->writeJsonOutput(output); diff --git a/DynamicModel.cc b/DynamicModel.cc index 213ead14..10db3a8b 100644 --- a/DynamicModel.cc +++ b/DynamicModel.cc @@ -5345,7 +5345,7 @@ DynamicModel::writeJsonOutput(ostream &output) const } void -DynamicModel::writeJsonComputingPassOutput(ostream &output) const +DynamicModel::writeJsonComputingPassOutput(ostream &output, bool writeDetails) const { ostringstream model_local_vars_output; // Used for storing model local vars ostringstream model_output; // Used for storing model temp vars and equations @@ -5383,13 +5383,17 @@ DynamicModel::writeJsonComputingPassOutput(ostream &output) const jacobian_output << ", "; int eq = it->first.first; - string var = symbol_table.getName(getSymbIDByDerivID(it->first.second)); - int lag = getLagByDerivID(it->first.second); + int var = it->first.second; + int col = getDynJacobianCol(var); expr_t d1 = it->second; - jacobian_output << "{\"eq\": " << eq + 1 - << ", \"var\": \"" << var << "\"" - << ", \"lag\": " << lag + if (writeDetails) + jacobian_output << "{\"eq\": " << eq + 1 + << ", \"var\": \"" << symbol_table.getName(getSymbIDByDerivID(var)) << "\"" + << ", \"lag\": " << getLagByDerivID(var); + else + jacobian_output << "{\"row\": " << eq + 1; + jacobian_output << ", \"col\": " << col + 1 << ", \"val\": \""; d1->writeJsonOutput(jacobian_output, temp_term_union, tef_terms); jacobian_output << "\"}" << endl; @@ -5412,17 +5416,27 @@ DynamicModel::writeJsonComputingPassOutput(ostream &output) const hessian_output << ", "; int eq = it->first.first; - string var1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); - int lag1 = getLagByDerivID(it->first.second.first); - string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); - int lag2 = getLagByDerivID(it->first.second.second); + int var1 = it->first.second.first; + int var2 = it->first.second.second; expr_t d2 = it->second; + int id1 = getDynJacobianCol(var1); + int id2 = getDynJacobianCol(var2); + int col_nb = id1 * dynJacobianColsNbr + id2; + int col_nb_sym = id2 * dynJacobianColsNbr + id1; - hessian_output << "{\"eq\": " << eq + 1 - << ", \"var1\": \"" << var1 << "\"" - << ", \"lag1\": " << lag1 - << ", \"var2\": \"" << var2 << "\"" - << ", \"lag2\": " << lag2 + if (writeDetails) + hessian_output << "{\"eq\": " << eq + 1 + << ", \"var1\": \"" << symbol_table.getName(getSymbIDByDerivID(var1)) << "\"" + << ", \"lag1\": " << getLagByDerivID(var1) + << ", \"var2\": \"" << symbol_table.getName(getSymbIDByDerivID(var2)) << "\"" + << ", \"lag2\": " << getLagByDerivID(var2); + else + hessian_output << "{\"row\": " << eq + 1; + + hessian_output << ", \"col\": [" << col_nb + 1; + if (id1 != id2) + hessian_output << ", " << col_nb_sym + 1; + hessian_output << "]" << ", \"val\": \""; d2->writeJsonOutput(hessian_output, temp_term_union, tef_terms); hessian_output << "\"}" << endl; @@ -5445,29 +5459,52 @@ DynamicModel::writeJsonComputingPassOutput(ostream &output) const third_derivatives_output << ", "; int eq = it->first.first; - string var1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); - int lag1 = getLagByDerivID(it->first.second.first); - string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.first)); - int lag2 = getLagByDerivID(it->first.second.second.first); - string var3 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); - int lag3 = getLagByDerivID(it->first.second.second.second); + int var1 = it->first.second.first; + int var2 = it->first.second.second.first; + int var3 = it->first.second.second.second; expr_t d3 = it->second; - third_derivatives_output << "{\"eq\": " << eq + 1 - << ", \"var1\": \"" << var1 << "\"" - << ", \"lag1\": " << lag1 - << ", \"var2\": \"" << var2 << "\"" - << ", \"lag2\": " << lag2 - << ", \"var3\": \"" << var3 << "\"" - << ", \"lag3\": " << lag3 + if (writeDetails) + third_derivatives_output << "{\"eq\": " << eq + 1 + << ", \"var1\": \"" << symbol_table.getName(getSymbIDByDerivID(var1)) << "\"" + << ", \"lag1\": " << getLagByDerivID(var1) + << ", \"var2\": \"" << symbol_table.getName(getSymbIDByDerivID(var2)) << "\"" + << ", \"lag2\": " << getLagByDerivID(var2) + << ", \"var3\": \"" << symbol_table.getName(getSymbIDByDerivID(var3)) << "\"" + << ", \"lag3\": " << getLagByDerivID(var3); + else + third_derivatives_output << "{\"row\": " << eq + 1; + + int id1 = getDynJacobianCol(var1); + int id2 = getDynJacobianCol(var2); + int id3 = getDynJacobianCol(var3); + set cols; + cols.insert(id1 * hessianColsNbr + id2 * dynJacobianColsNbr + id3); + cols.insert(id1 * hessianColsNbr + id3 * dynJacobianColsNbr + id2); + cols.insert(id2 * hessianColsNbr + id1 * dynJacobianColsNbr + id3); + cols.insert(id2 * hessianColsNbr + id3 * dynJacobianColsNbr + id1); + cols.insert(id3 * hessianColsNbr + id1 * dynJacobianColsNbr + id2); + cols.insert(id3 * hessianColsNbr + id2 * dynJacobianColsNbr + id1); + + third_derivatives_output << ", \"col\": ["; + for (set::iterator it2 = cols.begin(); it2 != cols.end(); it2++) + { + if (it2 != cols.begin()) + third_derivatives_output << ", "; + third_derivatives_output << *it2 + 1; + } + third_derivatives_output << "]" << ", \"val\": \""; d3->writeJsonOutput(third_derivatives_output, temp_term_union, tef_terms); third_derivatives_output << "\"}" << endl; } third_derivatives_output << "]}"; - output << "\"dynamic_model_derivatives\": {" - << model_local_vars_output.str() + if (writeDetails) + output << "\"dynamic_model_derivative_details\": {"; + else + output << "\"dynamic_model_derivatives\": {"; + output << model_local_vars_output.str() << ", " << model_output.str() << ", " << jacobian_output.str() << ", " << hessian_output.str() @@ -5476,7 +5513,7 @@ DynamicModel::writeJsonComputingPassOutput(ostream &output) const } void -DynamicModel::writeJsonParamsDerivativesFile(ostream &output) const +DynamicModel::writeJsonParamsDerivativesFile(ostream &output, bool writeDetails) const { if (!residuals_params_derivatives.size() && !residuals_params_second_derivatives.size() @@ -5510,11 +5547,17 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output) const jacobian_output << ", "; int eq = it->first.first; - string param = symbol_table.getName(getSymbIDByDerivID(it->first.second)); + int param = it->first.second; expr_t d1 = it->second; - jacobian_output << "{\"eq\": " << eq + 1 - << ", \"param\": \"" << param << "\"" + int param_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param)) + 1; + + if (writeDetails) + jacobian_output << "{\"eq\": " << eq + 1 + << ", \"param\": \"" << symbol_table.getName(getSymbIDByDerivID(param)) << "\""; + else + jacobian_output << "{\"row\": " << eq + 1; + jacobian_output << ", \"param_col\": " << param_col + 1 << ", \"val\": \""; d1->writeJsonOutput(jacobian_output, params_derivs_temporary_terms, tef_terms); jacobian_output << "\"}" << endl; @@ -5532,15 +5575,22 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output) const hessian_output << ", "; int eq = it->first.first; - string var = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); - int lag = getLagByDerivID(it->first.second.first); - string param = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); + int var = it->first.second.first; + int param = it->first.second.second; expr_t d2 = it->second; - hessian_output << "{\"eq\": " << eq + 1 - << ", \"var\": \"" << var << "\"" - << ", \"lag\": " << lag - << ", \"param\": \"" << param << "\"" + int var_col = getDynJacobianCol(var) + 1; + int param_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param)) + 1; + + if (writeDetails) + hessian_output << "{\"eq\": " << eq + 1 + << ", \"var\": \"" << symbol_table.getName(getSymbIDByDerivID(var)) << "\"" + << ", \"lag\": " << getLagByDerivID(var) + << ", \"param\": \"" << symbol_table.getName(getSymbIDByDerivID(param)) << "\""; + else + hessian_output << "{\"row\": " << eq + 1; + hessian_output << ", \"var_col\": " << var_col + 1 + << ", \"param_col\": " << param_col + 1 << ", \"val\": \""; d2->writeJsonOutput(hessian_output, params_derivs_temporary_terms, tef_terms); hessian_output << "\"}" << endl; @@ -5559,14 +5609,22 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output) const hessian1_output << ", "; int eq = it->first.first; - string param1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); - string param2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); + int param1 = it->first.second.first; + int param2 = it->first.second.second; expr_t d2 = it->second; - hessian1_output << "{\"eq\": " << eq + 1 - << ", \"param1\": \"" << param1 << "\"" - << ", \"param2\": \"" << param2 << "\"" - << ", \"val\": \""; + int param1_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param1)) + 1; + int param2_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param2)) + 1; + + if (writeDetails) + hessian1_output << "{\"eq\": " << eq + 1 + << ", \"param1\": \"" << symbol_table.getName(getSymbIDByDerivID(param1)) << "\"" + << ", \"param2\": \"" << symbol_table.getName(getSymbIDByDerivID(param2)) << "\""; + else + hessian1_output << "{\"row\": " << eq + 1; + hessian1_output << ", \"param1_col\": " << param1_col + 1 + << ", \"param2_col\": " << param2_col + 1 + << ", \"val\": \""; d2->writeJsonOutput(hessian1_output, params_derivs_temporary_terms, tef_terms); hessian1_output << "\"}" << endl; } @@ -5584,17 +5642,26 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output) const third_derivs_output << ", "; int eq = it->first.first; - string var = symbol_table.getName(it->first.second.first); - int lag = getLagByDerivID(it->first.second.first); - string param1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.first)); - string param2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); + int var = it->first.second.first; + int param1 = it->first.second.second.first; + int param2 = it->first.second.second.second; expr_t d2 = it->second; - third_derivs_output << "{\"eq\": " << eq + 1 - << ", \"var\": \"" << var << "\"" - << ", \"lag\": " << lag - << ", \"param1\": \"" << param1 << "\"" - << ", \"param2\": \"" << param2 << "\"" + int var_col = getDynJacobianCol(var) + 1; + int param1_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param1)) + 1; + int param2_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param2)) + 1; + + if (writeDetails) + third_derivs_output << "{\"eq\": " << eq + 1 + << ", \"var\": \"" << symbol_table.getName(var) << "\"" + << ", \"lag\": " << getLagByDerivID(var) + << ", \"param1\": \"" << symbol_table.getName(getSymbIDByDerivID(param1)) << "\"" + << ", \"param2\": \"" << symbol_table.getName(getSymbIDByDerivID(param2)) << "\""; + else + third_derivs_output << "{\"row\": " << eq + 1; + third_derivs_output << ", \"var_col\": " << var_col + 1 + << ", \"param1_col\": " << param1_col + 1 + << ", \"param2_col\": " << param2_col + 1 << ", \"val\": \""; d2->writeJsonOutput(third_derivs_output, params_derivs_temporary_terms, tef_terms); third_derivs_output << "\"}" << endl; @@ -5614,27 +5681,38 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output) const third_derivs1_output << ", "; int eq = it->first.first; - string var1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); - int lag1 = getLagByDerivID(it->first.second.first); - string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.first)); - int lag2 = getLagByDerivID(it->first.second.second.first); - string param = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); + int var1 = it->first.second.first; + int var2 = it->first.second.second.first; + int param = it->first.second.second.second; expr_t d2 = it->second; - third_derivs1_output << "{\"eq\": " << eq + 1 - << ", \"var1\": \"" << var1 << "\"" - << ", \"lag1\": " << lag1 - << ", \"var2\": \"" << var2 << "\"" - << ", \"lag2\": " << lag2 - << ", \"param1\": \"" << param << "\"" + int var1_col = getDynJacobianCol(var1) + 1; + int var2_col = getDynJacobianCol(var2) + 1; + int param_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param)) + 1; + + if (writeDetails) + third_derivs1_output << "{\"eq\": " << eq + 1 + << ", \"var1\": \"" << symbol_table.getName(getSymbIDByDerivID(var1)) << "\"" + << ", \"lag1\": " << getLagByDerivID(var1) + << ", \"var2\": \"" << symbol_table.getName(getSymbIDByDerivID(var2)) << "\"" + << ", \"lag2\": " << getLagByDerivID(var2) + << ", \"param\": \"" << symbol_table.getName(getSymbIDByDerivID(param)) << "\""; + else + third_derivs1_output << "{\"row\": " << eq + 1; + third_derivs1_output << ", \"var1_col\": " << var1_col + 1 + << ", \"var2_col\": " << var2_col + 1 + << ", \"param_col\": " << param_col + 1 << ", \"val\": \""; d2->writeJsonOutput(third_derivs1_output, params_derivs_temporary_terms, tef_terms); third_derivs1_output << "\"}" << endl; } third_derivs1_output << "]}" << endl; - output << "\"dynamic_model_params_derivatives\": {" - << model_local_vars_output.str() + if (writeDetails) + output << "\"dynamic_model_params_derivative_details\": {"; + else + output << "\"dynamic_model_params_derivatives\": {"; + output << model_local_vars_output.str() << ", " << model_output.str() << ", " << jacobian_output.str() << ", " << hessian_output.str() diff --git a/DynamicModel.hh b/DynamicModel.hh index 87e41e38..b0828a2b 100644 --- a/DynamicModel.hh +++ b/DynamicModel.hh @@ -221,10 +221,10 @@ public: void writeJsonOutput(ostream &output) const; //! Write JSON Output representation of dynamic model after computing pass - void writeJsonComputingPassOutput(ostream &output) const; + void writeJsonComputingPassOutput(ostream &output, bool writeDetails) const; //! Write JSON prams derivatives file - void writeJsonParamsDerivativesFile(ostream &output) const; + void writeJsonParamsDerivativesFile(ostream &output, bool writeDetails) const; //! Return true if the hessian is equal to zero inline bool checkHessianZero() const; diff --git a/DynareMain.cc b/DynareMain.cc index 3aa0aa3f..03c74ec6 100644 --- a/DynareMain.cc +++ b/DynareMain.cc @@ -45,7 +45,7 @@ void main2(stringstream &in, string &basename, bool debug, bool clear_all, bool #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) , bool cygwin, bool msvc, bool mingw #endif - , JsonOutputPointType json, JsonFileOutputType json_output_mode, bool onlyjson + , JsonOutputPointType json, JsonFileOutputType json_output_mode, bool onlyjson, bool jsonprintderivdetail ); void main1(char *modfile, string &basename, bool debug, bool save_macro, string &save_macro_file, @@ -62,7 +62,7 @@ usage() #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) << " [cygwin] [msvc] [mingw]" #endif - << "[json=parse|check|transform|compute] [jsonstdout] [onlyjson]" + << "[json=parse|check|transform|compute] [jsonstdout] [onlyjson] [jsonprintderivdetail]" << endl; exit(EXIT_FAILURE); } @@ -118,6 +118,7 @@ main(int argc, char **argv) JsonOutputPointType json = nojson; JsonFileOutputType json_output_mode = file; bool onlyjson = false; + bool jsonprintderivdetail = false; LanguageOutputType language = matlab; // Parse options @@ -300,6 +301,8 @@ main(int argc, char **argv) json_output_mode = standardout; else if (!strcmp(argv[arg], "onlyjson")) onlyjson = true; + else if (!strcmp(argv[arg], "jsonprintderivdetail")) + jsonprintderivdetail = true; else if (strlen(argv[arg]) >= 4 && !strncmp(argv[arg], "json", 4)) { if (strlen(argv[arg]) <= 5 || argv[arg][4] != '=') @@ -367,7 +370,7 @@ main(int argc, char **argv) #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) , cygwin, msvc, mingw #endif - , json, json_output_mode, onlyjson + , json, json_output_mode, onlyjson, jsonprintderivdetail ); return EXIT_SUCCESS; diff --git a/DynareMain2.cc b/DynareMain2.cc index 5139cd3d..c3a24936 100644 --- a/DynareMain2.cc +++ b/DynareMain2.cc @@ -34,7 +34,7 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) , bool cygwin, bool msvc, bool mingw #endif - , JsonOutputPointType json, JsonFileOutputType json_output_mode, bool onlyjson + , JsonOutputPointType json, JsonFileOutputType json_output_mode, bool onlyjson, bool jsonprintderivdetail ) { ParsingDriver p(warnings, nostrict); @@ -60,7 +60,7 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear // Do computations mod_file->computingPass(no_tmp_terms, output_mode, compute_xrefs, params_derivs_order); if (json == computingpass) - mod_file->writeJsonOutput(basename, json, json_output_mode, onlyjson); + mod_file->writeJsonOutput(basename, json, json_output_mode, onlyjson, jsonprintderivdetail); // Write outputs if (output_mode != none) diff --git a/ModFile.cc b/ModFile.cc index 32cb70bf..7ee204ad 100644 --- a/ModFile.cc +++ b/ModFile.cc @@ -1248,7 +1248,7 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output) } void -ModFile::writeJsonOutput(const string &basename, JsonOutputPointType json, JsonFileOutputType json_output_mode, bool onlyjson) +ModFile::writeJsonOutput(const string &basename, JsonOutputPointType json, JsonFileOutputType json_output_mode, bool onlyjson, bool jsonprintderivdetail) { if (json == nojson) return; @@ -1262,7 +1262,7 @@ ModFile::writeJsonOutput(const string &basename, JsonOutputPointType json, JsonF symbol_table.unfreeze(); if (json == computingpass) - writeJsonComputingPassOutput(basename, json_output_mode); + writeJsonComputingPassOutput(basename, json_output_mode, jsonprintderivdetail); switch (json) { @@ -1340,40 +1340,78 @@ ModFile::writeJsonOutputParsingCheck(const string &basename, JsonFileOutputType } void -ModFile::writeJsonComputingPassOutput(const string &basename, JsonFileOutputType json_output_mode) const +ModFile::writeJsonComputingPassOutput(const string &basename, JsonFileOutputType json_output_mode, bool jsonprintderivdetail) const { - ostringstream static_output; + ostringstream static_output, static_detail_output; static_output << "{"; - static_model.writeJsonComputingPassOutput(static_output); + static_model.writeJsonComputingPassOutput(static_output, false); static_output << "}" << endl; - ostringstream dynamic_output; + ostringstream dynamic_output, dynamic_detail_output; dynamic_output << "{"; - dynamic_model.writeJsonComputingPassOutput(dynamic_output); + dynamic_model.writeJsonComputingPassOutput(dynamic_output, false); dynamic_output << "}" << endl; - ostringstream tmp_out, static_paramsd_output; + ostringstream tmp_out, static_paramsd_output, static_paramsd_detail_output; tmp_out << ""; static_paramsd_output << ""; - static_model.writeJsonParamsDerivativesFile(tmp_out); + static_paramsd_detail_output << ""; + static_model.writeJsonParamsDerivativesFile(tmp_out, false); if (!tmp_out.str().empty()) static_paramsd_output << "{" << tmp_out.str() << "}" << endl; - ostringstream tmp1_out, dynamic_paramsd_output; + ostringstream tmp1_out, dynamic_paramsd_output, dynamic_paramsd_detail_output; tmp1_out << ""; dynamic_paramsd_output << ""; - dynamic_model.writeJsonParamsDerivativesFile(tmp1_out); + dynamic_paramsd_detail_output << ""; + dynamic_model.writeJsonParamsDerivativesFile(tmp1_out, false); if (!tmp1_out.str().empty()) dynamic_paramsd_output << "{" << tmp1_out.str() << "}" << endl; + if (jsonprintderivdetail) + { + static_detail_output << "{"; + static_model.writeJsonComputingPassOutput(static_detail_output, true); + static_detail_output << "}"; + + dynamic_detail_output << "{"; + dynamic_model.writeJsonComputingPassOutput(dynamic_detail_output, true); + dynamic_detail_output << "}"; + + ostringstream tmpd_out, tmpd1_out; + tmpd_out << ""; + tmpd1_out << ""; + static_model.writeJsonParamsDerivativesFile(tmpd_out, true); + if (!tmpd_out.str().empty()) + static_paramsd_detail_output << "{" << tmpd_out.str() << "}" << endl; + + dynamic_model.writeJsonParamsDerivativesFile(tmpd1_out, true); + if (!tmpd1_out.str().empty()) + dynamic_paramsd_detail_output << "{" << tmpd1_out.str() << "}" << endl; + } + if (json_output_mode == standardout) { - cout << static_output.str() << endl; - cout << dynamic_output.str() << endl; - if (!dynamic_paramsd_output.str().empty()) - cout << dynamic_paramsd_output.str() << endl; + cout << static_output.str() << endl + << dynamic_output.str() << endl; + if (!static_paramsd_output.str().empty()) cout << static_paramsd_output.str() << endl; + + if (!dynamic_paramsd_output.str().empty()) + cout << dynamic_paramsd_output.str() << endl; + + if (jsonprintderivdetail) + { + cout << static_detail_output.str() << endl + << dynamic_detail_output.str() << endl; + + if (!static_paramsd_detail_output.str().empty()) + cout << static_paramsd_detail_output.str() << endl; + + if (!dynamic_paramsd_detail_output.str().empty()) + cout << dynamic_paramsd_detail_output.str() << endl; + } } else { @@ -1387,56 +1425,50 @@ ModFile::writeJsonComputingPassOutput(const string &basename, JsonFileOutputType fname_static = basename + "_static.json"; fname_dynamic = basename + "_dynamic.json"; - ofstream jsonOutputFileStatic, jsonOutputFileDynamic; - jsonOutputFileStatic.open(fname_static.c_str(), ios::out | ios::binary); - if (!jsonOutputFileStatic.is_open()) - { - cerr << "ERROR: Can't open file " << fname_static << " for writing" << endl; - exit(EXIT_FAILURE); - } + writeJsonFileHelper(fname_static, static_output); + writeJsonFileHelper(fname_dynamic, dynamic_output); - jsonOutputFileDynamic.open(fname_dynamic.c_str(), ios::out | ios::binary); - if (!jsonOutputFileDynamic.is_open()) + if (jsonprintderivdetail) { - cerr << "ERROR: Can't open file " << fname_dynamic << " for writing" << endl; - exit(EXIT_FAILURE); - } + string fname_static_details, fname_dynamic_details; + fname_static_details = basename + "_static_details.json"; + fname_dynamic_details = basename + "_dynamic_details.json"; - jsonOutputFileStatic << static_output.str(); - jsonOutputFileStatic.close(); - jsonOutputFileDynamic << dynamic_output.str(); - jsonOutputFileDynamic.close(); + writeJsonFileHelper(fname_static_details, static_detail_output); + writeJsonFileHelper(fname_dynamic_details, dynamic_detail_output); + } if (!static_paramsd_output.str().empty()) { - string fname_static_params; + string fname_static_params, fname_static_params_details; fname_static_params = basename + "_static_params_derivs.json"; - ofstream jsonOutputFileStaticParamsDerivs; - jsonOutputFileStaticParamsDerivs.open(fname_static_params.c_str(), ios::out | ios::binary); - if (!jsonOutputFileStaticParamsDerivs.is_open()) - { - cerr << "ERROR: Can't open file " << fname_static_params << " for writing" << endl; - exit(EXIT_FAILURE); - } - - jsonOutputFileStaticParamsDerivs << static_paramsd_output.str(); - jsonOutputFileStaticParamsDerivs.close(); + fname_static_params_details = basename + "_static_params_derivs_details.json"; + writeJsonFileHelper(fname_static_params, static_paramsd_output); + writeJsonFileHelper(fname_static_params_details, static_paramsd_detail_output); } if (!dynamic_paramsd_output.str().empty()) { - string fname_dynamic_params; + string fname_dynamic_params, fname_dynamic_params_details; fname_dynamic_params = basename + "_params_derivs.json"; - ofstream jsonOutputFileDynamicParamsDerivs; - jsonOutputFileDynamicParamsDerivs.open(fname_dynamic_params.c_str(), ios::out | ios::binary); - if (!jsonOutputFileDynamicParamsDerivs.is_open()) - { - cerr << "ERROR: Can't open file " << fname_dynamic_params << " for writing" << endl; - exit(EXIT_FAILURE); - } - - jsonOutputFileDynamicParamsDerivs << dynamic_paramsd_output.str(); - jsonOutputFileDynamicParamsDerivs.close(); + fname_dynamic_params_details = basename + "_params_derivs_details.json"; + writeJsonFileHelper(fname_dynamic_params, dynamic_paramsd_output); + writeJsonFileHelper(fname_dynamic_params_details, dynamic_paramsd_detail_output); } } } + +void +ModFile::writeJsonFileHelper(string &fname, ostringstream &output) const +{ + ofstream jsonOutput; + jsonOutput.open(fname.c_str(), ios::out | ios::binary); + if (!jsonOutput.is_open()) + { + cerr << "ERROR: Can't open file " << fname << " for writing" << endl; + exit(EXIT_FAILURE); + } + jsonOutput << output.str(); + jsonOutput.close(); + +} diff --git a/ModFile.hh b/ModFile.hh index 385e97b6..c04f4de5 100644 --- a/ModFile.hh +++ b/ModFile.hh @@ -119,8 +119,8 @@ private: WarningConsolidation &warnings; //! Functions used in writing of JSON outut. See writeJsonOutput void writeJsonOutputParsingCheck(const string &basename, JsonFileOutputType json_output_mode) const; - void writeJsonComputingPassOutput(const string &basename, JsonFileOutputType json_output_mode) const; - + void writeJsonComputingPassOutput(const string &basename, JsonFileOutputType json_output_mode, bool jsonprintderivdetail) const; + void writeJsonFileHelper(string &fname, ostringstream &output) const; public: //! Add a statement void addStatement(Statement *st); @@ -174,7 +174,7 @@ public: //! Initially created to enable Julia to work with .mod files //! Potentially outputs ModFile after the various parts of processing (parsing, checkPass, transformPass, computingPass) //! Allows user of other host language platforms (python, fortran, etc) to provide support for dynare .mod files - void writeJsonOutput(const string &basename, JsonOutputPointType json, JsonFileOutputType json_output_mode, bool onlyjson); + void writeJsonOutput(const string &basename, JsonOutputPointType json, JsonFileOutputType json_output_mode, bool onlyjson, bool jsonprintderivdetail = false); }; #endif // ! MOD_FILE_HH diff --git a/StaticModel.cc b/StaticModel.cc index 35c9f516..65d4d632 100644 --- a/StaticModel.cc +++ b/StaticModel.cc @@ -2422,7 +2422,7 @@ StaticModel::writeJsonOutput(ostream &output) const } void -StaticModel::writeJsonComputingPassOutput(ostream &output) const +StaticModel::writeJsonComputingPassOutput(ostream &output, bool writeDetails) const { ostringstream model_local_vars_output; // Used for storing model local vars ostringstream model_output; // Used for storing model @@ -2463,11 +2463,17 @@ StaticModel::writeJsonComputingPassOutput(ostream &output) const jacobian_output << ", "; int eq = it->first.first; - string var = symbol_table.getName(getSymbIDByDerivID(it->first.second)); + int var = it->first.second; + int symb_id = getSymbIDByDerivID(var); + int col = symbol_table.getTypeSpecificID(symb_id); expr_t d1 = it->second; - jacobian_output << "{\"eq\": " << eq + 1 - << ", \"var\": \"" << var << "\"" + if (writeDetails) + jacobian_output << "{\"eq\": " << eq + 1 + << ", \"var\": \"" << symbol_table.getName(symb_id) << "\""; + else + jacobian_output << "{\"row\": " << eq + 1; + jacobian_output << ", \"col\": " << col + 1 << ", \"val\": \""; d1->writeJsonOutput(jacobian_output, temp_term_union, tef_terms); jacobian_output << "\"}" << endl; @@ -2491,13 +2497,27 @@ StaticModel::writeJsonComputingPassOutput(ostream &output) const hessian_output << ", "; int eq = it->first.first; - string var1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); - string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); + int symb_id1 = getSymbIDByDerivID(it->first.second.first); + int symb_id2 = getSymbIDByDerivID(it->first.second.second); expr_t d2 = it->second; - hessian_output << "{\"eq\": " << eq + 1 - << ", \"var1\": \"" << var1 << "\"" - << ", \"var2\": \"" << var2 << "\"" + int tsid1 = symbol_table.getTypeSpecificID(symb_id1); + int tsid2 = symbol_table.getTypeSpecificID(symb_id2); + + int col = tsid1*symbol_table.endo_nbr()+tsid2; + int col_sym = tsid2*symbol_table.endo_nbr()+tsid1; + + if (writeDetails) + hessian_output << "{\"eq\": " << eq + 1 + << ", \"var1\": \"" << symbol_table.getName(symb_id1) << "\"" + << ", \"var2\": \"" << symbol_table.getName(symb_id2) << "\""; + else + hessian_output << "{\"row\": " << eq + 1; + + hessian_output << ", \"col\": [" << col + 1; + if (symb_id1 != symb_id2) + hessian_output << ", " << col_sym + 1; + hessian_output << "]" << ", \"val\": \""; d2->writeJsonOutput(hessian_output, temp_term_union, tef_terms); hessian_output << "\"}" << endl; @@ -2520,23 +2540,49 @@ StaticModel::writeJsonComputingPassOutput(ostream &output) const third_derivatives_output << ", "; int eq = it->first.first; - string var1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); - string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.first)); - string var3 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); + int var1 = it->first.second.first; + int var2 = it->first.second.second.first; + int var3 = it->first.second.second.second; expr_t d3 = it->second; - third_derivatives_output << "{\"eq\": " << eq + 1 - << ", \"var1\": \"" << var1 << "\"" - << ", \"var2\": \"" << var2 << "\"" - << ", \"var3\": \"" << var3 << "\"" + if (writeDetails) + third_derivatives_output << "{\"eq\": " << eq + 1 + << ", \"var1\": \"" << symbol_table.getName(getSymbIDByDerivID(var1)) << "\"" + << ", \"var2\": \"" << symbol_table.getName(getSymbIDByDerivID(var2)) << "\"" + << ", \"var3\": \"" << symbol_table.getName(getSymbIDByDerivID(var3)) << "\""; + else + third_derivatives_output << "{\"row\": " << eq + 1; + + int id1 = getSymbIDByDerivID(var1); + int id2 = getSymbIDByDerivID(var2); + int id3 = getSymbIDByDerivID(var3); + set cols; + cols.insert(id1 * hessianColsNbr + id2 * JacobianColsNbr + id3); + cols.insert(id1 * hessianColsNbr + id3 * JacobianColsNbr + id2); + cols.insert(id2 * hessianColsNbr + id1 * JacobianColsNbr + id3); + cols.insert(id2 * hessianColsNbr + id3 * JacobianColsNbr + id1); + cols.insert(id3 * hessianColsNbr + id1 * JacobianColsNbr + id2); + cols.insert(id3 * hessianColsNbr + id2 * JacobianColsNbr + id1); + + third_derivatives_output << ", \"col\": ["; + for (set::iterator it2 = cols.begin(); it2 != cols.end(); it2++) + { + if (it2 != cols.begin()) + third_derivatives_output << ", "; + third_derivatives_output << *it2 + 1; + } + third_derivatives_output << "]" << ", \"val\": \""; d3->writeJsonOutput(third_derivatives_output, temp_term_union, tef_terms); third_derivatives_output << "\"}" << endl; } third_derivatives_output << "]}"; - output << "\"static_model_derivatives\": {" - << model_local_vars_output.str() + if (writeDetails) + output << "\"static_model_derivative_details\": {"; + else + output << "\"static_model_derivatives\": {"; + output << model_local_vars_output.str() << ", " << model_output.str() << ", " << jacobian_output.str() << ", " << hessian_output.str() @@ -2545,7 +2591,7 @@ StaticModel::writeJsonComputingPassOutput(ostream &output) const } void -StaticModel::writeJsonParamsDerivativesFile(ostream &output) const +StaticModel::writeJsonParamsDerivativesFile(ostream &output, bool writeDetails) const { if (!residuals_params_derivatives.size() && !residuals_params_second_derivatives.size() @@ -2579,11 +2625,17 @@ StaticModel::writeJsonParamsDerivativesFile(ostream &output) const jacobian_output << ", "; int eq = it->first.first; - string param = symbol_table.getName(getSymbIDByDerivID(it->first.second)); + int param = it->first.second; expr_t d1 = it->second; - jacobian_output << "{\"eq\": " << eq + 1 - << ", \"param\": \"" << param << "\"" + int param_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param)) + 1; + + if (writeDetails) + jacobian_output << "{\"eq\": " << eq + 1 + << ", \"param\": \"" << symbol_table.getName(getSymbIDByDerivID(param)) << "\""; + else + jacobian_output << "{\"row\": " << eq + 1; + jacobian_output << ", \"param_col\": " << param_col << ", \"val\": \""; d1->writeJsonOutput(jacobian_output, params_derivs_temporary_terms, tef_terms); jacobian_output << "\"}" << endl; @@ -2601,13 +2653,21 @@ StaticModel::writeJsonParamsDerivativesFile(ostream &output) const hessian_output << ", "; int eq = it->first.first; - string var = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); - string param = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); + int var = it->first.second.first; + int param = it->first.second.second; expr_t d2 = it->second; - hessian_output << "{\"eq\": " << eq + 1 - << ", \"var\": \"" << var << "\"" - << ", \"param\": \"" << param << "\"" + int var_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(var)) + 1; + int param_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param)) + 1; + + if (writeDetails) + hessian_output << "{\"eq\": " << eq + 1 + << ", \"var\": \"" << symbol_table.getName(getSymbIDByDerivID(var)) << "\"" + << ", \"param\": \"" << symbol_table.getName(getSymbIDByDerivID(param)) << "\""; + else + hessian_output << "{\"row\": " << eq + 1; + hessian_output << ", \"var_col\": " << var_col + << ", \"param_col\": " << param_col << ", \"val\": \""; d2->writeJsonOutput(hessian_output, params_derivs_temporary_terms, tef_terms); hessian_output << "\"}" << endl; @@ -2626,14 +2686,22 @@ StaticModel::writeJsonParamsDerivativesFile(ostream &output) const hessian1_output << ", "; int eq = it->first.first; - string param1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); - string param2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second)); + int param1 = it->first.second.first; + int param2 = it->first.second.second; expr_t d2 = it->second; - hessian1_output << "{\"eq\": " << eq + 1 - << ", \"param1\": \"" << param1 << "\"" - << ", \"param2\": \"" << param2 << "\"" - << ", \"val\": \""; + int param1_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param1)) + 1; + int param2_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param2)) + 1; + + if (writeDetails) + hessian1_output << "{\"eq\": " << eq + 1 + << ", \"param1\": \"" << symbol_table.getName(getSymbIDByDerivID(param1)) << "\"" + << ", \"param2\": \"" << symbol_table.getName(getSymbIDByDerivID(param2)) << "\""; + else + hessian1_output << "{\"row\": " << eq + 1; + hessian1_output << ", \"param1_col\": " << param1_col + << ", \"param2_col\": " << param2_col + << ", \"val\": \""; d2->writeJsonOutput(hessian1_output, params_derivs_temporary_terms, tef_terms); hessian1_output << "\"}" << endl; } @@ -2651,15 +2719,25 @@ StaticModel::writeJsonParamsDerivativesFile(ostream &output) const third_derivs_output << ", "; int eq = it->first.first; - string var = symbol_table.getName(it->first.second.first); - string param1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.first)); - string param2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); + int var = it->first.second.first; + int param1 = it->first.second.second.first; + int param2 = it->first.second.second.second; expr_t d2 = it->second; - third_derivs_output << "{\"eq\": " << eq + 1 - << ", \"var\": \"" << var << "\"" - << ", \"param1\": \"" << param1 << "\"" - << ", \"param2\": \"" << param2 << "\"" + int var_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(var)) + 1; + int param1_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param1)) + 1; + int param2_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param2)) + 1; + + if (writeDetails) + third_derivs_output << "{\"eq\": " << eq + 1 + << ", \"var\": \"" << symbol_table.getName(var) << "\"" + << ", \"param1\": \"" << symbol_table.getName(getSymbIDByDerivID(param1)) << "\"" + << ", \"param2\": \"" << symbol_table.getName(getSymbIDByDerivID(param2)) << "\""; + else + third_derivs_output << "{\"row\": " << eq + 1; + third_derivs_output << ", \"var_col\": " << var_col + << ", \"param1_col\": " << param1_col + << ", \"param2_col\": " << param2_col << ", \"val\": \""; d2->writeJsonOutput(third_derivs_output, params_derivs_temporary_terms, tef_terms); third_derivs_output << "\"}" << endl; @@ -2679,23 +2757,36 @@ StaticModel::writeJsonParamsDerivativesFile(ostream &output) const third_derivs1_output << ", "; int eq = it->first.first; - string var1 = symbol_table.getName(getSymbIDByDerivID(it->first.second.first)); - string var2 = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.first)); - string param = symbol_table.getName(getSymbIDByDerivID(it->first.second.second.second)); + int var1 = it->first.second.first; + int var2 = it->first.second.second.first; + int param = it->first.second.second.second; expr_t d2 = it->second; - third_derivs1_output << "{\"eq\": " << eq + 1 - << ", \"var1\": \"" << var1 << "\"" - << ", \"var2\": \"" << var2 << "\"" - << ", \"param1\": \"" << param << "\"" + int var1_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(var1)) + 1; + int var2_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(var2)) + 1; + int param_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param)) + 1; + + if (writeDetails) + third_derivs1_output << "{\"eq\": " << eq + 1 + << ", \"var1\": \"" << symbol_table.getName(getSymbIDByDerivID(var1)) << "\"" + << ", \"var2\": \"" << symbol_table.getName(getSymbIDByDerivID(var2)) << "\"" + << ", \"param1\": \"" << symbol_table.getName(getSymbIDByDerivID(param)) << "\""; + else + third_derivs1_output << "{\"row\": " << eq + 1; + third_derivs1_output << ", \"var1_col\": " << var1_col + << ", \"var2_col\": " << var2_col + << ", \"param_col\": " << param_col << ", \"val\": \""; d2->writeJsonOutput(third_derivs1_output, params_derivs_temporary_terms, tef_terms); third_derivs1_output << "\"}" << endl; } third_derivs1_output << "]}" << endl; - output << "\"static_model_params_derivatives\": {" - << model_local_vars_output.str() + if (writeDetails) + output << "\"static_model_params_derivative_details\": {"; + else + output << "\"static_model_params_derivatives\": {"; + output << model_local_vars_output.str() << ", " << model_output.str() << ", " << jacobian_output.str() << ", " << hessian_output.str() diff --git a/StaticModel.hh b/StaticModel.hh index d770896e..f1a7d36a 100644 --- a/StaticModel.hh +++ b/StaticModel.hh @@ -174,10 +174,10 @@ public: void writeJsonOutput(ostream &output) const; //! Write JSON representation of static model - void writeJsonComputingPassOutput(ostream &output) const; + void writeJsonComputingPassOutput(ostream &output, bool writeDetails) const; //! Writes file containing static parameters derivatives - void writeJsonParamsDerivativesFile(ostream &output) const; + void writeJsonParamsDerivativesFile(ostream &output, bool writeDetails) const; //! Writes file containing static parameters derivatives void writeParamsDerivativesFile(const string &basename, bool julia) const; From 2a3ef9d168a09ff6628961487f76109f526ef149 Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Mon, 6 Mar 2017 16:34:08 +0100 Subject: [PATCH 11/18] preprocessor: write equation cross references in JSON. #1387 --- DynamicModel.cc | 122 ++++++++++++++++++++++++++++++++++++++++++++++++ DynamicModel.hh | 17 ++++++- ExprNode.cc | 81 ++++++++++++++++++++++++++++++++ ExprNode.hh | 18 +++++++ ModFile.cc | 3 ++ 5 files changed, 240 insertions(+), 1 deletion(-) diff --git a/DynamicModel.cc b/DynamicModel.cc index 10db3a8b..c05529c4 100644 --- a/DynamicModel.cc +++ b/DynamicModel.cc @@ -5342,6 +5342,127 @@ void DynamicModel::writeJsonOutput(ostream &output) const { writeJsonModelEquations(output, false); + output << ", "; + writeJsonXrefs(output); +} + +void +DynamicModel::writeJsonXrefs(ostream &output) const +{ + output << "\"xrefs\": {" + << "\"parameters\": ["; + for (map, set >::const_iterator it = json_xref_param.begin(); + it != json_xref_param.end(); it++) + { + if (it != json_xref_param.begin()) + output << ", "; + output << "{\"parameter\": \"" << symbol_table.getName(it->first.first) << "\"" + << ", \"equations\": ["; + for (set::const_iterator it1 = it->second.begin(); + it1 != it->second.end(); it1++) + { + if (it1 != it->second.begin()) + output << ", "; + output << *it1 + 1; + } + output << "]}"; + } + output << "]" + << ", \"endogenous\": ["; + for (map, set >::const_iterator it = json_xref_endo.begin(); + it != json_xref_endo.end(); it++) + { + if (it != json_xref_endo.begin()) + output << ", "; + output << "{\"endogenous\": \"" << symbol_table.getName(it->first.first) << "\"" + << ", \"shift\": " << it->first.second + << ", \"equations\": ["; + for (set::const_iterator it1 = it->second.begin(); + it1 != it->second.end(); it1++) + { + if (it1 != it->second.begin()) + output << ", "; + output << *it1 + 1; + } + output << "]}"; + } + output << "]" + << ", \"exogenous\": ["; + for (map, set >::const_iterator it = json_xref_exo.begin(); + it != json_xref_exo.end(); it++) + { + if (it != json_xref_exo.begin()) + output << ", "; + output << "{\"exogenous\": \"" << symbol_table.getName(it->first.first) << "\"" + << ", \"shift\": " << it->first.second + << ", \"equations\": ["; + for (set::const_iterator it1 = it->second.begin(); + it1 != it->second.end(); it1++) + { + if (it1 != it->second.begin()) + output << ", "; + output << *it1 + 1; + } + output << "]}"; + } + output << "]" + << ", \"exogenous_deterministic\": ["; + for (map, set >::const_iterator it = json_xref_exo_det.begin(); + it != json_xref_exo_det.end(); it++) + { + if (it != json_xref_exo_det.begin()) + output << ", "; + output << "{\"exogenous_det\": \"" << symbol_table.getName(it->first.first) << "\"" + << ", \"shift\": " << it->first.second + << ", \"equations\": ["; + for (set::const_iterator it1 = it->second.begin(); + it1 != it->second.end(); it1++) + { + if (it1 != it->second.begin()) + output << ", "; + output << *it1 + 1; + } + output << "]}"; + } + output << "]}" << endl; +} + +void +DynamicModel::computeJsonXrefs() +{ + map xrefs; + int i = 0; + for (vector::iterator it = equations.begin(); + it != equations.end(); it++) + { + ExprNode::JsonEquationInfo ei; + (*it)->computeJsonXrefs(ei); + xrefs[i++] = ei; + } + + i = 0; + for (map::const_iterator it = xrefs.begin(); + it != xrefs.end(); it++, i++) + { + computeJsonRevXref(json_xref_param, it->second.param, i); + computeJsonRevXref(json_xref_endo, it->second.endo, i); + computeJsonRevXref(json_xref_exo, it->second.exo, i); + computeJsonRevXref(json_xref_exo_det, it->second.exo_det, i); + } +} + +void +DynamicModel::computeJsonRevXref(map, set > &xrefset, const set > &eiref, int eqn) +{ + for (set >::const_iterator it = eiref.begin(); + it != eiref.end(); it++) + { + set eq; + if (xrefset.find(*it) != xrefset.end()) + eq = xrefset[*it]; + eq.insert(eqn); + xrefset[*it] = eq; + } } void @@ -5721,3 +5842,4 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output, bool writeDetails) << ", " << third_derivs1_output.str() << "}"; } + diff --git a/DynamicModel.hh b/DynamicModel.hh index b0828a2b..cec66d97 100644 --- a/DynamicModel.hh +++ b/DynamicModel.hh @@ -62,6 +62,12 @@ private: /*! Set by computeDerivIDs() */ int max_exo_det_lag, max_exo_det_lead; + //! Cross references WITH lags (for #1387, potentially combine with cross references above upon decision by @michel) + map, set > json_xref_param; + map, set > json_xref_endo; + map, set > json_xref_exo; + map, set > json_xref_exo_det; + //! Number of columns of dynamic jacobian /*! Set by computeDerivID()s and computeDynJacobianCols() */ int dynJacobianColsNbr; @@ -189,6 +195,9 @@ private: /*! pair< pair, pair > */ vector, pair > > block_col_type; + //! Related to public function computeJsonXref + void computeJsonRevXref(map, set > &xrefset, const set > &eiref, int eqn); + //! List for each variable its block number and its maximum lag and lead inside the block vector > > variable_block_lead_lag; //! List for each equation its block number @@ -202,7 +211,10 @@ public: //! Adds a variable node /*! This implementation allows for non-zero lag */ virtual VariableNode *AddVariable(int symb_id, int lag = 0); - + + //! For computing cross references for json output (i.e. that contains lag information) #1387 + void computeJsonXrefs(); + //! Execute computations (variable sorting + derivation) /*! \param jacobianExo whether derivatives w.r. to exo and exo_det should be in the Jacobian (derivatives w.r. to endo are always computed) @@ -220,6 +232,9 @@ public: //! Write JSON Output void writeJsonOutput(ostream &output) const; + //! Write cross reference output if the xref maps have been filed + void writeJsonXrefs(ostream &output) const; + //! Write JSON Output representation of dynamic model after computing pass void writeJsonComputingPassOutput(ostream &output, bool writeDetails) const; diff --git a/ExprNode.cc b/ExprNode.cc index 5cc0298b..dfb66d3d 100644 --- a/ExprNode.cc +++ b/ExprNode.cc @@ -396,6 +396,11 @@ NumConstNode::computeXrefs(EquationInfo &ei) const { } +void +NumConstNode::computeJsonXrefs(JsonEquationInfo &ei) const +{ +} + expr_t NumConstNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -1131,6 +1136,34 @@ VariableNode::computeXrefs(EquationInfo &ei) const } } +void +VariableNode::computeJsonXrefs(JsonEquationInfo &ei) const +{ + switch (type) + { + case eEndogenous: + ei.endo.insert(make_pair(symb_id, lag)); + break; + case eExogenous: + ei.exo.insert(make_pair(symb_id, lag)); + break; + case eExogenousDet: + ei.exo_det.insert(make_pair(symb_id, lag)); + break; + case eParameter: + ei.param.insert(make_pair(symb_id, 0)); + break; + case eTrend: + case eLogTrend: + case eModelLocalVariable: + case eModFileLocalVariable: + case eStatementDeclaredVariable: + case eUnusedEndogenous: + case eExternalFunction: + break; + } +} + expr_t VariableNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -2558,6 +2591,12 @@ UnaryOpNode::computeXrefs(EquationInfo &ei) const arg->computeXrefs(ei); } +void +UnaryOpNode::computeJsonXrefs(JsonEquationInfo &ei) const +{ + arg->computeJsonXrefs(ei); +} + expr_t UnaryOpNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -3994,6 +4033,13 @@ BinaryOpNode::computeXrefs(EquationInfo &ei) const arg2->computeXrefs(ei); } +void +BinaryOpNode::computeJsonXrefs(JsonEquationInfo &ei) const +{ + arg1->computeJsonXrefs(ei); + arg2->computeJsonXrefs(ei); +} + expr_t BinaryOpNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -4761,6 +4807,14 @@ TrinaryOpNode::computeXrefs(EquationInfo &ei) const arg3->computeXrefs(ei); } +void +TrinaryOpNode::computeJsonXrefs(JsonEquationInfo &ei) const +{ + arg1->computeJsonXrefs(ei); + arg2->computeJsonXrefs(ei); + arg3->computeJsonXrefs(ei); +} + expr_t TrinaryOpNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -5644,6 +5698,15 @@ ExternalFunctionNode::computeXrefs(EquationInfo &ei) const (*it)->computeXrefs(ei); } +void +ExternalFunctionNode::computeJsonXrefs(JsonEquationInfo &ei) const +{ + vector dynamic_arguments; + for (vector::const_iterator it = arguments.begin(); + it != arguments.end(); it++) + (*it)->computeJsonXrefs(ei); +} + expr_t ExternalFunctionNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -6044,6 +6107,15 @@ FirstDerivExternalFunctionNode::computeXrefs(EquationInfo &ei) const (*it)->computeXrefs(ei); } +void +FirstDerivExternalFunctionNode::computeJsonXrefs(JsonEquationInfo &ei) const +{ + vector dynamic_arguments; + for (vector::const_iterator it = arguments.begin(); + it != arguments.end(); it++) + (*it)->computeJsonXrefs(ei); +} + SecondDerivExternalFunctionNode::SecondDerivExternalFunctionNode(DataTree &datatree_arg, int top_level_symb_id_arg, const vector &arguments_arg, @@ -6359,6 +6431,15 @@ SecondDerivExternalFunctionNode::computeXrefs(EquationInfo &ei) const (*it)->computeXrefs(ei); } +void +SecondDerivExternalFunctionNode::computeJsonXrefs(JsonEquationInfo &ei) const +{ + vector dynamic_arguments; + for (vector::const_iterator it = arguments.begin(); + it != arguments.end(); it++) + (*it)->computeJsonXrefs(ei); +} + void SecondDerivExternalFunctionNode::compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, diff --git a/ExprNode.hh b/ExprNode.hh index e4e5d9bc..c6dca035 100644 --- a/ExprNode.hh +++ b/ExprNode.hh @@ -171,6 +171,14 @@ protected: set exo_det; }; + struct JsonEquationInfo + { + set > param; + set > endo; + set > exo; + set > exo_det; + }; + public: ExprNode(DataTree &datatree_arg); virtual ~ExprNode(); @@ -310,6 +318,7 @@ public: */ // virtual void computeXrefs(set ¶m, set &endo, set &exo, set &exo_det) const = 0; virtual void computeXrefs(EquationInfo &ei) const = 0; + virtual void computeJsonXrefs(JsonEquationInfo &ei) const = 0; //! Try to normalize an equation linear in its endogenous variable virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const = 0; @@ -497,6 +506,7 @@ public: 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, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; + virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -553,6 +563,7 @@ public: 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, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; + virtual void computeJsonXrefs(JsonEquationInfo &ei) const; SymbolType get_type() const { @@ -652,6 +663,7 @@ public: }; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; + virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -756,6 +768,7 @@ public: } virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; + virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -841,6 +854,7 @@ public: 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, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; + virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -928,6 +942,7 @@ public: 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, deriv_node_temp_terms_t &tef_terms) const = 0; virtual expr_t toStatic(DataTree &static_datatree) const = 0; virtual void computeXrefs(EquationInfo &ei) const = 0; + virtual void computeJsonXrefs(JsonEquationInfo &ei) const = 0; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -989,6 +1004,7 @@ public: 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, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; + virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual expr_t buildSimilarExternalFunctionNode(vector &alt_args, DataTree &alt_datatree) const; virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const; }; @@ -1030,6 +1046,7 @@ public: deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; + virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual expr_t buildSimilarExternalFunctionNode(vector &alt_args, DataTree &alt_datatree) const; virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const; }; @@ -1073,6 +1090,7 @@ public: deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; + virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual expr_t buildSimilarExternalFunctionNode(vector &alt_args, DataTree &alt_datatree) const; virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const; }; diff --git a/ModFile.cc b/ModFile.cc index 7ee204ad..ea9cf4e3 100644 --- a/ModFile.cc +++ b/ModFile.cc @@ -414,6 +414,9 @@ ModFile::transformPass(bool nostrict) // Freeze the symbol table symbol_table.freeze(); + //! Need access to this info after transform pass so calculate it here + dynamic_model.computeJsonXrefs(); + /* Enforce the same number of equations and endogenous, except in three cases: - ramsey_model, ramsey_policy or discretionary_policy is used From cde54d7ad433895b37230e2d0676de2dac0a6f5c Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Fri, 10 Mar 2017 17:18:41 +0100 Subject: [PATCH 12/18] Revert "preprocessor: write equation cross references in JSON. #1387" This reverts commit 0ccc82300c3046d159554c24027ded09a93b687e. --- DynamicModel.cc | 122 ------------------------------------------------ DynamicModel.hh | 17 +------ ExprNode.cc | 81 -------------------------------- ExprNode.hh | 18 ------- ModFile.cc | 3 -- 5 files changed, 1 insertion(+), 240 deletions(-) diff --git a/DynamicModel.cc b/DynamicModel.cc index c05529c4..10db3a8b 100644 --- a/DynamicModel.cc +++ b/DynamicModel.cc @@ -5342,127 +5342,6 @@ void DynamicModel::writeJsonOutput(ostream &output) const { writeJsonModelEquations(output, false); - output << ", "; - writeJsonXrefs(output); -} - -void -DynamicModel::writeJsonXrefs(ostream &output) const -{ - output << "\"xrefs\": {" - << "\"parameters\": ["; - for (map, set >::const_iterator it = json_xref_param.begin(); - it != json_xref_param.end(); it++) - { - if (it != json_xref_param.begin()) - output << ", "; - output << "{\"parameter\": \"" << symbol_table.getName(it->first.first) << "\"" - << ", \"equations\": ["; - for (set::const_iterator it1 = it->second.begin(); - it1 != it->second.end(); it1++) - { - if (it1 != it->second.begin()) - output << ", "; - output << *it1 + 1; - } - output << "]}"; - } - output << "]" - << ", \"endogenous\": ["; - for (map, set >::const_iterator it = json_xref_endo.begin(); - it != json_xref_endo.end(); it++) - { - if (it != json_xref_endo.begin()) - output << ", "; - output << "{\"endogenous\": \"" << symbol_table.getName(it->first.first) << "\"" - << ", \"shift\": " << it->first.second - << ", \"equations\": ["; - for (set::const_iterator it1 = it->second.begin(); - it1 != it->second.end(); it1++) - { - if (it1 != it->second.begin()) - output << ", "; - output << *it1 + 1; - } - output << "]}"; - } - output << "]" - << ", \"exogenous\": ["; - for (map, set >::const_iterator it = json_xref_exo.begin(); - it != json_xref_exo.end(); it++) - { - if (it != json_xref_exo.begin()) - output << ", "; - output << "{\"exogenous\": \"" << symbol_table.getName(it->first.first) << "\"" - << ", \"shift\": " << it->first.second - << ", \"equations\": ["; - for (set::const_iterator it1 = it->second.begin(); - it1 != it->second.end(); it1++) - { - if (it1 != it->second.begin()) - output << ", "; - output << *it1 + 1; - } - output << "]}"; - } - output << "]" - << ", \"exogenous_deterministic\": ["; - for (map, set >::const_iterator it = json_xref_exo_det.begin(); - it != json_xref_exo_det.end(); it++) - { - if (it != json_xref_exo_det.begin()) - output << ", "; - output << "{\"exogenous_det\": \"" << symbol_table.getName(it->first.first) << "\"" - << ", \"shift\": " << it->first.second - << ", \"equations\": ["; - for (set::const_iterator it1 = it->second.begin(); - it1 != it->second.end(); it1++) - { - if (it1 != it->second.begin()) - output << ", "; - output << *it1 + 1; - } - output << "]}"; - } - output << "]}" << endl; -} - -void -DynamicModel::computeJsonXrefs() -{ - map xrefs; - int i = 0; - for (vector::iterator it = equations.begin(); - it != equations.end(); it++) - { - ExprNode::JsonEquationInfo ei; - (*it)->computeJsonXrefs(ei); - xrefs[i++] = ei; - } - - i = 0; - for (map::const_iterator it = xrefs.begin(); - it != xrefs.end(); it++, i++) - { - computeJsonRevXref(json_xref_param, it->second.param, i); - computeJsonRevXref(json_xref_endo, it->second.endo, i); - computeJsonRevXref(json_xref_exo, it->second.exo, i); - computeJsonRevXref(json_xref_exo_det, it->second.exo_det, i); - } -} - -void -DynamicModel::computeJsonRevXref(map, set > &xrefset, const set > &eiref, int eqn) -{ - for (set >::const_iterator it = eiref.begin(); - it != eiref.end(); it++) - { - set eq; - if (xrefset.find(*it) != xrefset.end()) - eq = xrefset[*it]; - eq.insert(eqn); - xrefset[*it] = eq; - } } void @@ -5842,4 +5721,3 @@ DynamicModel::writeJsonParamsDerivativesFile(ostream &output, bool writeDetails) << ", " << third_derivs1_output.str() << "}"; } - diff --git a/DynamicModel.hh b/DynamicModel.hh index cec66d97..b0828a2b 100644 --- a/DynamicModel.hh +++ b/DynamicModel.hh @@ -62,12 +62,6 @@ private: /*! Set by computeDerivIDs() */ int max_exo_det_lag, max_exo_det_lead; - //! Cross references WITH lags (for #1387, potentially combine with cross references above upon decision by @michel) - map, set > json_xref_param; - map, set > json_xref_endo; - map, set > json_xref_exo; - map, set > json_xref_exo_det; - //! Number of columns of dynamic jacobian /*! Set by computeDerivID()s and computeDynJacobianCols() */ int dynJacobianColsNbr; @@ -195,9 +189,6 @@ private: /*! pair< pair, pair > */ vector, pair > > block_col_type; - //! Related to public function computeJsonXref - void computeJsonRevXref(map, set > &xrefset, const set > &eiref, int eqn); - //! List for each variable its block number and its maximum lag and lead inside the block vector > > variable_block_lead_lag; //! List for each equation its block number @@ -211,10 +202,7 @@ public: //! Adds a variable node /*! This implementation allows for non-zero lag */ virtual VariableNode *AddVariable(int symb_id, int lag = 0); - - //! For computing cross references for json output (i.e. that contains lag information) #1387 - void computeJsonXrefs(); - + //! Execute computations (variable sorting + derivation) /*! \param jacobianExo whether derivatives w.r. to exo and exo_det should be in the Jacobian (derivatives w.r. to endo are always computed) @@ -232,9 +220,6 @@ public: //! Write JSON Output void writeJsonOutput(ostream &output) const; - //! Write cross reference output if the xref maps have been filed - void writeJsonXrefs(ostream &output) const; - //! Write JSON Output representation of dynamic model after computing pass void writeJsonComputingPassOutput(ostream &output, bool writeDetails) const; diff --git a/ExprNode.cc b/ExprNode.cc index dfb66d3d..5cc0298b 100644 --- a/ExprNode.cc +++ b/ExprNode.cc @@ -396,11 +396,6 @@ NumConstNode::computeXrefs(EquationInfo &ei) const { } -void -NumConstNode::computeJsonXrefs(JsonEquationInfo &ei) const -{ -} - expr_t NumConstNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -1136,34 +1131,6 @@ VariableNode::computeXrefs(EquationInfo &ei) const } } -void -VariableNode::computeJsonXrefs(JsonEquationInfo &ei) const -{ - switch (type) - { - case eEndogenous: - ei.endo.insert(make_pair(symb_id, lag)); - break; - case eExogenous: - ei.exo.insert(make_pair(symb_id, lag)); - break; - case eExogenousDet: - ei.exo_det.insert(make_pair(symb_id, lag)); - break; - case eParameter: - ei.param.insert(make_pair(symb_id, 0)); - break; - case eTrend: - case eLogTrend: - case eModelLocalVariable: - case eModFileLocalVariable: - case eStatementDeclaredVariable: - case eUnusedEndogenous: - case eExternalFunction: - break; - } -} - expr_t VariableNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -2591,12 +2558,6 @@ UnaryOpNode::computeXrefs(EquationInfo &ei) const arg->computeXrefs(ei); } -void -UnaryOpNode::computeJsonXrefs(JsonEquationInfo &ei) const -{ - arg->computeJsonXrefs(ei); -} - expr_t UnaryOpNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -4033,13 +3994,6 @@ BinaryOpNode::computeXrefs(EquationInfo &ei) const arg2->computeXrefs(ei); } -void -BinaryOpNode::computeJsonXrefs(JsonEquationInfo &ei) const -{ - arg1->computeJsonXrefs(ei); - arg2->computeJsonXrefs(ei); -} - expr_t BinaryOpNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -4807,14 +4761,6 @@ TrinaryOpNode::computeXrefs(EquationInfo &ei) const arg3->computeXrefs(ei); } -void -TrinaryOpNode::computeJsonXrefs(JsonEquationInfo &ei) const -{ - arg1->computeJsonXrefs(ei); - arg2->computeJsonXrefs(ei); - arg3->computeJsonXrefs(ei); -} - expr_t TrinaryOpNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -5698,15 +5644,6 @@ ExternalFunctionNode::computeXrefs(EquationInfo &ei) const (*it)->computeXrefs(ei); } -void -ExternalFunctionNode::computeJsonXrefs(JsonEquationInfo &ei) const -{ - vector dynamic_arguments; - for (vector::const_iterator it = arguments.begin(); - it != arguments.end(); it++) - (*it)->computeJsonXrefs(ei); -} - expr_t ExternalFunctionNode::cloneDynamic(DataTree &dynamic_datatree) const { @@ -6107,15 +6044,6 @@ FirstDerivExternalFunctionNode::computeXrefs(EquationInfo &ei) const (*it)->computeXrefs(ei); } -void -FirstDerivExternalFunctionNode::computeJsonXrefs(JsonEquationInfo &ei) const -{ - vector dynamic_arguments; - for (vector::const_iterator it = arguments.begin(); - it != arguments.end(); it++) - (*it)->computeJsonXrefs(ei); -} - SecondDerivExternalFunctionNode::SecondDerivExternalFunctionNode(DataTree &datatree_arg, int top_level_symb_id_arg, const vector &arguments_arg, @@ -6431,15 +6359,6 @@ SecondDerivExternalFunctionNode::computeXrefs(EquationInfo &ei) const (*it)->computeXrefs(ei); } -void -SecondDerivExternalFunctionNode::computeJsonXrefs(JsonEquationInfo &ei) const -{ - vector dynamic_arguments; - for (vector::const_iterator it = arguments.begin(); - it != arguments.end(); it++) - (*it)->computeJsonXrefs(ei); -} - void SecondDerivExternalFunctionNode::compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, diff --git a/ExprNode.hh b/ExprNode.hh index c6dca035..e4e5d9bc 100644 --- a/ExprNode.hh +++ b/ExprNode.hh @@ -171,14 +171,6 @@ protected: set exo_det; }; - struct JsonEquationInfo - { - set > param; - set > endo; - set > exo; - set > exo_det; - }; - public: ExprNode(DataTree &datatree_arg); virtual ~ExprNode(); @@ -318,7 +310,6 @@ public: */ // virtual void computeXrefs(set ¶m, set &endo, set &exo, set &exo_det) const = 0; virtual void computeXrefs(EquationInfo &ei) const = 0; - virtual void computeJsonXrefs(JsonEquationInfo &ei) const = 0; //! Try to normalize an equation linear in its endogenous variable virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const = 0; @@ -506,7 +497,6 @@ public: 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, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; - virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -563,7 +553,6 @@ public: 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, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; - virtual void computeJsonXrefs(JsonEquationInfo &ei) const; SymbolType get_type() const { @@ -663,7 +652,6 @@ public: }; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; - virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -768,7 +756,6 @@ public: } virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; - virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -854,7 +841,6 @@ public: 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, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; - virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -942,7 +928,6 @@ public: 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, deriv_node_temp_terms_t &tef_terms) const = 0; virtual expr_t toStatic(DataTree &static_datatree) const = 0; virtual void computeXrefs(EquationInfo &ei) const = 0; - virtual void computeJsonXrefs(JsonEquationInfo &ei) const = 0; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; @@ -1004,7 +989,6 @@ public: 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, deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; - virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual expr_t buildSimilarExternalFunctionNode(vector &alt_args, DataTree &alt_datatree) const; virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const; }; @@ -1046,7 +1030,6 @@ public: deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; - virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual expr_t buildSimilarExternalFunctionNode(vector &alt_args, DataTree &alt_datatree) const; virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const; }; @@ -1090,7 +1073,6 @@ public: deriv_node_temp_terms_t &tef_terms) const; virtual expr_t toStatic(DataTree &static_datatree) const; virtual void computeXrefs(EquationInfo &ei) const; - virtual void computeJsonXrefs(JsonEquationInfo &ei) const; virtual expr_t buildSimilarExternalFunctionNode(vector &alt_args, DataTree &alt_datatree) const; virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const; }; diff --git a/ModFile.cc b/ModFile.cc index ea9cf4e3..7ee204ad 100644 --- a/ModFile.cc +++ b/ModFile.cc @@ -414,9 +414,6 @@ ModFile::transformPass(bool nostrict) // Freeze the symbol table symbol_table.freeze(); - //! Need access to this info after transform pass so calculate it here - dynamic_model.computeJsonXrefs(); - /* Enforce the same number of equations and endogenous, except in three cases: - ramsey_model, ramsey_policy or discretionary_policy is used From 6e9e2eac40decbe73e6d44c55f60e32307f013b0 Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Fri, 10 Mar 2017 17:23:35 +0100 Subject: [PATCH 13/18] preprocessor: write JSON output for cross refs #1387 --- DynamicModel.cc | 83 +++++++++++++++++++++++++++++++++++++++++++++++++ DynamicModel.hh | 3 ++ DynareMain2.cc | 2 +- 3 files changed, 87 insertions(+), 1 deletion(-) diff --git a/DynamicModel.cc b/DynamicModel.cc index 1bd65d72..29858216 100644 --- a/DynamicModel.cc +++ b/DynamicModel.cc @@ -5446,6 +5446,89 @@ void DynamicModel::writeJsonOutput(ostream &output) const { writeJsonModelEquations(output, false); + output << ", "; + writeJsonXrefs(output); +} + +void +DynamicModel::writeJsonXrefs(ostream &output) const +{ + output << "\"xrefs\": {" + << "\"parameters\": ["; + for (map, set >::const_iterator it = xref_param.begin(); + it != xref_param.end(); it++) + { + if (it != xref_param.begin()) + output << ", "; + output << "{\"parameter\": \"" << symbol_table.getName(it->first.first) << "\"" + << ", \"equations\": ["; + for (set::const_iterator it1 = it->second.begin(); + it1 != it->second.end(); it1++) + { + if (it1 != it->second.begin()) + output << ", "; + output << *it1 + 1; + } + output << "]}"; + } + output << "]" + << ", \"endogenous\": ["; + for (map, set >::const_iterator it = xref_endo.begin(); + it != xref_endo.end(); it++) + { + if (it != xref_endo.begin()) + output << ", "; + output << "{\"endogenous\": \"" << symbol_table.getName(it->first.first) << "\"" + << ", \"shift\": " << it->first.second + << ", \"equations\": ["; + for (set::const_iterator it1 = it->second.begin(); + it1 != it->second.end(); it1++) + { + if (it1 != it->second.begin()) + output << ", "; + output << *it1 + 1; + } + output << "]}"; + } + output << "]" + << ", \"exogenous\": ["; + for (map, set >::const_iterator it = xref_exo.begin(); + it != xref_exo.end(); it++) + { + if (it != xref_exo.begin()) + output << ", "; + output << "{\"exogenous\": \"" << symbol_table.getName(it->first.first) << "\"" + << ", \"shift\": " << it->first.second + << ", \"equations\": ["; + for (set::const_iterator it1 = it->second.begin(); + it1 != it->second.end(); it1++) + { + if (it1 != it->second.begin()) + output << ", "; + output << *it1 + 1; + } + output << "]}"; + } + output << "]" + << ", \"exogenous_deterministic\": ["; + for (map, set >::const_iterator it = xref_exo_det.begin(); + it != xref_exo_det.end(); it++) + { + if (it != xref_exo_det.begin()) + output << ", "; + output << "{\"exogenous_det\": \"" << symbol_table.getName(it->first.first) << "\"" + << ", \"shift\": " << it->first.second + << ", \"equations\": ["; + for (set::const_iterator it1 = it->second.begin(); + it1 != it->second.end(); it1++) + { + if (it1 != it->second.begin()) + output << ", "; + output << *it1 + 1; + } + output << "]}"; + } + output << "]}" << endl; } void diff --git a/DynamicModel.hh b/DynamicModel.hh index 6001c017..c9c9da8a 100644 --- a/DynamicModel.hh +++ b/DynamicModel.hh @@ -245,6 +245,9 @@ public: //! Write JSON prams derivatives file void writeJsonParamsDerivativesFile(ostream &output, bool writeDetails) const; + //! Write cross reference output if the xref maps have been filed + void writeJsonXrefs(ostream &output) const; + //! Return true if the hessian is equal to zero inline bool checkHessianZero() const; diff --git a/DynareMain2.cc b/DynareMain2.cc index 5a870a62..55f8304e 100644 --- a/DynareMain2.cc +++ b/DynareMain2.cc @@ -50,7 +50,7 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear mod_file->writeJsonOutput(basename, json, json_output_mode, onlyjson); // Perform transformations on the model (creation of auxiliary vars and equations) - mod_file->transformPass(nostrict, compute_xrefs); + mod_file->transformPass(nostrict, compute_xrefs || json == transformpass); if (json == transformpass) mod_file->writeJsonOutput(basename, json, json_output_mode, onlyjson); From 3eddd5ce8882e8514bd1cc4e2b6fec7ff5b1c5f6 Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Wed, 15 Mar 2017 12:52:55 +0100 Subject: [PATCH 14/18] preprocessor: split equation output into lhs and rhs. #1387 --- ModelTree.cc | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/ModelTree.cc b/ModelTree.cc index 5b262870..20490239 100644 --- a/ModelTree.cc +++ b/ModelTree.cc @@ -1939,12 +1939,12 @@ ModelTree::writeJsonModelEquations(ostream &output, bool residuals) const if (eq > 0) output << ", "; + BinaryOpNode *eq_node = equations[eq]; + expr_t lhs = eq_node->get_arg1(); + expr_t rhs = eq_node->get_arg2(); + if (residuals) { - BinaryOpNode *eq_node = equations[eq]; - expr_t lhs = eq_node->get_arg1(); - expr_t rhs = eq_node->get_arg2(); - output << "{\"residual\": {" << "\"lhs\": \""; lhs->writeJsonOutput(output, temporary_terms, tef_terms); @@ -1970,8 +1970,10 @@ ModelTree::writeJsonModelEquations(ostream &output, bool residuals) const } else { - output << "{\"equation\": \""; - equations[eq]->writeJsonOutput(output, tt_empty, tef_terms); + output << "{\"lhs\": \""; + lhs->writeJsonOutput(output, tt_empty, tef_terms); + output << "\", \"rhs\": \""; + rhs->writeJsonOutput(output, tt_empty, tef_terms); output << "\"" << ", \"line\": " << equations_lineno[eq]; From 2670ca8db0628443d3b15059cc57bb50d570afc6 Mon Sep 17 00:00:00 2001 From: Johannes Pfeifer Date: Tue, 23 May 2017 13:20:47 +0200 Subject: [PATCH 15/18] Get rid of unused and superseded options_.colormap and make sure options_.plot_shock_decomp.colormap is set --- DynareBison.yy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DynareBison.yy b/DynareBison.yy index 4f9e0371..c82b7025 100644 --- a/DynareBison.yy +++ b/DynareBison.yy @@ -3381,7 +3381,7 @@ o_use_shock_groups : USE_SHOCK_GROUPS { driver.option_str("use_shock_groups","de o_psd_use_shock_groups : USE_SHOCK_GROUPS { driver.option_str("plot_shock_decomp.use_shock_groups","default"); } | USE_SHOCK_GROUPS EQUAL symbol { driver.option_str("plot_shock_decomp.use_shock_groups", $3); } ; -o_colormap : COLORMAP EQUAL symbol { driver.option_num("colormap",$3); }; +o_colormap : COLORMAP EQUAL symbol { driver.option_num("plot_shock_decomp.colormap",$3); }; o_psd_colormap : COLORMAP EQUAL symbol { driver.option_num("plot_shock_decomp.colormap",$3); }; range : symbol ':' symbol From 51feda7d02dbb84a3914f64a67d25ddf71f3f1cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Adjemian=20=28Charybdis=29?= Date: Wed, 14 Jun 2017 07:01:31 +0200 Subject: [PATCH 16/18] Fixed code indentation. --- CodeInterpreter.hh | 27 +- ComputingTasks.cc | 392 ++++++++++++------------ ComputingTasks.hh | 25 +- ConfigFile.cc | 79 +++-- ConfigFile.hh | 14 +- DataTree.hh | 3 +- DynamicModel.cc | 417 +++++++++++++------------ DynamicModel.hh | 15 +- DynareMain.cc | 90 +++--- DynareMain2.cc | 4 +- ExprNode.cc | 53 ++-- ExprNode.hh | 573 ++++++++++++++++++----------------- ExtendedPreprocessorTypes.hh | 6 +- MinimumFeedbackSet.cc | 2 +- ModFile.cc | 224 +++++++------- ModFile.hh | 8 +- ModelTree.cc | 79 ++--- ModelTree.hh | 15 +- ParsingDriver.cc | 121 ++++---- ParsingDriver.hh | 24 +- Shocks.cc | 37 ++- Shocks.hh | 2 +- Statement.cc | 52 ++-- Statement.hh | 5 +- StaticModel.cc | 46 ++- StaticModel.hh | 6 +- SteadyStateModel.cc | 12 +- SymbolList.hh | 12 +- SymbolTable.cc | 121 ++++---- SymbolTable.hh | 48 ++- WarningConsolidation.cc | 13 +- WarningConsolidation.hh | 26 +- macro/MacroDriver.cc | 6 +- macro/MacroDriver.hh | 5 +- macro/MacroValue.hh | 18 +- 35 files changed, 1325 insertions(+), 1255 deletions(-) diff --git a/CodeInterpreter.hh b/CodeInterpreter.hh index ad41b0ed..6d470720 100644 --- a/CodeInterpreter.hh +++ b/CodeInterpreter.hh @@ -228,15 +228,15 @@ enum TrinaryOpcode }; enum external_function_type -{ - ExternalFunctionWithoutDerivative, - ExternalFunctionWithFirstDerivative, - ExternalFunctionWithFirstandSecondDerivative, - ExternalFunctionNumericalFirstDerivative, - ExternalFunctionFirstDerivative, - ExternalFunctionNumericalSecondDerivative, - ExternalFunctionSecondDerivative -}; + { + ExternalFunctionWithoutDerivative, + ExternalFunctionWithFirstDerivative, + ExternalFunctionWithFirstandSecondDerivative, + ExternalFunctionNumericalFirstDerivative, + ExternalFunctionFirstDerivative, + ExternalFunctionNumericalSecondDerivative, + ExternalFunctionSecondDerivative + }; enum PriorDistributions { @@ -1451,9 +1451,9 @@ public: exogenous = vector(exogenous_arg); other_endogenous = vector(other_endogenous_arg); is_linear = is_linear_arg; endo_nbr = endo_nbr_arg; Max_Lag = Max_Lag_arg; Max_Lead = Max_Lead_arg; u_count_int = u_count_int_arg; - nb_col_jacob = nb_col_jacob_arg; - det_exo_size = det_exo_size_arg; nb_col_det_exo_jacob = nb_col_det_exo_jacob_arg; - exo_size = exo_size_arg; nb_col_exo_jacob = nb_col_exo_jacob_arg; + nb_col_jacob = nb_col_jacob_arg; + det_exo_size = det_exo_size_arg; nb_col_det_exo_jacob = nb_col_det_exo_jacob_arg; + exo_size = exo_size_arg; nb_col_exo_jacob = nb_col_exo_jacob_arg; other_endo_size = other_endo_size_arg; nb_col_other_endo_jacob = nb_col_other_endo_jacob_arg; }; inline @@ -1467,7 +1467,7 @@ public: is_linear = is_linear_arg; endo_nbr = endo_nbr_arg; Max_Lag = Max_Lag_arg; Max_Lead = Max_Lead_arg; u_count_int = u_count_int_arg; nb_col_jacob = nb_col_jacob_arg; det_exo_size = 0; exo_size = 0; other_endo_size = 0; - nb_col_det_exo_jacob = 0;nb_col_exo_jacob = 0;nb_col_other_endo_jacob = 0; + nb_col_det_exo_jacob = 0; nb_col_exo_jacob = 0; nb_col_other_endo_jacob = 0; } inline unsigned int get_size() @@ -2025,4 +2025,3 @@ public: #endif #pragma pack(pop) #endif - diff --git a/ComputingTasks.cc b/ComputingTasks.cc index 7eccf256..d3f2d1c1 100644 --- a/ComputingTasks.cc +++ b/ComputingTasks.cc @@ -222,11 +222,11 @@ PriorPosteriorFunctionStatement::checkPass(ModFileStructure &mod_file_struct, Wa { OptionsList::string_options_t::const_iterator it2 = options_list.string_options.find("function"); if (it2 == options_list.string_options.end() || it2->second.empty()) - { - cerr << "ERROR: both the prior_function and posterior_function commands require the 'function' argument" - << endl; - exit(EXIT_FAILURE); - } + { + cerr << "ERROR: both the prior_function and posterior_function commands require the 'function' argument" + << endl; + exit(EXIT_FAILURE); + } } void @@ -235,7 +235,7 @@ PriorPosteriorFunctionStatement::writeOutput(ostream &output, const string &base options_list.writeOutput(output); string type = "posterior"; if (prior_func) - type = "prior"; + type = "prior"; output << "oo_ = execute_prior_posterior_function(" << "'" << options_list.string_options.find("function")->second << "', " @@ -248,7 +248,7 @@ PriorPosteriorFunctionStatement::writeJsonOutput(ostream &output) const { string type = "posterior"; if (prior_func) - type = "prior"; + type = "prior"; output << "{\"statementName\": \"prior_posterior_function\", \"type\": \"" << type << "\""; if (options_list.getNumberOfOptions()) { @@ -289,14 +289,14 @@ StochSimulStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli it = options_list.num_options.find("hp_filter"); OptionsList::num_options_t::const_iterator it1 = options_list.num_options.find("bandpass.indicator"); OptionsList::num_options_t::const_iterator it2 = options_list.num_options.find("one_sided_hp_filter"); - if ((it != options_list.num_options.end() && it1 != options_list.num_options.end()) || - (it != options_list.num_options.end() && it2 != options_list.num_options.end()) || - (it1 != options_list.num_options.end() && it2 != options_list.num_options.end())) - { - cerr << "ERROR: stoch_simul: can only use one of hp, one-sided hp, and bandpass filters" - << endl; - exit(EXIT_FAILURE); - } + if ((it != options_list.num_options.end() && it1 != options_list.num_options.end()) + || (it != options_list.num_options.end() && it2 != options_list.num_options.end()) + || (it1 != options_list.num_options.end() && it2 != options_list.num_options.end())) + { + cerr << "ERROR: stoch_simul: can only use one of hp, one-sided hp, and bandpass filters" + << endl; + exit(EXIT_FAILURE); + } } void @@ -364,7 +364,7 @@ ForecastStatement::writeJsonOutput(ostream &output) const } RamseyModelStatement::RamseyModelStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg) : + const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), options_list(options_list_arg) { @@ -441,7 +441,7 @@ RamseyConstraintsStatement::RamseyConstraintsStatement(const SymbolTable &symbol void RamseyConstraintsStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) { - if ((mod_file_struct.ramsey_model_present != true) || ( mod_file_struct.ramsey_policy_present != true)) + if ((mod_file_struct.ramsey_model_present != true) || (mod_file_struct.ramsey_policy_present != true)) cerr << "ramsey_constraints: can only be used with ramsey_model or ramsey_policy" << endl; } @@ -452,26 +452,26 @@ RamseyConstraintsStatement::writeOutput(ostream &output, const string &basename, for (RamseyConstraintsStatement::constraints_t::const_iterator it = constraints.begin(); it != constraints.end(); ++it) { if (it != constraints.begin()) - output << ", "; + output << ", "; output << "{" << it->endo + 1 << ", '"; - switch(it->code) - { - case oLess: - output << '<'; - break; - case oGreater: - output << '>'; - break; - case oLessEqual: - output << "<="; - break; - case oGreaterEqual: - output << ">="; - break; - default: - cerr << "Ramsey constraints: this shouldn't happen." << endl; - exit(EXIT_FAILURE); - } + switch (it->code) + { + case oLess: + output << '<'; + break; + case oGreater: + output << '>'; + break; + case oLessEqual: + output << "<="; + break; + case oGreaterEqual: + output << ">="; + break; + default: + cerr << "Ramsey constraints: this shouldn't happen." << endl; + exit(EXIT_FAILURE); + } output << "', '"; it->expression->writeOutput(output); output << "'}" << endl; @@ -488,26 +488,26 @@ RamseyConstraintsStatement::writeJsonOutput(ostream &output) const for (RamseyConstraintsStatement::constraints_t::const_iterator it = constraints.begin(); it != constraints.end(); ++it) { if (it != constraints.begin()) - output << ", "; + output << ", "; output << "{\"constraint\": \"" << symbol_table.getName(it->endo) << " "; - switch(it->code) - { - case oLess: - output << '<'; - break; - case oGreater: - output << '>'; - break; - case oLessEqual: - output << "<="; - break; - case oGreaterEqual: - output << ">="; - break; - default: - cerr << "Ramsey constraints: this shouldn't happen." << endl; - exit(1); - } + switch (it->code) + { + case oLess: + output << '<'; + break; + case oGreater: + output << '>'; + break; + case oLessEqual: + output << "<="; + break; + case oGreaterEqual: + output << ">="; + break; + default: + cerr << "Ramsey constraints: this shouldn't happen." << endl; + exit(1); + } output << " "; it->expression->writeJsonOutput(output, temporary_terms_t(), tef_terms); output << "\"}" << endl; @@ -587,7 +587,7 @@ RamseyPolicyStatement::checkPass(ModFileStructure &mod_file_struct, WarningConso { // ramsey_model_present indicates that the model is augmented with the FOC of the planner problem mod_file_struct.ramsey_model_present = true; - // ramsey_policy_present indicates that ramsey_policy instruction for computation of first order approximation + // ramsey_policy_present indicates that ramsey_policy instruction for computation of first order approximation // of a stochastic Ramsey problem if present in the *.mod file mod_file_struct.ramsey_policy_present = true; @@ -682,7 +682,7 @@ RamseyPolicyStatement::writeJsonOutput(ostream &output) const } DiscretionaryPolicyStatement::DiscretionaryPolicyStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg) : + const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), options_list(options_list_arg) { @@ -775,16 +775,16 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli if (it != options_list.num_options.end()) { int order = atoi(it->second.c_str()); - + if (order > 2) { cerr << "ERROR: order > 2 is not supported in estimation" << endl; exit(EXIT_FAILURE); } - + mod_file_struct.order_option = max(mod_file_struct.order_option, order); } - + // Fill in mod_file_struct.partial_information it = options_list.num_options.find("partial_information"); if (it != options_list.num_options.end() && it->second == "1") @@ -797,8 +797,8 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli it = options_list.num_options.find("dsge_var"); if (it != options_list.num_options.end()) - // Fill in mod_file_struct.dsge_var_calibrated - mod_file_struct.dsge_var_calibrated = it->second; + // Fill in mod_file_struct.dsge_var_calibrated + mod_file_struct.dsge_var_calibrated = it->second; // Fill in mod_file_struct.dsge_var_estimated OptionsList::string_options_t::const_iterator it_str = options_list.string_options.find("dsge_var"); @@ -827,15 +827,15 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli exit(EXIT_FAILURE); } - if (options_list.string_options.find("datafile") == options_list.string_options.end() && - !mod_file_struct.estimation_data_statement_present) + if (options_list.string_options.find("datafile") == options_list.string_options.end() + && !mod_file_struct.estimation_data_statement_present) { cerr << "ERROR: The estimation statement requires a data file to be supplied via the datafile option." << endl; exit(EXIT_FAILURE); } - if (options_list.string_options.find("mode_file") != options_list.string_options.end() && - mod_file_struct.estim_params_use_calib) + if (options_list.string_options.find("mode_file") != options_list.string_options.end() + && mod_file_struct.estim_params_use_calib) { cerr << "ERROR: The mode_file option of the estimation statement is incompatible with the use_calibration option of the estimated_params_init block." << endl; exit(EXIT_FAILURE); @@ -912,7 +912,7 @@ DynareSensitivityStatement::writeOutput(ostream &output, const string &basename, OptionsList::string_options_t::const_iterator it2 = options_list.string_options.find("graph_format"); if (it2 != options_list.string_options.end()) output << "options_.graph_format = '" << it2->second << "';" << endl; - + output << "dynare_sensitivity(options_gsa);" << endl; } @@ -960,7 +960,7 @@ void UnitRootVarsStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const { output << "options_.diffuse_filter = 1;" << endl - << "options_.steadystate.nocheck = 1;" << endl; + << "options_.steadystate.nocheck = 1;" << endl; } void @@ -1976,8 +1976,8 @@ MSSBVAREstimationStatement::checkPass(ModFileStructure &mod_file_struct, Warning mod_file_struct.bvar_present = true; if (options_list.num_options.find("ms.create_init") == options_list.num_options.end()) - if (options_list.string_options.find("datafile") == options_list.string_options.end() || - options_list.num_options.find("ms.initial_year") == options_list.num_options.end()) + if (options_list.string_options.find("datafile") == options_list.string_options.end() + || options_list.num_options.find("ms.initial_year") == options_list.num_options.end()) { cerr << "ERROR: If you do not pass no_create_init to ms_estimation, " << "you must pass the datafile and initial_year options." << endl; @@ -2117,7 +2117,7 @@ MSSBVARComputeProbabilitiesStatement::writeJsonOutput(ostream &output) const } MSSBVARIrfStatement::MSSBVARIrfStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg) : + const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), options_list(options_list_arg) { @@ -2144,14 +2144,14 @@ MSSBVARIrfStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli if (it != options_list.num_options.end()) filtered_probabilities_present = true; - if ((filtered_probabilities_present && regime_present) || - (filtered_probabilities_present && regimes_present) || - (regimes_present && regime_present)) - { - cerr << "ERROR: You may only pass one of regime, regimes and " - << "filtered_probabilities to ms_irf" << endl; - exit(EXIT_FAILURE); - } + if ((filtered_probabilities_present && regime_present) + || (filtered_probabilities_present && regimes_present) + || (regimes_present && regime_present)) + { + cerr << "ERROR: You may only pass one of regime, regimes and " + << "filtered_probabilities to ms_irf" << endl; + exit(EXIT_FAILURE); + } } void @@ -2244,14 +2244,14 @@ MSSBVARVarianceDecompositionStatement::checkPass(ModFileStructure &mod_file_stru if (it != options_list.num_options.end()) filtered_probabilities_present = true; - if ((filtered_probabilities_present && regime_present) || - (filtered_probabilities_present && regimes_present) || - (regimes_present && regime_present)) - { - cerr << "ERROR: You may only pass one of regime, regimes and " - << "filtered_probabilities to ms_variance_decomposition" << endl; - exit(EXIT_FAILURE); - } + if ((filtered_probabilities_present && regime_present) + || (filtered_probabilities_present && regimes_present) + || (regimes_present && regime_present)) + { + cerr << "ERROR: You may only pass one of regime, regimes and " + << "filtered_probabilities to ms_variance_decomposition" << endl; + exit(EXIT_FAILURE); + } } void @@ -2551,19 +2551,19 @@ SvarIdentificationStatement::writeOutput(ostream &output, const string &basename for (svar_identification_restrictions_t::const_iterator it = restrictions.begin(); it != restrictions.end(); it++) { assert(it->lag >= 0); - if (it->lag == 0) + if (it->lag == 0) output << "options_.ms.Qi{" << it->equation << "}(" << it->restriction_nbr << ", " << it->variable + 1 << ") = "; - else - { - int col = (it->lag-1)*n+it->variable+1; - if (col > k) + else + { + int col = (it->lag-1)*n+it->variable+1; + if (col > k) { cerr << "ERROR: lag =" << it->lag << ", num endog vars = " << n << "current endog var index = " << it->variable << ". Index " << "out of bounds. If the above does not represent a logical error, please report this to the Dyanre Team." << endl; exit(EXIT_FAILURE); } - output << "options_.ms.Ri{" << it->equation << "}(" << it->restriction_nbr << ", " << col << ") = "; - } + output << "options_.ms.Ri{" << it->equation << "}(" << it->restriction_nbr << ", " << col << ") = "; + } it->value->writeOutput(output); output << ";" << endl; } @@ -2614,21 +2614,21 @@ MarkovSwitchingStatement::MarkovSwitchingStatement(const OptionsList &options_li if (it_num != options_list.num_options.end()) { using namespace boost; - OptionsList::num_options_t::const_iterator it_num_regimes = - options_list.num_options.find("ms.number_of_regimes"); + OptionsList::num_options_t::const_iterator it_num_regimes + = options_list.num_options.find("ms.number_of_regimes"); assert(it_num_regimes != options_list.num_options.end()); int num_regimes = lexical_cast< int >(it_num_regimes->second); vector tokenizedRestrictions; split(tokenizedRestrictions, it_num->second, is_any_of("["), token_compress_on); for (vector::iterator it = tokenizedRestrictions.begin(); - it != tokenizedRestrictions.end(); it++ ) + it != tokenizedRestrictions.end(); it++) if (it->size() > 0) { vector restriction; split(restriction, *it, is_any_of("], ")); for (vector::iterator it1 = restriction.begin(); - it1 != restriction.end(); ) + it1 != restriction.end();) if (it1->empty()) restriction.erase(it1); else @@ -2697,16 +2697,16 @@ MarkovSwitchingStatement::checkPass(ModFileStructure &mod_file_struct, WarningCo if (it_num != options_list.num_options.end()) { using namespace boost; - OptionsList::num_options_t::const_iterator it_num_regimes = - options_list.num_options.find("ms.number_of_regimes"); + OptionsList::num_options_t::const_iterator it_num_regimes + = options_list.num_options.find("ms.number_of_regimes"); assert(it_num_regimes != options_list.num_options.end()); int num_regimes = lexical_cast< int >(it_num_regimes->second); - vector col_trans_prob_sum (num_regimes, 0); - vector row_trans_prob_sum (num_regimes, 0); - vector all_restrictions_in_row (num_regimes, true); - vector all_restrictions_in_col (num_regimes, true); - for (int row=0; row col_trans_prob_sum(num_regimes, 0); + vector row_trans_prob_sum(num_regimes, 0); + vector all_restrictions_in_row(num_regimes, true); + vector all_restrictions_in_col(num_regimes, true); + for (int row = 0; row < num_regimes; row++) + for (int col = 0; col < num_regimes; col++) if (restriction_map.find(make_pair(row+1, col+1)) != restriction_map.end()) { row_trans_prob_sum[row] += restriction_map[make_pair(row+1, col+1)]; @@ -2718,41 +2718,41 @@ MarkovSwitchingStatement::checkPass(ModFileStructure &mod_file_struct, WarningCo all_restrictions_in_col[col] = false; } - for (int i=0; i= 1.0) { - cerr << "ERROR: When all transitions probabilities are specified for a certain " - << "regime, they must sum to 1" << endl; + cerr << "ERROR: When transition probabilites are not specified for every regime, " + << "their sum must be < 1" << endl; exit(EXIT_FAILURE); } - } - else - if (row_trans_prob_sum[i] >= 1.0) - { - cerr << "ERROR: When transition probabilites are not specified for every regime, " - << "their sum must be < 1" << endl; - exit(EXIT_FAILURE); - } - if (all_restrictions_in_col[i]) - { - if (col_trans_prob_sum[i] != 1.0) + if (all_restrictions_in_col[i]) + { + if (col_trans_prob_sum[i] != 1.0) + { + cerr << "ERROR: When all transitions probabilities are specified for a certain " + << "regime, they must sum to 1" << endl; + exit(EXIT_FAILURE); + } + } + else + if (col_trans_prob_sum[i] >= 1.0) { - cerr << "ERROR: When all transitions probabilities are specified for a certain " - << "regime, they must sum to 1" << endl; + cerr << "ERROR: When transition probabilites are not specified for every regime, " + << "their sum must be < 1" << endl; exit(EXIT_FAILURE); } - } - else - if (col_trans_prob_sum[i] >= 1.0) - { - cerr << "ERROR: When transition probabilites are not specified for every regime, " - << "their sum must be < 1" << endl; - exit(EXIT_FAILURE); - } } } @@ -2789,7 +2789,7 @@ MarkovSwitchingStatement::writeOutput(ostream &output, const string &basename, b } int restrictions_index = 0; - for (itR=restriction_map.begin(); itR != restriction_map.end(); itR++) + for (itR = restriction_map.begin(); itR != restriction_map.end(); itR++) output << "options_.ms.ms_chain(" << itChain->second << ").restrictions(" << ++restrictions_index << ") = {[" << itR->first.first << ", " << itR->first.second << ", " << itR->second << "]};" << endl; @@ -2800,8 +2800,8 @@ MarkovSwitchingStatement::writeCOutput(ostream &output, const string &basename) { output << endl; - OptionsList::num_options_t::const_iterator it = - options_list.num_options.find("ms.chain"); + OptionsList::num_options_t::const_iterator it + = options_list.num_options.find("ms.chain"); assert(it != options_list.num_options.end()); output << "chain = " << it->second << ";" << endl; @@ -2823,17 +2823,17 @@ MarkovSwitchingStatement::writeCOutput(ostream &output, const string &basename) vector tokenizedDomain; split(tokenizedDomain, it->second, is_any_of("[ ]"), token_compress_on); for (vector::iterator itvs = tokenizedDomain.begin(); - itvs != tokenizedDomain.end(); itvs++ ) + itvs != tokenizedDomain.end(); itvs++) if (!itvs->empty()) output << "duration.push_back(" << *itvs << ");" << endl; - OptionsList::symbol_list_options_t::const_iterator itsl = - options_list.symbol_list_options.find("ms.parameters"); + OptionsList::symbol_list_options_t::const_iterator itsl + = options_list.symbol_list_options.find("ms.parameters"); assert(itsl != options_list.symbol_list_options.end()); vector parameters = itsl->second.get_symbols(); output << "parameters.clear();" << endl; for (vector::iterator itp = parameters.begin(); - itp != parameters.end(); itp++ ) + itp != parameters.end(); itp++) output << "parameters.push_back(param_names[\"" << *itp << "\"]);" << endl; output << "restriction_map.clear();" << endl; @@ -2887,13 +2887,13 @@ SvarStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation it2 = options_list.string_options.find("ms.constants"); assert((it0 != options_list.string_options.end() && it1 == options_list.string_options.end() - && it2 == options_list.string_options.end()) || - (it0 == options_list.string_options.end() - && it1 != options_list.string_options.end() - && it2 == options_list.string_options.end()) || - (it0 == options_list.string_options.end() - && it1 == options_list.string_options.end() - && it2 != options_list.string_options.end())); + && it2 == options_list.string_options.end()) + || (it0 == options_list.string_options.end() + && it1 != options_list.string_options.end() + && it2 == options_list.string_options.end()) + || (it0 == options_list.string_options.end() + && it1 == options_list.string_options.end() + && it2 != options_list.string_options.end())); } void @@ -3006,15 +3006,15 @@ EstimationDataStatement::checkPass(ModFileStructure &mod_file_struct, WarningCon exit(EXIT_FAILURE); } - if ((options_list.string_options.find("file") == options_list.string_options.end()) && - (options_list.string_options.find("series") == options_list.string_options.end())) + if ((options_list.string_options.find("file") == options_list.string_options.end()) + && (options_list.string_options.find("series") == options_list.string_options.end())) { cerr << "ERROR: The file or series option must be passed to the data statement." << endl; exit(EXIT_FAILURE); } - if ((options_list.string_options.find("file") != options_list.string_options.end()) && - (options_list.string_options.find("series") != options_list.string_options.end())) + if ((options_list.string_options.find("file") != options_list.string_options.end()) + && (options_list.string_options.find("series") != options_list.string_options.end())) { cerr << "ERROR: The file and series options cannot be used simultaneously in the data statement." << endl; exit(EXIT_FAILURE); @@ -3235,8 +3235,8 @@ JointPriorStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli exit(EXIT_FAILURE); } - if (options_list.num_options.find("mean") == options_list.num_options.end() && - options_list.num_options.find("mode") == options_list.num_options.end()) + if (options_list.num_options.find("mean") == options_list.num_options.end() + && options_list.num_options.find("mode") == options_list.num_options.end()) { cerr << "ERROR: You must pass at least one of mean and mode to the prior statement." << endl; exit(EXIT_FAILURE); @@ -3259,13 +3259,13 @@ JointPriorStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli void JointPriorStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const { - for (vector::const_iterator it = joint_parameters.begin() ; it != joint_parameters.end(); it++) + for (vector::const_iterator it = joint_parameters.begin(); it != joint_parameters.end(); it++) output << "eifind = get_new_or_existing_ei_index('joint_parameter_prior_index', '" << *it << "', '');" << endl << "estimation_info.joint_parameter_prior_index(eifind) = {'" << *it << "'};" << endl; output << "key = {["; - for (vector::const_iterator it = joint_parameters.begin() ; it != joint_parameters.end(); it++) + for (vector::const_iterator it = joint_parameters.begin(); it != joint_parameters.end(); it++) output << "get_new_or_existing_ei_index('joint_parameter_prior_index', '" << *it << "', '') ..." << endl << " "; output << "]};" << endl; @@ -3306,13 +3306,13 @@ JointPriorStatement::writeOutputHelper(ostream &output, const string &field, con { OptionsList::num_options_t::const_iterator itn = options_list.num_options.find(field); output << lhs_field << "." << field << " = {"; - if (field=="variance") + if (field == "variance") output << "{"; if (itn != options_list.num_options.end()) output << itn->second; else output << "{}"; - if (field=="variance") + if (field == "variance") output << "}"; output << "};" << endl; } @@ -3322,7 +3322,7 @@ JointPriorStatement::writeJsonOutput(ostream &output) const { output << "{\"statementName\": \"joint_prior\"" << ", \"key\": ["; - for (vector::const_iterator it = joint_parameters.begin() ; it != joint_parameters.end(); it++) + for (vector::const_iterator it = joint_parameters.begin(); it != joint_parameters.end(); it++) { if (it != joint_parameters.begin()) output << ", "; @@ -3337,31 +3337,31 @@ JointPriorStatement::writeJsonOutput(ostream &output) const } output << ", \"shape\": "; - switch(prior_shape) + switch (prior_shape) { case eBeta: - output << "\"beta\""; + output << "\"beta\""; break; case eGamma: - output << "\"gamma\""; + output << "\"gamma\""; break; case eNormal: - output << "\"normal\""; + output << "\"normal\""; break; case eInvGamma: - output << "\"inv_gamma\""; + output << "\"inv_gamma\""; break; case eUniform: - output << "\"uniform\""; + output << "\"uniform\""; break; case eInvGamma2: - output << "\"inv_gamma2\""; + output << "\"inv_gamma2\""; break; case eDirichlet: - output << "\"dirichlet\""; + output << "\"dirichlet\""; break; case eWeibull: - output << "\"weibull\""; + output << "\"weibull\""; break; case eNoShape: cerr << "Impossible case." << endl; @@ -3396,16 +3396,16 @@ BasicPriorStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli exit(EXIT_FAILURE); } - if (options_list.num_options.find("mean") == options_list.num_options.end() && - options_list.num_options.find("mode") == options_list.num_options.end()) + if (options_list.num_options.find("mean") == options_list.num_options.end() + && options_list.num_options.find("mode") == options_list.num_options.end()) { cerr << "ERROR: You must pass at least one of mean and mode to the prior statement." << endl; exit(EXIT_FAILURE); } OptionsList::num_options_t::const_iterator it_stdev = options_list.num_options.find("stdev"); - if ((it_stdev == options_list.num_options.end() && variance == NULL) || - (it_stdev != options_list.num_options.end() && variance != NULL)) + if ((it_stdev == options_list.num_options.end() && variance == NULL) + || (it_stdev != options_list.num_options.end() && variance != NULL)) { cerr << "ERROR: You must pass exactly one of stdev and variance to the prior statement." << endl; exit(EXIT_FAILURE); @@ -3533,7 +3533,7 @@ BasicPriorStatement::writeCDomain(ostream &output) const vector tokenizedDomain; split(tokenizedDomain, it_num->second, is_any_of("[ ]"), token_compress_on); for (vector::iterator it = tokenizedDomain.begin(); - it != tokenizedDomain.end(); it++ ) + it != tokenizedDomain.end(); it++) if (!it->empty()) output << "domain.push_back(" << *it << ");" << endl; } @@ -3556,28 +3556,28 @@ BasicPriorStatement::writeCShape(ostream &output) const switch (prior_shape) { case eBeta: - output << "\"beta\";" << endl; + output << "\"beta\";" << endl; break; case eGamma: - output << "\"gamma\";" << endl; + output << "\"gamma\";" << endl; break; case eNormal: - output << "\"normal\";" << endl; + output << "\"normal\";" << endl; break; case eInvGamma: - output << "\"inv_gamma\";" << endl; + output << "\"inv_gamma\";" << endl; break; case eUniform: - output << "\"uniform\";" << endl; + output << "\"uniform\";" << endl; break; case eInvGamma2: - output << "\"inv_gamma2\";" << endl; + output << "\"inv_gamma2\";" << endl; break; case eDirichlet: - output << "\"dirichlet\";" << endl; + output << "\"dirichlet\";" << endl; break; case eWeibull: - output << "\"weibull\";" << endl; + output << "\"weibull\";" << endl; break; case eNoShape: assert(prior_shape != eNoShape); @@ -3591,28 +3591,28 @@ BasicPriorStatement::writeJsonShape(ostream &output) const switch (prior_shape) { case eBeta: - output << "\"beta\""; + output << "\"beta\""; break; case eGamma: - output << "\"gamma\""; + output << "\"gamma\""; break; case eNormal: - output << "\"normal\""; + output << "\"normal\""; break; case eInvGamma: - output << "\"inv_gamma\""; + output << "\"inv_gamma\""; break; case eUniform: - output << "\"uniform\""; + output << "\"uniform\""; break; case eInvGamma2: - output << "\"inv_gamma2\""; + output << "\"inv_gamma2\""; break; case eDirichlet: - output << "\"dirichlet\""; + output << "\"dirichlet\""; break; case eWeibull: - output << "\"weibull\""; + output << "\"weibull\""; break; case eNoShape: assert(prior_shape != eNoShape); @@ -3667,7 +3667,7 @@ StdPriorStatement::StdPriorStatement(const string &name_arg, const PriorDistributions &prior_shape_arg, const expr_t &variance_arg, const OptionsList &options_list_arg, - const SymbolTable &symbol_table_arg ) : + const SymbolTable &symbol_table_arg) : BasicPriorStatement(name_arg, subsample_name_arg, prior_shape_arg, variance_arg, options_list_arg), symbol_table(symbol_table_arg) { @@ -3724,7 +3724,7 @@ CorrPriorStatement::CorrPriorStatement(const string &name_arg1, const string &na const PriorDistributions &prior_shape_arg, const expr_t &variance_arg, const OptionsList &options_list_arg, - const SymbolTable &symbol_table_arg ) : + const SymbolTable &symbol_table_arg) : BasicPriorStatement(name_arg1, subsample_name_arg, prior_shape_arg, variance_arg, options_list_arg), name1(name_arg2), symbol_table(symbol_table_arg) @@ -3824,8 +3824,8 @@ PriorEqualStatement::PriorEqualStatement(const string &to_declaration_type_arg, void PriorEqualStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) { - if ((to_declaration_type != "par" && to_declaration_type != "std" && to_declaration_type != "corr") || - (from_declaration_type != "par" && from_declaration_type != "std" && from_declaration_type != "corr")) + if ((to_declaration_type != "par" && to_declaration_type != "std" && to_declaration_type != "corr") + || (from_declaration_type != "par" && from_declaration_type != "std" && from_declaration_type != "corr")) { cerr << "Internal Dynare Error" << endl; exit(EXIT_FAILURE); @@ -3856,7 +3856,6 @@ PriorEqualStatement::writeOutput(ostream &output, const string &basename, bool m else get_base_name(symbol_table.getType(from_name1), rhs_field); - if (to_declaration_type == "corr") lhs_field += "_corr"; @@ -4045,7 +4044,7 @@ OptionsStatement::writeCOutput(ostream &output, const string &basename) StdOptionsStatement::StdOptionsStatement(const string &name_arg, const string &subsample_name_arg, const OptionsList &options_list_arg, - const SymbolTable &symbol_table_arg ) : + const SymbolTable &symbol_table_arg) : BasicOptionsStatement(name_arg, subsample_name_arg, options_list_arg), symbol_table(symbol_table_arg) { @@ -4095,7 +4094,7 @@ StdOptionsStatement::writeCOutput(ostream &output, const string &basename) CorrOptionsStatement::CorrOptionsStatement(const string &name_arg1, const string &name_arg2, const string &subsample_name_arg, const OptionsList &options_list_arg, - const SymbolTable &symbol_table_arg ) : + const SymbolTable &symbol_table_arg) : BasicOptionsStatement(name_arg1, subsample_name_arg, options_list_arg), name1(name_arg2), symbol_table(symbol_table_arg) @@ -4189,8 +4188,8 @@ OptionsEqualStatement::OptionsEqualStatement(const string &to_declaration_type_a void OptionsEqualStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) { - if ((to_declaration_type != "par" && to_declaration_type != "std" && to_declaration_type != "corr") || - (from_declaration_type != "par" && from_declaration_type != "std" && from_declaration_type != "corr")) + if ((to_declaration_type != "par" && to_declaration_type != "std" && to_declaration_type != "corr") + || (from_declaration_type != "par" && from_declaration_type != "std" && from_declaration_type != "corr")) { cerr << "Internal Dynare Error" << endl; exit(EXIT_FAILURE); @@ -4236,7 +4235,6 @@ OptionsEqualStatement::writeOutput(ostream &output, const string &basename, bool else get_base_name(symbol_table.getType(from_name1), rhs_field); - if (to_declaration_type == "corr") lhs_field += "_corr"; diff --git a/ComputingTasks.hh b/ComputingTasks.hh index 6cec3e38..43b374c2 100644 --- a/ComputingTasks.hh +++ b/ComputingTasks.hh @@ -137,7 +137,7 @@ private: const OptionsList options_list; public: RamseyModelStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg); + const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeJsonOutput(ostream &output) const; @@ -146,11 +146,12 @@ public: class RamseyConstraintsStatement : public Statement { public: - struct Constraint { + struct Constraint + { int endo; BinaryOpcode code; expr_t expression; - }; + }; typedef vector constraints_t; private: const SymbolTable &symbol_table; @@ -186,7 +187,7 @@ private: const OptionsList options_list; public: DiscretionaryPolicyStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg); + const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeJsonOutput(ostream &output) const; @@ -455,7 +456,8 @@ public: /*! \param model_tree_arg the model tree used to store the objective function. It is owned by the PlannerObjectiveStatement, and will be deleted by its destructor */ PlannerObjectiveStatement(StaticModel *model_tree_arg); - virtual ~PlannerObjectiveStatement(); + virtual + ~PlannerObjectiveStatement(); /*! \todo check there are only endogenous variables at the current period in the objective (no exogenous, no lead/lag) */ virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); @@ -553,7 +555,7 @@ private: const OptionsList options_list; public: MSSBVARIrfStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg); + const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeJsonOutput(ostream &output) const; @@ -691,7 +693,7 @@ public: int lag; int variable; expr_t value; - }; + }; typedef vector< svar_identification_restriction > svar_identification_restrictions_t; private: @@ -705,7 +707,7 @@ public: SvarIdentificationStatement(const svar_identification_restrictions_t &restrictions_arg, const bool &upper_cholesky_present_arg, const bool &lower_cholesky_present_arg, - const bool &constants_exclusion_present_arg, + const bool &constants_exclusion_present_arg, const SymbolTable &symbol_table_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; @@ -819,11 +821,11 @@ public: virtual void writeJsonOutput(ostream &output) const; }; - class BasicPriorStatement : public Statement { public: - virtual ~BasicPriorStatement(); + virtual + ~BasicPriorStatement(); protected: const string name; const string subsample_name; @@ -932,7 +934,8 @@ public: class BasicOptionsStatement : public Statement { public: - virtual ~BasicOptionsStatement(); + virtual + ~BasicOptionsStatement(); protected: const string name; const string subsample_name; diff --git a/ConfigFile.cc b/ConfigFile.cc index d1fbd8b7..36a1faa7 100644 --- a/ConfigFile.cc +++ b/ConfigFile.cc @@ -102,7 +102,7 @@ ConfigFile::getConfigFileInfo(const string &config_file) if (config_file.empty()) { - string defaultConfigFile (""); + string defaultConfigFile(""); // Test OS and try to open default file #if defined(_WIN32) || defined(__CYGWIN32__) if (getenv("APPDATA") == NULL) @@ -122,42 +122,41 @@ ConfigFile::getConfigFileInfo(const string &config_file) defaultConfigFile += "\\dynare.ini"; } #else - if (getenv("HOME") == NULL) - { - if (parallel || parallel_test) - cerr << "ERROR: "; - else - cerr << "WARNING: "; - cerr << "HOME environment variable not found." << endl; - if (parallel || parallel_test) - exit(EXIT_FAILURE); - } - else - { - defaultConfigFile += getenv("HOME"); - defaultConfigFile += "/.dynare"; - } -#endif - configFile = new ifstream(defaultConfigFile.c_str(), fstream::in); - if (!configFile->is_open()) + if (getenv("HOME") == NULL) + { if (parallel || parallel_test) - { - cerr << "ERROR: Could not open the default config file (" << defaultConfigFile << ")" << endl; - exit(EXIT_FAILURE); - } + cerr << "ERROR: "; else - return; - } - else - { - configFile = new ifstream(config_file.c_str(), fstream::in); - if (!configFile->is_open()) + cerr << "WARNING: "; + cerr << "HOME environment variable not found." << endl; + if (parallel || parallel_test) + exit(EXIT_FAILURE); + } + else + { + defaultConfigFile += getenv("HOME"); + defaultConfigFile += "/.dynare"; + } +#endif + configFile = new ifstream(defaultConfigFile.c_str(), fstream::in); + if (!configFile->is_open()) + if (parallel || parallel_test) { - cerr << "ERROR: Couldn't open file " << config_file << endl;; + cerr << "ERROR: Could not open the default config file (" << defaultConfigFile << ")" << endl; exit(EXIT_FAILURE); } - } - + else + return; + } + else + { + configFile = new ifstream(config_file.c_str(), fstream::in); + if (!configFile->is_open()) + { + cerr << "ERROR: Couldn't open file " << config_file << endl;; + exit(EXIT_FAILURE); + } + } string name, computerName, port, userName, password, remoteDrive, remoteDirectory, dynarePath, matlabOctavePath, operatingSystem, @@ -271,7 +270,7 @@ ConfigFile::getConfigFileInfo(const string &config_file) vector tokenizedPath; split(tokenizedPath, tokenizedLine.back(), is_any_of(":"), token_compress_on); for (vector::iterator it = tokenizedPath.begin(); - it != tokenizedPath.end(); it++ ) + it != tokenizedPath.end(); it++) if (!it->empty()) { trim(*it); @@ -375,7 +374,7 @@ ConfigFile::getConfigFileInfo(const string &config_file) for (tokenizer >::iterator it = tokens.begin(); it != tokens.end(); it++) { - string token (*it); + string token(*it); if (token.compare("(") == 0) { begin_weight = true; @@ -525,10 +524,10 @@ void ConfigFile::checkPass(WarningConsolidation &warnings) const { bool global_init_file_declared = false; - for (vector::const_iterator it = hooks.begin() ; it != hooks.end(); it++) + for (vector::const_iterator it = hooks.begin(); it != hooks.end(); it++) { const map hookmap = (*it)->get_hooks(); - for (map ::const_iterator mapit = hookmap.begin() ; mapit != hookmap.end(); mapit++) + for (map ::const_iterator mapit = hookmap.begin(); mapit != hookmap.end(); mapit++) if (mapit->first.compare("global_init_file") == 0) if (global_init_file_declared == true) { @@ -686,10 +685,10 @@ vector ConfigFile::getIncludePaths() const { vector include_paths; - for (vector::const_iterator it = paths.begin() ; it != paths.end(); it++) + for (vector::const_iterator it = paths.begin(); it != paths.end(); it++) { map > pathmap = (*it)->get_paths(); - for (map >::const_iterator mapit = pathmap.begin() ; mapit != pathmap.end(); mapit++) + for (map >::const_iterator mapit = pathmap.begin(); mapit != pathmap.end(); mapit++) for (vector::const_iterator vecit = mapit->second.begin(); vecit != mapit->second.end(); vecit++) include_paths.push_back(*vecit); } @@ -699,10 +698,10 @@ ConfigFile::getIncludePaths() const void ConfigFile::writeHooks(ostream &output) const { - for (vector::const_iterator it = hooks.begin() ; it != hooks.end(); it++) + for (vector::const_iterator it = hooks.begin(); it != hooks.end(); it++) { map hookmap = (*it)->get_hooks(); - for (map ::const_iterator mapit = hookmap.begin() ; mapit != hookmap.end(); mapit++) + for (map ::const_iterator mapit = hookmap.begin(); mapit != hookmap.end(); mapit++) output << "options_." << mapit->first << " = '" << mapit->second << "';" << endl; } } diff --git a/ConfigFile.hh b/ConfigFile.hh index 3c761753..e054922f 100644 --- a/ConfigFile.hh +++ b/ConfigFile.hh @@ -37,18 +37,26 @@ public: private: map hooks; public: - inline mapget_hooks() { return hooks; }; + inline map + get_hooks() + { + return hooks; + }; }; class Path { public: - Path(vector &includepath_arg); + Path(vector &includepath_arg); ~Path(); private: map > paths; public: - inline map >get_paths() { return paths; }; + inline map > + get_paths() + { + return paths; + }; }; class SlaveNode diff --git a/DataTree.hh b/DataTree.hh index 83e59471..d7a1de5d 100644 --- a/DataTree.hh +++ b/DataTree.hh @@ -104,7 +104,8 @@ private: public: DataTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg, ExternalFunctionsTable &external_functions_table_arg); - virtual ~DataTree(); + virtual + ~DataTree(); //! Some predefined constants expr_t Zero, One, Two, MinusOne, NaN, Infinity, MinusInfinity, Pi; diff --git a/DynamicModel.cc b/DynamicModel.cc index 29858216..00820fa1 100644 --- a/DynamicModel.cc +++ b/DynamicModel.cc @@ -881,7 +881,7 @@ DynamicModel::writeModelEquationsCode(string &file_name, const string &bin_basen count_col_det_exo++; } } - + FBEGINBLOCK_ fbeginblock(symbol_table.endo_nbr(), simulation_type, 0, @@ -1140,30 +1140,30 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++) { count_col_det_exo++; - if (find (exo_det.begin(), exo_det.end(), *it1) == exo_det.end()) + if (find(exo_det.begin(), exo_det.end(), *it1) == exo_det.end()) exo_det.push_back(*it1); } - + unsigned int count_col_exo = 0; vector exo; for (lag_var_t::const_iterator it = exo_block[block].begin(); it != exo_block[block].end(); it++) for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++) { count_col_exo++; - if (find (exo.begin(), exo.end(), *it1) == exo.end()) + if (find(exo.begin(), exo.end(), *it1) == exo.end()) exo.push_back(*it1); } - + vector other_endo; unsigned int count_col_other_endo = 0; for (lag_var_t::const_iterator it = other_endo_block[block].begin(); it != other_endo_block[block].end(); it++) for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++) { count_col_other_endo++; - if (find (other_endo.begin(), other_endo.end(), *it1) == other_endo.end()) - other_endo.push_back(*it1); + if (find(other_endo.begin(), other_endo.end(), *it1) == other_endo.end()) + other_endo.push_back(*it1); } - + FBEGINBLOCK_ fbeginblock(block_mfs, simulation_type, getBlockFirstEquation(block), @@ -1187,7 +1187,7 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin other_endo ); fbeginblock.write(code_file, instruction_number); - + // The equations for (i = 0; i < (int) block_size; i++) { @@ -1202,10 +1202,10 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin if (dynamic_cast(*it) != NULL) (*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt2, map_idx, true, false, tef_terms); - FNUMEXPR_ fnumexpr(TemporaryTerm, (int) (map_idx.find((*it)->idx)->second)); + FNUMEXPR_ fnumexpr(TemporaryTerm, (int)(map_idx.find((*it)->idx)->second)); fnumexpr.write(code_file, instruction_number); (*it)->compile(code_file, instruction_number, false, tt2, map_idx, true, false, tef_terms); - FSTPT_ fstpt((int) (map_idx.find((*it)->idx)->second)); + FSTPT_ fstpt((int)(map_idx.find((*it)->idx)->second)); fstpt.write(code_file, instruction_number); // Insert current node into tt2 tt2.insert(*it); @@ -1543,7 +1543,7 @@ DynamicModel::writeDynamicMFile(const string &dynamic_basename) const << "% Outputs:" << endl << "% residual [M_.endo_nbr by 1] double vector of residuals of the dynamic model equations in order of " << endl << "% declaration of the equations." << endl - << "% Dynare may prepend auxiliary equations, see M_.aux_vars" << endl + << "% Dynare may prepend auxiliary equations, see M_.aux_vars" << endl << "% g1 [M_.endo_nbr by #dynamic variables] double Jacobian matrix of the dynamic model equations;" << endl << "% rows: equations in order of declaration" << endl << "% columns: variables in order stored in M_.lead_lag_incidence followed by the ones in M_.exo_names" << endl @@ -1554,7 +1554,7 @@ DynamicModel::writeDynamicMFile(const string &dynamic_basename) const << "% rows: equations in order of declaration" << endl << "% columns: variables in order stored in M_.lead_lag_incidence followed by the ones in M_.exo_names" << endl << "%" << endl - << "%" << endl + << "%" << endl << "% Warning : this file is generated automatically by Dynare" << endl << "% from model file (.mod)" << endl << endl; @@ -1959,11 +1959,11 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri << " else" << endl << " mthd='UNKNOWN';" << endl << " end;" << endl - << " if options_.verbosity" << endl + << " if options_.verbosity" << endl << " printline(41)" << endl << " disp(sprintf('MODEL SIMULATION (method=%s):',mthd))" << endl - << " skipline()" << endl - << " end" << endl + << " skipline()" << endl + << " end" << endl << " periods=options_.periods;" << endl << " maxit_=options_.simul.maxit;" << endl << " solve_tolf=options_.solve_tolf;" << endl @@ -2000,7 +2000,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri mDynamicModelFile << " g1=[];g2=[];g3=[];\n"; mDynamicModelFile << " y=" << dynamic_basename << "_" << block + 1 << "(y, x, params, steady_state, 0, y_kmin, periods);\n"; mDynamicModelFile << " tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n"; - mDynamicModelFile << " if any(isnan(tmp) | isinf(tmp))\n"; + mDynamicModelFile << " if any(isnan(tmp) | isinf(tmp))\n"; mDynamicModelFile << " disp(['Inf or Nan value during the evaluation of block " << block <<"']);\n"; mDynamicModelFile << " oo_.deterministic_simulation.error = 100;\n"; mDynamicModelFile << " varargout{1} = oo_;\n"; @@ -2370,7 +2370,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia << jacobian_output.str() << endl - // Initialize g2 matrix + // Initialize g2 matrix << "if nargout >= 3," << endl << " %" << endl << " % Hessian matrix" << endl @@ -2560,17 +2560,17 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de output << modstruct << "lead_lag_incidence = ["; // Loop on endogenous variables - int nstatic = 0, - nfwrd = 0, - npred = 0, - nboth = 0; + int nstatic = 0, + nfwrd = 0, + npred = 0, + nboth = 0; for (int endoID = 0; endoID < symbol_table.endo_nbr(); endoID++) { output << endl; - int sstatic = 1, - sfwrd = 0, - spred = 0, - sboth = 0; + int sstatic = 1, + sfwrd = 0, + spred = 0, + sboth = 0; // Loop on periods for (int lag = -max_endo_lag; lag <= max_endo_lead; lag++) { @@ -2766,29 +2766,29 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de i++; } output << "];\n"; - + //vector inter_state_var; output << "block_structure.block(" << block+1 << ").tm1 = zeros(" << i << ", " << state_var.size() << ");\n"; int count_other_endogenous = 1; for (set::const_iterator it_other_endogenous = other_endogenous.begin(); it_other_endogenous != other_endogenous.end(); it_other_endogenous++) { - for (vector::const_iterator it=state_var.begin(); it != state_var.end(); it++) + for (vector::const_iterator it = state_var.begin(); it != state_var.end(); it++) { //cout << "block = " << block+1 << " state_var = " << *it << " it_other_endogenous=" << *it_other_endogenous + 1 << "\n"; if (*it == *it_other_endogenous + 1) { - output << "block_structure.block(" << block+1 << ").tm1(" - << count_other_endogenous << ", " + output << "block_structure.block(" << block+1 << ").tm1(" + << count_other_endogenous << ", " << it - state_var.begin()+1 << ") = 1;\n"; - /*output << "block_structure.block(" << block+1 << ").tm1(" - << it - state_var.begin()+1 << ", " - << count_other_endogenous << ") = 1;\n";*/ + /*output << "block_structure.block(" << block+1 << ").tm1(" + << it - state_var.begin()+1 << ", " + << count_other_endogenous << ") = 1;\n";*/ //cout << "=>\n"; } } count_other_endogenous++; } - + output << "block_structure.block(" << block+1 << ").other_endo_nbr = " << i << ";\n"; tmp_s.str(""); @@ -2815,10 +2815,10 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } else if (lag == 0) { - if (find( local_state_var.begin(), local_state_var.end(), getBlockVariableID(block, it->first.second.first)+1) == local_state_var.end()) + if (find(local_state_var.begin(), local_state_var.end(), getBlockVariableID(block, it->first.second.first)+1) == local_state_var.end()) { - local_stat_var.push_back(getBlockVariableID(block, it->first.second.first)+1); - n_static++; + local_stat_var.push_back(getBlockVariableID(block, it->first.second.first)+1); + n_static++; } } else @@ -2830,7 +2830,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } else { - if (find(local_stat_var.begin(), local_stat_var.end(),getBlockVariableID(block, it->first.second.first)+1) != local_stat_var.end()) + if (find(local_stat_var.begin(), local_stat_var.end(), getBlockVariableID(block, it->first.second.first)+1) != local_stat_var.end()) n_static--; n_forward++; } @@ -2850,13 +2850,13 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de tmp_s.str(""); } vector inter_state_var; - for (vector::const_iterator it_l=local_state_var.begin(); it_l != local_state_var.end(); it_l++) - for (vector::const_iterator it=state_var.begin(); it != state_var.end(); it++) + for (vector::const_iterator it_l = local_state_var.begin(); it_l != local_state_var.end(); it_l++) + for (vector::const_iterator it = state_var.begin(); it != state_var.end(); it++) if (*it == *it_l) inter_state_var.push_back(it - state_var.begin()+1); output << "block_structure.block(" << block+1 << ").sorted_col_dr_ghx = ["; - for (vector::const_iterator it=inter_state_var.begin(); it != inter_state_var.end(); it++) - output << *it << " "; + for (vector::const_iterator it = inter_state_var.begin(); it != inter_state_var.end(); it++) + output << *it << " "; output << "];\n"; count_lead_lag_incidence = 0; output << "block_structure.block(" << block+1 << ").lead_lag_incidence_other = [];\n"; @@ -2901,10 +2901,10 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de output << "];\n"; vector variable_inv_reordered(nb_endo); - for (int i = 0; i< nb_endo; i++) + for (int i = 0; i < nb_endo; i++) variable_inv_reordered[variable_reordered[i]] = i; - - for (vector::const_iterator it=state_var.begin(); it != state_var.end(); it++) + + for (vector::const_iterator it = state_var.begin(); it != state_var.end(); it++) state_equ.push_back(equation_reordered[variable_inv_reordered[*it - 1]]+1); map >, int> lag_row_incidence; @@ -2957,11 +2957,11 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de i_nz_state_var[i] = n; unsigned int lp = n_obs; - for (unsigned int block = 0; block < nb_blocks; block++) + for (unsigned int block = 0; block < nb_blocks; block++) { int block_size = getBlockSize(block); int nze = 0; - + for (int i = 0; i < block_size; i++) { int var = getBlockVariableID(block, i); @@ -2980,22 +2980,21 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de vector::const_iterator it_state_equ = find(state_equ.begin(), state_equ.end(), getBlockEquationID(block, it->first.first)+1); if (it_state_equ != state_equ.end()) row_state_var_incidence.insert(make_pair(it_state_equ - state_equ.begin(), it_state_var - state_var.begin())); - } - - + } + } /*tmp_block_endo_derivative[make_pair(it->second.first, make_pair(it->first.second, it->first.first))] = it->second.second; - if (block == 0) - { - - vector::const_iterator it_state_equ = find(state_equ.begin(), state_equ.end(), getBlockEquationID(block, i)+1); - if (it_state_equ != state_equ.end()) - { - cout << "row_state_var_incidence[make_pair([" << *it_state_equ << "] " << it_state_equ - state_equ.begin() << ", [" << *it_state_var << "] " << it_state_var - state_var.begin() << ")] = 1;\n"; - row_state_var_incidence.insert(make_pair(it_state_equ - state_equ.begin(), it_state_var - state_var.begin())); - } - }*/ - set >::const_iterator row_state_var_incidence_it = row_state_var_incidence.begin(); + if (block == 0) + { + + vector::const_iterator it_state_equ = find(state_equ.begin(), state_equ.end(), getBlockEquationID(block, i)+1); + if (it_state_equ != state_equ.end()) + { + cout << "row_state_var_incidence[make_pair([" << *it_state_equ << "] " << it_state_equ - state_equ.begin() << ", [" << *it_state_var << "] " << it_state_var - state_var.begin() << ")] = 1;\n"; + row_state_var_incidence.insert(make_pair(it_state_equ - state_equ.begin(), it_state_var - state_var.begin())); + } + }*/ + set >::const_iterator row_state_var_incidence_it = row_state_var_incidence.begin(); bool diag = true; int nb_diag_r = 0; while (row_state_var_incidence_it != row_state_var_incidence.end() && diag) @@ -3008,12 +3007,12 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de if (equ != row_state_var_incidence_it->first) nb_diag_r++; } - + } - set > col_state_var_incidence; - for(set >::const_iterator row_state_var_incidence_it = row_state_var_incidence.begin();row_state_var_incidence_it != row_state_var_incidence.end(); row_state_var_incidence_it++) + set > col_state_var_incidence; + for (set >::const_iterator row_state_var_incidence_it = row_state_var_incidence.begin(); row_state_var_incidence_it != row_state_var_incidence.end(); row_state_var_incidence_it++) col_state_var_incidence.insert(make_pair(row_state_var_incidence_it->second, row_state_var_incidence_it->first)); - set >::const_iterator col_state_var_incidence_it = col_state_var_incidence.begin(); + set >::const_iterator col_state_var_incidence_it = col_state_var_incidence.begin(); diag = true; int nb_diag_c = 0; while (col_state_var_incidence_it != col_state_var_incidence.end() && diag) @@ -3027,13 +3026,13 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de nb_diag_c++; } } - nb_diag = min( nb_diag_r, nb_diag_c); + nb_diag = min(nb_diag_r, nb_diag_c); row_state_var_incidence.clear(); col_state_var_incidence.clear(); } for (int i = 0; i < nze; i++) - i_nz_state_var[lp + i] = lp + nze; - lp += nze; + i_nz_state_var[lp + i] = lp + nze; + lp += nze; } output << modstruct << "nz_state_var = ["; for (unsigned int i = 0; i < lp; i++) @@ -3041,8 +3040,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de output << "];" << endl; output << modstruct << "n_diag = " << nb_diag << ";" << endl; KF_index_file.write(reinterpret_cast(&nb_diag), sizeof(nb_diag)); - - + typedef pair > index_KF; vector v_index_KF; for (int i = 0; i < n; i++) @@ -3050,7 +3048,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de for (int j = n_obs; j < n; j++) { int j1 = j - n_obs; - int j1_n_state = j1 * n_state - n_obs ; + int j1_n_state = j1 * n_state - n_obs; if ((i < n_obs) || (i >= nb_diag + n_obs) || (j1 >= nb_diag)) for (int k = n_obs; k < i_nz_state_var[i]; k++) { @@ -3059,14 +3057,14 @@ 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(&size_v_index_KF), sizeof(size_v_index_KF)); + KF_index_file.write(reinterpret_cast(&size_v_index_KF), sizeof(size_v_index_KF)); for (vector::iterator it = v_index_KF.begin(); it != v_index_KF.end(); it++) KF_index_file.write(reinterpret_cast(&(*it)), sizeof(index_KF)); vector v_index_KF_2; int n_n_obs = n * n_obs; for (int i = 0; i < n; i++) - //i = 0; + //i = 0; for (int j = i; j < n; j++) { if ((i < n_obs) || (i >= nb_diag + n_obs) || (j < n_obs) || (j >= nb_diag + n_obs)) @@ -3078,16 +3076,16 @@ 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(&size_v_index_KF_2), sizeof(size_v_index_KF_2)); + KF_index_file.write(reinterpret_cast(&size_v_index_KF_2), sizeof(size_v_index_KF_2)); for (vector::iterator it = v_index_KF_2.begin(); it != v_index_KF_2.end(); it++) - KF_index_file.write(reinterpret_cast(&(*it)), sizeof(index_KF)); + KF_index_file.write(reinterpret_cast(&(*it)), sizeof(index_KF)); KF_index_file.close(); } - output << modstruct << "state_var = ["; + output << modstruct << "state_var = ["; - for (vector::const_iterator it=state_var.begin(); it != state_var.end(); it++) - output << *it << " "; - output << "];" << endl; + for (vector::const_iterator it = state_var.begin(); it != state_var.end(); it++) + output << *it << " "; + output << "];" << endl; } // Writing initialization for some other variables @@ -3101,21 +3099,21 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de output << modstruct << "maximum_endo_lag = " << max_endo_lag << ";" << endl << modstruct << "maximum_endo_lead = " << max_endo_lead << ";" << endl - << outstruct << "steady_state = zeros(" << symbol_table.endo_nbr() << (julia ? ")" : ", 1);" ) << endl; + << outstruct << "steady_state = zeros(" << symbol_table.endo_nbr() << (julia ? ")" : ", 1);") << endl; output << modstruct << "maximum_exo_lag = " << max_exo_lag << ";" << endl << modstruct << "maximum_exo_lead = " << max_exo_lead << ";" << endl - << outstruct << "exo_steady_state = zeros(" << symbol_table.exo_nbr() << (julia ? ")" : ", 1);" ) << endl; + << outstruct << "exo_steady_state = zeros(" << symbol_table.exo_nbr() << (julia ? ")" : ", 1);") << endl; if (symbol_table.exo_det_nbr()) { output << modstruct << "maximum_exo_det_lag = " << max_exo_det_lag << ";" << endl << modstruct << "maximum_exo_det_lead = " << max_exo_det_lead << ";" << endl - << outstruct << "exo_det_steady_state = zeros(" << symbol_table.exo_det_nbr() << (julia ? ")" : ", 1);" ) << endl; + << outstruct << "exo_det_steady_state = zeros(" << symbol_table.exo_det_nbr() << (julia ? ")" : ", 1);") << endl; } output << modstruct << "params = " << (julia ? "fill(NaN, " : "NaN(") - << symbol_table.param_nbr() << (julia ? ")" : ", 1);" ) << endl; + << symbol_table.param_nbr() << (julia ? ")" : ", 1);") << endl; if (compute_xrefs) writeXrefs(output); @@ -3123,7 +3121,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de // Write number of non-zero derivatives // Use -1 if the derivatives have not been computed output << modstruct << (julia ? "nnzderivatives" : "NNZDerivatives") - << " = [" << NNZDerivatives[0] << "; "; + << " = [" << NNZDerivatives[0] << "; "; if (order > 1) output << NNZDerivatives[1] << "; "; else @@ -3169,7 +3167,7 @@ DynamicModel::computingPass(bool jacobianExo, bool hessian, bool thirdDerivative assert(jacobianExo || !(hessian || thirdDerivatives || paramsDerivsOrder)); initializeVariablesAndEquations(); - + // Prepare for derivation computeDerivIDs(); @@ -3532,7 +3530,7 @@ DynamicModel::collect_block_first_order_derivatives() int var = symbol_table.getTypeSpecificID(getSymbIDByDerivID(it2->first.second)); int lag = getLagByDerivID(it2->first.second); int block_eq = equation_2_block[eq]; - int block_var=0; + int block_var = 0; derivative_t tmp_derivative; lag_var_t lag_var; switch (getTypeByDerivID(it2->first.second)) @@ -4478,7 +4476,6 @@ DynamicModel::substituteLeadLagInternal(aux_var_t type, bool deterministic_model equations[i] = substeq; } - // Substitute in aux_equations // Without this loop, the auxiliary equations in equations // will diverge from those in aux_equations @@ -4678,7 +4675,7 @@ DynamicModel::fillEvalContext(eval_context_t &eval_context) const vector trendVars = symbol_table.getTrendVarIds(); for (vector ::const_iterator it = trendVars.begin(); it != trendVars.end(); it++) - eval_context[*it] = 2; //not <= 0 bc of log, not 1 bc of powers + eval_context[*it] = 2; //not <= 0 bc of log, not 1 bc of powers } bool @@ -4724,7 +4721,7 @@ DynamicModel::dynamicOnlyEquationsNbr() const } #ifndef PRIVATE_BUFFER_SIZE -#define PRIVATE_BUFFER_SIZE 1024 +# define PRIVATE_BUFFER_SIZE 1024 #endif bool @@ -4785,10 +4782,10 @@ DynamicModel::isChecksumMatching(const string &basename) const } char private_buffer[PRIVATE_BUFFER_SIZE]; - while(buffer) + while (buffer) { - buffer.get(private_buffer,PRIVATE_BUFFER_SIZE); - result.process_bytes(private_buffer,strlen(private_buffer)); + buffer.get(private_buffer, PRIVATE_BUFFER_SIZE); + result.process_bytes(private_buffer, strlen(private_buffer)); } bool basename_dir_exists = false; @@ -4800,8 +4797,8 @@ DynamicModel::isChecksumMatching(const string &basename) const if (r < 0) if (errno != EEXIST) { - perror("ERROR"); - exit(EXIT_FAILURE); + perror("ERROR"); + exit(EXIT_FAILURE); } else basename_dir_exists = true; @@ -4816,25 +4813,25 @@ DynamicModel::isChecksumMatching(const string &basename) const { checksum_file.open(filename.c_str(), ios::in | ios::binary); if (checksum_file.is_open()) - { - checksum_file >> old_checksum; - checksum_file.close(); - } + { + checksum_file >> old_checksum; + checksum_file.close(); + } } // write new checksum file if none or different from old checksum if (old_checksum != result.checksum()) - { - checksum_file.open(filename.c_str(), ios::out | ios::binary); - if (!checksum_file.is_open()) - { - cerr << "ERROR: Can't open file " << filename << endl; - exit(EXIT_FAILURE); - } - checksum_file << result.checksum(); - checksum_file.close(); - return false; - } - + { + checksum_file.open(filename.c_str(), ios::out | ios::binary); + if (!checksum_file.is_open()) + { + cerr << "ERROR: Can't open file " << filename << endl; + exit(EXIT_FAILURE); + } + checksum_file << result.checksum(); + checksum_file.close(); + return false; + } + return true; } @@ -4848,26 +4845,26 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d { // Loop on periods for (int lag = 0; lag <= 2; lag++) - { - lag_presence[lag] = 1; + { + lag_presence[lag] = 1; try { getDerivID(symbol_table.getID(eEndogenous, endoID), lag-1); } catch (UnknownDerivIDException &e) { - lag_presence[lag] = 0; + lag_presence[lag] = 0; } } if (lag_presence[0] == 1) - if (lag_presence[2] == 1) - zeta_mixed.push_back(endoID); - else - zeta_back.push_back(endoID); + if (lag_presence[2] == 1) + zeta_mixed.push_back(endoID); + else + zeta_back.push_back(endoID); else if (lag_presence[2] == 1) - zeta_fwrd.push_back(endoID); + zeta_fwrd.push_back(endoID); else - zeta_static.push_back(endoID); + zeta_static.push_back(endoID); } output << "size_t nstatic = " << zeta_static.size() << ";" << endl @@ -4877,8 +4874,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d output << "size_t zeta_static[" << zeta_static.size() << "] = {"; for (vector::iterator i = zeta_static.begin(); i != zeta_static.end(); ++i) { - if ( i != zeta_static.begin() ) - output << ","; + if (i != zeta_static.begin()) + output << ","; output << *i; } output << "};" << endl; @@ -4886,8 +4883,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d output << "size_t zeta_back[" << zeta_back.size() << "] = {"; for (vector::iterator i = zeta_back.begin(); i != zeta_back.end(); ++i) { - if ( i != zeta_back.begin() ) - output << ","; + if (i != zeta_back.begin()) + output << ","; output << *i; } output << "};" << endl; @@ -4895,8 +4892,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d output << "size_t zeta_fwrd[" << zeta_fwrd.size() << "] = {"; for (vector::iterator i = zeta_fwrd.begin(); i != zeta_fwrd.end(); ++i) { - if ( i != zeta_fwrd.begin() ) - output << ","; + if (i != zeta_fwrd.begin()) + output << ","; output << *i; } output << "};" << endl; @@ -4904,8 +4901,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d output << "size_t zeta_mixed[" << zeta_mixed.size() << "] = {"; for (vector::iterator i = zeta_mixed.begin(); i != zeta_mixed.end(); ++i) { - if ( i != zeta_mixed.begin() ) - output << ","; + if (i != zeta_mixed.begin()) + output << ","; output << *i; } output << "};" << endl; @@ -4925,8 +4922,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d output << NNZDerivatives[0] << "," << NNZDerivatives[1] << "," << NNZDerivatives[2] << "};" << endl; break; default: - cerr << "Order larger than 3 not implemented" << endl; - exit(EXIT_FAILURE); + cerr << "Order larger than 3 not implemented" << endl; + exit(EXIT_FAILURE); } } @@ -4978,7 +4975,7 @@ DynamicModel::writeResidualsC(const string &basename, bool cuda) const << endl << " /* Residual equations */" << endl << model_output.str() - << "}" << endl; + << "}" << endl; writePowerDeriv(mDynamicModelFile); writeNormcdf(mDynamicModelFile); @@ -5090,7 +5087,6 @@ DynamicModel::writeFirstDerivativesC_csr(const string &basename, bool cuda) cons // this is always empty here, but needed by d1->writeOutput deriv_node_temp_terms_t tef_terms; - // Indexing derivatives in column order vector D; for (first_derivatives_t::const_iterator it = first_derivatives.begin(); @@ -5103,35 +5099,35 @@ DynamicModel::writeFirstDerivativesC_csr(const string &basename, bool cuda) cons SymbolType type = getTypeByDerivID(dynvar); int tsid = symbol_table.getTypeSpecificID(symb_id); int col_id; - switch(type) - { - case eEndogenous: - col_id = tsid+(lag+1)*symbol_table.endo_nbr(); - break; - case eExogenous: - col_id = tsid+3*symbol_table.endo_nbr(); - break; - case eExogenousDet: - col_id = tsid+3*symbol_table.endo_nbr()+symbol_table.exo_nbr(); - break; - default: - std::cerr << "This case shouldn't happen" << std::endl; - exit(EXIT_FAILURE); - } - derivative deriv(col_id + eq*cols_nbr,col_id,eq,it->second); + switch (type) + { + case eEndogenous: + col_id = tsid+(lag+1)*symbol_table.endo_nbr(); + break; + case eExogenous: + col_id = tsid+3*symbol_table.endo_nbr(); + break; + case eExogenousDet: + col_id = tsid+3*symbol_table.endo_nbr()+symbol_table.exo_nbr(); + break; + default: + std::cerr << "This case shouldn't happen" << std::endl; + exit(EXIT_FAILURE); + } + derivative deriv(col_id + eq *cols_nbr, col_id, eq, it->second); D.push_back(deriv); } - sort(D.begin(), D.end(), derivative_less_than() ); + sort(D.begin(), D.end(), derivative_less_than()); // writing sparse Jacobian vector row_ptr(equations.size()); - fill(row_ptr.begin(),row_ptr.end(),0.0); + fill(row_ptr.begin(), row_ptr.end(), 0.0); int k = 0; - for(vector::const_iterator it = D.begin(); it != D.end(); ++it) + for (vector::const_iterator it = D.begin(); it != D.end(); ++it) { row_ptr[it->row_nbr]++; mDynamicModelFile << "col_ptr[" << k << "] " - << "=" << it->col_nbr << ";" << endl; + << "=" << it->col_nbr << ";" << endl; mDynamicModelFile << "value[" << k << "] = "; // oCstaticModel makes reference to the static variables it->value->writeOutput(mDynamicModelFile, oCDynamic2Model, temporary_terms, tef_terms); @@ -5142,20 +5138,20 @@ DynamicModel::writeFirstDerivativesC_csr(const string &basename, bool cuda) cons // row_ptr must point to the relative address of the first element of the row int cumsum = 0; mDynamicModelFile << "int row_ptr_data[" << row_ptr.size() + 1 << "] = { 0"; - for (vector::iterator it=row_ptr.begin(); it != row_ptr.end(); ++it) + for (vector::iterator it = row_ptr.begin(); it != row_ptr.end(); ++it) { cumsum += *it; mDynamicModelFile << ", " << cumsum; } mDynamicModelFile << "};" << endl - << "int i;" << endl - << "for (i=0; i < " << row_ptr.size() + 1 << "; i++) row_ptr[i] = row_ptr_data[i];" << endl; + << "int i;" << endl + << "for (i=0; i < " << row_ptr.size() + 1 << "; i++) row_ptr[i] = row_ptr_data[i];" << endl; mDynamicModelFile << "}" << endl; mDynamicModelFile.close(); } - void +void DynamicModel::writeSecondDerivativesC_csr(const string &basename, bool cuda) const { @@ -5211,26 +5207,26 @@ DynamicModel::writeSecondDerivativesC_csr(const string &basename, bool cuda) con int col_nb = id1 * dynJacobianColsNbr + id2; - derivative deriv(col_nb + eq*hessianColsNbr,col_nb,eq,it->second); + derivative deriv(col_nb + eq *hessianColsNbr, col_nb, eq, it->second); D.push_back(deriv); if (id1 != id2) - { - col_nb = id2 * dynJacobianColsNbr + id1; - derivative deriv(col_nb + eq*hessianColsNbr,col_nb,eq,it->second); - D.push_back(deriv); - } + { + col_nb = id2 * dynJacobianColsNbr + id1; + derivative deriv(col_nb + eq *hessianColsNbr, col_nb, eq, it->second); + D.push_back(deriv); + } } - sort(D.begin(), D.end(), derivative_less_than() ); + sort(D.begin(), D.end(), derivative_less_than()); // Writing Hessian vector row_ptr(equations.size()); - fill(row_ptr.begin(),row_ptr.end(),0.0); + fill(row_ptr.begin(), row_ptr.end(), 0.0); int k = 0; - for(vector::const_iterator it = D.begin(); it != D.end(); ++it) + for (vector::const_iterator it = D.begin(); it != D.end(); ++it) { row_ptr[it->row_nbr]++; mDynamicModelFile << "col_ptr[" << k << "] " - << "=" << it->col_nbr << ";" << endl; + << "=" << it->col_nbr << ";" << endl; mDynamicModelFile << "value[" << k << "] = "; // oCstaticModel makes reference to the static variables it->value->writeOutput(mDynamicModelFile, oCStaticModel, temporary_terms, tef_terms); @@ -5241,7 +5237,7 @@ DynamicModel::writeSecondDerivativesC_csr(const string &basename, bool cuda) con // row_ptr must point to the relative address of the first element of the row int cumsum = 0; mDynamicModelFile << "row_ptr = [ 0"; - for (vector::iterator it=row_ptr.begin(); it != row_ptr.end(); ++it) + for (vector::iterator it = row_ptr.begin(); it != row_ptr.end(); ++it) { cumsum += *it; mDynamicModelFile << ", " << cumsum; @@ -5314,55 +5310,55 @@ DynamicModel::writeThirdDerivativesC_csr(const string &basename, bool cuda) cons vector cols; long unsigned int col_nb = id1 * hessianColsNbr + id2 * dynJacobianColsNbr + id3; int thirdDColsNbr = hessianColsNbr*dynJacobianColsNbr; - derivative deriv(col_nb + eq*thirdDColsNbr,col_nb,eq,it->second); + derivative deriv(col_nb + eq *thirdDColsNbr, col_nb, eq, it->second); D.push_back(deriv); cols.push_back(col_nb); col_nb = id1 * hessianColsNbr + id3 * dynJacobianColsNbr + id2; - if (find(cols.begin(),cols.end(),col_nb) == cols.end()) - { - derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); - D.push_back(deriv); - cols.push_back(col_nb); - } + if (find(cols.begin(), cols.end(), col_nb) == cols.end()) + { + derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second); + D.push_back(deriv); + cols.push_back(col_nb); + } col_nb = id2 * hessianColsNbr + id1 * dynJacobianColsNbr + id3; - if (find(cols.begin(),cols.end(),col_nb) == cols.end()) - { - derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); - D.push_back(deriv); - cols.push_back(col_nb); - } + if (find(cols.begin(), cols.end(), col_nb) == cols.end()) + { + derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second); + D.push_back(deriv); + cols.push_back(col_nb); + } col_nb = id2 * hessianColsNbr + id3 * dynJacobianColsNbr + id1; - if (find(cols.begin(),cols.end(),col_nb) == cols.end()) - { - derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); - D.push_back(deriv); - cols.push_back(col_nb); - } + if (find(cols.begin(), cols.end(), col_nb) == cols.end()) + { + derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second); + D.push_back(deriv); + cols.push_back(col_nb); + } col_nb = id3 * hessianColsNbr + id1 * dynJacobianColsNbr + id2; - if (find(cols.begin(),cols.end(),col_nb) == cols.end()) - { - derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); - D.push_back(deriv); - cols.push_back(col_nb); - } + if (find(cols.begin(), cols.end(), col_nb) == cols.end()) + { + derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second); + D.push_back(deriv); + cols.push_back(col_nb); + } col_nb = id3 * hessianColsNbr + id2 * dynJacobianColsNbr + id1; - if (find(cols.begin(),cols.end(),col_nb) == cols.end()) - { - derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); - D.push_back(deriv); - } + if (find(cols.begin(), cols.end(), col_nb) == cols.end()) + { + derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second); + D.push_back(deriv); + } } - sort(D.begin(), D.end(), derivative_less_than() ); + sort(D.begin(), D.end(), derivative_less_than()); vector row_ptr(equations.size()); - fill(row_ptr.begin(),row_ptr.end(),0.0); + fill(row_ptr.begin(), row_ptr.end(), 0.0); int k = 0; - for(vector::const_iterator it = D.begin(); it != D.end(); ++it) + for (vector::const_iterator it = D.begin(); it != D.end(); ++it) { row_ptr[it->row_nbr]++; mDynamicModelFile << "col_ptr[" << k << "] " - << "=" << it->col_nbr << ";" << endl; + << "=" << it->col_nbr << ";" << endl; mDynamicModelFile << "value[" << k << "] = "; // oCstaticModel makes reference to the static variables it->value->writeOutput(mDynamicModelFile, oCStaticModel, temporary_terms, tef_terms); @@ -5373,7 +5369,7 @@ DynamicModel::writeThirdDerivativesC_csr(const string &basename, bool cuda) cons // row_ptr must point to the relative address of the first element of the row int cumsum = 0; mDynamicModelFile << "row_ptr = [ 0"; - for (vector::iterator it=row_ptr.begin(); it != row_ptr.end(); ++it) + for (vector::iterator it = row_ptr.begin(); it != row_ptr.end(); ++it) { cumsum += *it; mDynamicModelFile << ", " << cumsum; @@ -5397,26 +5393,26 @@ DynamicModel::writeCCOutput(ostream &output, const string &basename, bool block_ { // Loop on periods for (int lag = 0; lag <= 2; lag++) - { - lag_presence[lag] = 1; + { + lag_presence[lag] = 1; try { getDerivID(symbol_table.getID(eEndogenous, endoID), lag-1); } catch (UnknownDerivIDException &e) { - lag_presence[lag] = 0; + lag_presence[lag] = 0; } } if (lag_presence[0] == 1) - if (lag_presence[2] == 1) - output << "zeta_mixed.push_back(" << endoID << ");" << endl; - else - output << "zeta_back.push_back(" << endoID << ");" << endl; + if (lag_presence[2] == 1) + output << "zeta_mixed.push_back(" << endoID << ");" << endl; + else + output << "zeta_back.push_back(" << endoID << ");" << endl; else if (lag_presence[2] == 1) - output << "zeta_fwrd.push_back(" << endoID << ");" << endl; + output << "zeta_fwrd.push_back(" << endoID << ");" << endl; else - output << "zeta_static.push_back(" << endoID << ");" << endl; + output << "zeta_static.push_back(" << endoID << ");" << endl; } output << "nstatic = zeta_static.size();" << endl @@ -5441,7 +5437,6 @@ DynamicModel::writeCCOutput(ostream &output, const string &basename, bool block_ << "NNZDerivatives.push_back(-1);" << endl; } - void DynamicModel::writeJsonOutput(ostream &output) const { diff --git a/DynamicModel.hh b/DynamicModel.hh index c9c9da8a..4e4b6453 100644 --- a/DynamicModel.hh +++ b/DynamicModel.hh @@ -285,7 +285,7 @@ public: //! Returns number of static only equations size_t staticOnlyEquationsNbr() const; - + //! Returns number of dynamic only equations size_t dynamicOnlyEquationsNbr() const; @@ -337,7 +337,7 @@ public: //! Transforms the model by creating aux vars for the diff of forward vars /*! If subset is empty, does the transformation for all fwrd vars; otherwise - restrict it to the vars in subset */ + restrict it to the vars in subset */ void differentiateForwardVars(const vector &subset); //! Fills eval context with values of model local variables and auxiliary variables @@ -535,7 +535,7 @@ DynamicModel::checkHessianZero() const return second_derivatives.empty(); } -//! Classes to re-order derivatives for various sparse storage formats +//! Classes to re-order derivatives for various sparse storage formats class derivative { public: @@ -543,14 +543,17 @@ public: long unsigned int col_nbr; unsigned int row_nbr; expr_t value; - derivative(long unsigned int arg1, long unsigned int arg2, int arg3, expr_t arg4): - linear_address(arg1), col_nbr(arg2), row_nbr(arg3), value(arg4) {}; + derivative(long unsigned int arg1, long unsigned int arg2, int arg3, expr_t arg4) : + linear_address(arg1), col_nbr(arg2), row_nbr(arg3), value(arg4) + { + }; }; class derivative_less_than { public: - bool operator()(const derivative & d1, const derivative & d2) const + bool + operator()(const derivative &d1, const derivative &d2) const { return d1.linear_address < d2.linear_address; } diff --git a/DynareMain.cc b/DynareMain.cc index 03c74ec6..14d594c4 100644 --- a/DynareMain.cc +++ b/DynareMain.cc @@ -130,8 +130,8 @@ main(int argc, char **argv) clear_all = false; else if (strlen(argv[arg]) >= 19 && !strncmp(argv[arg], "params_derivs_order", 19)) { - if (strlen(argv[arg]) >= 22 || argv[arg][19] != '=' || - !(argv[arg][20] == '0' || argv[arg][20] == '1' || argv[arg][20] == '2')) + if (strlen(argv[arg]) >= 22 || argv[arg][19] != '=' + || !(argv[arg][20] == '0' || argv[arg][20] == '1' || argv[arg][20] == '2')) { cerr << "Incorrect syntax for params_derivs_order option" << endl; usage(); @@ -228,12 +228,12 @@ main(int argc, char **argv) size_t equal_index = string(argv[arg]).find('='); if (equal_index != string::npos) { - string key = string(argv[arg]).erase(equal_index).erase(0,2); + string key = string(argv[arg]).erase(equal_index).erase(0, 2); defines[key] = string(argv[arg]).erase(0, equal_index+1); } else { - string key = string(argv[arg]).erase(0,2); + string key = string(argv[arg]).erase(0, 2); defines[key] = "1"; } } @@ -245,36 +245,36 @@ main(int argc, char **argv) << "must not be separated from -I by whitespace." << endl; usage(); } - path.push_back(string(argv[arg]).erase(0,2)); + path.push_back(string(argv[arg]).erase(0, 2)); } else if (strlen(argv[arg]) >= 6 && !strncmp(argv[arg], "output", 6)) { - if (strlen(argv[arg]) <= 7 || argv[arg][6] != '=') - { - cerr << "Incorrect syntax for ouput option" << endl; - usage(); - } - if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 7, "dynamic", 7)) - output_mode = dynamic; - else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 7, "first", 5)) - output_mode = first; - else if (strlen(argv[arg]) == 13 && !strncmp(argv[arg] + 7, "second", 6)) - output_mode = second; - else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 7, "third", 5)) - output_mode = third; - else - { - cerr << "Incorrect syntax for ouput option" << endl; - usage(); + if (strlen(argv[arg]) <= 7 || argv[arg][6] != '=') + { + cerr << "Incorrect syntax for ouput option" << endl; + usage(); + } + if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 7, "dynamic", 7)) + output_mode = dynamic; + else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 7, "first", 5)) + output_mode = first; + else if (strlen(argv[arg]) == 13 && !strncmp(argv[arg] + 7, "second", 6)) + output_mode = second; + else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 7, "third", 5)) + output_mode = third; + else + { + cerr << "Incorrect syntax for ouput option" << endl; + usage(); } } else if (strlen(argv[arg]) >= 8 && !strncmp(argv[arg], "language", 8)) { - if (strlen(argv[arg]) <= 9 || argv[arg][8] != '=') - { - cerr << "Incorrect syntax for language option" << endl; - usage(); - } + if (strlen(argv[arg]) <= 9 || argv[arg][8] != '=') + { + cerr << "Incorrect syntax for language option" << endl; + usage(); + } if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 9, "julia", 5)) language = julia; @@ -302,26 +302,26 @@ main(int argc, char **argv) else if (!strcmp(argv[arg], "onlyjson")) onlyjson = true; else if (!strcmp(argv[arg], "jsonprintderivdetail")) - jsonprintderivdetail = true; + jsonprintderivdetail = true; else if (strlen(argv[arg]) >= 4 && !strncmp(argv[arg], "json", 4)) { - if (strlen(argv[arg]) <= 5 || argv[arg][4] != '=') - { - cerr << "Incorrect syntax for json option" << endl; - usage(); - } - if (strlen(argv[arg]) == 10 && !strncmp(argv[arg] + 5, "parse", 5)) - json = parsing; - else if (strlen(argv[arg]) == 10 && !strncmp(argv[arg] + 5, "check", 5)) - json = checkpass; - else if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 5, "transform", 9)) - json = transformpass; - else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 5, "compute", 7)) - json = computingpass; - else - { - cerr << "Incorrect syntax for json option" << endl; - usage(); + if (strlen(argv[arg]) <= 5 || argv[arg][4] != '=') + { + cerr << "Incorrect syntax for json option" << endl; + usage(); + } + if (strlen(argv[arg]) == 10 && !strncmp(argv[arg] + 5, "parse", 5)) + json = parsing; + else if (strlen(argv[arg]) == 10 && !strncmp(argv[arg] + 5, "check", 5)) + json = checkpass; + else if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 5, "transform", 9)) + json = transformpass; + else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 5, "compute", 7)) + json = computingpass; + else + { + cerr << "Incorrect syntax for json option" << endl; + usage(); } } else diff --git a/DynareMain2.cc b/DynareMain2.cc index 55f8304e..758b278f 100644 --- a/DynareMain2.cc +++ b/DynareMain2.cc @@ -69,9 +69,9 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear mod_file->writeOutputFiles(basename, clear_all, clear_global, no_log, no_warn, console, nograph, nointeractive, config_file, check_model_changes, minimal_workspace, compute_xrefs #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) - , cygwin, msvc, mingw + , cygwin, msvc, mingw #endif - ); + ); delete mod_file; diff --git a/ExprNode.cc b/ExprNode.cc index 1c03bc03..4e09b5b0 100644 --- a/ExprNode.cc +++ b/ExprNode.cc @@ -107,7 +107,7 @@ ExprNode::collectVariables(SymbolType type, set &result) const set > symbs_lags; collectDynamicVariables(type, symbs_lags); transform(symbs_lags.begin(), symbs_lags.end(), inserter(result, result.begin()), - boost::bind(&pair::first,_1)); + boost::bind(&pair::first, _1)); } void @@ -537,7 +537,6 @@ NumConstNode::substituteStaticAuxiliaryVariable() const return const_cast(this); } - VariableNode::VariableNode(DataTree &datatree_arg, int symb_id_arg, int lag_arg) : ExprNode(datatree_arg), symb_id(symb_id_arg), @@ -904,7 +903,7 @@ VariableNode::substituteStaticAuxiliaryVariable() const } return const_cast(this); } - + double VariableNode::eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException) { @@ -1013,17 +1012,17 @@ VariableNode::collectDynamicVariables(SymbolType type_arg, set > pair VariableNode::normalizeEquation(int var_endo, vector > > &List_of_Op_RHS) const { - /* The equation has to be normalized with respect to the current endogenous variable ascribed to it. - The two input arguments are : - - The ID of the endogenous variable associated to the equation. - - The list of operators and operands needed to normalize the equation* - - The pair returned by NormalizeEquation is composed of - - a flag indicating if the expression returned contains (flag = 1) or not (flag = 0) - the endogenous variable related to the equation. - If the expression contains more than one occurence of the associated endogenous variable, - the flag is equal to 2. - - an expression equal to the RHS if flag = 0 and equal to NULL elsewhere + /* The equation has to be normalized with respect to the current endogenous variable ascribed to it. + The two input arguments are : + - The ID of the endogenous variable associated to the equation. + - The list of operators and operands needed to normalize the equation* + + The pair returned by NormalizeEquation is composed of + - a flag indicating if the expression returned contains (flag = 1) or not (flag = 0) + the endogenous variable related to the equation. + If the expression contains more than one occurence of the associated endogenous variable, + the flag is equal to 2. + - an expression equal to the RHS if flag = 0 and equal to NULL elsewhere */ if (type == eEndogenous) { @@ -1501,7 +1500,7 @@ VariableNode::removeTrendLeadLag(map trend_symbols_map) const expr_t noTrendLeadLagNode = new VariableNode(datatree, it->first, 0); bool log_trend = get_type() == eLogTrend; expr_t trend = it->second; - + if (get_lag() > 0) { expr_t growthFactorSequence = trend->decreaseLeadsLags(-1); @@ -2003,7 +2002,7 @@ UnaryOpNode::writeJsonOutput(ostream &output, break; } - bool close_parenthesis = false; + bool close_parenthesis = false; /* Enclose argument with parentheses if: - current opcode is not uminus, or @@ -2352,9 +2351,9 @@ UnaryOpNode::normalizeEquation(int var_endo, vector expr_t UnaryOpNode::substituteExpectation(subst_table_t &subst_table, vector &neweqs, bool partial_information_model) const { - if (op_code==oExpectation) + if (op_code == oExpectation) { subst_table_t::iterator it = subst_table.find(const_cast(this)); if (it != subst_table.end()) @@ -3689,7 +3688,7 @@ BinaryOpNode::Compute_RHS(expr_t arg1, expr_t arg2, int op, int op_type) const pair BinaryOpNode::normalizeEquation(int var_endo, vector > > &List_of_Op_RHS) const { - /* Checks if the current value of the endogenous variable related to the equation + /* Checks if the current value of the endogenous variable related to the equation is present in the arguments of the binary operator. */ vector > > List_of_Op_RHS1, List_of_Op_RHS2; int is_endogenous_present_1, is_endogenous_present_2; @@ -3702,17 +3701,17 @@ BinaryOpNode::normalizeEquation(int var_endo, vectornormalizeEquation(var_endo, List_of_Op_RHS2); is_endogenous_present_2 = res.first; expr_t_2 = res.second; - + /* If the two expressions contains the current value of the endogenous variable associated to the equation the equation could not be normalized and the process is given-up.*/ if (is_endogenous_present_1 == 2 || is_endogenous_present_2 == 2) return (make_pair(2, (expr_t) NULL)); else if (is_endogenous_present_1 && is_endogenous_present_2) return (make_pair(2, (expr_t) NULL)); - else if (is_endogenous_present_1) /*If the current values of the endogenous variable associated to the equation + 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 == oEqual) /* The end of the normalization process : + if (op_code == oEqual) /* The end of the normalization process : All the operations needed to normalize the equation are applied. */ { pair > it; @@ -3727,7 +3726,7 @@ BinaryOpNode::normalizeEquation(int var_endo, vector &subset, subst_table_t &subst_table, vector &neweqs) const { @@ -4877,7 +4875,6 @@ TrinaryOpNode::substituteExpectation(subst_table_t &subst_table, vector &subset, subst_table_t &subst_table, vector &neweqs) const { diff --git a/ExprNode.hh b/ExprNode.hh index 7b5e2463..33cfc730 100644 --- a/ExprNode.hh +++ b/ExprNode.hh @@ -89,16 +89,16 @@ enum ExprNodeOutputType || (output_type) == oMatlabDynamicSparseSteadyStateOperator \ || (output_type) == oSteadyStateFile) -#define IS_JULIA(output_type) ((output_type) == oJuliaStaticModel \ - || (output_type) == oJuliaDynamicModel \ +#define IS_JULIA(output_type) ((output_type) == oJuliaStaticModel \ + || (output_type) == oJuliaDynamicModel \ || (output_type) == oJuliaDynamicSteadyStateOperator \ || (output_type) == oJuliaSteadyStateFile) -#define IS_C(output_type) ((output_type) == oCDynamicModel \ - || (output_type) == oCDynamic2Model \ - || (output_type) == oCStaticModel \ - || (output_type) == oCDynamicSteadyStateOperator \ - || (output_type) == oCSteadyStateFile) +#define IS_C(output_type) ((output_type) == oCDynamicModel \ + || (output_type) == oCDynamic2Model \ + || (output_type) == oCStaticModel \ + || (output_type) == oCDynamicSteadyStateOperator \ + || (output_type) == oCSteadyStateFile) #define IS_LATEX(output_type) ((output_type) == oLatexStaticModel \ || (output_type) == oLatexDynamicModel \ @@ -122,345 +122,346 @@ enum ExprNodeOutputType #define MIN_COST(is_matlab) ((is_matlab) ? MIN_COST_MATLAB : MIN_COST_C) //! 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; -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; + 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; + 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; + protected: + //! Reference to the enclosing DataTree + DataTree &datatree; - //! Index number - int idx; + //! Index number + int idx; - //! Is the data member non_null_derivatives initialized ? - bool preparedForDerivation; + //! Is the data member non_null_derivatives initialized ? + bool preparedForDerivation; - //! Set of derivation IDs with respect to which the derivative is potentially non-null - set non_null_derivatives; + //! Set of derivation IDs with respect to which the derivative is potentially non-null + set non_null_derivatives; - //! Used for caching of first order derivatives (when non-null) - map derivatives; + //! Used for caching of first order derivatives (when non-null) + map derivatives; - //! 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 &temp_terms_map, bool is_matlab) const; + //! 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 &temp_terms_map, bool is_matlab) const; - //! For creating equation cross references - struct EquationInfo - { - set > param; - set > endo; - set > exo; - set > exo_det; - }; + //! For creating equation cross references + struct EquationInfo + { + set > param; + set > endo; + set > exo; + set > exo_det; + }; -public: - ExprNode(DataTree &datatree_arg); - virtual ~ExprNode(); + public: + ExprNode(DataTree &datatree_arg); + virtual + ~ExprNode(); - //! Initializes data member non_null_derivatives - virtual void prepareForDerivation() = 0; + //! 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); + //! 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 &recursive_variables) = 0; + //! 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 &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; + //! 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; - //! Fills temporary_terms set, using reference counts - /*! 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(map > &reference_count, - map &temp_terms_map, - bool is_matlab, NodeTreeReference tr) const; + //! Fills temporary_terms set, using reference counts + /*! 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(map > &reference_count, + map &temp_terms_map, + bool is_matlab, NodeTreeReference tr) 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,out] tef_terms the set of already written external function nodes - */ - virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; + //! 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,out] tef_terms the set of already written external function nodes + */ + virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; - //! returns true if the expr node contains an external function - virtual bool containsExternalFunction() 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 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 (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; + //! 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; - //! Writes output of node in JSON syntax - virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; + //! Writes output of node in JSON syntax + virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; - virtual int precedenceJson(const temporary_terms_t &temporary_terms) const; + 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, - 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 &efout, + //! 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, deriv_node_temp_terms_t &tef_terms) 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; + //! Write the JSON output of an external function in a string vector + //! Allows the insertion of commas if necessary + virtual void writeJsonExternalFunctionOutput(vector &efout, + const temporary_terms_t &temporary_terms, + 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 > &result) const = 0; + 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 (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 &result) 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 > &result) const = 0; - //! 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 > &result) const; + //! 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 &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 > &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 > &result) const; - virtual void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const = 0; + //! 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 > &result) const; - virtual void computeTemporaryTerms(map &reference_count, - temporary_terms_t &temporary_terms, - map > &first_occurence, - int Curr_block, - vector< vector > &v_temporary_terms, - int equation) const; + virtual void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const = 0; - class EvalException + virtual void computeTemporaryTerms(map &reference_count, + temporary_terms_t &temporary_terms, + map > &first_occurence, + int Curr_block, + vector< vector > &v_temporary_terms, + int equation) const; - { - }; + class EvalException - class EvalExternalFunctionException : public EvalException + { + }; - { - }; + class EvalExternalFunctionException : public EvalException - virtual double eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException) = 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, 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 ¶m, set &endo, set &exo, set &exo_det) const = 0; - virtual void computeXrefs(EquationInfo &ei) const = 0; - //! Try to normalize an equation linear in its endogenous variable - virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const = 0; + virtual double eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException) = 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, 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; - //! Returns the maximum lead of endogenous in this expression - /*! Always returns a non-negative value */ - virtual int maxEndoLead() const = 0; + /*! + Compute cross references for equations + */ + // virtual void computeXrefs(set ¶m, set &endo, set &exo, set &exo_det) const = 0; + virtual void computeXrefs(EquationInfo &ei) const = 0; + //! Try to normalize an equation linear in its endogenous variable + virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) 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 lead of endogenous in this expression + /*! Always returns a non-negative value */ + virtual int maxEndoLead() 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 lead of exogenous in this expression + /*! Always returns a non-negative value */ + virtual int maxExoLead() 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 lag of endogenous in this expression + /*! Always returns a non-negative value */ + virtual int maxEndoLag() const = 0; - //! Returns the relative period of the most forward term in this expression - /*! A negative value means that the expression contains only lagged variables */ - virtual int maxLead() const = 0; + //! Returns the maximum lag of exogenous in this expression + /*! Always returns a non-negative value */ + virtual int maxExoLag() 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; + //! Returns the relative period of the most forward term in this expression + /*! A negative value means that the expression contains only lagged variables */ + virtual int maxLead() const = 0; - //! Type for the substitution map used in the process of creating auxiliary vars for leads >= 2 - typedef map subst_table_t; + //! 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; - //! 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 &neweqs) const; + //! Type for the substitution map used in the process of creating auxiliary vars for leads >= 2 + typedef map subst_table_t; - //! 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 &neweqs) const; + //! 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 &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. + //! 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 &neweqs) const; - 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 + //! 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. - \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 &neweqs, bool deterministic_model) const = 0; + 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 - //! 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 &neweqs) const = 0; + \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 &neweqs, bool deterministic_model) 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 &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 &neweqs) 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 &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 &neweqs, bool partial_information_model) 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 &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 &neweqs) const = 0; - virtual expr_t decreaseLeadsLagsPredeterminedVariables() 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 &neweqs, bool partial_information_model) 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 &subset, subst_table_t &subst_table, vector &neweqs) const = 0; + virtual expr_t decreaseLeadsLagsPredeterminedVariables() 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; + //! 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 &subset, subst_table_t &subst_table, vector &neweqs) const = 0; - //! Returns true if the expression contains one or several endogenous variable - virtual bool containsEndogenous(void) 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 exogenous variable - virtual bool containsExogenous() const = 0; + //! Returns true if the expression contains one or several endogenous variable + virtual bool containsEndogenous(void) 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; + //! Returns true if the expression contains one or several exogenous variable + virtual bool containsExogenous() const = 0; - //! Replaces the Trend var with datatree.One - virtual expr_t replaceTrendVar() 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; - //! 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; + //! Replaces the Trend var with datatree.One + virtual expr_t replaceTrendVar() const = 0; - //! Add ExprNodes to the provided datatree - virtual expr_t cloneDynamic(DataTree &dynamic_datatree) 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; - //! Move a trend variable with lag/lead to time t by dividing/multiplying by its growth factor - virtual expr_t removeTrendLeadLag(map trend_symbols_map) const = 0; + //! Add ExprNodes to the provided datatree + virtual expr_t cloneDynamic(DataTree &dynamic_datatree) 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; + //! Move a trend variable with lag/lead to time t by dividing/multiplying by its growth factor + virtual expr_t removeTrendLeadLag(map trend_symbols_map) const = 0; - //! Substitute auxiliary variables by their expression in static model - virtual expr_t substituteStaticAuxiliaryVariable() 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; + }; //! Object used to compare two nodes (using their indexes) struct ExprNodeLess @@ -563,7 +564,11 @@ public: { return symb_id; }; - int get_lag() const { return lag; }; + int + get_lag() const + { + return lag; + }; virtual pair normalizeEquation(int symb_id_endo, vector > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map &recursive_variables); virtual int maxEndoLead() const; diff --git a/ExtendedPreprocessorTypes.hh b/ExtendedPreprocessorTypes.hh index 26c8ac19..e40c73ee 100644 --- a/ExtendedPreprocessorTypes.hh +++ b/ExtendedPreprocessorTypes.hh @@ -24,9 +24,9 @@ enum FileOutputType { none, // outputs files for Matlab/Octave processing dynamic, // outputs _dynamic.* and related files - first, // outputs _first_derivatives.* and related files - second, // outputs _first_derivatives.*, _second_derivatives.* and related files - third, // outputs _first_derivatives.*, _second_derivatives.*, _third_derivatives.* and related files + first, // outputs _first_derivatives.* and related files + second, // outputs _first_derivatives.*, _second_derivatives.* and related files + third, // outputs _first_derivatives.*, _second_derivatives.*, _third_derivatives.* and related files }; enum LanguageOutputType diff --git a/MinimumFeedbackSet.cc b/MinimumFeedbackSet.cc index 479c8f22..a84a994a 100644 --- a/MinimumFeedbackSet.cc +++ b/MinimumFeedbackSet.cc @@ -175,7 +175,7 @@ namespace MFS if (in_degree(vertex, G) > 0 && out_degree(vertex, G) > 0) for (tie(it_in, in_end) = in_edges(vertex, G); it_in != in_end; ++it_in) for (tie(it_out, out_end) = out_edges(vertex, G); it_out != out_end; ++it_out) - if (source(*it_in, G) == target(*it_out, G) && source(*it_in, G) != target(*it_in, G)) // not a loop + if (source(*it_in, G) == target(*it_out, G) && source(*it_in, G) != target(*it_in, G)) // not a loop Doublet.push_back(source(*it_in, G)); return Doublet; } diff --git a/ModFile.cc b/ModFile.cc index 3c6ece94..e0462b6b 100644 --- a/ModFile.cc +++ b/ModFile.cc @@ -39,7 +39,7 @@ ModFile::ModFile(WarningConsolidation &warnings_arg) orig_ramsey_dynamic_model(symbol_table, num_constants, external_functions_table), static_model(symbol_table, num_constants, external_functions_table), steady_state_model(symbol_table, num_constants, external_functions_table, static_model), - linear(false), block(false), byte_code(false), use_dll(false), no_static(false), + linear(false), block(false), byte_code(false), use_dll(false), no_static(false), differentiate_forward_vars(false), nonstationary_variables(false), param_used_with_lead_lag(false), warnings(warnings_arg) { @@ -148,10 +148,10 @@ ModFile::checkPass(bool nostrict) exit(EXIT_FAILURE); } - if (((mod_file_struct.ramsey_model_present || mod_file_struct.discretionary_policy_present) + if (((mod_file_struct.ramsey_model_present || mod_file_struct.discretionary_policy_present) && !mod_file_struct.planner_objective_present) || (!(mod_file_struct.ramsey_model_present || mod_file_struct.discretionary_policy_present) - && mod_file_struct.planner_objective_present)) + && mod_file_struct.planner_objective_present)) { cerr << "ERROR: A planner_objective statement must be used with a ramsey_model, a ramsey_policy or a discretionary_policy statement and vice versa." << endl; exit(EXIT_FAILURE); @@ -256,25 +256,25 @@ ModFile::checkPass(bool nostrict) cerr << "ERROR: the number of equations marked [static] must be equal to the number of equations marked [dynamic]" << endl; exit(EXIT_FAILURE); } - - if (dynamic_model.staticOnlyEquationsNbr() > 0 && - (mod_file_struct.ramsey_model_present || mod_file_struct.discretionary_policy_present)) + + if (dynamic_model.staticOnlyEquationsNbr() > 0 + && (mod_file_struct.ramsey_model_present || mod_file_struct.discretionary_policy_present)) { cerr << "ERROR: marking equations as [static] or [dynamic] is not possible with ramsey_model, ramsey_policy or discretionary_policy" << endl; exit(EXIT_FAILURE); } - if (stochastic_statement_present && - (dynamic_model.isUnaryOpUsed(oSign) - || dynamic_model.isUnaryOpUsed(oAbs) - || dynamic_model.isBinaryOpUsed(oMax) - || dynamic_model.isBinaryOpUsed(oMin) - || dynamic_model.isBinaryOpUsed(oGreater) - || dynamic_model.isBinaryOpUsed(oLess) - || dynamic_model.isBinaryOpUsed(oGreaterEqual) - || dynamic_model.isBinaryOpUsed(oLessEqual) - || dynamic_model.isBinaryOpUsed(oEqualEqual) - || dynamic_model.isBinaryOpUsed(oDifferent))) + if (stochastic_statement_present + && (dynamic_model.isUnaryOpUsed(oSign) + || dynamic_model.isUnaryOpUsed(oAbs) + || dynamic_model.isBinaryOpUsed(oMax) + || dynamic_model.isBinaryOpUsed(oMin) + || dynamic_model.isBinaryOpUsed(oGreater) + || dynamic_model.isBinaryOpUsed(oLess) + || dynamic_model.isBinaryOpUsed(oGreaterEqual) + || dynamic_model.isBinaryOpUsed(oLessEqual) + || dynamic_model.isBinaryOpUsed(oEqualEqual) + || dynamic_model.isBinaryOpUsed(oDifferent))) warnings << "WARNING: you are using a function (max, min, abs, sign) or an operator (<, >, <=, >=, ==, !=) which is unsuitable for a stochastic context; see the reference manual, section about \"Expressions\", for more details." << endl; // Test if some estimated parameters are used within the values of shocks @@ -289,7 +289,7 @@ ModFile::checkPass(bool nostrict) { cerr << "ERROR: some estimated parameters ("; for (set::const_iterator it = parameters_intersect.begin(); - it != parameters_intersect.end(); ) + it != parameters_intersect.end();) { cerr << symbol_table.getName(*it); if (++it != parameters_intersect.end()) @@ -363,7 +363,7 @@ ModFile::transformPass(bool nostrict, bool compute_xrefs) /* clone the model then clone the new equations back to the original because we have to call computeDerivIDs (in computeRamseyPolicyFOCs and computingPass) - */ + */ if (linear) dynamic_model.cloneDynamic(orig_ramsey_dynamic_model); dynamic_model.cloneDynamic(ramsey_FOC_equations_dynamic_model); @@ -497,64 +497,64 @@ ModFile::computingPass(bool no_tmp_terms, FileOutputType output, int params_deri // Compute static model and its derivatives dynamic_model.toStatic(static_model); if (!no_static) - { - if (mod_file_struct.stoch_simul_present - || mod_file_struct.estimation_present || mod_file_struct.osr_present - || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present - || mod_file_struct.calib_smoother_present) - static_model.set_cutoff_to_zero(); + { + if (mod_file_struct.stoch_simul_present + || mod_file_struct.estimation_present || mod_file_struct.osr_present + || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present + || mod_file_struct.calib_smoother_present) + static_model.set_cutoff_to_zero(); - const bool static_hessian = mod_file_struct.identification_present - || mod_file_struct.estimation_analytic_derivation; + const bool static_hessian = mod_file_struct.identification_present + || mod_file_struct.estimation_analytic_derivation; int paramsDerivsOrder = 0; if (mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation) paramsDerivsOrder = params_derivs_order; - static_model.computingPass(global_eval_context, no_tmp_terms, static_hessian, - false, paramsDerivsOrder, block, byte_code); - } + static_model.computingPass(global_eval_context, no_tmp_terms, static_hessian, + false, paramsDerivsOrder, block, byte_code); + } // Set things to compute for dynamic model if (mod_file_struct.perfect_foresight_solver_present || mod_file_struct.check_present - || mod_file_struct.stoch_simul_present - || mod_file_struct.estimation_present || mod_file_struct.osr_present - || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present - || mod_file_struct.calib_smoother_present) - { - if (mod_file_struct.perfect_foresight_solver_present) - dynamic_model.computingPass(true, false, false, none, global_eval_context, no_tmp_terms, block, use_dll, byte_code); - else - { - if (mod_file_struct.stoch_simul_present - || mod_file_struct.estimation_present || mod_file_struct.osr_present - || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present - || mod_file_struct.calib_smoother_present) - dynamic_model.set_cutoff_to_zero(); - if (mod_file_struct.order_option < 1 || mod_file_struct.order_option > 3) - { - cerr << "ERROR: Incorrect order option..." << endl; - exit(EXIT_FAILURE); - } - bool hessian = mod_file_struct.order_option >= 2 - || mod_file_struct.identification_present - || mod_file_struct.estimation_analytic_derivation - || linear - || output == second - || output == third; - bool thirdDerivatives = mod_file_struct.order_option == 3 - || mod_file_struct.estimation_analytic_derivation - || output == third; - int paramsDerivsOrder = 0; - if (mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation) - paramsDerivsOrder = params_derivs_order; - dynamic_model.computingPass(true, hessian, thirdDerivatives, paramsDerivsOrder, global_eval_context, no_tmp_terms, block, use_dll, byte_code); - if (linear && mod_file_struct.ramsey_model_present) - orig_ramsey_dynamic_model.computingPass(true, true, false, paramsDerivsOrder, global_eval_context, no_tmp_terms, block, use_dll, byte_code); - } - } - else // No computing task requested, compute derivatives up to 2nd order by default - dynamic_model.computingPass(true, true, false, none, global_eval_context, no_tmp_terms, block, use_dll, byte_code); + || mod_file_struct.stoch_simul_present + || mod_file_struct.estimation_present || mod_file_struct.osr_present + || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present + || mod_file_struct.calib_smoother_present) + { + if (mod_file_struct.perfect_foresight_solver_present) + dynamic_model.computingPass(true, false, false, none, global_eval_context, no_tmp_terms, block, use_dll, byte_code); + else + { + if (mod_file_struct.stoch_simul_present + || mod_file_struct.estimation_present || mod_file_struct.osr_present + || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present + || mod_file_struct.calib_smoother_present) + dynamic_model.set_cutoff_to_zero(); + if (mod_file_struct.order_option < 1 || mod_file_struct.order_option > 3) + { + cerr << "ERROR: Incorrect order option..." << endl; + exit(EXIT_FAILURE); + } + bool hessian = mod_file_struct.order_option >= 2 + || mod_file_struct.identification_present + || mod_file_struct.estimation_analytic_derivation + || linear + || output == second + || output == third; + bool thirdDerivatives = mod_file_struct.order_option == 3 + || mod_file_struct.estimation_analytic_derivation + || output == third; + int paramsDerivsOrder = 0; + if (mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation) + paramsDerivsOrder = params_derivs_order; + dynamic_model.computingPass(true, hessian, thirdDerivatives, paramsDerivsOrder, global_eval_context, no_tmp_terms, block, use_dll, byte_code); + if (linear && mod_file_struct.ramsey_model_present) + orig_ramsey_dynamic_model.computingPass(true, true, false, paramsDerivsOrder, global_eval_context, no_tmp_terms, block, use_dll, byte_code); + } + } + else // No computing task requested, compute derivatives up to 2nd order by default + dynamic_model.computingPass(true, true, false, none, global_eval_context, no_tmp_terms, block, use_dll, byte_code); - if ((linear && !mod_file_struct.ramsey_model_present && !dynamic_model.checkHessianZero()) || - (linear && mod_file_struct.ramsey_model_present && !orig_ramsey_dynamic_model.checkHessianZero())) + if ((linear && !mod_file_struct.ramsey_model_present && !dynamic_model.checkHessianZero()) + || (linear && mod_file_struct.ramsey_model_present && !orig_ramsey_dynamic_model.checkHessianZero())) { map eqs; if (mod_file_struct.ramsey_model_present) @@ -620,18 +620,18 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo if (clear_all) mOutputFile << "if isoctave || matlab_ver_less_than('8.6')" << endl << " clear all" << endl - << "else" << endl - << " clearvars -global" << endl - << " clear_persistent_variables(fileparts(which('dynare')), false)" << endl - << "end" << endl; + << "else" << endl + << " clearvars -global" << endl + << " clear_persistent_variables(fileparts(which('dynare')), false)" << endl + << "end" << endl; else if (clear_global) mOutputFile << "clear M_ options_ oo_ estim_params_ bayestopt_ dataset_ dataset_info estimation_info ys0_ ex0_;" << endl; mOutputFile << "tic0 = tic;" << endl - << "% Save empty dates and dseries objects in memory." << endl - << "dates('initialize');" << endl - << "dseries('initialize');" << endl - << "% Define global variables." << endl + << "% Save empty dates and dseries objects in memory." << endl + << "dates('initialize');" << endl + << "dseries('initialize');" << endl + << "% Define global variables." << endl << "global M_ options_ oo_ estim_params_ bayestopt_ dataset_ dataset_info estimation_info ys0_ ex0_" << endl << "options_ = [];" << endl << "M_.fname = '" << basename << "';" << endl @@ -721,7 +721,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo bool hasModelChanged = !dynamic_model.isChecksumMatching(basename); if (!check_model_changes) hasModelChanged = true; - + if (hasModelChanged) { // Erase possible remnants of previous runs @@ -736,7 +736,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo unlink((basename + "_steadystate2.m").c_str()); unlink((basename + "_set_auxiliary_variables.m").c_str()); } - + if (!use_dll) { mOutputFile << "erase_compiled_function('" + basename + "_static');" << endl; @@ -744,7 +744,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo } #if defined(_WIN32) || defined(__CYGWIN32__) -#if (defined(_MSC_VER) && _MSC_VER < 1700) +# if (defined(_MSC_VER) && _MSC_VER < 1700) // If using USE_DLL with MSVC 10.0 or earlier, check that the user didn't use a function not supported by the compiler (because MSVC <= 10.0 doesn't comply with C99 standard) if (use_dll && msvc) { @@ -764,7 +764,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo exit(EXIT_FAILURE); } } -#endif +# endif #endif // Compile the dynamic MEX file for use_dll option @@ -774,10 +774,10 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) if (msvc) // MATLAB/Windows + Microsoft Visual C++ - mOutputFile << "dyn_mex('msvc', '" << basename << "', " << !check_model_changes << ")" << endl; + mOutputFile << "dyn_mex('msvc', '" << basename << "', " << !check_model_changes << ")" << endl; else if (cygwin) // MATLAB/Windows + Cygwin g++ - mOutputFile << "dyn_mex('cygwin', '" << basename << "', " << !check_model_changes << ")" << endl; + mOutputFile << "dyn_mex('cygwin', '" << basename << "', " << !check_model_changes << ")" << endl; else if (mingw) // MATLAB/Windows + MinGW g++ mOutputFile << "dyn_mex('mingw', '" << basename << "', " << !check_model_changes << ")" << endl; @@ -855,7 +855,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo config_file.writeEndParallel(mOutputFile); mOutputFile << endl << endl - << "disp(['Total computing time : ' dynsec2hms(toc(tic0)) ]);" << endl; + << "disp(['Total computing time : ' dynsec2hms(toc(tic0)) ]);" << endl; if (!no_warn) { @@ -866,7 +866,6 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo << " disp('Note: warning(s) encountered in MATLAB/Octave code')" << endl << "end" << endl; } - if (!no_log) mOutputFile << "diary off" << endl; @@ -877,16 +876,16 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo { // Create static and dynamic files if (dynamic_model.equation_number() > 0) - { - if (!no_static) - { - static_model.writeStaticFile(basename, block, byte_code, use_dll, false); - static_model.writeParamsDerivativesFile(basename, false); - } + { + if (!no_static) + { + static_model.writeStaticFile(basename, block, byte_code, use_dll, false); + static_model.writeParamsDerivativesFile(basename, false); + } - dynamic_model.writeDynamicFile(basename, block, byte_code, use_dll, mod_file_struct.order_option, false); - dynamic_model.writeParamsDerivativesFile(basename, false); - } + dynamic_model.writeDynamicFile(basename, block, byte_code, use_dll, mod_file_struct.order_option, false); + dynamic_model.writeParamsDerivativesFile(basename, false); + } // Create steady state file steady_state_model.writeSteadyStateFile(basename, mod_file_struct.ramsey_model_present, false); @@ -898,7 +897,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo void ModFile::writeExternalFiles(const string &basename, FileOutputType output, LanguageOutputType language) const { - switch(language) + switch (language) { case c: writeExternalFilesC(basename, output); @@ -926,7 +925,6 @@ ModFile::writeExternalFilesC(const string &basename, FileOutputType output) cons if (!no_static) static_model.writeStaticFile(basename, false, false, true, false); - // static_model.writeStaticCFile(basename, block, byte_code, use_dll); // static_model.writeParamsDerivativesFileC(basename, cuda); // static_model.writeAuxVarInitvalC(mOutputFile, oMatlabOutsideModel, cuda); @@ -939,8 +937,8 @@ ModFile::writeExternalFilesC(const string &basename, FileOutputType output) cons dynamic_model.writeSecondDerivativesC_csr(basename, cuda); else if (output == third) { - dynamic_model.writeSecondDerivativesC_csr(basename, cuda); - dynamic_model.writeThirdDerivativesC_csr(basename, cuda); + dynamic_model.writeSecondDerivativesC_csr(basename, cuda); + dynamic_model.writeThirdDerivativesC_csr(basename, cuda); } } @@ -984,7 +982,7 @@ ModFile::writeModelC(const string &basename) const // Print statements for (vector::const_iterator it = statements.begin(); it != statements.end(); it++) - (*it)->writeCOutput(mDriverCFile, basename); + (*it)->writeCOutput(mDriverCFile, basename); mDriverCFile << "} DynareInfo;" << endl; mDriverCFile.close(); @@ -1044,8 +1042,8 @@ ModFile::writeExternalFilesCC(const string &basename, FileOutputType output) con dynamic_model.writeSecondDerivativesC_csr(basename, cuda); else if (output == third) { - dynamic_model.writeSecondDerivativesC_csr(basename, cuda); - dynamic_model.writeThirdDerivativesC_csr(basename, cuda); + dynamic_model.writeSecondDerivativesC_csr(basename, cuda); + dynamic_model.writeThirdDerivativesC_csr(basename, cuda); } } @@ -1089,7 +1087,7 @@ ModFile::writeModelCC(const string &basename) const // Print statements for (vector::const_iterator it = statements.begin(); it != statements.end(); it++) - (*it)->writeCOutput(mDriverCFile, basename); + (*it)->writeCOutput(mDriverCFile, basename); mDriverCFile << "};" << endl; mDriverCFile.close(); @@ -1165,7 +1163,7 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output) << "if isfile(\"" << basename << "SteadyState2.jl" "\")" << endl << " using " << basename << "SteadyState2" << endl << "end" << endl << endl - << "export model_, options_, oo_" << endl; + << "export model_, options_, oo_" << endl; // Write Output jlOutputFile << endl @@ -1223,9 +1221,9 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output) steady_state_model.writeSteadyStateFile(basename, mod_file_struct.ramsey_model_present, true); // Print statements (includes parameter values) - for (vector::const_iterator it = statements.begin(); - it != statements.end(); it++) - (*it)->writeJuliaOutput(jlOutputFile, basename); + for (vector::const_iterator it = statements.begin(); + it != statements.end(); it++) + (*it)->writeJuliaOutput(jlOutputFile, basename); jlOutputFile << "model_.static = " << basename << "Static.static!" << endl << "model_.dynamic = " << basename << "Dynamic.dynamic!" << endl @@ -1245,7 +1243,7 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output) << " using " << basename << "DynamicParamsDerivs" << endl << " model_.dynamic_params_derivs = " << basename << "DynamicParamsDerivs.params_derivs" << endl << "end" << endl - << "end" << endl; + << "end" << endl; jlOutputFile.close(); cout << "done" << endl; } @@ -1331,11 +1329,11 @@ ModFile::writeJsonOutputParsingCheck(const string &basename, JsonFileOutputType exit(EXIT_FAILURE); } } - else - { - cerr << "ERROR: Missing file name" << endl; - exit(EXIT_FAILURE); - } + else + { + cerr << "ERROR: Missing file name" << endl; + exit(EXIT_FAILURE); + } jsonOutputFile << output.str(); jsonOutputFile.close(); diff --git a/ModFile.hh b/ModFile.hh index 935c5231..d8bb587c 100644 --- a/ModFile.hh +++ b/ModFile.hh @@ -41,7 +41,7 @@ using namespace std; // for checksum computation #ifndef PRIVATE_BUFFER_SIZE -#define PRIVATE_BUFFER_SIZE 1024 +# define PRIVATE_BUFFER_SIZE 1024 #endif //! The abstract representation of a "mod" file @@ -91,9 +91,9 @@ public: bool differentiate_forward_vars; /*! If the 'differentiate_forward_vars' option is used, contains the set of - endogenous with respect to which to do the transformation; - if empty, means that the transformation must be applied to all endos - with a lead */ + endogenous with respect to which to do the transformation; + if empty, means that the transformation must be applied to all endos + with a lead */ vector differentiate_forward_vars_subset; //! Are nonstationary variables present ? diff --git a/ModelTree.cc b/ModelTree.cc index 20490239..ecfb7fee 100644 --- a/ModelTree.cc +++ b/ModelTree.cc @@ -212,7 +212,7 @@ ModelTree::computeNonSingularNormalization(jacob_map_t &contemporaneous_jacobian if (first_derivatives.find(make_pair(it->first.first, getDerivID(symbol_table.getID(eEndogenous, it->first.second), 0))) == first_derivatives.end()) first_derivatives[make_pair(it->first.first, getDerivID(symbol_table.getID(eEndogenous, it->first.second), 0))] = Zero; } - catch(DataTree::UnknownDerivIDException &e) + catch (DataTree::UnknownDerivIDException &e) { cerr << "The variable " << symbol_table.getName(symbol_table.getID(eEndogenous, it->first.second)) << " does not appear at the current period (i.e. with no lead and no lag); this case is not handled by the 'block' option of the 'model' block." << endl; @@ -332,19 +332,19 @@ ModelTree::computePrologueAndEpilogue(const jacob_map_t &static_jacobian_arg, ve eq2endo[*it] = i; equation_reordered[i] = i; variable_reordered[*it] = i; - } - if (cutoff == 0) - { + } + if (cutoff == 0) + { set > endo; for (int i = 0; i < n; i++) - { + { endo.clear(); - equations[i]->collectEndogenous(endo); - for (set >::const_iterator it = endo.begin(); it != endo.end(); it++) - IM[i * n + endo2eq[it->first]] = true; - } - } - else + equations[i]->collectEndogenous(endo); + for (set >::const_iterator it = endo.begin(); it != endo.end(); it++) + IM[i * n + endo2eq[it->first]] = true; + } + } + else for (jacob_map_t::const_iterator it = static_jacobian_arg.begin(); it != static_jacobian_arg.end(); it++) IM[it->first.first * n + endo2eq[it->first.second]] = true; bool something_has_been_done = true; @@ -546,22 +546,22 @@ ModelTree::computeBlockDecompositionAndFeedbackVariablesForEachBlock(const jacob { reverse_equation_reordered[equation_reordered[i]] = i; reverse_variable_reordered[variable_reordered[i]] = i; - } - jacob_map_t tmp_normalized_contemporaneous_jacobian; - if (cutoff == 0) - { + } + jacob_map_t tmp_normalized_contemporaneous_jacobian; + if (cutoff == 0) + { set > endo; for (int i = 0; i < nb_var; i++) - { + { endo.clear(); - equations[i]->collectEndogenous(endo); - for (set >::const_iterator it = endo.begin(); it != endo.end(); it++) - tmp_normalized_contemporaneous_jacobian[make_pair(i, it->first)] = 1; + equations[i]->collectEndogenous(endo); + for (set >::const_iterator it = endo.begin(); it != endo.end(); it++) + tmp_normalized_contemporaneous_jacobian[make_pair(i, it->first)] = 1; - } - } - else - tmp_normalized_contemporaneous_jacobian = static_jacobian; + } + } + else + tmp_normalized_contemporaneous_jacobian = static_jacobian; for (jacob_map_t::const_iterator it = tmp_normalized_contemporaneous_jacobian.begin(); it != tmp_normalized_contemporaneous_jacobian.end(); it++) if (reverse_equation_reordered[it->first.first] >= (int) prologue && reverse_equation_reordered[it->first.first] < (int) (nb_var - epilogue) && reverse_variable_reordered[it->first.second] >= (int) prologue && reverse_variable_reordered[it->first.second] < (int) (nb_var - epilogue) @@ -887,7 +887,7 @@ ModelTree::reduceBlocksAndTypeDetermination(const dynamic_jacob_map_t &dynamic_j int c_Size = (block_type_size_mfs[block_type_size_mfs.size()-1]).second.first; int first_equation = (block_type_size_mfs[block_type_size_mfs.size()-1]).first.second; if (c_Size > 0 && ((prev_Type == EVALUATE_FORWARD && Simulation_Type == EVALUATE_FORWARD && !is_lead) - || (prev_Type == EVALUATE_BACKWARD && Simulation_Type == EVALUATE_BACKWARD && !is_lag))) + || (prev_Type == EVALUATE_BACKWARD && Simulation_Type == EVALUATE_BACKWARD && !is_lag))) { for (int j = first_equation; j < first_equation+c_Size; j++) { @@ -1125,10 +1125,10 @@ ModelTree::computeTemporaryTerms(bool is_matlab) temporary_terms_g2.clear(); temporary_terms_g3.clear(); map temp_terms_map; - temp_terms_map[eResiduals]=temporary_terms_res; - temp_terms_map[eFirstDeriv]=temporary_terms_g1; - temp_terms_map[eSecondDeriv]=temporary_terms_g2; - temp_terms_map[eThirdDeriv]=temporary_terms_g3; + temp_terms_map[eResiduals] = temporary_terms_res; + temp_terms_map[eFirstDeriv] = temporary_terms_g1; + temp_terms_map[eSecondDeriv] = temporary_terms_g2; + temp_terms_map[eThirdDeriv] = temporary_terms_g3; for (vector::iterator it = equations.begin(); it != equations.end(); it++) @@ -1386,17 +1386,17 @@ ModelTree::compileTemporaryTerms(ostream &code_file, unsigned int &instruction_n (*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt2, map_idx, dynamic, steady_dynamic, tef_terms); } - FNUMEXPR_ fnumexpr(TemporaryTerm, (int) (map_idx.find((*it)->idx)->second)); + FNUMEXPR_ fnumexpr(TemporaryTerm, (int)(map_idx.find((*it)->idx)->second)); fnumexpr.write(code_file, instruction_number); (*it)->compile(code_file, instruction_number, false, tt2, map_idx, dynamic, steady_dynamic, tef_terms); if (dynamic) { - FSTPT_ fstpt((int) (map_idx.find((*it)->idx)->second)); + FSTPT_ fstpt((int)(map_idx.find((*it)->idx)->second)); fstpt.write(code_file, instruction_number); } else { - FSTPST_ fstpst((int) (map_idx.find((*it)->idx)->second)); + FSTPST_ fstpst((int)(map_idx.find((*it)->idx)->second)); fstpst.write(code_file, instruction_number); } // Insert current node into tt2 @@ -1871,11 +1871,11 @@ ModelTree::computeParamsDerivativesTemporaryTerms() map > reference_count; params_derivs_temporary_terms.clear(); map temp_terms_map; - temp_terms_map[eResidualsParamsDeriv]=params_derivs_temporary_terms_res; - temp_terms_map[eJacobianParamsDeriv]=params_derivs_temporary_terms_g1; - temp_terms_map[eResidualsParamsSecondDeriv]=params_derivs_temporary_terms_res2; - temp_terms_map[eJacobianParamsSecondDeriv]=params_derivs_temporary_terms_g12; - temp_terms_map[eHessianParamsDeriv]=params_derivs_temporary_terms_g2; + temp_terms_map[eResidualsParamsDeriv] = params_derivs_temporary_terms_res; + temp_terms_map[eJacobianParamsDeriv] = params_derivs_temporary_terms_g1; + temp_terms_map[eResidualsParamsSecondDeriv] = params_derivs_temporary_terms_res2; + temp_terms_map[eJacobianParamsSecondDeriv] = params_derivs_temporary_terms_g12; + temp_terms_map[eHessianParamsDeriv] = params_derivs_temporary_terms_g2; for (first_derivatives_t::iterator it = residuals_params_derivatives.begin(); it != residuals_params_derivatives.end(); it++) @@ -1918,7 +1918,8 @@ ModelTree::computeParamsDerivativesTemporaryTerms() params_derivs_temporary_terms_g2 = temp_terms_map[eHessianParamsDeriv]; } -bool ModelTree::isNonstationary(int symb_id) const +bool +ModelTree::isNonstationary(int symb_id) const { return (nonstationary_symbols_map.find(symb_id) != nonstationary_symbols_map.end()); @@ -1928,7 +1929,7 @@ void ModelTree::writeJsonModelEquations(ostream &output, bool residuals) const { deriv_node_temp_terms_t tef_terms; - vector > eqtags; + vector > eqtags; temporary_terms_t tt_empty; if (residuals) output << endl << "\"residuals\":[" << endl; @@ -1986,7 +1987,7 @@ ModelTree::writeJsonModelEquations(ostream &output, bool residuals) const { output << ", \"tags\": {"; int i = 0; - for (vector >:: const_iterator it = eqtags.begin(); it != eqtags.end(); it++, i++) + for (vector >::const_iterator it = eqtags.begin(); it != eqtags.end(); it++, i++) { if (i != 0) output << ", "; diff --git a/ModelTree.hh b/ModelTree.hh index 057bfc8e..8a9a6877 100644 --- a/ModelTree.hh +++ b/ModelTree.hh @@ -128,7 +128,6 @@ protected: */ third_derivatives_t hessian_params_derivatives; - //! Temporary terms for the static/dynamic file (those which will be noted Txxxx) temporary_terms_t temporary_terms; temporary_terms_t temporary_terms_res; @@ -144,7 +143,6 @@ protected: temporary_terms_t params_derivs_temporary_terms_g12; temporary_terms_t params_derivs_temporary_terms_g2; - //! Trend variables and their growth factors map trend_symbols_map; @@ -177,7 +175,7 @@ protected: void computeTemporaryTerms(bool is_matlab); //! Computes temporary terms for the file containing parameters derivatives void computeParamsDerivativesTemporaryTerms(); -//! Writes temporary terms + //! Writes temporary terms void writeTemporaryTerms(const temporary_terms_t &tt, const temporary_terms_t &ttm1, ostream &output, ExprNodeOutputType output_type, deriv_node_temp_terms_t &tef_terms) const; void writeJsonTemporaryTerms(const temporary_terms_t &tt, const temporary_terms_t &ttm1, ostream &output, deriv_node_temp_terms_t &tef_terms, string &concat) const; //! Compiles temporary terms @@ -274,11 +272,12 @@ protected: virtual unsigned int getBlockMaxLag(int block_number) const = 0; //! Return the maximum lead in a block virtual unsigned int getBlockMaxLead(int block_number) const = 0; - inline void setBlockLeadLag(int block, int max_lag, int max_lead) - { - block_lag_lead[block] = make_pair(max_lag, max_lead); - }; - + inline void + setBlockLeadLag(int block, int max_lag, int max_lead) + { + block_lag_lead[block] = make_pair(max_lag, max_lead); + }; + //! Return the type of equation (equation_number) belonging to the block block_number virtual EquationType getBlockEquationType(int block_number, int equation_number) const = 0; //! Return true if the equation has been normalized diff --git a/ParsingDriver.cc b/ParsingDriver.cc index 3129df07..2fbab28f 100644 --- a/ParsingDriver.cc +++ b/ParsingDriver.cc @@ -134,7 +134,7 @@ ParsingDriver::create_error_string(const Dynare::parser::location_type &l, const stream << ", cols " << l.begin.column << "-" << l.end.column - 1; else stream << ", col " << l.begin.column << " -" - << " line " << l.end.line << ", col " << l.end.column - 1; + << " line " << l.end.line << ", col " << l.end.column - 1; stream << ": " << m << endl; } @@ -259,8 +259,8 @@ void ParsingDriver::declare_statement_local_variable(string *name) { if (mod_file->symbol_table.exists(*name)) - error("Symbol " + *name + " cannot be assigned within a statement " + - "while being assigned elsewhere in the modfile"); + error("Symbol " + *name + " cannot be assigned within a statement " + +"while being assigned elsewhere in the modfile"); declare_symbol(name, eStatementDeclaredVariable, NULL, NULL); delete name; } @@ -366,7 +366,7 @@ ParsingDriver::add_model_variable(string *name) { // This could be endog or param too. Just declare something to continue parsing, // knowing that processing will end at the end of parsing of the model block - declare_exogenous(new string (*name)); + declare_exogenous(new string(*name)); undeclared_model_vars.insert(*name); symb_id = mod_file->symbol_table.getID(*name); } @@ -752,7 +752,7 @@ ParsingDriver::add_det_shock(string *var, bool conditional_forecast) } det_shocks[symb_id] = v; - + det_shocks_periods.clear(); det_shocks_values.clear(); delete var; @@ -888,7 +888,7 @@ ParsingDriver::end_svar_identification() mod_file->addStatement(new SvarIdentificationStatement(svar_ident_restrictions, svar_upper_cholesky, svar_lower_cholesky, - svar_constants_exclusion, + svar_constants_exclusion, mod_file->symbol_table)); svar_restriction_symbols.clear(); svar_equation_restrictions.clear(); @@ -910,19 +910,19 @@ ParsingDriver::combine_lag_and_restriction(string *lag) for (map >::const_iterator it = svar_equation_restrictions.begin(); it != svar_equation_restrictions.end(); it++) for (vector::const_iterator it1 = it->second.begin(); - it1 != it->second.end(); it1++) + it1 != it->second.end(); it1++) { - SvarIdentificationStatement::svar_identification_restriction new_restriction; - new_restriction.equation = it->first; - if (current_lag > 0) - new_restriction.restriction_nbr = ++svar_Ri_restriction_nbr[it->first]; - else - new_restriction.restriction_nbr = ++svar_Qi_restriction_nbr[it->first]; - new_restriction.lag = current_lag; - new_restriction.variable = *it1; - new_restriction.value = data_tree->One; - svar_ident_restrictions.push_back(new_restriction); - } + SvarIdentificationStatement::svar_identification_restriction new_restriction; + new_restriction.equation = it->first; + if (current_lag > 0) + new_restriction.restriction_nbr = ++svar_Ri_restriction_nbr[it->first]; + else + new_restriction.restriction_nbr = ++svar_Qi_restriction_nbr[it->first]; + new_restriction.lag = current_lag; + new_restriction.variable = *it1; + new_restriction.value = data_tree->One; + svar_ident_restrictions.push_back(new_restriction); + } // svar_ident_exclusion_values[make_pair(current_lag, it->first)] = it->second; svar_upper_cholesky = false; @@ -962,7 +962,7 @@ ParsingDriver::add_in_svar_restriction_symbols(string *tmp_var) delete tmp_var; } -void +void ParsingDriver::add_restriction_equation_nbr(string *eq_nbr) { svar_equation_nbr = atoi(eq_nbr->c_str()); @@ -986,14 +986,14 @@ ParsingDriver::add_positive_restriction_element(expr_t value, string *variable, // if the expression is not on the left handside, change its sign if (!svar_left_handside) value = add_uminus(value); - + add_restriction_element(value, variable, lag); } void ParsingDriver::add_positive_restriction_element(string *variable, string *lag) { - expr_t value(data_tree->One); + expr_t value(data_tree->One); // if the expression is not on the left handside, change its sign if (!svar_left_handside) @@ -1015,7 +1015,7 @@ ParsingDriver::add_negative_restriction_element(expr_t value, string *variable, void ParsingDriver::add_negative_restriction_element(string *variable, string *lag) { - expr_t value(data_tree->One); + expr_t value(data_tree->One); // if the expression is on the left handside, change its sign if (svar_left_handside) @@ -1034,21 +1034,21 @@ ParsingDriver::add_restriction_element(expr_t value, string *variable, string *l if (svar_restriction_type == ParsingDriver::NOT_SET) { if (current_lag == 0) - { - svar_restriction_type = ParsingDriver::Qi_TYPE; - ++svar_Qi_restriction_nbr[svar_equation_nbr]; - } + { + svar_restriction_type = ParsingDriver::Qi_TYPE; + ++svar_Qi_restriction_nbr[svar_equation_nbr]; + } else - { - svar_restriction_type = ParsingDriver::Ri_TYPE; - ++svar_Ri_restriction_nbr[svar_equation_nbr]; - } + { + svar_restriction_type = ParsingDriver::Ri_TYPE; + ++svar_Ri_restriction_nbr[svar_equation_nbr]; + } } else { if ((svar_restriction_type == Qi_TYPE && current_lag > 0) - || (svar_restriction_type == Ri_TYPE && current_lag == 0)) - error("SVAR_IDENTIFICATION: a single restrictions must affect either Qi or Ri, but not both"); + || (svar_restriction_type == Ri_TYPE && current_lag == 0)) + error("SVAR_IDENTIFICATION: a single restrictions must affect either Qi or Ri, but not both"); } SvarIdentificationStatement::svar_identification_restriction new_restriction; new_restriction.equation = svar_equation_nbr; @@ -1213,7 +1213,7 @@ ParsingDriver::option_symbol_list(const string &name_option) != options_list.symbol_list_options.end()) error("option " + name_option + " declared twice"); - if (name_option.compare("irf_shocks")==0) + if (name_option.compare("irf_shocks") == 0) { vector shocks = symbol_list.get_symbols(); for (vector::const_iterator it = shocks.begin(); @@ -1222,7 +1222,7 @@ ParsingDriver::option_symbol_list(const string &name_option) error("Variables passed to irf_shocks must be exogenous. Caused by: " + *it); } - if (name_option.compare("ms.parameters")==0) + if (name_option.compare("ms.parameters") == 0) { vector parameters = symbol_list.get_symbols(); for (vector::const_iterator it = parameters.begin(); @@ -1415,7 +1415,7 @@ ParsingDriver::copy_subsamples(string *to_name1, string *to_name2, string *from_ if (!from_name2->empty()) check_symbol_existence(*from_name2); - if (subsample_declarations.find(make_pair(*from_name1,*from_name2)) == subsample_declarations.end()) + if (subsample_declarations.find(make_pair(*from_name1, *from_name2)) == subsample_declarations.end()) { string err = *from_name1; if (!from_name2->empty()) @@ -1426,8 +1426,8 @@ ParsingDriver::copy_subsamples(string *to_name1, string *to_name2, string *from_ mod_file->addStatement(new SubsamplesEqualStatement(*to_name1, *to_name2, *from_name1, *from_name2, mod_file->symbol_table)); - subsample_declarations[make_pair(*to_name1, *to_name2)] = - subsample_declarations[make_pair(*from_name1, *from_name2)]; + subsample_declarations[make_pair(*to_name1, *to_name2)] + = subsample_declarations[make_pair(*from_name1, *from_name2)]; delete to_name1; delete to_name2; @@ -1461,7 +1461,7 @@ ParsingDriver::check_subsample_declaration_exists(string *name1, string *subsamp if (subsample_name->empty()) return; - string *str_empty = new string (""); + string *str_empty = new string(""); check_subsample_declaration_exists(name1, str_empty, subsample_name); delete str_empty; } @@ -1474,13 +1474,13 @@ ParsingDriver::check_subsample_declaration_exists(string *name1, string *name2, check_symbol_existence(*name1); if (!name2->empty()) - check_symbol_existence(*name2); + check_symbol_existence(*name2); subsample_declarations_t::const_iterator it = subsample_declarations.find(make_pair(*name1, *name2)); if (it == subsample_declarations.end()) { it = subsample_declarations.find(make_pair(*name2, *name1)); - if (it== subsample_declarations.end()) + if (it == subsample_declarations.end()) { string err = *name1; if (!name2->empty()) @@ -1494,7 +1494,6 @@ ParsingDriver::check_subsample_declaration_exists(string *name1, string *name2, error("The subsample name " + *subsample_name + " was not previously declared in a subsample statement."); } - void ParsingDriver::set_prior(string *name, string *subsample_name) { @@ -1509,9 +1508,9 @@ ParsingDriver::set_prior(string *name, string *subsample_name) } void -ParsingDriver::set_joint_prior(vector*symbol_vec) +ParsingDriver::set_joint_prior(vector *symbol_vec) { - for (vector::const_iterator it=symbol_vec->begin(); it != symbol_vec->end(); it++) + for (vector::const_iterator it = symbol_vec->begin(); it != symbol_vec->end(); it++) add_joint_parameter(*it); mod_file->addStatement(new JointPriorStatement(joint_parameters, prior_shape, options_list)); joint_parameters.clear(); @@ -1621,7 +1620,7 @@ ParsingDriver::check_symbol_is_endogenous_or_exogenous(string *name) { check_symbol_existence(*name); int symb_id = mod_file->symbol_table.getID(*name); - switch(mod_file->symbol_table.getType(symb_id)) + switch (mod_file->symbol_table.getType(symb_id)) { case eEndogenous: case eExogenous: @@ -2034,7 +2033,7 @@ ParsingDriver::ms_compute_probabilities() void ParsingDriver::ms_irf() { - mod_file->addStatement(new MSSBVARIrfStatement(symbol_list,options_list)); + mod_file->addStatement(new MSSBVARIrfStatement(symbol_list, options_list)); symbol_list.clear(); options_list.clear(); } @@ -2175,7 +2174,7 @@ ParsingDriver::add_model_equal(expr_t arg1, expr_t arg2) expr_t id = model_tree->AddEqual(arg1, arg2); // Detect if the equation is tagged [static] - bool is_static_only = false; + bool is_static_only = false; for (vector >::const_iterator it = eq_tags.begin(); it != eq_tags.end(); ++it) if (it->first == "static") @@ -2188,7 +2187,7 @@ ParsingDriver::add_model_equal(expr_t arg1, expr_t arg2) { if (!id->isInStaticForm()) error("An equation tagged [static] cannot contain leads, lags, expectations or STEADY_STATE operators"); - + dynamic_model->addStaticOnlyEquation(id, location.begin.line); } else @@ -2681,7 +2680,7 @@ ParsingDriver::add_model_var_or_external_function(string *function_name, bool in if (rv.first) { // assume it's a lead/lagged variable - declare_exogenous(new string (*function_name)); + declare_exogenous(new string(*function_name)); return add_model_variable(mod_file->symbol_table.getID(*function_name), (int) rv.second); } else @@ -2839,18 +2838,19 @@ ParsingDriver::add_moment_calibration_item(string *endo1, string *endo2, string c.lags = *lags; delete lags; - + assert(range->size() == 2); c.lower_bound = *((*range)[0]); c.upper_bound = *((*range)[1]); delete (*range)[0]; delete (*range)[1]; delete range; - + moment_calibration_constraints.push_back(c); } -void ParsingDriver::end_moment_calibration() +void +ParsingDriver::end_moment_calibration() { mod_file->addStatement(new MomentCalibration(moment_calibration_constraints, mod_file->symbol_table)); @@ -2876,18 +2876,19 @@ ParsingDriver::add_irf_calibration_item(string *endo, string *periods, string *e if (mod_file->symbol_table.getType(*exo) != eExogenous) error("Variable " + *endo + " is not an exogenous."); delete exo; - + assert(range->size() == 2); c.lower_bound = *((*range)[0]); c.upper_bound = *((*range)[1]); delete (*range)[0]; delete (*range)[1]; delete range; - + irf_calibration_constraints.push_back(c); } -void ParsingDriver::end_irf_calibration() +void +ParsingDriver::end_irf_calibration() { mod_file->addStatement(new IrfCalibration(irf_calibration_constraints, mod_file->symbol_table, @@ -2909,7 +2910,6 @@ ParsingDriver::histval_file(string *filename) delete filename; } - void ParsingDriver::perfect_foresight_setup() { @@ -2927,7 +2927,7 @@ ParsingDriver::perfect_foresight_solver() void ParsingDriver::prior_posterior_function(bool prior_func) { - mod_file->addStatement(new PriorPosteriorFunctionStatement((bool)prior_func, options_list)); + mod_file->addStatement(new PriorPosteriorFunctionStatement((bool) prior_func, options_list)); options_list.clear(); } @@ -2941,25 +2941,25 @@ ParsingDriver::add_ramsey_constraints_statement() void ParsingDriver::ramsey_constraint_add_less(const string *name, const expr_t rhs) { - add_ramsey_constraint(name,oLess,rhs); + add_ramsey_constraint(name, oLess, rhs); } void ParsingDriver::ramsey_constraint_add_greater(const string *name, const expr_t rhs) { - add_ramsey_constraint(name,oGreater,rhs); + add_ramsey_constraint(name, oGreater, rhs); } void ParsingDriver::ramsey_constraint_add_less_equal(const string *name, const expr_t rhs) { - add_ramsey_constraint(name,oLessEqual,rhs); + add_ramsey_constraint(name, oLessEqual, rhs); } void ParsingDriver::ramsey_constraint_add_greater_equal(const string *name, const expr_t rhs) { - add_ramsey_constraint(name,oGreaterEqual,rhs); + add_ramsey_constraint(name, oGreaterEqual, rhs); } void @@ -2996,7 +2996,6 @@ ParsingDriver::add_shock_group_element(string *name) delete name; } - void ParsingDriver::add_shock_group(string *name) { diff --git a/ParsingDriver.hh b/ParsingDriver.hh index 8eb7ba6d..ad9a75e3 100644 --- a/ParsingDriver.hh +++ b/ParsingDriver.hh @@ -171,7 +171,7 @@ private: map > svar_equation_restrictions; //! Temporary storage for restrictions in an equation within an svar_identification block vector svar_restriction_symbols; - //! Temporary storage for constants exculsion within an svar_identification + //! Temporary storage for constants exculsion within an svar_identification bool svar_constants_exclusion; //! Temporary storage for upper cholesky within an svar_identification block bool svar_upper_cholesky; @@ -182,8 +182,8 @@ private: //! Temporary storage for left/right handside of a restriction equation within an svar_identificaton block bool svar_left_handside; //! Temporary storage for current restriction number in svar_identification block - map svar_Qi_restriction_nbr; - map svar_Ri_restriction_nbr; + map svar_Qi_restriction_nbr; + map svar_Ri_restriction_nbr; //! Stores undeclared model variables set undeclared_model_vars; //! Temporary storage for restriction type @@ -239,7 +239,9 @@ private: ostringstream model_errors; public: - ParsingDriver(WarningConsolidation &warnings_arg, bool nostrict_arg) : warnings(warnings_arg), nostrict(nostrict_arg), model_error_encountered(false) { }; + ParsingDriver(WarningConsolidation &warnings_arg, bool nostrict_arg) : warnings(warnings_arg), nostrict(nostrict_arg), model_error_encountered(false) + { + }; //! Starts parsing, and constructs the MOD file representation /*! The returned pointer should be deleted after use */ @@ -449,11 +451,11 @@ public: //! Sets the prior for a parameter void set_prior(string *arg1, string *arg2); //! Sets the joint prior for a set of parameters - void set_joint_prior(vector*symbol_vec); + void set_joint_prior(vector *symbol_vec); //! Adds a parameters to the list of joint parameters void add_joint_parameter(string *name); //! Adds the variance option to its temporary holding place - void set_prior_variance(expr_t variance=NULL); + void set_prior_variance(expr_t variance = NULL); //! Copies the prior from_name to_name void copy_prior(string *to_declaration_type, string *to_name1, string *to_name2, string *to_subsample_name, string *from_declaration_type, string *from_name1, string *from_name2, string *from_subsample_name); @@ -468,7 +470,7 @@ public: void set_std_options(string *arg1, string *arg2); //! Sets the prior for estimated correlation void set_corr_prior(string *arg1, string *arg2, string *arg3); - //! Sets the options for estimated correlation + //! Sets the options for estimated correlation void set_corr_options(string *arg1, string *arg2, string *arg3); //! Runs estimation process void run_estimation(); @@ -501,11 +503,11 @@ public: void add_restriction_equation_nbr(string *eq_nbr); //! Svar_Identification Statement: record presence of equal sign void add_restriction_equal(); - //! Svar_Idenditification Statement: add coefficient of a linear restriction (positive value) + //! Svar_Idenditification Statement: add coefficient of a linear restriction (positive value) void add_positive_restriction_element(expr_t value, string *variable, string *lag); - //! Svar_Idenditification Statement: add unit coefficient of a linear restriction + //! Svar_Idenditification Statement: add unit coefficient of a linear restriction void add_positive_restriction_element(string *variable, string *lag); - //! Svar_Idenditification Statement: add coefficient of a linear restriction (negative value) + //! Svar_Idenditification Statement: add coefficient of a linear restriction (negative value) void add_negative_restriction_element(expr_t value, string *variable, string *lag); //! Svar_Idenditification Statement: add negative unit coefficient of a linear restriction void add_negative_restriction_element(string *variable, string *lag); @@ -534,7 +536,7 @@ public: void run_load_params_and_steady_state(string *filename); void run_save_params_and_steady_state(string *filename); void run_identification(); - void add_mc_filename(string *filename, string *prior = new string("1")); + void add_mc_filename(string *filename, string *prior = new string ("1")); void run_model_comparison(); //! Begin a planner_objective statement void begin_planner_objective(); diff --git a/Shocks.cc b/Shocks.cc index 4835b370..5a932061 100644 --- a/Shocks.cc +++ b/Shocks.cc @@ -79,17 +79,17 @@ AbstractShocksStatement::writeJsonDetShocks(ostream &output) const output << ", "; output << "{\"var\": \"" << symbol_table.getName(it->first) << "\", " << "\"values\": ["; - for (vector::const_iterator it1 = it->second.begin(); - it1 != it->second.end(); it1++) - { - if (it1 != it->second.begin()) - output << ", "; - output << "{\"period1\": " << it1->period1 << ", " - << "\"period2\": " << it1->period2 << ", " - << "\"value\": \""; - it1->value->writeJsonOutput(output, temporary_terms_t(), tef_terms); - output << "\"}"; - } + for (vector::const_iterator it1 = it->second.begin(); + it1 != it->second.end(); it1++) + { + if (it1 != it->second.begin()) + output << ", "; + output << "{\"period1\": " << it1->period1 << ", " + << "\"period2\": " << it1->period2 << ", " + << "\"value\": \""; + it1->value->writeJsonOutput(output, temporary_terms_t(), tef_terms); + output << "\"}"; + } output << "]}"; } output << "]"; @@ -122,9 +122,9 @@ ShocksStatement::writeOutput(ostream &output, const string &basename, bool minim output << "M_.det_shocks = [];" << endl; output << "M_.Sigma_e = zeros(" << symbol_table.exo_nbr() << ", " - << symbol_table.exo_nbr() << ");" << endl - << "M_.Correlation_matrix = eye(" << symbol_table.exo_nbr() << ", " - << symbol_table.exo_nbr() << ");" << endl; + << symbol_table.exo_nbr() << ");" << endl + << "M_.Correlation_matrix = eye(" << symbol_table.exo_nbr() << ", " + << symbol_table.exo_nbr() << ");" << endl; if (has_calibrated_measurement_errors()) output << "M_.H = zeros(" << symbol_table.observedVariablesNbr() << ", " @@ -151,7 +151,6 @@ ShocksStatement::writeOutput(ostream &output, const string &basename, bool minim output << "M_.sigma_e_is_diagonal = 1;" << endl; } - void ShocksStatement::writeJsonOutput(ostream &output) const { @@ -349,7 +348,7 @@ ShocksStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidati { int symb_id1 = it->first.first; int symb_id2 = it->first.second; - + if (!((symbol_table.getType(symb_id1) == eExogenous && symbol_table.getType(symb_id2) == eExogenous) || (symbol_table.isObservedVariable(symb_id1) @@ -367,7 +366,7 @@ ShocksStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidati { int symb_id1 = it->first.first; int symb_id2 = it->first.second; - + if (!((symbol_table.getType(symb_id1) == eExogenous && symbol_table.getType(symb_id2) == eExogenous) || (symbol_table.isObservedVariable(symb_id1) @@ -606,7 +605,7 @@ ShockGroupsStatement::writeOutput(ostream &output, const string &basename, bool { int i = 1; bool unique_label = true; - for (vector::const_iterator it = shock_groups.begin(); it != shock_groups.end(); it++, unique_label=true) + for (vector::const_iterator it = shock_groups.begin(); it != shock_groups.end(); it++, unique_label = true) { for (vector::const_iterator it1 = it+1; it1 != shock_groups.end(); it1++) if (it->name == it1->name) @@ -623,7 +622,7 @@ ShockGroupsStatement::writeOutput(ostream &output, const string &basename, bool << ".group" << i << ".label = '" << it->name << "';" << endl << "M_.shock_groups." << name << ".group" << i << ".shocks = {"; - for ( vector::const_iterator it1 = it->list.begin(); it1 != it->list.end(); it1++) + for (vector::const_iterator it1 = it->list.begin(); it1 != it->list.end(); it1++) output << " '" << *it1 << "'"; output << "};" << endl; i++; diff --git a/Shocks.hh b/Shocks.hh index 76f49ffe..618bf34b 100644 --- a/Shocks.hh +++ b/Shocks.hh @@ -164,5 +164,5 @@ public: ShockGroupsStatement(const group_t &shock_groups_arg, const string &name_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; }; - + #endif diff --git a/Statement.cc b/Statement.cc index 82ced981..e3e54b3b 100644 --- a/Statement.cc +++ b/Statement.cc @@ -78,11 +78,13 @@ Statement::writeCOutput(ostream &output, const string &basename) { } -void Statement::writeJuliaOutput(ostream &output, const string &basename) +void +Statement::writeJuliaOutput(ostream &output, const string &basename) { } -void Statement::writeJsonOutput(ostream &output) const +void +Statement::writeJsonOutput(ostream &output) const { } @@ -105,7 +107,7 @@ NativeStatement::writeOutput(ostream &output, const string &basename, bool minim sregex regex_dollar = sregex::compile("(\\$)"+date_regex); string ns = regex_replace(native_statement, regex_lookbehind, "dates('$&')"); - ns = regex_replace(ns, regex_dollar, "$2" ); //replace $DATE with DATE + ns = regex_replace(ns, regex_dollar, "$2"); //replace $DATE with DATE output << ns << endl; } @@ -182,9 +184,9 @@ OptionsList::writeOutput(ostream &output, const string &option_group) const { // Initialize option_group as an empty struct iff the field does not exist! unsigned idx = option_group.find_last_of("."); - if (idxfirst << "\": " << it->second; it++; - if (it != num_options.end() || - !(paired_num_options.empty() && - string_options.empty() && - date_options.empty() && - symbol_list_options.empty() && - vector_int_options.empty())) + if (it != num_options.end() + || !(paired_num_options.empty() + && string_options.empty() + && date_options.empty() + && symbol_list_options.empty() + && vector_int_options.empty())) output << ", "; } @@ -255,11 +257,11 @@ OptionsList::writeJsonOutput(ostream &output) const { output << "\""<< it->first << "\": [" << it->second.first << " " << it->second.second << "]"; it++; - if (it != paired_num_options.end() || - !(string_options.empty() && - date_options.empty() && - symbol_list_options.empty() && - vector_int_options.empty())) + if (it != paired_num_options.end() + || !(string_options.empty() + && date_options.empty() + && symbol_list_options.empty() + && vector_int_options.empty())) output << ", "; } @@ -268,10 +270,10 @@ OptionsList::writeJsonOutput(ostream &output) const { output << "\""<< it->first << "\": \"" << it->second << "\""; it++; - if (it != string_options.end() || - !(date_options.empty() && - symbol_list_options.empty() && - vector_int_options.empty())) + if (it != string_options.end() + || !(date_options.empty() + && symbol_list_options.empty() + && vector_int_options.empty())) output << ", "; } @@ -280,9 +282,9 @@ OptionsList::writeJsonOutput(ostream &output) const { output << "\""<< it->first << "\": \"" << it->second << "\""; it++; - if (it != date_options.end() || - !(symbol_list_options.empty() && - vector_int_options.empty())) + if (it != date_options.end() + || !(symbol_list_options.empty() + && vector_int_options.empty())) output << ", "; } @@ -292,8 +294,8 @@ OptionsList::writeJsonOutput(ostream &output) const output << "\""<< it->first << "\":"; it->second.writeJsonOutput(output); it++; - if (it != symbol_list_options.end() || - !vector_int_options.empty()) + if (it != symbol_list_options.end() + || !vector_int_options.empty()) output << ", "; } diff --git a/Statement.hh b/Statement.hh index 54f13a76..ceb81957 100644 --- a/Statement.hh +++ b/Statement.hh @@ -120,7 +120,7 @@ public: bool occbin_option; //! Stores the original number of equations in the model_block int orig_eq_nbr; - //! Stores the number of equations added to the Ramsey model + //! Stores the number of equations added to the Ramsey model int ramsey_eq_nbr; }; @@ -128,7 +128,8 @@ public: class Statement { public: - virtual ~Statement(); + virtual + ~Statement(); //! Do some internal check, and fill the ModFileStructure class /*! Don't forget to update ComputingTasks.hh, Shocks.hh and NumericalInitialization.hh if you modify the signature of this diff --git a/StaticModel.cc b/StaticModel.cc index 65d4d632..ecc50640 100644 --- a/StaticModel.cc +++ b/StaticModel.cc @@ -661,10 +661,10 @@ StaticModel::writeModelEquationsCode_Block(const string file_name, const string if (dynamic_cast(*it) != NULL) (*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt2, map_idx, false, false, tef_terms); - FNUMEXPR_ fnumexpr(TemporaryTerm, (int) (map_idx.find((*it)->idx)->second)); + FNUMEXPR_ fnumexpr(TemporaryTerm, (int)(map_idx.find((*it)->idx)->second)); fnumexpr.write(code_file, instruction_number); (*it)->compile(code_file, instruction_number, false, tt2, map_idx, false, false, tef_terms); - FSTPST_ fstpst((int) (map_idx.find((*it)->idx)->second)); + FSTPST_ fstpst((int)(map_idx.find((*it)->idx)->second)); fstpst.write(code_file, instruction_number); // Insert current node into tt2 tt2.insert(*it); @@ -854,12 +854,12 @@ StaticModel::writeModelEquationsCode_Block(const string file_name, const string if (dynamic_cast(*it) != NULL) (*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt3, map_idx2[block], false, false, tef_terms2); - FNUMEXPR_ fnumexpr(TemporaryTerm, (int) (map_idx2[block].find((*it)->idx)->second)); + FNUMEXPR_ fnumexpr(TemporaryTerm, (int)(map_idx2[block].find((*it)->idx)->second)); fnumexpr.write(code_file, instruction_number); (*it)->compile(code_file, instruction_number, false, tt3, map_idx2[block], false, false, tef_terms); - FSTPST_ fstpst((int) (map_idx2[block].find((*it)->idx)->second)); + FSTPST_ fstpst((int)(map_idx2[block].find((*it)->idx)->second)); fstpst.write(code_file, instruction_number); // Insert current node into tt2 tt3.insert(*it); @@ -1058,14 +1058,14 @@ StaticModel::computingPass(const eval_context_t &eval_context, bool no_tmp_terms neweqs.push_back(dynamic_cast(eq_tmp->toStatic(*this))); } - for (unsigned int eq = 0; eq < aux_equations.size(); eq++) + for (unsigned int eq = 0; eq < aux_equations.size(); eq++) { expr_t eq_tmp = aux_equations[eq]->substituteStaticAuxiliaryDefinition(); neweqs.push_back(dynamic_cast(eq_tmp->toStatic(*this))); } - + equations.clear(); - copy(neweqs.begin(),neweqs.end(),back_inserter(equations)); + copy(neweqs.begin(), neweqs.end(), back_inserter(equations)); // Compute derivatives w.r. to all endogenous, and possibly exogenous and exogenous deterministic set vars; @@ -1074,8 +1074,8 @@ StaticModel::computingPass(const eval_context_t &eval_context, bool no_tmp_terms int id = symbol_table.getID(eEndogenous, i); // if (!symbol_table.isAuxiliaryVariableButNotMultiplier(id)) vars.insert(getDerivID(id, 0)); - } - + } + // Launch computations cout << "Computing static model derivatives:" << endl << " - order 1" << endl; @@ -1190,7 +1190,7 @@ StaticModel::writeStaticMFile(const string &func_name) const << "% columns: variables in declaration order" << endl << "% rows: equations in order of declaration" << endl << "%" << endl - << "%" << endl + << "%" << endl << "% Warning : this file is generated automatically by Dynare" << endl << "% from model file (.mod)" << endl << endl; @@ -1338,7 +1338,6 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c int id2 = getSymbIDByDerivID(var2); int id3 = getSymbIDByDerivID(var3); - // Reference column number for the g3 matrix int ref_col = id1 * hessianColsNbr + id2 * JacobianColsNbr + id3; @@ -1440,15 +1439,15 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c // Initialize g3 matrix StaticOutput << "if nargout >= 4," << endl - << " %" << endl - << " % Third order derivatives" << endl - << " %" << endl - << endl; + << " %" << endl + << " % Third order derivatives" << endl + << " %" << endl + << endl; int ncols = hessianColsNbr * JacobianColsNbr; if (third_derivatives.size()) StaticOutput << " v3 = zeros(" << NNZDerivatives[2] << ",3);" << endl - << third_derivatives_output.str() - << " g3 = sparse(v3(:,1),v3(:,2),v3(:,3)," << nrows << "," << ncols << ");" << endl; + << third_derivatives_output.str() + << " g3 = sparse(v3(:,1),v3(:,2),v3(:,3)," << nrows << "," << ncols << ");" << endl; else // Either 3rd derivatives is all zero, or we didn't compute it StaticOutput << " g3 = sparse([],[],[]," << nrows << "," << ncols << ");" << endl; StaticOutput << "end" << endl @@ -1622,7 +1621,6 @@ StaticModel::writeStaticCFile(const string &func_name) const output << "#define max(a, b) (((a) > (b)) ? (a) : (b))" << endl << "#define min(a, b) (((a) > (b)) ? (b) : (a))" << endl; - // Write function definition if oPowerDeriv is used writePowerDerivCHeader(output); writeNormcdfCHeader(output); @@ -1754,7 +1752,7 @@ StaticModel::writeStaticFile(const string &basename, bool block, bool bytecode, chdir(".."); writeStaticBlockMFSFile(basename); } - else if(use_dll) + else if (use_dll) writeStaticCFile(basename); else if (julia) writeStaticJuliaFile(basename); @@ -1859,7 +1857,7 @@ StaticModel::writeOutput(ostream &output, bool block) const for (int i = 0; i < nb_endo; i++) output << " " << equation_reordered[i]+1; output << "];\n"; - + map, int> row_incidence; for (first_derivatives_t::const_iterator it = first_derivatives.begin(); it != first_derivatives.end(); it++) @@ -2129,9 +2127,10 @@ StaticModel::writeAuxVarInitval(ostream &output, ExprNodeOutputType output_type) } } -void StaticModel::writeSetAuxiliaryVariables(const string &basename, const bool julia) const +void +StaticModel::writeSetAuxiliaryVariables(const string &basename, const bool julia) const { - + string func_name = basename + "_set_auxiliary_variables"; string filename = julia ? func_name + ".jl" : func_name + ".m"; string comment = julia ? "#" : "%"; @@ -2311,7 +2310,6 @@ StaticModel::writeParamsDerivativesFile(const string &basename, bool julia) cons third_derivs1_output << ";" << endl; } - ofstream paramsDerivsFile; string filename = julia ? basename + "StaticParamsDerivs.jl" : basename + "_static_params_derivs.m"; paramsDerivsFile.open(filename.c_str(), ios::out | ios::binary); @@ -2582,7 +2580,7 @@ StaticModel::writeJsonComputingPassOutput(ostream &output, bool writeDetails) co output << "\"static_model_derivative_details\": {"; else output << "\"static_model_derivatives\": {"; - output << model_local_vars_output.str() + output << model_local_vars_output.str() << ", " << model_output.str() << ", " << jacobian_output.str() << ", " << hessian_output.str() diff --git a/StaticModel.hh b/StaticModel.hh index f1a7d36a..2dcc8197 100644 --- a/StaticModel.hh +++ b/StaticModel.hh @@ -224,12 +224,14 @@ public: return (block_type_firstequation_size_mfs[block_number].second.first); }; //! Return the number of exogenous variable in the block block_number - virtual unsigned int getBlockExoSize(int block_number) const + virtual unsigned int + getBlockExoSize(int block_number) const { return 0; }; //! Return the number of colums in the jacobian matrix for exogenous variable in the block block_number - virtual unsigned int getBlockExoColSize(int block_number) const + virtual unsigned int + getBlockExoColSize(int block_number) const { return 0; } diff --git a/SteadyStateModel.cc b/SteadyStateModel.cc index 7630823f..5fc9dc1d 100644 --- a/SteadyStateModel.cc +++ b/SteadyStateModel.cc @@ -72,7 +72,7 @@ SteadyStateModel::checkPass(bool ramsey_model, WarningConsolidation &warnings) c if (find(so_far_defined.begin(), so_far_defined.end(), symb_ids[j]) != so_far_defined.end()) warnings << "WARNING: in the 'steady_state_model' block, variable '" << symbol_table.getName(symb_ids[j]) << "' is declared twice" << endl; - + // Check that expression has no undefined symbol if (!ramsey_model) { @@ -187,15 +187,15 @@ SteadyStateModel::writeSteadyStateFileC(const string &basename, bool ramsey_mode output << "#include " << endl; output << "void steadystate(" - << "const double *exo_, const double *params, double *ys_, int *info)" << endl + << "const double *exo_, const double *params, double *ys_, int *info)" << endl << "// Steady state file generated by Dynare preprocessor" << endl - << "{" << endl + << "{" << endl << " *info = 0;" << endl; if (def_table.size() == 0) { output << " return;" << endl - << "}" << endl; + << "}" << endl; return; } @@ -204,11 +204,11 @@ SteadyStateModel::writeSteadyStateFileC(const string &basename, bool ramsey_mode const vector &symb_ids = def_table[i].first; output << " "; if (symb_ids.size() > 1) - std::cout << "Error: in C, multiple returns are not permitted in steady_state_model" << std::endl; + std::cout << "Error: in C, multiple returns are not permitted in steady_state_model" << std::endl; variable_node_map_t::const_iterator it = variable_node_map.find(make_pair(symb_ids[0], 0)); assert(it != variable_node_map.end()); if (it->second->get_type() == eModFileLocalVariable) - output << "double "; + output << "double "; dynamic_cast(it->second)->writeOutput(output, oCSteadyStateFile); output << "="; def_table[i].second->writeOutput(output, oCSteadyStateFile); diff --git a/SymbolList.hh b/SymbolList.hh index 8ad5f9d2..26c61c50 100644 --- a/SymbolList.hh +++ b/SymbolList.hh @@ -44,9 +44,17 @@ public: //! Clears all content void clear(); //! Get a copy of the string vector - vector get_symbols() const { return symbols; }; + vector + get_symbols() const + { + return symbols; + }; //! Is Empty - int empty() const { return symbols.empty(); }; + int + empty() const + { + return symbols.empty(); + }; }; #endif diff --git a/SymbolTable.cc b/SymbolTable.cc index 9db683db..7a2a3da4 100644 --- a/SymbolTable.cc +++ b/SymbolTable.cc @@ -43,7 +43,7 @@ SymbolTable::SymbolTable() : frozen(false), size(0) } int -SymbolTable::addSymbol(const string &name, SymbolType type, const string &tex_name, const vector *> *partition_value) throw (AlreadyDeclaredException, FrozenException) +SymbolTable::addSymbol(const string &name, SymbolType type, const string &tex_name, const vector *> *partition_value) throw (AlreadyDeclaredException, FrozenException) { if (frozen) throw FrozenException(); @@ -89,7 +89,7 @@ SymbolTable::addSymbol(const string &name, SymbolType type, const string &tex_na { map pmv; for (vector *>::const_iterator it = partition_value->begin(); - it != partition_value->end(); it++) + it != partition_value->end(); it++) pmv[*((*it)->first)] = *((*it)->second); partition_value_map[id] = pmv; } @@ -228,7 +228,6 @@ SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException) << "M_.exo_names_tex = char(M_.exo_names_tex, '" << getTeXName(exo_ids[id]) << "');" << endl << "M_.exo_names_long = char(M_.exo_names_long, '" << getLongName(exo_ids[id]) << "');" << endl; - map > partitions = getPartitionsForType(eExogenous); for (map >::const_iterator it = partitions.begin(); it != partitions.end(); it++) @@ -304,7 +303,7 @@ SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException) output << it1->second; output << "' "; } - output << "};" << endl; + output << "};" << endl; } } @@ -420,7 +419,7 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException) { output << "char *exo_names[" << exo_nbr() << "];" << endl; for (int id = 0; id < exo_nbr(); id++) - output << "exo_names[" << id << "] = \"" << getName(exo_ids[id]) << "\";" << endl; + output << "exo_names[" << id << "] = \"" << getName(exo_ids[id]) << "\";" << endl; } output << endl @@ -429,7 +428,7 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException) { output << "char *exo_det_names[" << exo_det_nbr() << "];" << endl; for (int id = 0; id < exo_det_nbr(); id++) - output << "exo_det_names[" << id << "] = \"" << getName(exo_det_ids[id]) << "\";" << endl; + output << "exo_det_names[" << id << "] = \"" << getName(exo_det_ids[id]) << "\";" << endl; } output << endl @@ -438,7 +437,7 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException) { output << "char *endo_names[" << endo_nbr() << "];" << endl; for (int id = 0; id < endo_nbr(); id++) - output << "endo_names[" << id << "] = \"" << getName(endo_ids[id]) << "\";" << endl; + output << "endo_names[" << id << "] = \"" << getName(endo_ids[id]) << "\";" << endl; } output << endl @@ -447,7 +446,7 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException) { output << "char *param_names[" << param_nbr() << "];" << endl; for (int id = 0; id < param_nbr(); id++) - output << "param_names[" << id << "] = \"" << getName(param_ids[id]) << "\";" << endl; + output << "param_names[" << id << "] = \"" << getName(param_ids[id]) << "\";" << endl; } // Write the auxiliary variable table @@ -456,37 +455,37 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException) { output << "struct aux_vars_t *av[" << aux_vars.size() << "];" << endl; for (int i = 0; i < (int) aux_vars.size(); i++) - { - output << "av[" << i << "].endo_index = " << getTypeSpecificID(aux_vars[i].get_symb_id()) << ";" << endl - << "av[" << i << "].type = " << aux_vars[i].get_type() << ";" << endl; - switch (aux_vars[i].get_type()) - { - case avEndoLead: - case avExoLead: - case avExpectation: - case avMultiplier: - case avDiffForward: - break; - case avEndoLag: - case avExoLag: - output << "av[" << i << "].orig_index = " << getTypeSpecificID(aux_vars[i].get_orig_symb_id()) << ";" << endl - << "av[" << i << "].orig_lead_lag = " << aux_vars[i].get_orig_lead_lag() << ";" << endl; - break; - } - } + { + output << "av[" << i << "].endo_index = " << getTypeSpecificID(aux_vars[i].get_symb_id()) << ";" << endl + << "av[" << i << "].type = " << aux_vars[i].get_type() << ";" << endl; + switch (aux_vars[i].get_type()) + { + case avEndoLead: + case avExoLead: + case avExpectation: + case avMultiplier: + case avDiffForward: + break; + case avEndoLag: + case avExoLag: + output << "av[" << i << "].orig_index = " << getTypeSpecificID(aux_vars[i].get_orig_symb_id()) << ";" << endl + << "av[" << i << "].orig_lead_lag = " << aux_vars[i].get_orig_lead_lag() << ";" << endl; + break; + } + } } output << "int predeterminedNbr = " << predeterminedNbr() << ";" << endl; if (predeterminedNbr() > 0) { - output << "int predetermined_variables[" << predeterminedNbr() << "] = {"; + output << "int predetermined_variables[" << predeterminedNbr() << "] = {"; for (set::const_iterator it = predetermined_variables.begin(); - it != predetermined_variables.end(); it++) - { - if ( it != predetermined_variables.begin() ) - output << ","; - output << getTypeSpecificID(*it); - } + it != predetermined_variables.end(); it++) + { + if (it != predetermined_variables.begin()) + output << ","; + output << getTypeSpecificID(*it); + } output << "};" << endl; } @@ -495,13 +494,13 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException) { output << "int varobs[" << observedVariablesNbr() << "] = {"; for (vector::const_iterator it = varobs.begin(); - it != varobs.end(); it++) - { - if ( it != varobs.begin() ) - output << ","; - output << getTypeSpecificID(*it); - } - output << "};" << endl; + it != varobs.end(); it++) + { + if (it != varobs.begin()) + output << ","; + output << getTypeSpecificID(*it); + } + output << "};" << endl; } } @@ -940,27 +939,27 @@ SymbolTable::writeJuliaOutput(ostream &output) const throw (NotYetFrozenExceptio output << "]" << endl; } - if (predeterminedNbr() > 0) - { - output << "# Predetermined Variables" << endl - << "model_.pred_vars = [ " << endl; - for (set::const_iterator it = predetermined_variables.begin(); - it != predetermined_variables.end(); it++) - output << " DynareModel.PredVars(" - << getTypeSpecificID(*it)+1 << ")" << endl; - output << " ]" << endl; - } + if (predeterminedNbr() > 0) + { + output << "# Predetermined Variables" << endl + << "model_.pred_vars = [ " << endl; + for (set::const_iterator it = predetermined_variables.begin(); + it != predetermined_variables.end(); it++) + output << " DynareModel.PredVars(" + << getTypeSpecificID(*it)+1 << ")" << endl; + output << " ]" << endl; + } - if (observedVariablesNbr() > 0) - { - output << "# Observed Variables" << endl - << "options_.obs_vars = [" << endl; - for (vector::const_iterator it = varobs.begin(); - it != varobs.end(); it++) - output << " DynareModel.ObsVars(" - << getTypeSpecificID(*it)+1 << ")" << endl; - output << " ]" << endl; - } + if (observedVariablesNbr() > 0) + { + output << "# Observed Variables" << endl + << "options_.obs_vars = [" << endl; + for (vector::const_iterator it = varobs.begin(); + it != varobs.end(); it++) + output << " DynareModel.ObsVars(" + << getTypeSpecificID(*it)+1 << ")" << endl; + output << " ]" << endl; + } } void @@ -969,7 +968,7 @@ SymbolTable::writeJsonOutput(ostream &output) const output << "\"endogenous\": "; writeJsonVarVector(output, endo_ids); - output << ", \"exogenous\":" ; + output << ", \"exogenous\":"; writeJsonVarVector(output, exo_ids); output << ", \"exogenous_deterministic\": "; diff --git a/SymbolTable.hh b/SymbolTable.hh index 370c5e77..fb9a54dd 100644 --- a/SymbolTable.hh +++ b/SymbolTable.hh @@ -58,13 +58,41 @@ private: expr_t expr_node; //! Auxiliary variable definition public: AuxVarInfo(int symb_id_arg, aux_var_t type_arg, int orig_symb_id, int orig_lead_lag, int equation_number_for_multiplier_arg, int information_set_arg, expr_t expr_node_arg); - int get_symb_id() const { return symb_id; }; - aux_var_t get_type() const { return type; }; - int get_orig_symb_id() const { return orig_symb_id; }; - int get_orig_lead_lag() const { return orig_lead_lag; }; - int get_equation_number_for_multiplier() const { return equation_number_for_multiplier; }; - int get_information_set() const { return information_set; }; - expr_t get_expr_node() const { return expr_node; } ; + int + get_symb_id() const + { + return symb_id; + }; + aux_var_t + get_type() const + { + return type; + }; + int + get_orig_symb_id() const + { + return orig_symb_id; + }; + int + get_orig_lead_lag() const + { + return orig_lead_lag; + }; + int + get_equation_number_for_multiplier() const + { + return equation_number_for_multiplier; + }; + int + get_information_set() const + { + return information_set; + }; + expr_t + get_expr_node() const + { + return expr_node; + }; }; //! Stores the symbol table @@ -250,7 +278,11 @@ public: */ int searchAuxiliaryVars(int orig_symb_id, int orig_lead_lag) const throw (SearchFailedException); //! Returns the number of auxiliary variables - int AuxVarsSize() const { return aux_vars.size(); }; + int + AuxVarsSize() const + { + return aux_vars.size(); + }; //! Retruns expr_node for an auxiliary variable expr_t getAuxiliaryVarsExprNode(int symb_id) const throw (SearchFailedException); //! Tests if symbol already exists diff --git a/WarningConsolidation.cc b/WarningConsolidation.cc index 653d4730..f026dea8 100644 --- a/WarningConsolidation.cc +++ b/WarningConsolidation.cc @@ -20,8 +20,9 @@ #include "WarningConsolidation.hh" #include -WarningConsolidation& -operator<< (WarningConsolidation& wcc, const string &warning) +WarningConsolidation +& +operator<<(WarningConsolidation &wcc, const string &warning) { if (wcc.no_warn) return wcc; @@ -31,8 +32,8 @@ operator<< (WarningConsolidation& wcc, const string &warning) return wcc; }; -WarningConsolidation& -operator<< (WarningConsolidation& wcc, const Dynare::location& loc) +WarningConsolidation & +operator<<(WarningConsolidation &wcc, const Dynare::location &loc) { if (wcc.no_warn) return wcc; @@ -54,8 +55,8 @@ operator<< (WarningConsolidation& wcc, const Dynare::location& loc) return wcc; }; -WarningConsolidation& -operator<< (WarningConsolidation& wcc, ostream& (*pf) (ostream&)) +WarningConsolidation & +operator<<(WarningConsolidation &wcc, ostream & (*pf)(ostream &)) { if (wcc.no_warn) return wcc; diff --git a/WarningConsolidation.hh b/WarningConsolidation.hh index 135a54a3..582af0f4 100644 --- a/WarningConsolidation.hh +++ b/WarningConsolidation.hh @@ -34,16 +34,28 @@ private: bool no_warn; public: - WarningConsolidation(bool no_warn_arg) : no_warn(no_warn_arg) { }; - ~WarningConsolidation() { }; + WarningConsolidation(bool no_warn_arg) : no_warn(no_warn_arg) + { + }; + ~WarningConsolidation() + { + }; //! 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, const string &warning); + friend WarningConsolidation &operator<<(WarningConsolidation &wcc, const Dynare::location &loc); + friend WarningConsolidation &operator<<(WarningConsolidation &wcc, ostream & (*pf)(ostream &)); - inline void addWarning(const string &w) { warnings << w; }; - inline void addWarning(ostream& (*pf) (ostream&)) { warnings << pf; }; + inline void + addWarning(const string &w) + { + warnings << w; + }; + inline void + addWarning(ostream & (*pf)(ostream &)) + { + warnings << pf; + }; //! Write Warnings to m file void writeOutput(ostream &output) const; diff --git a/macro/MacroDriver.cc b/macro/MacroDriver.cc index 1d13c5ce..c5193cc6 100644 --- a/macro/MacroDriver.cc +++ b/macro/MacroDriver.cc @@ -55,14 +55,14 @@ MacroDriver::parse(const string &f, ostream &out, bool debug, bool no_line_macro an @#endif or an @#endfor - but no newline - no longer trigger an error. */ stringstream file_with_endl; - for (map::iterator it=defines.begin(); - it!=defines.end(); it++) + for (map::iterator it = defines.begin(); + it != defines.end(); it++) try { boost::lexical_cast(it->second); file_with_endl << "@#define " << it->first << " = " << it->second << endl; } - catch(boost::bad_lexical_cast &) + catch (boost::bad_lexical_cast &) { file_with_endl << "@#define " << it->first << " = \"" << it->second << "\"" << endl; } diff --git a/macro/MacroDriver.hh b/macro/MacroDriver.hh index 83828b2e..7b828b02 100644 --- a/macro/MacroDriver.hh +++ b/macro/MacroDriver.hh @@ -177,12 +177,13 @@ public: //! Constructor MacroDriver(); //! Destructor - virtual ~MacroDriver(); + virtual + ~MacroDriver(); //! Starts parsing a file, returns output in out /*! \param no_line_macro should we omit the @#line statements ? */ void parse(const string &f, ostream &out, bool debug, bool no_line_macro, - map defines, vector path); + map defines, vector path); //! Name of main file being parsed string file; diff --git a/macro/MacroValue.hh b/macro/MacroValue.hh index c9da9c3d..64f0cdef 100644 --- a/macro/MacroValue.hh +++ b/macro/MacroValue.hh @@ -49,7 +49,8 @@ public: { }; MacroValue(MacroDriver &driver_arg); - virtual ~MacroValue(); + virtual + ~MacroValue(); //! Applies + operator virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError) = 0; //! Applies unary + operator @@ -118,7 +119,8 @@ private: const int value; public: IntMV(MacroDriver &driver, int value_arg); - virtual ~IntMV(); + virtual + ~IntMV(); //! Computes arithmetic addition virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError); //! Unary plus @@ -158,7 +160,11 @@ public: If mv2 < mv1, returns an empty range (for consistency with MATLAB). */ static const MacroValue *new_range(MacroDriver &driver, const MacroValue *mv1, const MacroValue *mv2) throw (TypeError); - inline int get_int_value() const { return value; }; + inline int + get_int_value() const + { + return value; + }; }; //! Represents a string value in macro language @@ -170,7 +176,8 @@ private: const string value; public: StringMV(MacroDriver &driver, const string &value_arg); - virtual ~StringMV(); + virtual + ~StringMV(); //! Computes string concatenation virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError); virtual const MacroValue *operator==(const MacroValue &mv) const throw (TypeError); @@ -202,7 +209,8 @@ private: const vector values; public: ArrayMV(MacroDriver &driver, const vector &values_arg); - virtual ~ArrayMV(); + virtual + ~ArrayMV(); //! Computes array concatenation /*! Both array must be of same type */ virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError); From 6255858d210dab443da55718c3b78a3b00f7ad31 Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Wed, 14 Jun 2017 23:40:30 +0200 Subject: [PATCH 17/18] preprocessor: fix bug: check whether second string in pair is empty. closes #1469 --- ModelTree.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ModelTree.cc b/ModelTree.cc index 9bfb30ea..52de1aa1 100644 --- a/ModelTree.cc +++ b/ModelTree.cc @@ -1588,7 +1588,7 @@ ModelTree::writeLatexModelFile(const string &basename, ExprNodeOutputType output content_output << iteqt->second.first; - if (!empty(iteqt->second.second)) + if (iteqt->second.second.empty()) content_output << "= `" << iteqt->second.second << "'"; wrote_eq_tag = true; From 7153f19aab774c8b6154a3e305e28bf5a87187ad Mon Sep 17 00:00:00 2001 From: Houtan Bastani Date: Wed, 14 Jun 2017 23:49:10 +0200 Subject: [PATCH 18/18] preprocessor: remove comparison warnings from compilation of ModelTree.cc --- ModelTree.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ModelTree.cc b/ModelTree.cc index 52de1aa1..11f9d1e1 100644 --- a/ModelTree.cc +++ b/ModelTree.cc @@ -232,7 +232,7 @@ ModelTree::computeNonSingularNormalization(jacob_map_t &contemporaneous_jacobian void ModelTree::computeNormalizedEquations(multimap &endo2eqs) const { - for (int i = 0; i < equations.size(); i++) + for (size_t i = 0; i < equations.size(); i++) { VariableNode *lhs = dynamic_cast(equations[i]->get_arg1()); if (lhs == NULL) @@ -247,7 +247,7 @@ ModelTree::computeNormalizedEquations(multimap &endo2eqs) const if (endo.find(make_pair(symbol_table.getTypeSpecificID(symb_id), 0)) != endo.end()) continue; - endo2eqs.insert(make_pair(symbol_table.getTypeSpecificID(symb_id), i)); + endo2eqs.insert(make_pair(symbol_table.getTypeSpecificID(symb_id), (int) i)); cout << "Endogenous " << symbol_table.getName(symb_id) << " normalized in equation " << (i+1) << endl; } } @@ -1667,7 +1667,7 @@ ModelTree::addNonstationaryVariables(vector nonstationary_vars, bool log_de void ModelTree::initializeVariablesAndEquations() { - for (int j = 0; j < equations.size(); j++) + for (size_t j = 0; j < equations.size(); j++) { equation_reordered.push_back(j); variable_reordered.push_back(j);