diff --git a/CodeInterpreter.hh b/CodeInterpreter.hh index ae9251588fd7dc6e5ff534043e1b0a62d66f4159..90774f6a697d87eef24319c9b4ab7369c9319df8 100644 --- a/CodeInterpreter.hh +++ b/CodeInterpreter.hh @@ -29,11 +29,11 @@ # include "linbcg.hh" #endif #ifdef BYTE_CODE -#ifndef DEBUG_EX - #include "mex.h" -#else - #include "mex_interface.hh" -#endif +# ifndef DEBUG_EX +# include "mex.h" +# else +# include "mex_interface.hh" +# endif #endif #ifdef _MSC_VER @@ -52,9 +52,9 @@ typedef unsigned __int64 uint64_t; using namespace std; /** -* \enum Tags -* \brief The differents flags of the bytecode -*/ + * \enum Tags + * \brief The differents flags of the bytecode + */ enum Tags { FLDZ, //!< Stores zero in the stack - 0 @@ -95,8 +95,7 @@ enum Tags FOK //!< Used for debugging purpose - 1B -}; - + }; enum BlockType { @@ -114,8 +113,6 @@ enum EquationType E_SOLVE //!< No simple evaluation of the equation, it has to be solved }; - - enum BlockSimulationType { UNKNOWN, //!< Unknown simulation type @@ -188,10 +185,10 @@ enum TrinaryOpcode oNormcdf }; - struct Block_contain_type - { - int Equation, Variable, Own_Derivative; - }; +struct Block_contain_type +{ + int Equation, Variable, Own_Derivative; +}; #pragma pack(push, 1) class TagWithoutArgument @@ -199,8 +196,14 @@ class TagWithoutArgument protected: uint8_t op_code; public: - inline TagWithoutArgument(uint8_t op_code_arg) : op_code(op_code_arg) {}; - inline void write(ostream &CompileCode) {CompileCode.write(reinterpret_cast<char *>(this), sizeof(*this)); }; + inline TagWithoutArgument(uint8_t op_code_arg) : op_code(op_code_arg) + { + }; + inline void + write(ostream &CompileCode) + { + CompileCode.write(reinterpret_cast<char *>(this), sizeof(*this)); + }; }; template < class T1 > @@ -210,9 +213,17 @@ protected: uint8_t op_code; T1 arg1; public: - inline TagWithOneArgument(uint8_t op_code_arg) : op_code(op_code_arg) {}; - inline TagWithOneArgument(uint8_t op_code_arg, T1 arg_arg1) : op_code(op_code_arg), arg1(arg_arg1) {}; - inline void write(ostream &CompileCode) {CompileCode.write(reinterpret_cast<char *>(this), sizeof(TagWithOneArgument)); }; + inline TagWithOneArgument(uint8_t op_code_arg) : op_code(op_code_arg) + { + }; + inline TagWithOneArgument(uint8_t op_code_arg, T1 arg_arg1) : op_code(op_code_arg), arg1(arg_arg1) + { + }; + inline void + write(ostream &CompileCode) + { + CompileCode.write(reinterpret_cast<char *>(this), sizeof(TagWithOneArgument)); + }; }; template < class T1, class T2 > @@ -223,9 +234,17 @@ protected: T1 arg1; T2 arg2; public: - inline TagWithTwoArguments(uint8_t op_code_arg) : op_code(op_code_arg) {}; - inline TagWithTwoArguments(uint8_t op_code_arg, T1 arg_arg1, T2 arg_arg2) : op_code(op_code_arg), arg1(arg_arg1), arg2(arg_arg2) {}; - inline void write(ostream &CompileCode) {CompileCode.write(reinterpret_cast<char *>(this), sizeof(*this)); }; + inline TagWithTwoArguments(uint8_t op_code_arg) : op_code(op_code_arg) + { + }; + inline TagWithTwoArguments(uint8_t op_code_arg, T1 arg_arg1, T2 arg_arg2) : op_code(op_code_arg), arg1(arg_arg1), arg2(arg_arg2) + { + }; + inline void + write(ostream &CompileCode) + { + CompileCode.write(reinterpret_cast<char *>(this), sizeof(*this)); + }; }; template < class T1, class T2, class T3 > @@ -237,238 +256,458 @@ protected: T2 arg2; T3 arg3; public: - inline TagWithThreeArguments(uint8_t op_code_arg) : op_code(op_code_arg) {}; - inline TagWithThreeArguments(uint8_t op_code_arg, T1 arg_arg1, T2 arg_arg2, T3 arg_arg3) : op_code(op_code_arg), arg1(arg_arg1), arg2(arg_arg2), arg3(arg_arg3) {}; - inline void write(ostream &CompileCode) {CompileCode.write(reinterpret_cast<char *>(this), sizeof(*this)); }; + inline TagWithThreeArguments(uint8_t op_code_arg) : op_code(op_code_arg) + { + }; + inline TagWithThreeArguments(uint8_t op_code_arg, T1 arg_arg1, T2 arg_arg2, T3 arg_arg3) : op_code(op_code_arg), arg1(arg_arg1), arg2(arg_arg2), arg3(arg_arg3) + { + }; + inline void + write(ostream &CompileCode) + { + CompileCode.write(reinterpret_cast<char *>(this), sizeof(*this)); + }; }; - - class FLDZ_ : public TagWithoutArgument { public: - inline FLDZ_() : TagWithoutArgument(FLDZ) {}; + inline FLDZ_() : TagWithoutArgument(FLDZ) + { + }; }; class FEND_ : public TagWithoutArgument { public: - inline FEND_() : TagWithoutArgument(FEND) {}; + inline FEND_() : TagWithoutArgument(FEND) + { + }; }; class FENDBLOCK_ : public TagWithoutArgument { public: - inline FENDBLOCK_() : TagWithoutArgument(FENDBLOCK) {}; + inline FENDBLOCK_() : TagWithoutArgument(FENDBLOCK) + { + }; }; class FENDEQU_ : public TagWithoutArgument { public: - inline FENDEQU_() : TagWithoutArgument(FENDEQU) {}; + inline FENDEQU_() : TagWithoutArgument(FENDEQU) + { + }; }; class FCUML_ : public TagWithoutArgument { public: - inline FCUML_() : TagWithoutArgument(FCUML) {}; + inline FCUML_() : TagWithoutArgument(FCUML) + { + }; }; class FDIMT_ : public TagWithOneArgument<unsigned int> { public: - inline FDIMT_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FDIMT) {}; - inline FDIMT_(unsigned int size_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FDIMT,size_arg) {}; - inline unsigned int get_size() {return arg1;}; + inline FDIMT_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FDIMT) + { + }; + inline FDIMT_(unsigned int size_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FDIMT, size_arg) + { + }; + inline unsigned int + get_size() + { + return arg1; + }; }; class FDIMST_ : public TagWithOneArgument<unsigned int> { public: - inline FDIMST_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FDIMST) {}; - inline FDIMST_(const unsigned int size_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FDIMST,size_arg) {}; - inline unsigned int get_size() {return arg1;}; + inline FDIMST_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FDIMST) + { + }; + inline FDIMST_(const unsigned int size_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FDIMST, size_arg) + { + }; + inline unsigned int + get_size() + { + return arg1; + }; }; class FLDC_ : public TagWithOneArgument<double> { public: - inline FLDC_() : TagWithOneArgument<double>::TagWithOneArgument(FLDC) {}; - inline FLDC_(const double value_arg) : TagWithOneArgument<double>::TagWithOneArgument(FLDC,value_arg) {}; - inline double get_value() {return arg1;}; + inline FLDC_() : TagWithOneArgument<double>::TagWithOneArgument(FLDC) + { + }; + inline FLDC_(const double value_arg) : TagWithOneArgument<double>::TagWithOneArgument(FLDC, value_arg) + { + }; + inline double + get_value() + { + return arg1; + }; }; class FLDU_ : public TagWithOneArgument<unsigned int> { public: - inline FLDU_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDU) {}; - inline FLDU_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDU,pos_arg) {}; - inline unsigned int get_pos() {return arg1;}; + inline FLDU_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDU) + { + }; + inline FLDU_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDU, pos_arg) + { + }; + inline unsigned int + get_pos() + { + return arg1; + }; }; class FLDSU_ : public TagWithOneArgument<unsigned int> { public: - inline FLDSU_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDSU) {}; - inline FLDSU_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDSU,pos_arg) {}; - inline unsigned int get_pos() {return arg1;}; + inline FLDSU_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDSU) + { + }; + inline FLDSU_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDSU, pos_arg) + { + }; + inline unsigned int + get_pos() + { + return arg1; + }; }; class FLDR_ : public TagWithOneArgument<unsigned int> { public: - inline FLDR_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDR) {}; - inline FLDR_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDR,pos_arg) {}; - inline unsigned int get_pos() {return arg1;}; + inline FLDR_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDR) + { + }; + inline FLDR_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDR, pos_arg) + { + }; + inline unsigned int + get_pos() + { + return arg1; + }; }; class FLDT_ : public TagWithOneArgument<unsigned int> { public: - inline FLDT_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDT) {}; - inline FLDT_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDT,pos_arg) {}; - inline unsigned int get_pos() {return arg1;}; + inline FLDT_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDT) + { + }; + inline FLDT_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDT, pos_arg) + { + }; + inline unsigned int + get_pos() + { + return arg1; + }; }; class FLDST_ : public TagWithOneArgument<unsigned int> { public: - inline FLDST_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDST) {}; - inline FLDST_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDST,pos_arg) {}; - inline unsigned int get_pos() {return arg1;}; + inline FLDST_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDST) + { + }; + inline FLDST_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FLDST, pos_arg) + { + }; + inline unsigned int + get_pos() + { + return arg1; + }; }; class FSTPT_ : public TagWithOneArgument<unsigned int> { public: - inline FSTPT_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPT) {}; - inline FSTPT_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPT,pos_arg) {}; - inline unsigned int get_pos() {return arg1;}; + inline FSTPT_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPT) + { + }; + inline FSTPT_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPT, pos_arg) + { + }; + inline unsigned int + get_pos() + { + return arg1; + }; }; class FSTPST_ : public TagWithOneArgument<unsigned int> { public: - inline FSTPST_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPST) {}; - inline FSTPST_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPST,pos_arg) {}; - inline unsigned int get_pos() {return arg1;}; + inline FSTPST_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPST) + { + }; + inline FSTPST_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPST, pos_arg) + { + }; + inline unsigned int + get_pos() + { + return arg1; + }; }; class FSTPR_ : public TagWithOneArgument<unsigned int> { public: - inline FSTPR_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPR) {}; - inline FSTPR_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPR,pos_arg) {}; - inline unsigned int get_pos() {return arg1;}; + inline FSTPR_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPR) + { + }; + inline FSTPR_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPR, pos_arg) + { + }; + inline unsigned int + get_pos() + { + return arg1; + }; }; class FSTPU_ : public TagWithOneArgument<unsigned int> { public: - inline FSTPU_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPU) {}; - inline FSTPU_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPU,pos_arg) {}; - inline unsigned int get_pos() {return arg1;}; + inline FSTPU_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPU) + { + }; + inline FSTPU_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPU, pos_arg) + { + }; + inline unsigned int + get_pos() + { + return arg1; + }; }; class FSTPSU_ : public TagWithOneArgument<unsigned int> { public: - inline FSTPSU_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPSU) {}; - inline FSTPSU_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPSU,pos_arg) {}; - inline unsigned int get_pos() {return arg1;}; + inline FSTPSU_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPSU) + { + }; + inline FSTPSU_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPSU, pos_arg) + { + }; + inline unsigned int + get_pos() + { + return arg1; + }; }; - class FSTPG_ : public TagWithOneArgument<unsigned int> { public: - inline FSTPG_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPG,0) {}; - inline FSTPG_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPG,pos_arg) {}; - inline unsigned int get_pos() {return arg1;}; + inline FSTPG_() : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPG, 0) + { + }; + inline FSTPG_(const unsigned int pos_arg) : TagWithOneArgument<unsigned int>::TagWithOneArgument(FSTPG, pos_arg) + { + }; + inline unsigned int + get_pos() + { + return arg1; + }; }; class FUNARY_ : public TagWithOneArgument<uint8_t> { public: - inline FUNARY_() : TagWithOneArgument<uint8_t>::TagWithOneArgument(FUNARY) {}; - inline FUNARY_(uint8_t op_type_arg) : TagWithOneArgument<uint8_t>::TagWithOneArgument(FUNARY,op_type_arg) {}; - inline uint8_t get_op_type() {return arg1;}; + inline FUNARY_() : TagWithOneArgument<uint8_t>::TagWithOneArgument(FUNARY) + { + }; + inline FUNARY_(uint8_t op_type_arg) : TagWithOneArgument<uint8_t>::TagWithOneArgument(FUNARY, op_type_arg) + { + }; + inline uint8_t + get_op_type() + { + return arg1; + }; }; class FBINARY_ : public TagWithOneArgument<uint8_t> { public: - inline FBINARY_() : TagWithOneArgument<uint8_t>::TagWithOneArgument(FBINARY) {}; - inline FBINARY_(const int op_type_arg) : TagWithOneArgument<uint8_t>::TagWithOneArgument(FBINARY,op_type_arg) {}; - inline uint8_t get_op_type() {return arg1;}; + inline FBINARY_() : TagWithOneArgument<uint8_t>::TagWithOneArgument(FBINARY) + { + }; + inline FBINARY_(const int op_type_arg) : TagWithOneArgument<uint8_t>::TagWithOneArgument(FBINARY, op_type_arg) + { + }; + inline uint8_t + get_op_type() + { + return arg1; + }; }; class FOK_ : public TagWithOneArgument<int> { public: - inline FOK_() : TagWithOneArgument<int>::TagWithOneArgument(FOK) {}; - inline FOK_(const int arg_arg) : TagWithOneArgument<int>::TagWithOneArgument(FOK,arg_arg) {}; - inline int get_arg() {return arg1;}; + inline FOK_() : TagWithOneArgument<int>::TagWithOneArgument(FOK) + { + }; + inline FOK_(const int arg_arg) : TagWithOneArgument<int>::TagWithOneArgument(FOK, arg_arg) + { + }; + inline int + get_arg() + { + return arg1; + }; }; class FLDVS_ : public TagWithTwoArguments<uint8_t, unsigned int> { public: - inline FLDVS_() : TagWithTwoArguments<uint8_t, unsigned int>::TagWithTwoArguments(FLDVS) {}; - inline FLDVS_(uint8_t type_arg, const unsigned int pos_arg) : TagWithTwoArguments<uint8_t, unsigned int>::TagWithTwoArguments(FLDVS, type_arg, pos_arg) {}; - inline uint8_t get_type() {return arg1;}; - inline unsigned int get_pos() {return arg2;}; + inline FLDVS_() : TagWithTwoArguments<uint8_t, unsigned int>::TagWithTwoArguments(FLDVS) + { + }; + inline FLDVS_(uint8_t type_arg, const unsigned int pos_arg) : TagWithTwoArguments<uint8_t, unsigned int>::TagWithTwoArguments(FLDVS, type_arg, pos_arg) + { + }; + inline uint8_t + get_type() + { + return arg1; + }; + inline unsigned int + get_pos() + { + return arg2; + }; }; class FLDSV_ : public TagWithTwoArguments<uint8_t, unsigned int> { public: - inline FLDSV_() : TagWithTwoArguments<uint8_t, unsigned int>::TagWithTwoArguments(FLDSV) {}; + inline FLDSV_() : TagWithTwoArguments<uint8_t, unsigned int>::TagWithTwoArguments(FLDSV) + { + }; inline FLDSV_(const uint8_t type_arg, const unsigned int pos_arg) : - TagWithTwoArguments<uint8_t, unsigned int>::TagWithTwoArguments(FLDSV, type_arg, pos_arg) {}; - inline uint8_t get_type() {return arg1;}; - inline unsigned int get_pos() {return arg2;}; + TagWithTwoArguments<uint8_t, unsigned int>::TagWithTwoArguments(FLDSV, type_arg, pos_arg) + { + }; + inline uint8_t + get_type() + { + return arg1; + }; + inline unsigned int + get_pos() + { + return arg2; + }; }; class FSTPSV_ : public TagWithTwoArguments<uint8_t, unsigned int> { public: - inline FSTPSV_() : TagWithTwoArguments<uint8_t, unsigned int>::TagWithTwoArguments(FSTPSV) {}; + inline FSTPSV_() : TagWithTwoArguments<uint8_t, unsigned int>::TagWithTwoArguments(FSTPSV) + { + }; inline FSTPSV_(const uint8_t type_arg, const unsigned int pos_arg) : - TagWithTwoArguments<uint8_t, unsigned int>::TagWithTwoArguments(FSTPSV, type_arg, pos_arg) {}; - inline uint8_t get_type() {return arg1;}; - inline unsigned int get_pos() {return arg2;}; + TagWithTwoArguments<uint8_t, unsigned int>::TagWithTwoArguments(FSTPSV, type_arg, pos_arg) + { + }; + inline uint8_t + get_type() + { + return arg1; + }; + inline unsigned int + get_pos() + { + return arg2; + }; }; - - class FLDV_ : public TagWithThreeArguments<uint8_t, unsigned int, int> { public: - inline FLDV_() : TagWithThreeArguments<uint8_t, unsigned int, int>::TagWithThreeArguments(FLDV) {}; + inline FLDV_() : TagWithThreeArguments<uint8_t, unsigned int, int>::TagWithThreeArguments(FLDV) + { + }; inline FLDV_(const int type_arg, const unsigned int pos_arg) : - TagWithThreeArguments<uint8_t, unsigned int, int>::TagWithThreeArguments(FLDV, type_arg, pos_arg, 0) {}; + TagWithThreeArguments<uint8_t, unsigned int, int>::TagWithThreeArguments(FLDV, type_arg, pos_arg, 0) + { + }; inline FLDV_(const int type_arg, const unsigned int pos_arg, const int lead_lag_arg) : - TagWithThreeArguments<uint8_t, unsigned int, int>::TagWithThreeArguments(FLDV, type_arg, pos_arg, lead_lag_arg) {}; - inline uint8_t get_type() {return arg1;}; - inline unsigned int get_pos() {return arg2;}; - inline int get_lead_lag() {return arg3;}; + TagWithThreeArguments<uint8_t, unsigned int, int>::TagWithThreeArguments(FLDV, type_arg, pos_arg, lead_lag_arg) + { + }; + inline uint8_t + get_type() + { + return arg1; + }; + inline unsigned int + get_pos() + { + return arg2; + }; + inline int + get_lead_lag() + { + return arg3; + }; }; class FSTPV_ : public TagWithThreeArguments<uint8_t, unsigned int, int> { public: - inline FSTPV_() : TagWithThreeArguments<uint8_t, unsigned int, int>::TagWithThreeArguments(FSTPV) {}; + inline FSTPV_() : TagWithThreeArguments<uint8_t, unsigned int, int>::TagWithThreeArguments(FSTPV) + { + }; inline FSTPV_(const int type_arg, const unsigned int pos_arg) : - TagWithThreeArguments<uint8_t, unsigned int, int>::TagWithThreeArguments(FSTPV, type_arg, pos_arg, 0) {}; + TagWithThreeArguments<uint8_t, unsigned int, int>::TagWithThreeArguments(FSTPV, type_arg, pos_arg, 0) + { + }; inline FSTPV_(const int type_arg, const unsigned int pos_arg, const int lead_lag_arg) : - TagWithThreeArguments<uint8_t, unsigned int, int>::TagWithThreeArguments(FSTPV, type_arg, pos_arg, lead_lag_arg) {}; - inline uint8_t get_type() {return arg1;}; - inline unsigned int get_pos() {return arg2;}; - inline int get_lead_lag() {return arg3;}; + TagWithThreeArguments<uint8_t, unsigned int, int>::TagWithThreeArguments(FSTPV, type_arg, pos_arg, lead_lag_arg) + { + }; + inline uint8_t + get_type() + { + return arg1; + }; + inline unsigned int + get_pos() + { + return arg2; + }; + inline int + get_lead_lag() + { + return arg3; + }; }; - class FBEGINBLOCK_ { private: @@ -484,312 +723,354 @@ private: int Max_Lead; int u_count_int; public: - inline FBEGINBLOCK_(){ op_code = FBEGINBLOCK; size = 0; type = UNKNOWN; /*variable = NULL; equation = NULL;*/ - is_linear = false; endo_nbr = 0; Max_Lag = 0; Max_Lead = 0; u_count_int = 0;}; + inline FBEGINBLOCK_() + { + op_code = FBEGINBLOCK; size = 0; type = UNKNOWN; /*variable = NULL; equation = NULL;*/ + is_linear = false; endo_nbr = 0; Max_Lag = 0; Max_Lead = 0; u_count_int = 0; + }; inline FBEGINBLOCK_(unsigned int &size_arg, BlockSimulationType &type_arg, int unsigned first_element, int unsigned &block_size, const vector<int> &variable_arg, const vector<int> &equation_arg, bool is_linear_arg, int endo_nbr_arg, int Max_Lag_arg, int Max_Lead_arg, int &u_count_int_arg) - { op_code = FBEGINBLOCK; size = size_arg; type = type_arg; - variable = vector<int>(variable_arg.begin()+first_element, variable_arg.begin()+(first_element+block_size)); - equation = vector<int>(equation_arg.begin()+first_element, equation_arg.begin()+(first_element+block_size)); - 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;/*Block_Contain.clear();*/}; - inline unsigned int get_size() { return size;}; - inline uint8_t get_type() { return type;}; - inline bool get_is_linear() { return is_linear;}; - inline int get_endo_nbr() { return endo_nbr;}; - inline int get_Max_Lag() { return Max_Lag;}; - inline int get_Max_Lead() { return Max_Lead;}; - inline int get_u_count_int() { return u_count_int;}; - inline vector<Block_contain_type> get_Block_Contain() {return Block_Contain_;}; - inline void write(ostream &CompileCode) - { - CompileCode.write(reinterpret_cast<char *>(&op_code), sizeof(op_code)); - CompileCode.write(reinterpret_cast<char *>(&size), sizeof(size)); - CompileCode.write(reinterpret_cast<char *>(&type), sizeof(type)); - for(int i = 0; i<size ;i++) - { - CompileCode.write(reinterpret_cast<char *>(&variable[i]), sizeof(variable[0])); - CompileCode.write(reinterpret_cast<char *>(&equation[i]), sizeof(equation[0])); - } - if (type==SOLVE_TWO_BOUNDARIES_SIMPLE || type==SOLVE_TWO_BOUNDARIES_COMPLETE || - type==SOLVE_BACKWARD_COMPLETE || type==SOLVE_FORWARD_COMPLETE) - { - CompileCode.write(reinterpret_cast<char *>(&is_linear), sizeof(is_linear)); - CompileCode.write(reinterpret_cast<char *>(&endo_nbr), sizeof(endo_nbr)); - CompileCode.write(reinterpret_cast<char *>(&Max_Lag), sizeof(Max_Lag)); - CompileCode.write(reinterpret_cast<char *>(&Max_Lead), sizeof(Max_Lead)); - CompileCode.write(reinterpret_cast<char *>(&u_count_int), sizeof(u_count_int)); - } - }; + { + op_code = FBEGINBLOCK; size = size_arg; type = type_arg; + variable = vector<int>(variable_arg.begin()+first_element, variable_arg.begin()+(first_element+block_size)); + equation = vector<int>(equation_arg.begin()+first_element, equation_arg.begin()+(first_element+block_size)); + 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; /*Block_Contain.clear();*/ + }; + inline unsigned int + get_size() + { + return size; + }; + inline uint8_t + get_type() + { + return type; + }; + inline bool + get_is_linear() + { + return is_linear; + }; + inline int + get_endo_nbr() + { + return endo_nbr; + }; + inline int + get_Max_Lag() + { + return Max_Lag; + }; + inline int + get_Max_Lead() + { + return Max_Lead; + }; + inline int + get_u_count_int() + { + return u_count_int; + }; + inline vector<Block_contain_type> + get_Block_Contain() + { + return Block_Contain_; + }; + inline void + write(ostream &CompileCode) + { + CompileCode.write(reinterpret_cast<char *>(&op_code), sizeof(op_code)); + CompileCode.write(reinterpret_cast<char *>(&size), sizeof(size)); + CompileCode.write(reinterpret_cast<char *>(&type), sizeof(type)); + for (int i = 0; i < size; i++) + { + CompileCode.write(reinterpret_cast<char *>(&variable[i]), sizeof(variable[0])); + CompileCode.write(reinterpret_cast<char *>(&equation[i]), sizeof(equation[0])); + } + if (type == SOLVE_TWO_BOUNDARIES_SIMPLE || type == SOLVE_TWO_BOUNDARIES_COMPLETE + || type == SOLVE_BACKWARD_COMPLETE || type == SOLVE_FORWARD_COMPLETE) + { + CompileCode.write(reinterpret_cast<char *>(&is_linear), sizeof(is_linear)); + CompileCode.write(reinterpret_cast<char *>(&endo_nbr), sizeof(endo_nbr)); + CompileCode.write(reinterpret_cast<char *>(&Max_Lag), sizeof(Max_Lag)); + CompileCode.write(reinterpret_cast<char *>(&Max_Lead), sizeof(Max_Lead)); + CompileCode.write(reinterpret_cast<char *>(&u_count_int), sizeof(u_count_int)); + } + }; #ifdef BYTE_CODE - inline uint8_t* load(uint8_t *code) - { - op_code = FBEGINBLOCK; code += sizeof(op_code); - memcpy(&size, code, sizeof(size)); code += sizeof(size); - memcpy(&type, code, sizeof(type)); code += sizeof(type); - for(int i = 0; i<size ;i++) - { - Block_contain_type bc; - memcpy(&bc.Variable, code, sizeof(bc.Variable)); code += sizeof(bc.Variable); - memcpy(&bc.Equation, code, sizeof(bc.Equation)); code += sizeof(bc.Equation); - Block_Contain_.push_back(bc); - } - if (type==SOLVE_TWO_BOUNDARIES_SIMPLE || type==SOLVE_TWO_BOUNDARIES_COMPLETE || - type==SOLVE_BACKWARD_COMPLETE || type==SOLVE_FORWARD_COMPLETE) - { - memcpy(&is_linear, code, sizeof(is_linear)); code += sizeof(is_linear); - memcpy(&endo_nbr, code, sizeof(endo_nbr)); code += sizeof(endo_nbr); - memcpy(&Max_Lag, code, sizeof(Max_Lag)); code += sizeof(Max_Lag); - memcpy(&Max_Lead, code, sizeof(Max_Lead)); code += sizeof(Max_Lead); - memcpy(&u_count_int, code, sizeof(u_count_int)); code += sizeof(u_count_int); - } - return code; - }; + inline uint8_t * + load(uint8_t *code) + { + op_code = FBEGINBLOCK; code += sizeof(op_code); + memcpy(&size, code, sizeof(size)); code += sizeof(size); + memcpy(&type, code, sizeof(type)); code += sizeof(type); + for (int i = 0; i < size; i++) + { + Block_contain_type bc; + memcpy(&bc.Variable, code, sizeof(bc.Variable)); code += sizeof(bc.Variable); + memcpy(&bc.Equation, code, sizeof(bc.Equation)); code += sizeof(bc.Equation); + Block_Contain_.push_back(bc); + } + if (type == SOLVE_TWO_BOUNDARIES_SIMPLE || type == SOLVE_TWO_BOUNDARIES_COMPLETE + || type == SOLVE_BACKWARD_COMPLETE || type == SOLVE_FORWARD_COMPLETE) + { + memcpy(&is_linear, code, sizeof(is_linear)); code += sizeof(is_linear); + memcpy(&endo_nbr, code, sizeof(endo_nbr)); code += sizeof(endo_nbr); + memcpy(&Max_Lag, code, sizeof(Max_Lag)); code += sizeof(Max_Lag); + memcpy(&Max_Lead, code, sizeof(Max_Lead)); code += sizeof(Max_Lead); + memcpy(&u_count_int, code, sizeof(u_count_int)); code += sizeof(u_count_int); + } + return code; + }; #endif }; - - #ifdef BYTE_CODE -typedef vector<pair<Tags, void* > > tags_liste_type; +typedef vector<pair<Tags, void * > > tags_liste_type; class CodeLoad { private: uint8_t *code; public: - inline void* get_current_code() {return code;}; - inline tags_liste_type get_op_code(string file_name) - { - tags_liste_type tags_liste; - ifstream CompiledCode; - streamoff Code_Size; - CompiledCode.open((file_name + ".cod").c_str(),std::ios::in | std::ios::binary| std::ios::ate); - if (!CompiledCode.is_open()) - { - return tags_liste; - } - Code_Size=CompiledCode.tellg(); - CompiledCode.seekg(std::ios::beg); - code=(uint8_t*)mxMalloc(Code_Size); - CompiledCode.seekg(0); - CompiledCode.read(reinterpret_cast<char *>(code), Code_Size); - CompiledCode.close(); - bool done = false; - while(!done) - { - switch (*code) - { - case FLDZ: -#ifdef DEBUGL - mexPrintf("FLDZ = %d size = %d\n",FLDZ, sizeof(FLDZ_)); -#endif - tags_liste.push_back(make_pair(FLDZ, code)); - code += sizeof(FLDZ_); - break; - case FEND: -#ifdef DEBUGL - mexPrintf("FEND\n"); -#endif - tags_liste.push_back(make_pair(FEND, code)); - code += sizeof(FEND_); - done = true; - break; - case FENDBLOCK: -#ifdef DEBUGL - mexPrintf("FENDBLOCK\n"); -#endif - tags_liste.push_back(make_pair(FENDBLOCK, code)); - code += sizeof(FENDBLOCK_); - break; - case FENDEQU: -#ifdef DEBUGL - mexPrintf("FENDEQU\n"); -#endif - tags_liste.push_back(make_pair(FENDEQU, code)); - code += sizeof(FENDEQU_); - break; - case FCUML: -#ifdef DEBUGL - mexPrintf("FCUML\n"); -#endif - tags_liste.push_back(make_pair(FCUML, code)); - code += sizeof(FCUML_); - break; - case FDIMT: -#ifdef DEBUGL - mexPrintf("FDIMT = %d size = %d\n",FDIMT, sizeof(FDIMT_)); -#endif - tags_liste.push_back(make_pair(FDIMT, code)); - code += sizeof(FDIMT_); - break; - case FDIMST: -#ifdef DEBUGL - mexPrintf("FDIMST\n"); -#endif - tags_liste.push_back(make_pair(FDIMST, code)); - code += sizeof(FDIMST_); - break; - case FLDC: -#ifdef DEBUGL - mexPrintf("FLDC\n"); -#endif - tags_liste.push_back(make_pair(FLDC, code)); - code += sizeof(FLDC_); - break; - case FLDU: -#ifdef DEBUGL - mexPrintf("FLDU\n"); -#endif - tags_liste.push_back(make_pair(FLDU, code)); - code += sizeof(FLDU_); - break; - case FLDSU: -#ifdef DEBUGL - mexPrintf("FLDSU\n"); -#endif - tags_liste.push_back(make_pair(FLDSU, code)); - code += sizeof(FLDSU_); - break; - case FLDR: -#ifdef DEBUGL - mexPrintf("FLDR\n"); -#endif - tags_liste.push_back(make_pair(FLDR, code)); - code += sizeof(FLDR_); - break; - case FLDT: -#ifdef DEBUGL - mexPrintf("FLDT\n"); -#endif - tags_liste.push_back(make_pair(FLDT, code)); - code += sizeof(FLDT_); - break; - case FLDST: -#ifdef DEBUGL - mexPrintf("FLDST\n"); -#endif - tags_liste.push_back(make_pair(FLDST, code)); - code += sizeof(FLDST_); - break; - case FSTPT: -#ifdef DEBUGL - mexPrintf("FSTPT = %d size = %d\n",FSTPT, sizeof(FSTPT_)); -#endif - tags_liste.push_back(make_pair(FSTPT, code)); - code += sizeof(FSTPT_); - break; - case FSTPST: -#ifdef DEBUGL - mexPrintf("FSTPST\n"); -#endif - tags_liste.push_back(make_pair(FSTPST, code)); - code += sizeof(FSTPST_); - break; - case FSTPR: -#ifdef DEBUGL - mexPrintf("FSTPR\n"); -#endif - tags_liste.push_back(make_pair(FSTPR, code)); - code += sizeof(FSTPR_); - break; - case FSTPU: -#ifdef DEBUGL - mexPrintf("FSTPU\n"); -#endif - tags_liste.push_back(make_pair(FSTPU, code)); - code += sizeof(FSTPU_); - break; - case FSTPSU: -#ifdef DEBUGL - mexPrintf("FSTPSU\n"); -#endif - tags_liste.push_back(make_pair(FSTPSU, code)); - code += sizeof(FSTPSU_); - break; - case FSTPG: -#ifdef DEBUGL - mexPrintf("FSTPG\n"); -#endif - tags_liste.push_back(make_pair(FSTPG, code)); - code += sizeof(FSTPG_); - break; - case FUNARY: -#ifdef DEBUGL - mexPrintf("FUNARY\n"); -#endif - tags_liste.push_back(make_pair(FUNARY, code)); - code += sizeof(FUNARY_); - break; - case FBINARY: -#ifdef DEBUGL - mexPrintf("FBINARY\n"); -#endif - tags_liste.push_back(make_pair(FBINARY, code)); - code += sizeof(FBINARY_); - break; - case FOK: -#ifdef DEBUGL - mexPrintf("FOK\n"); -#endif - tags_liste.push_back(make_pair(FOK, code)); - code += sizeof(FOK_); - break; - case FLDVS: -#ifdef DEBUGL - mexPrintf("FLDVS\n"); -#endif - tags_liste.push_back(make_pair(FLDVS, code)); - code += sizeof(FLDVS_); - break; - case FLDSV: -#ifdef DEBUGL - mexPrintf("FLDSV\n"); -#endif - tags_liste.push_back(make_pair(FLDSV, code)); - code += sizeof(FLDSV_); - break; - case FSTPSV: -#ifdef DEBUGL - mexPrintf("FSTPSV\n"); -#endif - tags_liste.push_back(make_pair(FSTPSV, code)); - code += sizeof(FSTPSV_); - break; - case FLDV: -#ifdef DEBUGL - mexPrintf("FLDV\n"); -#endif - tags_liste.push_back(make_pair(FLDV, code)); - code += sizeof(FLDV_); - break; - case FSTPV: -#ifdef DEBUGL - mexPrintf("FSTPV\n"); -#endif - tags_liste.push_back(make_pair(FSTPV, code)); - code += sizeof(FSTPV_); - break; - case FBEGINBLOCK: -#ifdef DEBUGL - mexPrintf("FBEGINBLOCK\n"); -#endif - { - FBEGINBLOCK_ *fbegin_block = new FBEGINBLOCK_; - - code = fbegin_block->load(code); - - tags_liste.push_back(make_pair(FBEGINBLOCK, fbegin_block)); - } - break; - default: - mexPrintf("Unknown Tag value=%d code=%x\n",*code, code); - done = true; - } - } - return tags_liste; - }; + inline void * + get_current_code() + { + return code; + }; + inline tags_liste_type + get_op_code(string file_name) + { + tags_liste_type tags_liste; + ifstream CompiledCode; + streamoff Code_Size; + CompiledCode.open((file_name + ".cod").c_str(), std::ios::in | std::ios::binary| std::ios::ate); + if (!CompiledCode.is_open()) + { + return tags_liste; + } + Code_Size = CompiledCode.tellg(); + CompiledCode.seekg(std::ios::beg); + code = (uint8_t *) mxMalloc(Code_Size); + CompiledCode.seekg(0); + CompiledCode.read(reinterpret_cast<char *>(code), Code_Size); + CompiledCode.close(); + bool done = false; + while (!done) + { + switch (*code) + { + case FLDZ: +# ifdef DEBUGL + mexPrintf("FLDZ = %d size = %d\n", FLDZ, sizeof(FLDZ_)); +# endif + tags_liste.push_back(make_pair(FLDZ, code)); + code += sizeof(FLDZ_); + break; + case FEND: +# ifdef DEBUGL + mexPrintf("FEND\n"); +# endif + tags_liste.push_back(make_pair(FEND, code)); + code += sizeof(FEND_); + done = true; + break; + case FENDBLOCK: +# ifdef DEBUGL + mexPrintf("FENDBLOCK\n"); +# endif + tags_liste.push_back(make_pair(FENDBLOCK, code)); + code += sizeof(FENDBLOCK_); + break; + case FENDEQU: +# ifdef DEBUGL + mexPrintf("FENDEQU\n"); +# endif + tags_liste.push_back(make_pair(FENDEQU, code)); + code += sizeof(FENDEQU_); + break; + case FCUML: +# ifdef DEBUGL + mexPrintf("FCUML\n"); +# endif + tags_liste.push_back(make_pair(FCUML, code)); + code += sizeof(FCUML_); + break; + case FDIMT: +# ifdef DEBUGL + mexPrintf("FDIMT = %d size = %d\n", FDIMT, sizeof(FDIMT_)); +# endif + tags_liste.push_back(make_pair(FDIMT, code)); + code += sizeof(FDIMT_); + break; + case FDIMST: +# ifdef DEBUGL + mexPrintf("FDIMST\n"); +# endif + tags_liste.push_back(make_pair(FDIMST, code)); + code += sizeof(FDIMST_); + break; + case FLDC: +# ifdef DEBUGL + mexPrintf("FLDC\n"); +# endif + tags_liste.push_back(make_pair(FLDC, code)); + code += sizeof(FLDC_); + break; + case FLDU: +# ifdef DEBUGL + mexPrintf("FLDU\n"); +# endif + tags_liste.push_back(make_pair(FLDU, code)); + code += sizeof(FLDU_); + break; + case FLDSU: +# ifdef DEBUGL + mexPrintf("FLDSU\n"); +# endif + tags_liste.push_back(make_pair(FLDSU, code)); + code += sizeof(FLDSU_); + break; + case FLDR: +# ifdef DEBUGL + mexPrintf("FLDR\n"); +# endif + tags_liste.push_back(make_pair(FLDR, code)); + code += sizeof(FLDR_); + break; + case FLDT: +# ifdef DEBUGL + mexPrintf("FLDT\n"); +# endif + tags_liste.push_back(make_pair(FLDT, code)); + code += sizeof(FLDT_); + break; + case FLDST: +# ifdef DEBUGL + mexPrintf("FLDST\n"); +# endif + tags_liste.push_back(make_pair(FLDST, code)); + code += sizeof(FLDST_); + break; + case FSTPT: +# ifdef DEBUGL + mexPrintf("FSTPT = %d size = %d\n", FSTPT, sizeof(FSTPT_)); +# endif + tags_liste.push_back(make_pair(FSTPT, code)); + code += sizeof(FSTPT_); + break; + case FSTPST: +# ifdef DEBUGL + mexPrintf("FSTPST\n"); +# endif + tags_liste.push_back(make_pair(FSTPST, code)); + code += sizeof(FSTPST_); + break; + case FSTPR: +# ifdef DEBUGL + mexPrintf("FSTPR\n"); +# endif + tags_liste.push_back(make_pair(FSTPR, code)); + code += sizeof(FSTPR_); + break; + case FSTPU: +# ifdef DEBUGL + mexPrintf("FSTPU\n"); +# endif + tags_liste.push_back(make_pair(FSTPU, code)); + code += sizeof(FSTPU_); + break; + case FSTPSU: +# ifdef DEBUGL + mexPrintf("FSTPSU\n"); +# endif + tags_liste.push_back(make_pair(FSTPSU, code)); + code += sizeof(FSTPSU_); + break; + case FSTPG: +# ifdef DEBUGL + mexPrintf("FSTPG\n"); +# endif + tags_liste.push_back(make_pair(FSTPG, code)); + code += sizeof(FSTPG_); + break; + case FUNARY: +# ifdef DEBUGL + mexPrintf("FUNARY\n"); +# endif + tags_liste.push_back(make_pair(FUNARY, code)); + code += sizeof(FUNARY_); + break; + case FBINARY: +# ifdef DEBUGL + mexPrintf("FBINARY\n"); +# endif + tags_liste.push_back(make_pair(FBINARY, code)); + code += sizeof(FBINARY_); + break; + case FOK: +# ifdef DEBUGL + mexPrintf("FOK\n"); +# endif + tags_liste.push_back(make_pair(FOK, code)); + code += sizeof(FOK_); + break; + case FLDVS: +# ifdef DEBUGL + mexPrintf("FLDVS\n"); +# endif + tags_liste.push_back(make_pair(FLDVS, code)); + code += sizeof(FLDVS_); + break; + case FLDSV: +# ifdef DEBUGL + mexPrintf("FLDSV\n"); +# endif + tags_liste.push_back(make_pair(FLDSV, code)); + code += sizeof(FLDSV_); + break; + case FSTPSV: +# ifdef DEBUGL + mexPrintf("FSTPSV\n"); +# endif + tags_liste.push_back(make_pair(FSTPSV, code)); + code += sizeof(FSTPSV_); + break; + case FLDV: +# ifdef DEBUGL + mexPrintf("FLDV\n"); +# endif + tags_liste.push_back(make_pair(FLDV, code)); + code += sizeof(FLDV_); + break; + case FSTPV: +# ifdef DEBUGL + mexPrintf("FSTPV\n"); +# endif + tags_liste.push_back(make_pair(FSTPV, code)); + code += sizeof(FSTPV_); + break; + case FBEGINBLOCK: +# ifdef DEBUGL + mexPrintf("FBEGINBLOCK\n"); +# endif + { + FBEGINBLOCK_ *fbegin_block = new FBEGINBLOCK_; + + code = fbegin_block->load(code); + + tags_liste.push_back(make_pair(FBEGINBLOCK, fbegin_block)); + } + break; + default: + mexPrintf("Unknown Tag value=%d code=%x\n", *code, code); + done = true; + } + } + return tags_liste; + }; }; #endif #pragma pack(pop) diff --git a/ComputingTasks.cc b/ComputingTasks.cc index 949c21f093b12f1e6632c3d542c7389232dfed72..ac377eca612e19776a544ee4f2053c1fd464708b 100644 --- a/ComputingTasks.cc +++ b/ComputingTasks.cc @@ -67,18 +67,19 @@ ModelInfoStatement::ModelInfoStatement(const OptionsList &options_list_arg) : { } -void ModelInfoStatement::checkPass(ModFileStructure &mod_file_struct) +void +ModelInfoStatement::checkPass(ModFileStructure &mod_file_struct) { //mod_file_struct.model_info_present = true; } -void ModelInfoStatement::writeOutput(ostream &output, const string &basename) const +void +ModelInfoStatement::writeOutput(ostream &output, const string &basename) const { options_list.writeOutput(output); output << "model_info();\n"; } - SimulStatement::SimulStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -112,7 +113,7 @@ StochSimulStatement::checkPass(ModFileStructure &mod_file_struct) // Fill in option_order of mod_file_struct OptionsList::num_options_type::const_iterator it = options_list.num_options.find("order"); if (it != options_list.num_options.end()) - mod_file_struct.order_option = max(mod_file_struct.order_option,atoi(it->second.c_str())); + mod_file_struct.order_option = max(mod_file_struct.order_option, atoi(it->second.c_str())); // Fill in mod_file_struct.partial_information it = options_list.num_options.find("partial_information"); @@ -211,7 +212,7 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct) // Fill in option_order of mod_file_struct OptionsList::num_options_type::const_iterator it = options_list.num_options.find("order"); if (it != options_list.num_options.end()) - mod_file_struct.order_option = max(mod_file_struct.order_option,atoi(it->second.c_str())); + mod_file_struct.order_option = max(mod_file_struct.order_option, atoi(it->second.c_str())); // Fill in mod_file_struct.partial_information it = options_list.num_options.find("partial_information"); @@ -274,7 +275,7 @@ DynareSensitivityStatement::checkPass(ModFileStructure &mod_file_struct) void DynareSensitivityStatement::writeOutput(ostream &output, const string &basename) const { - options_list.writeOutput(output,"options_gsa"); + options_list.writeOutput(output, "options_gsa"); output << "dynare_sensitivity(options_gsa);" << endl; } @@ -362,12 +363,12 @@ EstimatedParamsStatement::writeOutput(ostream &output, const string &basename) c vector<EstimationParams>::const_iterator it; - for(it = estim_params_list.begin(); it != estim_params_list.end(); it++) + for (it = estim_params_list.begin(); it != estim_params_list.end(); it++) { int symb_id = symbol_table.getTypeSpecificID(it->name) + 1; SymbolType symb_type = symbol_table.getType(it->name); - switch(it->type) + switch (it->type) { case 1: if (symb_type == eExogenous) @@ -421,7 +422,7 @@ EstimatedParamsInitStatement::writeOutput(ostream &output, const string &basenam { vector<EstimationParams>::const_iterator it; - for(it = estim_params_list.begin(); it != estim_params_list.end(); it++) + for (it = estim_params_list.begin(); it != estim_params_list.end(); it++) { int symb_id = symbol_table.getTypeSpecificID(it->name) + 1; SymbolType symb_type = symbol_table.getType(it->name); @@ -482,7 +483,7 @@ EstimatedParamsBoundsStatement::writeOutput(ostream &output, const string &basen { vector<EstimationParams>::const_iterator it; - for(it = estim_params_list.begin(); it != estim_params_list.end(); it++) + for (it = estim_params_list.begin(); it != estim_params_list.end(); it++) { int symb_id = symbol_table.getTypeSpecificID(it->name) + 1; SymbolType symb_type = symbol_table.getType(it->name); @@ -570,7 +571,7 @@ ObservationTrendsStatement::writeOutput(ostream &output, const string &basename) trend_elements_type::const_iterator it; - for(it = trend_elements.begin(); it != trend_elements.end(); it++) + for (it = trend_elements.begin(); it != trend_elements.end(); it++) { SymbolType type = symbol_table.getType(it->first); if (type == eEndogenous) @@ -604,7 +605,7 @@ CalibVarStatement::writeOutput(ostream &output, const string &basename) const << "% CALIB_VAR" << endl << "%" << endl; - for(int i = 1; i < 4 ; i++) + for (int i = 1; i < 4; i++) { output << "calib_var_index{" << i << "} = [];\n"; output << "calib_targets{" << i << "} = [];\n"; @@ -612,8 +613,8 @@ CalibVarStatement::writeOutput(ostream &output, const string &basename) const } // Print calibration variances - for(calib_var_type::const_iterator it = calib_var.begin(); - it != calib_var.end(); it++) + for (calib_var_type::const_iterator it = calib_var.begin(); + it != calib_var.end(); it++) { const string &name = it->first; const string &weight = it->second.first; @@ -639,8 +640,8 @@ CalibVarStatement::writeOutput(ostream &output, const string &basename) const } // Print calibration covariances - for(calib_covar_type::const_iterator it = calib_covar.begin(); - it != calib_covar.end(); it++) + for (calib_covar_type::const_iterator it = calib_covar.begin(); + it != calib_covar.end(); it++) { const string &name1 = it->first.first; const string &name2 = it->first.second; @@ -670,8 +671,8 @@ CalibVarStatement::writeOutput(ostream &output, const string &basename) const // Print calibration autocorrelations int max_iar = 3; - for(calib_ac_type::const_iterator it = calib_ac.begin(); - it != calib_ac.end(); it++) + for (calib_ac_type::const_iterator it = calib_ac.begin(); + it != calib_ac.end(); it++) { const string &name = it->first.first; int iar = it->first.second + 3; @@ -683,7 +684,7 @@ CalibVarStatement::writeOutput(ostream &output, const string &basename) const if (iar > max_iar) { // Create new variables - for(int i = max_iar + 1; i <= iar; i++) + for (int i = max_iar + 1; i <= iar; i++) { output << "calib_var_index{" << i << "} = [];\n"; output << "calib_targets{" << i << "} = [];\n"; @@ -736,7 +737,7 @@ OsrStatement::checkPass(ModFileStructure &mod_file_struct) // Fill in option_order of mod_file_struct OptionsList::num_options_type::const_iterator it = options_list.num_options.find("order"); if (it != options_list.num_options.end()) - mod_file_struct.order_option = max(mod_file_struct.order_option,atoi(it->second.c_str())); + mod_file_struct.order_option = max(mod_file_struct.order_option, atoi(it->second.c_str())); // Fill in mod_file_struct.partial_information it = options_list.num_options.find("partial_information"); @@ -776,8 +777,8 @@ OptimWeightsStatement::writeOutput(ostream &output, const string &basename) cons << "optim_weights_ = sparse(M_.endo_nbr,M_.endo_nbr);" << endl << "obj_var_ = [];" << endl << endl; - for(var_weights_type::const_iterator it = var_weights.begin(); - it != var_weights.end(); it++) + for (var_weights_type::const_iterator it = var_weights.begin(); + it != var_weights.end(); it++) { const string &name = it->first; const NodeID value = it->second; @@ -788,8 +789,8 @@ OptimWeightsStatement::writeOutput(ostream &output, const string &basename) cons output << "obj_var_ = [obj_var_; " << id << "];\n"; } - for(covar_weights_type::const_iterator it = covar_weights.begin(); - it != covar_weights.end(); it++) + for (covar_weights_type::const_iterator it = covar_weights.begin(); + it != covar_weights.end(); it++) { const string &name1 = it->first.first; const string &name2 = it->first.second; @@ -848,8 +849,8 @@ ModelComparisonStatement::writeOutput(ostream &output, const string &basename) c output << "ModelNames_ = {};" << endl; output << "ModelPriors_ = [];" << endl; - for(filename_list_type::const_iterator it = filename_list.begin(); - it != filename_list.end(); it++) + for (filename_list_type::const_iterator it = filename_list.begin(); + it != filename_list.end(); it++) { output << "ModelNames_ = { ModelNames_{:} '" << (*it).first << "'};" << endl; output << "ModelPriors_ = [ ModelPriors_ ; " << (*it).second << "];" << endl; @@ -959,8 +960,6 @@ MS_SBVARStatement::writeOutput(ostream &output, const string &basename) const output << "swz_sbvar(1,M_,options_);" << endl; } - - IdentificationStatement::IdentificationStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -1002,7 +1001,7 @@ WriteLatexStaticModelStatement::writeOutput(ostream &output, const string &basen } ShockDecompositionStatement::ShockDecompositionStatement(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) { @@ -1104,7 +1103,7 @@ SvarIdentificationStatement::writeOutput(ostream &output, const string &basename int r = getMaxLag(); int k = r*n+m; - if (k<1) + if (k < 1) { cerr << "ERROR: lag = " << r << ", number of endogenous variables = " << n @@ -1113,7 +1112,7 @@ SvarIdentificationStatement::writeOutput(ostream &output, const string &basename << " of the .mod file, please report it to the Dynare Team." << endl; exit(EXIT_FAILURE); } - if (n<1) + if (n < 1) { cerr << "ERROR: Number of endogenous variables = " << n << "< 1. If this is not a logical " << "error in the specification of the .mod file, please report it to the Dynare Team." << endl; @@ -1128,7 +1127,7 @@ SvarIdentificationStatement::writeOutput(ostream &output, const string &basename { int j = it->second.at(h) + 1; int i = it->first.second; - if (j < 1 || j > n || (int)h+1 > n || i < 1) + if (j < 1 || j > n || (int) h+1 > n || i < 1) { cerr << "SvarIdentificationStatement::writeOutput() Should not arrive here (2). Please report this to the Dynare Team." << endl; exit(EXIT_FAILURE); @@ -1186,12 +1185,12 @@ MarkovSwitchingStatement::writeOutput(ostream &output, const string &basename) c itState = options_list.num_options.find("ms.state"); itNOS = options_list.num_options.find("ms.number_of_states"); - if (itState != options_list.num_options.end() && - itNOS == options_list.num_options.end()) + if (itState != options_list.num_options.end() + && itNOS == options_list.num_options.end()) output << "options_.ms.ms_chain(" << itChain->second << ").state(" << itState->second << ").duration = " << itDuration->second << ";" << endl; - else if (itState == options_list.num_options.end() && - itNOS != options_list.num_options.end()) - for (int i=0; i<atoi(itNOS->second.c_str()); i++) + else if (itState == options_list.num_options.end() + && itNOS != options_list.num_options.end()) + for (int i = 0; i < atoi(itNOS->second.c_str()); i++) output << "options_.ms.ms_chain(" << itChain->second << ").state(" << i+1 << ").duration = " << itDuration->second << ";" << endl; else { @@ -1200,7 +1199,6 @@ MarkovSwitchingStatement::writeOutput(ostream &output, const string &basename) c } } - SvarStatement::SvarStatement(const OptionsList &options_list_arg) : options_list(options_list_arg) { @@ -1224,17 +1222,17 @@ SvarStatement::writeOutput(ostream &output, const string &basename) const it0 = options_list.string_options.find("ms.coefficients"); it1 = options_list.string_options.find("ms.variances"); it2 = options_list.string_options.find("ms.constants"); - if (it0 != options_list.string_options.end() && - it1 == options_list.string_options.end() && - it2 == options_list.string_options.end()) + if (it0 != options_list.string_options.end() + && it1 == options_list.string_options.end() + && it2 == options_list.string_options.end()) output << "." << it0->second; - else if (it0 == options_list.string_options.end() && - it1 != options_list.string_options.end() && - it2 == options_list.string_options.end()) + else if (it0 == options_list.string_options.end() + && it1 != options_list.string_options.end() + && it2 == options_list.string_options.end()) output << "." << it1->second; - else if (it0 == options_list.string_options.end() && - it1 == options_list.string_options.end() && - it2 != options_list.string_options.end()) + else if (it0 == options_list.string_options.end() + && it1 == options_list.string_options.end() + && it2 != options_list.string_options.end()) output << "." << it2->second; else { @@ -1249,8 +1247,8 @@ SvarStatement::writeOutput(ostream &output, const string &basename) const if (itv->second.size() > 1) { output << "["; - for (vector<int>::const_iterator viit=itv->second.begin(); - viit!=itv->second.end(); viit++) + for (vector<int>::const_iterator viit = itv->second.begin(); + viit != itv->second.end(); viit++) output << *viit << ";"; output << "];" << endl; } diff --git a/ComputingTasks.hh b/ComputingTasks.hh index 5d0a0aea79e1ba88096402d42c189a50aaeb5674..cfedca2ba77b0ff6f5fdd2829f47ebfc3f9b1f80 100644 --- a/ComputingTasks.hh +++ b/ComputingTasks.hh @@ -272,7 +272,8 @@ public: string name, name2, prior; NodeID init_val, low_bound, up_bound, mean, std, p3, p4, jscale; - void init(const DataTree &datatree) + void + init(const DataTree &datatree) { type = 0; name = ""; @@ -465,7 +466,7 @@ private: const OptionsList options_list; public: ShockDecompositionStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg); + const OptionsList &options_list_arg); virtual void writeOutput(ostream &output, const string &basename) const; }; diff --git a/DataTree.cc b/DataTree.cc index c116adfba710a65f2517016f1ff19086c5d1720a..712d4e90b663325a153c2dc9424a2bf20082c2a9 100644 --- a/DataTree.cc +++ b/DataTree.cc @@ -265,7 +265,8 @@ DataTree::AddLog(NodeID iArg1) } } -NodeID DataTree::AddLog10(NodeID iArg1) +NodeID +DataTree::AddLog10(NodeID iArg1) { if (iArg1 != Zero && iArg1 != One) return AddUnaryOp(oLog10, iArg1); @@ -459,8 +460,8 @@ DataTree::AddUnknownFunction(const string &function_name, const vector<NodeID> & bool DataTree::isSymbolUsed(int symb_id) const { - for(variable_node_map_type::const_iterator it = variable_node_map.begin(); - it != variable_node_map.end(); it++) + for (variable_node_map_type::const_iterator it = variable_node_map.begin(); + it != variable_node_map.end(); it++) if (it->first.first == symb_id) return true; @@ -485,8 +486,8 @@ DataTree::getDynJacobianCol(int deriv_id) const throw (UnknownDerivIDException) bool DataTree::containsSteadyStateOperator() const { - for(unary_op_node_map_type::const_iterator it = unary_op_node_map.begin(); - it != unary_op_node_map.end(); it++) + for (unary_op_node_map_type::const_iterator it = unary_op_node_map.begin(); + it != unary_op_node_map.end(); it++) if (it->first.second == oSteadyState) return true; diff --git a/DataTree.hh b/DataTree.hh index 1bd4b40d82ea3db8589dcbf08dfc3cc927d293c1..039aae26da90a9e0185062fd1ee9d466b757de64 100644 --- a/DataTree.hh +++ b/DataTree.hh @@ -58,7 +58,7 @@ protected: unary_op_node_map_type unary_op_node_map; typedef map<pair<pair<NodeID, NodeID>, BinaryOpcode>, BinaryOpNode *> binary_op_node_map_type; binary_op_node_map_type binary_op_node_map; - typedef map<pair<pair<pair<NodeID, NodeID>,NodeID>, TrinaryOpcode>, TrinaryOpNode *> trinary_op_node_map_type; + typedef map<pair<pair<pair<NodeID, NodeID>, NodeID>, TrinaryOpcode>, TrinaryOpNode *> trinary_op_node_map_type; trinary_op_node_map_type trinary_op_node_map; //! Stores local variables value (maps symbol ID to corresponding node) @@ -94,7 +94,9 @@ public: { public: string name; - LocalVariableException(const string &name_arg) : name(name_arg) {} + LocalVariableException(const string &name_arg) : name(name_arg) + { + } }; //! Adds a numerical constant @@ -190,7 +192,11 @@ public: virtual int getDynJacobianCol(int deriv_id) const throw (UnknownDerivIDException); //! Returns bool indicating whether DataTree represents a Dynamic Model (returns true in DynamicModel.hh) - virtual bool isDynamic() const { return false; }; + virtual bool + isDynamic() const + { + return false; + }; }; inline NodeID @@ -232,7 +238,7 @@ DataTree::AddUnaryOp(UnaryOpcode op_code, NodeID arg, int arg_exp_info_set) double val = UnaryOpNode::eval_opcode(op_code, argval); return AddPossiblyNegativeConstant(val); } - catch(ExprNode::EvalException &e) + catch (ExprNode::EvalException &e) { } } @@ -254,7 +260,7 @@ DataTree::AddBinaryOp(NodeID arg1, BinaryOpcode op_code, NodeID arg2) double val = BinaryOpNode::eval_opcode(argval1, op_code, argval2); return AddPossiblyNegativeConstant(val); } - catch(ExprNode::EvalException &e) + catch (ExprNode::EvalException &e) { } return new BinaryOpNode(*this, arg1, op_code, arg2); @@ -276,7 +282,7 @@ DataTree::AddTrinaryOp(NodeID arg1, TrinaryOpcode op_code, NodeID arg2, NodeID a double val = TrinaryOpNode::eval_opcode(argval1, op_code, argval2, argval3); return AddPossiblyNegativeConstant(val); } - catch(ExprNode::EvalException &e) + catch (ExprNode::EvalException &e) { } return new TrinaryOpNode(*this, arg1, op_code, arg2, arg3); diff --git a/DynamicModel.cc b/DynamicModel.cc index 90f3d22959e89f360d3fc563c53c3f7a2a846882..26b7c2c91a08d5de8ea87755504f5620a4bbc308 100644 --- a/DynamicModel.cc +++ b/DynamicModel.cc @@ -37,15 +37,15 @@ DynamicModel::DynamicModel(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg) : - ModelTree(symbol_table_arg, num_constants_arg), - max_lag(0), max_lead(0), - max_endo_lag(0), max_endo_lead(0), - max_exo_lag(0), max_exo_lead(0), - max_exo_det_lag(0), max_exo_det_lead(0), - dynJacobianColsNbr(0), - global_temporary_terms(true), - cutoff(1e-15), - mfs(0) + ModelTree(symbol_table_arg, num_constants_arg), + max_lag(0), max_lead(0), + max_endo_lag(0), max_endo_lead(0), + max_exo_lag(0), max_exo_lead(0), + max_exo_det_lag(0), max_exo_det_lead(0), + dynJacobianColsNbr(0), + global_temporary_terms(true), + cutoff(1e-15), + mfs(0) { } @@ -57,17 +57,16 @@ DynamicModel::AddVariable(int symb_id, int lag) void DynamicModel::compileDerivative(ofstream &code_file, int eq, int symb_id, int lag, map_idx_type &map_idx) const - { - first_derivatives_type::const_iterator it = first_derivatives.find(make_pair(eq, getDerivID(symbol_table.getID(eEndogenous, symb_id), lag))); - if (it != first_derivatives.end()) - (it->second)->compile(code_file, false, temporary_terms, map_idx, true, false); - else - { - FLDZ_ fldz; - fldz.write(code_file); - } - } - +{ + first_derivatives_type::const_iterator it = first_derivatives.find(make_pair(eq, getDerivID(symbol_table.getID(eEndogenous, symb_id), lag))); + if (it != first_derivatives.end()) + (it->second)->compile(code_file, false, temporary_terms, map_idx, true, false); + else + { + FLDZ_ fldz; + fldz.write(code_file); + } +} void DynamicModel::compileChainRuleDerivative(ofstream &code_file, int eqr, int varr, int lag, map_idx_type &map_idx) const @@ -82,7 +81,6 @@ DynamicModel::compileChainRuleDerivative(ofstream &code_file, int eqr, int varr, } } - void DynamicModel::computeTemporaryTermsOrdered() { @@ -97,10 +95,10 @@ DynamicModel::computeTemporaryTermsOrdered() unsigned int nb_blocks = getNbBlocks(); v_temporary_terms = vector<vector<temporary_terms_type> >(nb_blocks); - v_temporary_terms_inuse = vector<temporary_terms_inuse_type> (nb_blocks); + v_temporary_terms_inuse = vector<temporary_terms_inuse_type>(nb_blocks); temporary_terms.clear(); - if(!global_temporary_terms) + if (!global_temporary_terms) { for (unsigned int block = 0; block < nb_blocks; block++) { @@ -112,17 +110,17 @@ DynamicModel::computeTemporaryTermsOrdered() v_temporary_terms[block] = vector<temporary_terms_type>(block_size); for (unsigned int i = 0; i < block_size; i++) { - if (i<block_nb_recursives && isBlockEquationRenormalized( block, i)) - getBlockEquationRenormalizedNodeID( block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); + if (i < block_nb_recursives && isBlockEquationRenormalized(block, i)) + getBlockEquationRenormalizedNodeID(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); else { - eq_node = (BinaryOpNode*)getBlockEquationNodeID(block, i); + eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i); eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); } } for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) { - NodeID id=it->second.second; + NodeID id = it->second.second; id->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1); } for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++) @@ -146,17 +144,17 @@ DynamicModel::computeTemporaryTermsOrdered() v_temporary_terms[block] = vector<temporary_terms_type>(block_size); for (unsigned int i = 0; i < block_size; i++) { - if (i<block_nb_recursives && isBlockEquationRenormalized( block, i)) - getBlockEquationRenormalizedNodeID( block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); + if (i < block_nb_recursives && isBlockEquationRenormalized(block, i)) + getBlockEquationRenormalizedNodeID(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); else { - eq_node = (BinaryOpNode*)getBlockEquationNodeID(block, i); + eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i); eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); } } for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) { - NodeID id=it->second.second; + NodeID id = it->second.second; id->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1); } for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++) @@ -173,17 +171,17 @@ DynamicModel::computeTemporaryTermsOrdered() set<int> temporary_terms_in_use; for (unsigned int i = 0; i < block_size; i++) { - if (i<block_nb_recursives && isBlockEquationRenormalized( block, i)) - getBlockEquationRenormalizedNodeID( block, i)->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block); + if (i < block_nb_recursives && isBlockEquationRenormalized(block, i)) + getBlockEquationRenormalizedNodeID(block, i)->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block); else { - eq_node = (BinaryOpNode*)getBlockEquationNodeID(block, i); + eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i); eq_node->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block); } } for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) { - NodeID id=it->second.second; + NodeID id = it->second.second; id->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block); } for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++) @@ -193,1736 +191,1734 @@ DynamicModel::computeTemporaryTermsOrdered() v_temporary_terms_inuse[block] = temporary_terms_in_use; } // Add a mapping form node ID to temporary terms order - int j=0; + int j = 0; for (temporary_terms_type::const_iterator it = temporary_terms.begin(); it != temporary_terms.end(); it++) - map_idx[(*it)->idx]=j++; + map_idx[(*it)->idx] = j++; } } void DynamicModel::writeModelEquationsOrdered_M(const string &dynamic_basename) const - { - string tmp_s, sps; - ostringstream tmp_output, tmp1_output, global_output; - NodeID lhs=NULL, rhs=NULL; - BinaryOpNode *eq_node; - ostringstream Uf[symbol_table.endo_nbr()]; - map<NodeID, int> reference_count; - temporary_terms_type local_temporary_terms; - ofstream output; - int nze, nze_exo, nze_other_endo; - vector<int> feedback_variables; - ExprNodeOutputType local_output_type; - - if(global_temporary_terms) - { - local_output_type = oMatlabDynamicModelSparse; - local_temporary_terms = temporary_terms; - } - else - local_output_type = oMatlabDynamicModelSparseLocalTemporaryTerms; - - //---------------------------------------------------------------------- - //For each block - for (unsigned int block = 0; block < getNbBlocks(); block++) - { - - //recursive_variables.clear(); - feedback_variables.clear(); - //For a block composed of a single equation determines wether we have to evaluate or to solve the equation - nze = derivative_endo[block].size(); - nze_other_endo = derivative_other_endo[block].size(); - nze_exo = derivative_exo[block].size(); - BlockSimulationType simulation_type = getBlockSimulationType(block); - unsigned int block_size = getBlockSize(block); - unsigned int block_mfs = getBlockMfs(block); - unsigned int block_recursive = block_size - block_mfs; - unsigned int block_exo_size = exo_block[block].size(); - unsigned int block_exo_det_size = exo_det_block[block].size(); - unsigned int block_other_endo_size = other_endo_block[block].size(); - int block_max_lag=max_leadlag_block[block].first; - if(global_temporary_terms) - { - local_output_type = oMatlabDynamicModelSparse; - local_temporary_terms = temporary_terms; - } - else - local_output_type = oMatlabDynamicModelSparseLocalTemporaryTerms; - - tmp1_output.str(""); - tmp1_output << dynamic_basename << "_" << block+1 << ".m"; - output.open(tmp1_output.str().c_str(), ios::out | ios::binary); - output << "%\n"; - output << "% " << tmp1_output.str() << " : Computes dynamic model for Dynare\n"; - output << "%\n"; - output << "% Warning : this file is generated automatically by Dynare\n"; - output << "% from model file (.mod)\n\n"; - output << "%/\n"; - if (simulation_type ==EVALUATE_BACKWARD || simulation_type ==EVALUATE_FORWARD) - { - output << "function [y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, jacobian_eval, y_kmin, periods)\n"; - } - else if (simulation_type ==SOLVE_FORWARD_COMPLETE || simulation_type ==SOLVE_BACKWARD_COMPLETE) - output << "function [residual, y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, it_, jacobian_eval)\n"; - else if (simulation_type ==SOLVE_BACKWARD_SIMPLE || simulation_type ==SOLVE_FORWARD_SIMPLE) - output << "function [residual, y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, it_, jacobian_eval)\n"; - else - output << "function [residual, y, g1, g2, g3, b, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, periods, jacobian_eval, y_kmin, y_size)\n"; - BlockType block_type; - if(simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE ||simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) - block_type = SIMULTAN; - else if(simulation_type == SOLVE_FORWARD_COMPLETE ||simulation_type == SOLVE_BACKWARD_COMPLETE) - block_type = SIMULTANS; - else if((simulation_type == SOLVE_FORWARD_SIMPLE ||simulation_type == SOLVE_BACKWARD_SIMPLE || - simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) - && getBlockFirstEquation(block) < prologue) - block_type = PROLOGUE; - else if((simulation_type == SOLVE_FORWARD_SIMPLE ||simulation_type == SOLVE_BACKWARD_SIMPLE || - simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) - && getBlockFirstEquation(block) >= equations.size() - epilogue) - block_type = EPILOGUE; - else - block_type = SIMULTANS; - output << " % ////////////////////////////////////////////////////////////////////////" << endl - << " % //" << string(" Block ").substr(int(log10(block + 1))) << block + 1 << " " << BlockType0(block_type) - << " //" << endl - << " % // Simulation type " - << BlockSim(simulation_type) << " //" << endl - << " % ////////////////////////////////////////////////////////////////////////" << endl; - output << " global options_;" << endl; - //The Temporary terms - if (simulation_type ==EVALUATE_BACKWARD || simulation_type ==EVALUATE_FORWARD) - { - output << " if(jacobian_eval)\n"; - output << " g1 = spalloc(" << block_mfs << ", " << block_mfs*(1+getBlockMaxLag(block)+getBlockMaxLead(block)) << ", " << nze << ");\n"; - output << " g1_x=spalloc(" << block_size << ", " << (block_exo_size + block_exo_det_size)* - (1+max(exo_det_max_leadlag_block[block].first, exo_max_leadlag_block[block].first)+max(exo_det_max_leadlag_block[block].second, exo_max_leadlag_block[block].second)) - << ", " << nze_exo << ");\n"; - output << " g1_o=spalloc(" << block_size << ", " << block_other_endo_size* - (1+other_endo_max_leadlag_block[block].first+other_endo_max_leadlag_block[block].second) - << ", " << nze_other_endo << ");\n"; - output << " end;\n"; - } - else - { - output << " if(jacobian_eval)\n"; - output << " g1 = spalloc(" << block_size << ", " << block_size*(1+getBlockMaxLag(block)+getBlockMaxLead(block)) << ", " << nze << ");\n"; - output << " g1_x=spalloc(" << block_size << ", " << (block_exo_size + block_exo_det_size)* - (1+max(exo_det_max_leadlag_block[block].first, exo_max_leadlag_block[block].first)+max(exo_det_max_leadlag_block[block].second, exo_max_leadlag_block[block].second)) - << ", " << nze_exo << ");\n"; - output << " g1_o=spalloc(" << block_size << ", " << block_other_endo_size* - (1+other_endo_max_leadlag_block[block].first+other_endo_max_leadlag_block[block].second) - << ", " << nze_other_endo << ");\n"; - output << " else\n"; - if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE) - { - output << " g1 = spalloc(" << block_mfs << "*options_.periods, " - << block_mfs << "*(options_.periods+" << max_leadlag_block[block].first+max_leadlag_block[block].second+1 << ")" - << ", " << nze << "*options_.periods);\n"; - } - else - { - output << " g1 = spalloc(" << block_mfs - << ", " << block_mfs << ", " << nze << ");\n"; - output << " g1_tmp_r = spalloc(" << block_recursive - << ", " << block_size << ", " << nze << ");\n"; - output << " g1_tmp_b = spalloc(" << block_mfs - << ", " << block_size << ", " << nze << ");\n"; - } - output << " end;\n"; - } +{ + string tmp_s, sps; + ostringstream tmp_output, tmp1_output, global_output; + NodeID lhs = NULL, rhs = NULL; + BinaryOpNode *eq_node; + ostringstream Uf[symbol_table.endo_nbr()]; + map<NodeID, int> reference_count; + temporary_terms_type local_temporary_terms; + ofstream output; + int nze, nze_exo, nze_other_endo; + vector<int> feedback_variables; + ExprNodeOutputType local_output_type; - output << " g2=0;g3=0;\n"; - if (v_temporary_terms_inuse[block].size()) - { - tmp_output.str(""); - for (temporary_terms_inuse_type::const_iterator it = v_temporary_terms_inuse[block].begin(); - it != v_temporary_terms_inuse[block].end(); it++) - tmp_output << " T" << *it; - output << " global" << tmp_output.str() << ";\n"; - } - if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE) - { - temporary_terms_type tt2; - tt2.clear(); - for(int i=0; i< (int) block_size; i++) - { - if (v_temporary_terms[block][i].size() && global_temporary_terms) - { - output << " " << "% //Temporary variables initialization" << endl - << " " << "T_zeros = zeros(y_kmin+periods, 1);" << endl; - for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); - it != v_temporary_terms[block][i].end(); it++) - { - output << " "; - (*it)->writeOutput(output, oMatlabDynamicModel, local_temporary_terms); - output << " = T_zeros;" << endl; - } - } - } - } - if (simulation_type==SOLVE_BACKWARD_SIMPLE || simulation_type==SOLVE_FORWARD_SIMPLE || simulation_type==SOLVE_BACKWARD_COMPLETE || simulation_type==SOLVE_FORWARD_COMPLETE) - output << " residual=zeros(" << block_mfs << ",1);\n"; - else if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE) - output << " residual=zeros(" << block_mfs << ",y_kmin+periods);\n"; - if (simulation_type==EVALUATE_BACKWARD) - output << " for it_ = (y_kmin+periods):y_kmin+1\n"; - if (simulation_type==EVALUATE_FORWARD) - output << " for it_ = y_kmin+1:(y_kmin+periods)\n"; - - if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE) - { - output << " b = zeros(periods*y_size,1);" << endl - << " for it_ = y_kmin+1:(periods+y_kmin)" << endl - << " Per_y_=it_*y_size;" << endl - << " Per_J_=(it_-y_kmin-1)*y_size;" << endl - << " Per_K_=(it_-1)*y_size;" << endl; - sps=" "; - } - else - if (simulation_type==EVALUATE_BACKWARD || simulation_type==EVALUATE_FORWARD ) - sps = " "; + if (global_temporary_terms) + { + local_output_type = oMatlabDynamicModelSparse; + local_temporary_terms = temporary_terms; + } + else + local_output_type = oMatlabDynamicModelSparseLocalTemporaryTerms; + + //---------------------------------------------------------------------- + //For each block + for (unsigned int block = 0; block < getNbBlocks(); block++) + { + + //recursive_variables.clear(); + feedback_variables.clear(); + //For a block composed of a single equation determines wether we have to evaluate or to solve the equation + nze = derivative_endo[block].size(); + nze_other_endo = derivative_other_endo[block].size(); + nze_exo = derivative_exo[block].size(); + BlockSimulationType simulation_type = getBlockSimulationType(block); + unsigned int block_size = getBlockSize(block); + unsigned int block_mfs = getBlockMfs(block); + unsigned int block_recursive = block_size - block_mfs; + unsigned int block_exo_size = exo_block[block].size(); + unsigned int block_exo_det_size = exo_det_block[block].size(); + unsigned int block_other_endo_size = other_endo_block[block].size(); + int block_max_lag = max_leadlag_block[block].first; + if (global_temporary_terms) + { + local_output_type = oMatlabDynamicModelSparse; + local_temporary_terms = temporary_terms; + } + else + local_output_type = oMatlabDynamicModelSparseLocalTemporaryTerms; + + tmp1_output.str(""); + tmp1_output << dynamic_basename << "_" << block+1 << ".m"; + output.open(tmp1_output.str().c_str(), ios::out | ios::binary); + output << "%\n"; + output << "% " << tmp1_output.str() << " : Computes dynamic model for Dynare\n"; + output << "%\n"; + output << "% Warning : this file is generated automatically by Dynare\n"; + output << "% from model file (.mod)\n\n"; + output << "%/\n"; + if (simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + { + output << "function [y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, jacobian_eval, y_kmin, periods)\n"; + } + else if (simulation_type == SOLVE_FORWARD_COMPLETE || simulation_type == SOLVE_BACKWARD_COMPLETE) + output << "function [residual, y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, it_, jacobian_eval)\n"; + else if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE) + output << "function [residual, y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, it_, jacobian_eval)\n"; + else + output << "function [residual, y, g1, g2, g3, b, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, periods, jacobian_eval, y_kmin, y_size)\n"; + BlockType block_type; + if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) + block_type = SIMULTAN; + else if (simulation_type == SOLVE_FORWARD_COMPLETE || simulation_type == SOLVE_BACKWARD_COMPLETE) + block_type = SIMULTANS; + else if ((simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_SIMPLE + || simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + && getBlockFirstEquation(block) < prologue) + block_type = PROLOGUE; + else if ((simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_SIMPLE + || simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + && getBlockFirstEquation(block) >= equations.size() - epilogue) + block_type = EPILOGUE; + else + block_type = SIMULTANS; + output << " % ////////////////////////////////////////////////////////////////////////" << endl + << " % //" << string(" Block ").substr(int (log10(block + 1))) << block + 1 << " " << BlockType0(block_type) + << " //" << endl + << " % // Simulation type " + << BlockSim(simulation_type) << " //" << endl + << " % ////////////////////////////////////////////////////////////////////////" << endl; + output << " global options_;" << endl; + //The Temporary terms + if (simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + { + output << " if(jacobian_eval)\n"; + output << " g1 = spalloc(" << block_mfs << ", " << block_mfs*(1+getBlockMaxLag(block)+getBlockMaxLead(block)) << ", " << nze << ");\n"; + output << " g1_x=spalloc(" << block_size << ", " << (block_exo_size + block_exo_det_size) + *(1+max(exo_det_max_leadlag_block[block].first, exo_max_leadlag_block[block].first)+max(exo_det_max_leadlag_block[block].second, exo_max_leadlag_block[block].second)) + << ", " << nze_exo << ");\n"; + output << " g1_o=spalloc(" << block_size << ", " << block_other_endo_size + *(1+other_endo_max_leadlag_block[block].first+other_endo_max_leadlag_block[block].second) + << ", " << nze_other_endo << ");\n"; + output << " end;\n"; + } + else + { + output << " if(jacobian_eval)\n"; + output << " g1 = spalloc(" << block_size << ", " << block_size*(1+getBlockMaxLag(block)+getBlockMaxLead(block)) << ", " << nze << ");\n"; + output << " g1_x=spalloc(" << block_size << ", " << (block_exo_size + block_exo_det_size) + *(1+max(exo_det_max_leadlag_block[block].first, exo_max_leadlag_block[block].first)+max(exo_det_max_leadlag_block[block].second, exo_max_leadlag_block[block].second)) + << ", " << nze_exo << ");\n"; + output << " g1_o=spalloc(" << block_size << ", " << block_other_endo_size + *(1+other_endo_max_leadlag_block[block].first+other_endo_max_leadlag_block[block].second) + << ", " << nze_other_endo << ");\n"; + output << " else\n"; + if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) + { + output << " g1 = spalloc(" << block_mfs << "*options_.periods, " + << block_mfs << "*(options_.periods+" << max_leadlag_block[block].first+max_leadlag_block[block].second+1 << ")" + << ", " << nze << "*options_.periods);\n"; + } else - sps=""; - // The equations - for (unsigned int i = 0; i < block_size; i++) - { - temporary_terms_type tt2; - tt2.clear(); - if (v_temporary_terms[block].size()) - { - output << " " << "% //Temporary variables" << endl; - for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); - it != v_temporary_terms[block][i].end(); it++) - { - output << " " << sps; - (*it)->writeOutput(output, local_output_type, local_temporary_terms); - output << " = "; - (*it)->writeOutput(output, local_output_type, tt2); - // Insert current node into tt2 - tt2.insert(*it); - output << ";" << endl; - } - } + { + output << " g1 = spalloc(" << block_mfs + << ", " << block_mfs << ", " << nze << ");\n"; + output << " g1_tmp_r = spalloc(" << block_recursive + << ", " << block_size << ", " << nze << ");\n"; + output << " g1_tmp_b = spalloc(" << block_mfs + << ", " << block_size << ", " << nze << ");\n"; + } + output << " end;\n"; + } - int variable_ID = getBlockVariableID(block, i); - int equation_ID = getBlockEquationID(block, i); - EquationType equ_type = getBlockEquationType(block, i); - string sModel = symbol_table.getName(symbol_table.getID(eEndogenous, variable_ID)) ; - eq_node = (BinaryOpNode*)getBlockEquationNodeID(block,i); - lhs = eq_node->get_arg1(); - rhs = eq_node->get_arg2(); - tmp_output.str(""); - lhs->writeOutput(tmp_output, local_output_type, local_temporary_terms); - switch (simulation_type) - { - case EVALUATE_BACKWARD: - case EVALUATE_FORWARD: -evaluation: if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE) - output << " % equation " << getBlockEquationID(block, i)+1 << " variable : " << sModel - << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl; - output << " "; - if (equ_type == E_EVALUATE) - { - output << tmp_output.str(); - output << " = "; - rhs->writeOutput(output, local_output_type, local_temporary_terms); - } - else if (equ_type == E_EVALUATE_S) - { - output << "%" << tmp_output.str(); - output << " = "; - if (isBlockEquationRenormalized(block, i)) - { - rhs->writeOutput(output, local_output_type, local_temporary_terms); - output << "\n "; - tmp_output.str(""); - eq_node = (BinaryOpNode *)getBlockEquationRenormalizedNodeID(block, i); - lhs = eq_node->get_arg1(); - rhs = eq_node->get_arg2(); - lhs->writeOutput(output, local_output_type, local_temporary_terms); - output << " = "; - rhs->writeOutput(output, local_output_type, local_temporary_terms); - } - } - else - { - cerr << "Type missmatch for equation " << equation_ID+1 << "\n"; - exit(EXIT_FAILURE); - } - output << ";\n"; - break; - case SOLVE_BACKWARD_SIMPLE: - case SOLVE_FORWARD_SIMPLE: - case SOLVE_BACKWARD_COMPLETE: - case SOLVE_FORWARD_COMPLETE: - if (i<block_recursive) - goto evaluation; - feedback_variables.push_back(variable_ID); - output << " % equation " << equation_ID+1 << " variable : " << sModel - << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl; - output << " " << "residual(" << i+1-block_recursive << ") = ("; - goto end; - case SOLVE_TWO_BOUNDARIES_COMPLETE: - case SOLVE_TWO_BOUNDARIES_SIMPLE: - if (i<block_recursive) - goto evaluation; - feedback_variables.push_back(variable_ID); - output << " % equation " << equation_ID+1 << " variable : " << sModel - << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl; - Uf[equation_ID] << " b(" << i+1-block_recursive << "+Per_J_) = -residual(" << i+1-block_recursive << ", it_)"; - output << " residual(" << i+1-block_recursive << ", it_) = ("; - goto end; - default: -end: - output << tmp_output.str(); - output << ") - ("; - rhs->writeOutput(output, local_output_type, local_temporary_terms); - output << ");\n"; + output << " g2=0;g3=0;\n"; + if (v_temporary_terms_inuse[block].size()) + { + tmp_output.str(""); + for (temporary_terms_inuse_type::const_iterator it = v_temporary_terms_inuse[block].begin(); + it != v_temporary_terms_inuse[block].end(); it++) + tmp_output << " T" << *it; + output << " global" << tmp_output.str() << ";\n"; + } + if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) + { + temporary_terms_type tt2; + tt2.clear(); + for (int i = 0; i < (int) block_size; i++) + { + if (v_temporary_terms[block][i].size() && global_temporary_terms) + { + output << " " << "% //Temporary variables initialization" << endl + << " " << "T_zeros = zeros(y_kmin+periods, 1);" << endl; + for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); + it != v_temporary_terms[block][i].end(); it++) + { + output << " "; + (*it)->writeOutput(output, oMatlabDynamicModel, local_temporary_terms); + output << " = T_zeros;" << endl; + } + } + } + } + if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE) + output << " residual=zeros(" << block_mfs << ",1);\n"; + else if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) + output << " residual=zeros(" << block_mfs << ",y_kmin+periods);\n"; + if (simulation_type == EVALUATE_BACKWARD) + output << " for it_ = (y_kmin+periods):y_kmin+1\n"; + if (simulation_type == EVALUATE_FORWARD) + output << " for it_ = y_kmin+1:(y_kmin+periods)\n"; + + if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) + { + output << " b = zeros(periods*y_size,1);" << endl + << " for it_ = y_kmin+1:(periods+y_kmin)" << endl + << " Per_y_=it_*y_size;" << endl + << " Per_J_=(it_-y_kmin-1)*y_size;" << endl + << " Per_K_=(it_-1)*y_size;" << endl; + sps = " "; + } + else + if (simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + sps = " "; + else + sps = ""; + // The equations + for (unsigned int i = 0; i < block_size; i++) + { + temporary_terms_type tt2; + tt2.clear(); + if (v_temporary_terms[block].size()) + { + output << " " << "% //Temporary variables" << endl; + for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); + it != v_temporary_terms[block][i].end(); it++) + { + output << " " << sps; + (*it)->writeOutput(output, local_output_type, local_temporary_terms); + output << " = "; + (*it)->writeOutput(output, local_output_type, tt2); + // Insert current node into tt2 + tt2.insert(*it); + output << ";" << endl; + } + } + + int variable_ID = getBlockVariableID(block, i); + int equation_ID = getBlockEquationID(block, i); + EquationType equ_type = getBlockEquationType(block, i); + string sModel = symbol_table.getName(symbol_table.getID(eEndogenous, variable_ID)); + eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i); + lhs = eq_node->get_arg1(); + rhs = eq_node->get_arg2(); + tmp_output.str(""); + lhs->writeOutput(tmp_output, local_output_type, local_temporary_terms); + switch (simulation_type) + { + case EVALUATE_BACKWARD: + case EVALUATE_FORWARD: + evaluation: if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) + output << " % equation " << getBlockEquationID(block, i)+1 << " variable : " << sModel + << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl; + output << " "; + if (equ_type == E_EVALUATE) + { + output << tmp_output.str(); + output << " = "; + rhs->writeOutput(output, local_output_type, local_temporary_terms); + } + else if (equ_type == E_EVALUATE_S) + { + output << "%" << tmp_output.str(); + output << " = "; + if (isBlockEquationRenormalized(block, i)) + { + rhs->writeOutput(output, local_output_type, local_temporary_terms); + output << "\n "; + tmp_output.str(""); + eq_node = (BinaryOpNode *) getBlockEquationRenormalizedNodeID(block, i); + lhs = eq_node->get_arg1(); + rhs = eq_node->get_arg2(); + lhs->writeOutput(output, local_output_type, local_temporary_terms); + output << " = "; + rhs->writeOutput(output, local_output_type, local_temporary_terms); + } + } + else + { + cerr << "Type missmatch for equation " << equation_ID+1 << "\n"; + exit(EXIT_FAILURE); + } + output << ";\n"; + break; + case SOLVE_BACKWARD_SIMPLE: + case SOLVE_FORWARD_SIMPLE: + case SOLVE_BACKWARD_COMPLETE: + case SOLVE_FORWARD_COMPLETE: + if (i < block_recursive) + goto evaluation; + feedback_variables.push_back(variable_ID); + output << " % equation " << equation_ID+1 << " variable : " << sModel + << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl; + output << " " << "residual(" << i+1-block_recursive << ") = ("; + goto end; + case SOLVE_TWO_BOUNDARIES_COMPLETE: + case SOLVE_TWO_BOUNDARIES_SIMPLE: + if (i < block_recursive) + goto evaluation; + feedback_variables.push_back(variable_ID); + output << " % equation " << equation_ID+1 << " variable : " << sModel + << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl; + Uf[equation_ID] << " b(" << i+1-block_recursive << "+Per_J_) = -residual(" << i+1-block_recursive << ", it_)"; + output << " residual(" << i+1-block_recursive << ", it_) = ("; + goto end; + default: + end: + output << tmp_output.str(); + output << ") - ("; + rhs->writeOutput(output, local_output_type, local_temporary_terms); + output << ");\n"; #ifdef CONDITION - if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE) - output << " condition(" << i+1 << ")=0;\n"; + if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) + output << " condition(" << i+1 << ")=0;\n"; #endif - } - } - // The Jacobian if we have to solve the block - if (simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE) - output << " " << sps << "% Jacobian " << endl; + } + } + // The Jacobian if we have to solve the block + if (simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE) + output << " " << sps << "% Jacobian " << endl; + else + if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE + || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE) + output << " % Jacobian " << endl << " if jacobian_eval" << endl; else - if (simulation_type==SOLVE_BACKWARD_SIMPLE || simulation_type==SOLVE_FORWARD_SIMPLE || - simulation_type==SOLVE_BACKWARD_COMPLETE || simulation_type==SOLVE_FORWARD_COMPLETE) - output << " % Jacobian " << endl << " if jacobian_eval" << endl; - else - output << " % Jacobian " << endl << " if jacobian_eval" << endl; - switch (simulation_type) - { - case EVALUATE_BACKWARD: - case EVALUATE_FORWARD: - for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++) - { - int lag = it->first.first; - int eq = it->first.second.first; - int var = it->first.second.second; - int eqr = getBlockInitialEquationID(block, eq); - int varr = getBlockInitialVariableID(block, var); - - NodeID id = it->second; - - output << " g1(" << eqr+1 << ", " << varr+1+(lag+block_max_lag)*block_size << ") = "; - id->writeOutput(output, local_output_type, local_temporary_terms); - output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var)) - << "(" << lag - << ") " << var+1 - << ", equation=" << eq+1 << endl; - } - for (t_derivative::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++) - { - int lag = it->first.first; - int eq = it->first.second.first; - int var = it->first.second.second; - int eqr = getBlockInitialEquationID(block, eq); - NodeID id = it->second; - - output << " g1_o(" << eqr+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = "; - id->writeOutput(output, local_output_type, local_temporary_terms); - output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var)) - << "(" << lag - << ") " << var+1 - << ", equation=" << eq+1 << endl; - } - output << " varargout{1}=g1_x;\n"; - output << " varargout{2}=g1_o;\n"; - output << " end;" << endl; - output << " end;" << endl; - break; - case SOLVE_BACKWARD_SIMPLE: - case SOLVE_FORWARD_SIMPLE: - case SOLVE_BACKWARD_COMPLETE: - case SOLVE_FORWARD_COMPLETE: - for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++) - { - int lag = it->first.first; - unsigned int eq = it->first.second.first; - unsigned int var = it->first.second.second; - NodeID id = it->second; - - output << " g1(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = "; - id->writeOutput(output, local_output_type, local_temporary_terms); - output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var)) - << "(" << lag - << ") " << var+1 - << ", equation=" << eq+1 << endl; - } + output << " % Jacobian " << endl << " if jacobian_eval" << endl; + switch (simulation_type) + { + case EVALUATE_BACKWARD: + case EVALUATE_FORWARD: + for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++) + { + int lag = it->first.first; + int eq = it->first.second.first; + int var = it->first.second.second; + int eqr = getBlockInitialEquationID(block, eq); + int varr = getBlockInitialVariableID(block, var); + + NodeID id = it->second; + + output << " g1(" << eqr+1 << ", " << varr+1+(lag+block_max_lag)*block_size << ") = "; + id->writeOutput(output, local_output_type, local_temporary_terms); + output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var)) + << "(" << lag + << ") " << var+1 + << ", equation=" << eq+1 << endl; + } + for (t_derivative::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++) + { + int lag = it->first.first; + int eq = it->first.second.first; + int var = it->first.second.second; + int eqr = getBlockInitialEquationID(block, eq); + NodeID id = it->second; + + output << " g1_o(" << eqr+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = "; + id->writeOutput(output, local_output_type, local_temporary_terms); + output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var)) + << "(" << lag + << ") " << var+1 + << ", equation=" << eq+1 << endl; + } + output << " varargout{1}=g1_x;\n"; + output << " varargout{2}=g1_o;\n"; + output << " end;" << endl; + output << " end;" << endl; + break; + case SOLVE_BACKWARD_SIMPLE: + case SOLVE_FORWARD_SIMPLE: + case SOLVE_BACKWARD_COMPLETE: + case SOLVE_FORWARD_COMPLETE: + for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++) + { + int lag = it->first.first; + unsigned int eq = it->first.second.first; + unsigned int var = it->first.second.second; + NodeID id = it->second; + + output << " g1(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = "; + id->writeOutput(output, local_output_type, local_temporary_terms); + output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var)) + << "(" << lag + << ") " << var+1 + << ", equation=" << eq+1 << endl; + } - for (t_derivative::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++) - { - int lag = it->first.first; - unsigned int eq = it->first.second.first; - unsigned int var = it->first.second.second; - NodeID id = it->second; - - output << " g1_o(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = "; - id->writeOutput(output, local_output_type, local_temporary_terms); - output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var)) - << "(" << lag - << ") " << var+1 - << ", equation=" << eq+1 << endl; - } - output << " varargout{1}=g1_x;\n"; - output << " varargout{2}=g1_o;\n"; - output << " else" << endl; - for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) - { - unsigned int eq = it->first.first; - unsigned int var = it->first.second; - unsigned int eqr = getBlockEquationID(block, eq); - unsigned int varr = getBlockVariableID(block, var); - NodeID id = it->second.second; - int lag = it->second.first; - output << " g1(" << eq+1 << ", " << var+1-block_recursive << ") = "; - id->writeOutput(output, local_output_type, local_temporary_terms); - output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr)) - << "(" << lag - << ") " << varr+1 - << ", equation=" << eqr+1 << endl; - } - output << " end;\n"; - break; - case SOLVE_TWO_BOUNDARIES_SIMPLE: - case SOLVE_TWO_BOUNDARIES_COMPLETE: - output << " if ~jacobian_eval" << endl; - for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) - { - unsigned int eq = it->first.first; - unsigned int var = it->first.second; - unsigned int eqr = getBlockEquationID(block, eq); - unsigned int varr = getBlockVariableID(block, var); - ostringstream tmp_output; - NodeID id = it->second.second; - int lag = it->second.first; - if(eq>=block_recursive and var>=block_recursive) - { - if (lag==0) - Uf[eqr] << "+g1(" << eq+1-block_recursive - << "+Per_J_, " << var+1-block_recursive - << "+Per_K_)*y(it_, " << varr+1 << ")"; - else if (lag==1) - Uf[eqr] << "+g1(" << eq+1-block_recursive - << "+Per_J_, " << var+1-block_recursive - << "+Per_y_)*y(it_+1, " << varr+1 << ")"; - else if (lag>0) - Uf[eqr] << "+g1(" << eq+1-block_recursive - << "+Per_J_, " << var+1-block_recursive - << "+y_size*(it_+" << lag-1 << "))*y(it_+" << lag << ", " << varr+1 << ")"; - else if (lag<0) - Uf[eqr] << "+g1(" << eq+1-block_recursive - << "+Per_J_, " << var+1-block_recursive - << "+y_size*(it_" << lag-1 << "))*y(it_" << lag << ", " << varr+1 << ")"; - if (lag==0) - tmp_output << " g1(" << eq+1-block_recursive << "+Per_J_, " - << var+1-block_recursive << "+Per_K_) = "; - else if (lag==1) - tmp_output << " g1(" << eq+1-block_recursive << "+Per_J_, " - << var+1-block_recursive << "+Per_y_) = "; - else if (lag>0) - tmp_output << " g1(" << eq+1-block_recursive << "+Per_J_, " - << var+1-block_recursive << "+y_size*(it_+" << lag-1 << ")) = "; - else if (lag<0) - tmp_output << " g1(" << eq+1-block_recursive << "+Per_J_, " - << var+1-block_recursive << "+y_size*(it_" << lag-1 << ")) = "; - output << " " << tmp_output.str(); - id->writeOutput(output, local_output_type, local_temporary_terms); - output << ";"; - output << " %2 variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr)) - << "(" << lag << ") " << varr+1 - << ", equation=" << eqr+1 << " (" << eq+1 << ")" << endl; - } + for (t_derivative::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++) + { + int lag = it->first.first; + unsigned int eq = it->first.second.first; + unsigned int var = it->first.second.second; + NodeID id = it->second; + + output << " g1_o(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = "; + id->writeOutput(output, local_output_type, local_temporary_terms); + output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var)) + << "(" << lag + << ") " << var+1 + << ", equation=" << eq+1 << endl; + } + output << " varargout{1}=g1_x;\n"; + output << " varargout{2}=g1_o;\n"; + output << " else" << endl; + for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) + { + unsigned int eq = it->first.first; + unsigned int var = it->first.second; + unsigned int eqr = getBlockEquationID(block, eq); + unsigned int varr = getBlockVariableID(block, var); + NodeID id = it->second.second; + int lag = it->second.first; + output << " g1(" << eq+1 << ", " << var+1-block_recursive << ") = "; + id->writeOutput(output, local_output_type, local_temporary_terms); + output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr)) + << "(" << lag + << ") " << varr+1 + << ", equation=" << eqr+1 << endl; + } + output << " end;\n"; + break; + case SOLVE_TWO_BOUNDARIES_SIMPLE: + case SOLVE_TWO_BOUNDARIES_COMPLETE: + output << " if ~jacobian_eval" << endl; + for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) + { + unsigned int eq = it->first.first; + unsigned int var = it->first.second; + unsigned int eqr = getBlockEquationID(block, eq); + unsigned int varr = getBlockVariableID(block, var); + ostringstream tmp_output; + NodeID id = it->second.second; + int lag = it->second.first; + if (eq >= block_recursive and var >= block_recursive) + { + if (lag == 0) + Uf[eqr] << "+g1(" << eq+1-block_recursive + << "+Per_J_, " << var+1-block_recursive + << "+Per_K_)*y(it_, " << varr+1 << ")"; + else if (lag == 1) + Uf[eqr] << "+g1(" << eq+1-block_recursive + << "+Per_J_, " << var+1-block_recursive + << "+Per_y_)*y(it_+1, " << varr+1 << ")"; + else if (lag > 0) + Uf[eqr] << "+g1(" << eq+1-block_recursive + << "+Per_J_, " << var+1-block_recursive + << "+y_size*(it_+" << lag-1 << "))*y(it_+" << lag << ", " << varr+1 << ")"; + else if (lag < 0) + Uf[eqr] << "+g1(" << eq+1-block_recursive + << "+Per_J_, " << var+1-block_recursive + << "+y_size*(it_" << lag-1 << "))*y(it_" << lag << ", " << varr+1 << ")"; + if (lag == 0) + tmp_output << " g1(" << eq+1-block_recursive << "+Per_J_, " + << var+1-block_recursive << "+Per_K_) = "; + else if (lag == 1) + tmp_output << " g1(" << eq+1-block_recursive << "+Per_J_, " + << var+1-block_recursive << "+Per_y_) = "; + else if (lag > 0) + tmp_output << " g1(" << eq+1-block_recursive << "+Per_J_, " + << var+1-block_recursive << "+y_size*(it_+" << lag-1 << ")) = "; + else if (lag < 0) + tmp_output << " g1(" << eq+1-block_recursive << "+Per_J_, " + << var+1-block_recursive << "+y_size*(it_" << lag-1 << ")) = "; + output << " " << tmp_output.str(); + id->writeOutput(output, local_output_type, local_temporary_terms); + output << ";"; + output << " %2 variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr)) + << "(" << lag << ") " << varr+1 + << ", equation=" << eqr+1 << " (" << eq+1 << ")" << endl; + } #ifdef CONDITION - output << " if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n"; - output << " condition(" << eqr << ")=u(" << u << "+Per_u_);\n"; + output << " if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n"; + output << " condition(" << eqr << ")=u(" << u << "+Per_u_);\n"; #endif - } - for (unsigned int i = 0; i < block_size; i++) - { - if (i>=block_recursive) - output << " " << Uf[getBlockEquationID(block, i)].str() << ";\n"; + } + for (unsigned int i = 0; i < block_size; i++) + { + if (i >= block_recursive) + output << " " << Uf[getBlockEquationID(block, i)].str() << ";\n"; #ifdef CONDITION - output << " if (fabs(condition(" << i+1 << "))<fabs(u(" << i << "+Per_u_)))\n"; - output << " condition(" << i+1 << ")=u(" << i+1 << "+Per_u_);\n"; + output << " if (fabs(condition(" << i+1 << "))<fabs(u(" << i << "+Per_u_)))\n"; + output << " condition(" << i+1 << ")=u(" << i+1 << "+Per_u_);\n"; #endif - } + } #ifdef CONDITION - for (m=0;m<=ModelBlock->Block_List[block].Max_Lead+ModelBlock->Block_List[block].Max_Lag;m++) - { - k=m-ModelBlock->Block_List[block].Max_Lag; - for (i=0;i<ModelBlock->Block_List[block].IM_lead_lag[m].size;i++) - { - unsigned int eq=ModelBlock->Block_List[block].IM_lead_lag[m].Equ_Index[i]; - unsigned int var=ModelBlock->Block_List[block].IM_lead_lag[m].Var_Index[i]; - unsigned int u=ModelBlock->Block_List[block].IM_lead_lag[m].u[i]; - unsigned int eqr=ModelBlock->Block_List[block].IM_lead_lag[m].Equ[i]; - output << " u(" << u+1 << "+Per_u_) = u(" << u+1 << "+Per_u_) / condition(" << eqr+1 << ");\n"; - } - } - for (i = 0;i < ModelBlock->Block_List[block].Size;i++) - output << " u(" << i+1 << "+Per_u_) = u(" << i+1 << "+Per_u_) / condition(" << i+1 << ");\n"; + for (m = 0; m <= ModelBlock->Block_List[block].Max_Lead+ModelBlock->Block_List[block].Max_Lag; m++) + { + k = m-ModelBlock->Block_List[block].Max_Lag; + for (i = 0; i < ModelBlock->Block_List[block].IM_lead_lag[m].size; i++) + { + unsigned int eq = ModelBlock->Block_List[block].IM_lead_lag[m].Equ_Index[i]; + unsigned int var = ModelBlock->Block_List[block].IM_lead_lag[m].Var_Index[i]; + unsigned int u = ModelBlock->Block_List[block].IM_lead_lag[m].u[i]; + unsigned int eqr = ModelBlock->Block_List[block].IM_lead_lag[m].Equ[i]; + output << " u(" << u+1 << "+Per_u_) = u(" << u+1 << "+Per_u_) / condition(" << eqr+1 << ");\n"; + } + } + for (i = 0; i < ModelBlock->Block_List[block].Size; i++) + output << " u(" << i+1 << "+Per_u_) = u(" << i+1 << "+Per_u_) / condition(" << i+1 << ");\n"; #endif - output << " else" << endl; + output << " else" << endl; - for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++) - { - int lag = it->first.first; - unsigned int eq = it->first.second.first; - unsigned int var = it->first.second.second; - NodeID id = it->second; - output << " g1(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = "; - id->writeOutput(output, local_output_type, local_temporary_terms); - output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var)) - << "(" << lag - << ") " << var+1 - << ", equation=" << eq+1 << endl; - } - for (t_derivative::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++) - { - int lag = it->first.first; - unsigned int eq = it->first.second.first; - unsigned int var = it->first.second.second; - NodeID id = it->second; - - output << " g1_o(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = "; - id->writeOutput(output, local_output_type, local_temporary_terms); - output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var)) - << "(" << lag - << ") " << var+1 - << ", equation=" << eq+1 << endl; - } - output << " varargout{1}=g1_x;\n"; - output << " varargout{2}=g1_o;\n"; - output << " end;\n"; - output << " end;\n"; - break; - default: - break; - } - output.close(); - } - } + for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++) + { + int lag = it->first.first; + unsigned int eq = it->first.second.first; + unsigned int var = it->first.second.second; + NodeID id = it->second; + output << " g1(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = "; + id->writeOutput(output, local_output_type, local_temporary_terms); + output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var)) + << "(" << lag + << ") " << var+1 + << ", equation=" << eq+1 << endl; + } + for (t_derivative::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++) + { + int lag = it->first.first; + unsigned int eq = it->first.second.first; + unsigned int var = it->first.second.second; + NodeID id = it->second; + + output << " g1_o(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = "; + id->writeOutput(output, local_output_type, local_temporary_terms); + output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var)) + << "(" << lag + << ") " << var+1 + << ", equation=" << eq+1 << endl; + } + output << " varargout{1}=g1_x;\n"; + output << " varargout{2}=g1_o;\n"; + output << " end;\n"; + output << " end;\n"; + break; + default: + break; + } + output.close(); + } +} void DynamicModel::writeModelEquationsCodeOrdered(const string file_name, const string bin_basename, map_idx_type map_idx) const +{ + struct Uff_l { - struct Uff_l - { - int u, var, lag; - Uff_l *pNext; - }; - - struct Uff - { - Uff_l *Ufl, *Ufl_First; - }; - - int i,v; - string tmp_s; - ostringstream tmp_output; - ofstream code_file; - NodeID lhs=NULL, rhs=NULL; - BinaryOpNode *eq_node; - Uff Uf[symbol_table.endo_nbr()]; - map<NodeID, int> reference_count; - vector<int> feedback_variables; - bool file_open=false; - - string main_name=file_name; - main_name+=".cod"; - code_file.open(main_name.c_str(), ios::out | ios::binary | ios::ate ); - if (!code_file.is_open()) - { - cout << "Error : Can't open file \"" << main_name << "\" for writing\n"; - exit(EXIT_FAILURE); - } - //Temporary variables declaration - - FDIMT_ fdimt(temporary_terms.size()); - fdimt.write(code_file); - - for (unsigned int block = 0; block < getNbBlocks(); block++) - { - feedback_variables.clear(); - if (block>0) - { - FENDBLOCK_ fendblock; - fendblock.write(code_file); - } - int count_u; - int u_count_int=0; - BlockSimulationType simulation_type = getBlockSimulationType(block); - unsigned int block_size = getBlockSize(block); - unsigned int block_mfs = getBlockMfs(block); - unsigned int block_recursive = block_size - block_mfs; - int block_max_lag=max_leadlag_block[block].first; - - if (simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || - simulation_type==SOLVE_BACKWARD_COMPLETE || simulation_type==SOLVE_FORWARD_COMPLETE) - { - Write_Inf_To_Bin_File(file_name, bin_basename, block, u_count_int,file_open, - simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE); - file_open=true; - } - FBEGINBLOCK_ fbeginblock(block_mfs, - simulation_type, - getBlockFirstEquation(block), - block_size, - variable_reordered, - equation_reordered, - blocks_linear[block], - symbol_table.endo_nbr(), - block_max_lag, - block_max_lag, - u_count_int - ); - fbeginblock.write(code_file); - - // The equations - for (i = 0;i < (int) block_size;i++) - { - //The Temporary terms - temporary_terms_type tt2; - tt2.clear(); - if (v_temporary_terms[block][i].size()) - { - for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); - it != v_temporary_terms[block][i].end(); it++) - { - (*it)->compile(code_file, false, tt2, map_idx, true, false); - FSTPT_ fstpt((int)(map_idx.find((*it)->idx)->second)); - fstpt.write(code_file); - // Insert current node into tt2 - tt2.insert(*it); + int u, var, lag; + Uff_l *pNext; + }; + + struct Uff + { + Uff_l *Ufl, *Ufl_First; + }; + + int i, v; + string tmp_s; + ostringstream tmp_output; + ofstream code_file; + NodeID lhs = NULL, rhs = NULL; + BinaryOpNode *eq_node; + Uff Uf[symbol_table.endo_nbr()]; + map<NodeID, int> reference_count; + vector<int> feedback_variables; + bool file_open = false; + + string main_name = file_name; + main_name += ".cod"; + code_file.open(main_name.c_str(), ios::out | ios::binary | ios::ate); + if (!code_file.is_open()) + { + cout << "Error : Can't open file \"" << main_name << "\" for writing\n"; + exit(EXIT_FAILURE); + } + //Temporary variables declaration + + FDIMT_ fdimt(temporary_terms.size()); + fdimt.write(code_file); + + for (unsigned int block = 0; block < getNbBlocks(); block++) + { + feedback_variables.clear(); + if (block > 0) + { + FENDBLOCK_ fendblock; + fendblock.write(code_file); + } + int count_u; + int u_count_int = 0; + BlockSimulationType simulation_type = getBlockSimulationType(block); + unsigned int block_size = getBlockSize(block); + unsigned int block_mfs = getBlockMfs(block); + unsigned int block_recursive = block_size - block_mfs; + int block_max_lag = max_leadlag_block[block].first; + + if (simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE + || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE) + { + Write_Inf_To_Bin_File(file_name, bin_basename, block, u_count_int, file_open, + simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE); + file_open = true; + } + FBEGINBLOCK_ fbeginblock(block_mfs, + simulation_type, + getBlockFirstEquation(block), + block_size, + variable_reordered, + equation_reordered, + blocks_linear[block], + symbol_table.endo_nbr(), + block_max_lag, + block_max_lag, + u_count_int + ); + fbeginblock.write(code_file); + + // The equations + for (i = 0; i < (int) block_size; i++) + { + //The Temporary terms + temporary_terms_type tt2; + tt2.clear(); + if (v_temporary_terms[block][i].size()) + { + for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); + it != v_temporary_terms[block][i].end(); it++) + { + (*it)->compile(code_file, false, tt2, map_idx, true, false); + FSTPT_ fstpt((int)(map_idx.find((*it)->idx)->second)); + fstpt.write(code_file); + // Insert current node into tt2 + tt2.insert(*it); #ifdef DEBUGC - cout << "FSTPT " << v << "\n"; - code_file.write(&FOK, sizeof(FOK)); - code_file.write(reinterpret_cast<char *>(&k), sizeof(k)); - ki++; + cout << "FSTPT " << v << "\n"; + code_file.write(&FOK, sizeof(FOK)); + code_file.write(reinterpret_cast<char *>(&k), sizeof(k)); + ki++; #endif - } - } + } + } #ifdef DEBUGC - for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); - it != v_temporary_terms[block][i].end(); it++) - { - map_idx_type::const_iterator ii=map_idx.find((*it)->idx); - cout << "map_idx[" << (*it)->idx <<"]=" << ii->second << "\n"; - } + for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); + it != v_temporary_terms[block][i].end(); it++) + { + map_idx_type::const_iterator ii = map_idx.find((*it)->idx); + cout << "map_idx[" << (*it)->idx <<"]=" << ii->second << "\n"; + } #endif - int variable_ID, equation_ID; - EquationType equ_type; + int variable_ID, equation_ID; + EquationType equ_type; - - switch (simulation_type) - { -evaluation: - case EVALUATE_BACKWARD: - case EVALUATE_FORWARD: - equ_type = getBlockEquationType(block, i); - if (equ_type == E_EVALUATE) - { - eq_node = (BinaryOpNode*)getBlockEquationNodeID(block,i); - lhs = eq_node->get_arg1(); - rhs = eq_node->get_arg2(); - rhs->compile(code_file, false, temporary_terms, map_idx, true, false); - lhs->compile(code_file, true, temporary_terms, map_idx, true, false); - } - else if (equ_type == E_EVALUATE_S) - { - eq_node = (BinaryOpNode*)getBlockEquationRenormalizedNodeID(block,i); - lhs = eq_node->get_arg1(); - rhs = eq_node->get_arg2(); - rhs->compile(code_file, false, temporary_terms, map_idx, true, false); - lhs->compile(code_file, true, temporary_terms, map_idx, true, false); - } - break; - case SOLVE_BACKWARD_COMPLETE: - case SOLVE_FORWARD_COMPLETE: - case SOLVE_TWO_BOUNDARIES_COMPLETE: - case SOLVE_TWO_BOUNDARIES_SIMPLE: - if (i< (int) block_recursive) - goto evaluation; - variable_ID = getBlockVariableID(block, i); - equation_ID = getBlockEquationID(block, i); - feedback_variables.push_back(variable_ID); - Uf[equation_ID].Ufl=NULL; - goto end; - default: -end: - eq_node = (BinaryOpNode*)getBlockEquationNodeID(block, i); - lhs = eq_node->get_arg1(); - rhs = eq_node->get_arg2(); - lhs->compile(code_file, false, temporary_terms, map_idx, true, false); - rhs->compile(code_file, false, temporary_terms, map_idx, true, false); - - FBINARY_ fbinary(oMinus); - fbinary.write(code_file); - FSTPR_ fstpr(i - block_recursive); - fstpr.write(code_file); - } - } - FENDEQU_ fendequ; - fendequ.write(code_file); - // The Jacobian if we have to solve the block - if (simulation_type != EVALUATE_BACKWARD - && simulation_type != EVALUATE_FORWARD) - { - switch (simulation_type) + switch (simulation_type) + { + evaluation: + case EVALUATE_BACKWARD: + case EVALUATE_FORWARD: + equ_type = getBlockEquationType(block, i); + if (equ_type == E_EVALUATE) + { + eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i); + lhs = eq_node->get_arg1(); + rhs = eq_node->get_arg2(); + rhs->compile(code_file, false, temporary_terms, map_idx, true, false); + lhs->compile(code_file, true, temporary_terms, map_idx, true, false); + } + else if (equ_type == E_EVALUATE_S) + { + eq_node = (BinaryOpNode *) getBlockEquationRenormalizedNodeID(block, i); + lhs = eq_node->get_arg1(); + rhs = eq_node->get_arg2(); + rhs->compile(code_file, false, temporary_terms, map_idx, true, false); + lhs->compile(code_file, true, temporary_terms, map_idx, true, false); + } + break; + case SOLVE_BACKWARD_COMPLETE: + case SOLVE_FORWARD_COMPLETE: + case SOLVE_TWO_BOUNDARIES_COMPLETE: + case SOLVE_TWO_BOUNDARIES_SIMPLE: + if (i < (int) block_recursive) + goto evaluation; + variable_ID = getBlockVariableID(block, i); + equation_ID = getBlockEquationID(block, i); + feedback_variables.push_back(variable_ID); + Uf[equation_ID].Ufl = NULL; + goto end; + default: + end: + eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i); + lhs = eq_node->get_arg1(); + rhs = eq_node->get_arg2(); + lhs->compile(code_file, false, temporary_terms, map_idx, true, false); + rhs->compile(code_file, false, temporary_terms, map_idx, true, false); + + FBINARY_ fbinary(oMinus); + fbinary.write(code_file); + FSTPR_ fstpr(i - block_recursive); + fstpr.write(code_file); + } + } + FENDEQU_ fendequ; + fendequ.write(code_file); + // The Jacobian if we have to solve the block + if (simulation_type != EVALUATE_BACKWARD + && simulation_type != EVALUATE_FORWARD) + { + switch (simulation_type) + { + case SOLVE_BACKWARD_SIMPLE: + case SOLVE_FORWARD_SIMPLE: + compileDerivative(code_file, getBlockEquationID(block, 0), getBlockVariableID(block, 0), 0, map_idx); { - case SOLVE_BACKWARD_SIMPLE: - case SOLVE_FORWARD_SIMPLE: - compileDerivative(code_file, getBlockEquationID(block, 0), getBlockVariableID(block, 0), 0, map_idx); - { - FSTPG_ fstpg(0); - fstpg.write(code_file); - } - break; - - case SOLVE_BACKWARD_COMPLETE: - case SOLVE_FORWARD_COMPLETE: - case SOLVE_TWO_BOUNDARIES_COMPLETE: - case SOLVE_TWO_BOUNDARIES_SIMPLE: - count_u = feedback_variables.size(); - for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) - { - unsigned int eq = it->first.first; - unsigned int var = it->first.second; - unsigned int eqr = getBlockEquationID(block, eq); - unsigned int varr = getBlockVariableID(block, var); - int lag = it->second.first; - if(eq>=block_recursive and var>=block_recursive) - { - if (!Uf[eqr].Ufl) - { - Uf[eqr].Ufl=(Uff_l*)malloc(sizeof(Uff_l)); - Uf[eqr].Ufl_First=Uf[eqr].Ufl; - } - else - { - Uf[eqr].Ufl->pNext=(Uff_l*)malloc(sizeof(Uff_l)); - Uf[eqr].Ufl=Uf[eqr].Ufl->pNext; - } - Uf[eqr].Ufl->pNext=NULL; - Uf[eqr].Ufl->u=count_u; - Uf[eqr].Ufl->var=varr; - Uf[eqr].Ufl->lag=lag; - compileChainRuleDerivative(code_file, eqr, varr, lag, map_idx); - FSTPU_ fstpu(count_u); - fstpu.write(code_file); - count_u++; - } - } - for (i = 0;i < (int) block_size;i++) - { - if(i>= (int) block_recursive) - { - FLDR_ fldr(i-block_recursive); - fldr.write(code_file); - - FLDZ_ fldz; - fldz.write(code_file); - - v=getBlockEquationID(block, i); - for (Uf[v].Ufl=Uf[v].Ufl_First; Uf[v].Ufl; Uf[v].Ufl=Uf[v].Ufl->pNext) - { - FLDU_ fldu(Uf[v].Ufl->u); - fldu.write(code_file); - FLDV_ fldv(eEndogenous, Uf[v].Ufl->var, Uf[v].Ufl->lag); - fldv.write(code_file); - - FBINARY_ fbinary(oTimes); - fbinary.write(code_file); - - FCUML_ fcuml; - fcuml.write(code_file); - } - Uf[v].Ufl=Uf[v].Ufl_First; - while (Uf[v].Ufl) - { - Uf[v].Ufl_First=Uf[v].Ufl->pNext; - free(Uf[v].Ufl); - Uf[v].Ufl=Uf[v].Ufl_First; - } - FBINARY_ fbinary(oMinus); - fbinary.write(code_file); - - FSTPU_ fstpu(i - block_recursive); - fstpu.write(code_file); - } - } - break; - default: - break; + FSTPG_ fstpg(0); + fstpg.write(code_file); } - } - } - FENDBLOCK_ fendblock; - fendblock.write(code_file); - FEND_ fend; - fend.write(code_file); - code_file.close(); - } + break; + + case SOLVE_BACKWARD_COMPLETE: + case SOLVE_FORWARD_COMPLETE: + case SOLVE_TWO_BOUNDARIES_COMPLETE: + case SOLVE_TWO_BOUNDARIES_SIMPLE: + count_u = feedback_variables.size(); + for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) + { + unsigned int eq = it->first.first; + unsigned int var = it->first.second; + unsigned int eqr = getBlockEquationID(block, eq); + unsigned int varr = getBlockVariableID(block, var); + int lag = it->second.first; + if (eq >= block_recursive and var >= block_recursive) + { + if (!Uf[eqr].Ufl) + { + Uf[eqr].Ufl = (Uff_l *) malloc(sizeof(Uff_l)); + Uf[eqr].Ufl_First = Uf[eqr].Ufl; + } + else + { + Uf[eqr].Ufl->pNext = (Uff_l *) malloc(sizeof(Uff_l)); + Uf[eqr].Ufl = Uf[eqr].Ufl->pNext; + } + Uf[eqr].Ufl->pNext = NULL; + Uf[eqr].Ufl->u = count_u; + Uf[eqr].Ufl->var = varr; + Uf[eqr].Ufl->lag = lag; + compileChainRuleDerivative(code_file, eqr, varr, lag, map_idx); + FSTPU_ fstpu(count_u); + fstpu.write(code_file); + count_u++; + } + } + for (i = 0; i < (int) block_size; i++) + { + if (i >= (int) block_recursive) + { + FLDR_ fldr(i-block_recursive); + fldr.write(code_file); + + FLDZ_ fldz; + fldz.write(code_file); + + v = getBlockEquationID(block, i); + for (Uf[v].Ufl = Uf[v].Ufl_First; Uf[v].Ufl; Uf[v].Ufl = Uf[v].Ufl->pNext) + { + FLDU_ fldu(Uf[v].Ufl->u); + fldu.write(code_file); + FLDV_ fldv(eEndogenous, Uf[v].Ufl->var, Uf[v].Ufl->lag); + fldv.write(code_file); + + FBINARY_ fbinary(oTimes); + fbinary.write(code_file); + + FCUML_ fcuml; + fcuml.write(code_file); + } + Uf[v].Ufl = Uf[v].Ufl_First; + while (Uf[v].Ufl) + { + Uf[v].Ufl_First = Uf[v].Ufl->pNext; + free(Uf[v].Ufl); + Uf[v].Ufl = Uf[v].Ufl_First; + } + FBINARY_ fbinary(oMinus); + fbinary.write(code_file); + + FSTPU_ fstpu(i - block_recursive); + fstpu.write(code_file); + } + } + break; + default: + break; + } + } + } + FENDBLOCK_ fendblock; + fendblock.write(code_file); + FEND_ fend; + fend.write(code_file); + code_file.close(); +} void DynamicModel::writeDynamicMFile(const string &dynamic_basename) const - { - string filename = dynamic_basename + ".m"; - - ofstream mDynamicModelFile; - mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary); - if (!mDynamicModelFile.is_open()) - { - cerr << "Error: Can't open file " << filename << " for writing" << endl; - exit(EXIT_FAILURE); - } - mDynamicModelFile << "function [residual, g1, g2, g3] = " << dynamic_basename << "(y, x, params, it_)" << endl - << "%" << endl - << "% Status : Computes dynamic model for Dynare" << endl - << "%" << endl - << "% Warning : this file is generated automatically by Dynare" << endl - << "% from model file (.mod)" << endl << endl; - - if (containsSteadyStateOperator()) - mDynamicModelFile << "global oo_;" << endl << endl; - - writeDynamicModel(mDynamicModelFile, false); - - mDynamicModelFile.close(); - } +{ + string filename = dynamic_basename + ".m"; + + ofstream mDynamicModelFile; + mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary); + if (!mDynamicModelFile.is_open()) + { + cerr << "Error: Can't open file " << filename << " for writing" << endl; + exit(EXIT_FAILURE); + } + mDynamicModelFile << "function [residual, g1, g2, g3] = " << dynamic_basename << "(y, x, params, it_)" << endl + << "%" << endl + << "% Status : Computes dynamic model for Dynare" << endl + << "%" << endl + << "% Warning : this file is generated automatically by Dynare" << endl + << "% from model file (.mod)" << endl << endl; + + if (containsSteadyStateOperator()) + mDynamicModelFile << "global oo_;" << endl << endl; + + writeDynamicModel(mDynamicModelFile, false); + + mDynamicModelFile.close(); +} void DynamicModel::writeDynamicCFile(const string &dynamic_basename) const - { - string filename = dynamic_basename + ".c"; - ofstream mDynamicModelFile; - - mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary); - if (!mDynamicModelFile.is_open()) - { - cerr << "Error: Can't open file " << filename << " for writing" << endl; - exit(EXIT_FAILURE); - } - mDynamicModelFile << "/*" << endl - << " * " << filename << " : Computes dynamic model for Dynare" << endl - << " *" << endl - << " * Warning : this file is generated automatically by Dynare" << endl - << " * from model file (.mod)" << endl - << endl - << " */" << endl - << "#include <math.h>" << endl - << "#include \"mex.h\"" << endl - << endl - << "#define max(a, b) (((a) > (b)) ? (a) : (b))" << endl - << "#define min(a, b) (((a) > (b)) ? (b) : (a))" << endl; - - // Writing the function body - writeDynamicModel(mDynamicModelFile, true); - - // Writing the gateway routine - mDynamicModelFile << "/* The gateway routine */" << endl - << "void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])" << endl - << "{" << endl - << " double *y, *x, *params;" << endl - << " double *residual, *g1, *v2, *v3;" << endl - << " int nb_row_x, it_;" << endl - << endl - << " /* Create a pointer to the input matrix y. */" << endl - << " y = mxGetPr(prhs[0]);" << endl - << endl - << " /* Create a pointer to the input matrix x. */" << endl - << " x = mxGetPr(prhs[1]);" << endl - << endl - << " /* Create a pointer to the input matrix params. */" << endl - << " params = mxGetPr(prhs[2]);" << endl - << endl - << " /* Fetch time index */" << endl - << " it_ = (int) mxGetScalar(prhs[3]) - 1;" << endl - << endl - << " /* Gets number of rows of matrix x. */" << endl - << " nb_row_x = mxGetM(prhs[1]);" << endl - << endl - << " residual = NULL;" << endl - << " if (nlhs >= 1)" << endl - << " {" << endl - << " /* Set the output pointer to the output matrix residual. */" << endl - << " plhs[0] = mxCreateDoubleMatrix(" << equations.size() << ",1, mxREAL);" << endl - << " /* Create a C pointer to a copy of the output matrix residual. */" << endl - << " residual = mxGetPr(plhs[0]);" << endl - << " }" << endl - << endl - << " g1 = NULL;" << endl - << " if (nlhs >= 2)" << endl - << " {" << endl - << " /* Set the output pointer to the output matrix g1. */" << endl - - << " plhs[1] = mxCreateDoubleMatrix(" << equations.size() << ", " << dynJacobianColsNbr << ", mxREAL);" << endl - << " /* Create a C pointer to a copy of the output matrix g1. */" << endl - << " g1 = mxGetPr(plhs[1]);" << endl - << " }" << endl - << endl - << " v2 = NULL;" << endl - << " if (nlhs >= 3)" << endl - << " {" << endl - << " /* Set the output pointer to the output matrix v2. */" << endl - << " plhs[2] = mxCreateDoubleMatrix(" << NNZDerivatives[1] << ", " << 3 - << ", mxREAL);" << endl - << " v2 = mxGetPr(plhs[2]);" << endl - << " }" << endl - << endl - << " if (nlhs >= 4)" << endl - << " {" << endl - << " /* Set the output pointer to the output matrix v3. */" << endl - << " plhs[3] = mxCreateDoubleMatrix(" << NNZDerivatives[2] << ", " << 3 << ", mxREAL);" << endl - << " v3 = mxGetPr(plhs[3]);" << endl - << " }" << endl - << endl - << " /* Call the C subroutines. */" << endl - << " Dynamic(y, x, nb_row_x, params, it_, residual, g1, v2, v3);" << endl - << "}" << endl; - mDynamicModelFile.close(); - } +{ + string filename = dynamic_basename + ".c"; + ofstream mDynamicModelFile; + + mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary); + if (!mDynamicModelFile.is_open()) + { + cerr << "Error: Can't open file " << filename << " for writing" << endl; + exit(EXIT_FAILURE); + } + mDynamicModelFile << "/*" << endl + << " * " << filename << " : Computes dynamic model for Dynare" << endl + << " *" << endl + << " * Warning : this file is generated automatically by Dynare" << endl + << " * from model file (.mod)" << endl + << endl + << " */" << endl + << "#include <math.h>" << endl + << "#include \"mex.h\"" << endl + << endl + << "#define max(a, b) (((a) > (b)) ? (a) : (b))" << endl + << "#define min(a, b) (((a) > (b)) ? (b) : (a))" << endl; + + // Writing the function body + writeDynamicModel(mDynamicModelFile, true); + + // Writing the gateway routine + mDynamicModelFile << "/* The gateway routine */" << endl + << "void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])" << endl + << "{" << endl + << " double *y, *x, *params;" << endl + << " double *residual, *g1, *v2, *v3;" << endl + << " int nb_row_x, it_;" << endl + << endl + << " /* Create a pointer to the input matrix y. */" << endl + << " y = mxGetPr(prhs[0]);" << endl + << endl + << " /* Create a pointer to the input matrix x. */" << endl + << " x = mxGetPr(prhs[1]);" << endl + << endl + << " /* Create a pointer to the input matrix params. */" << endl + << " params = mxGetPr(prhs[2]);" << endl + << endl + << " /* Fetch time index */" << endl + << " it_ = (int) mxGetScalar(prhs[3]) - 1;" << endl + << endl + << " /* Gets number of rows of matrix x. */" << endl + << " nb_row_x = mxGetM(prhs[1]);" << endl + << endl + << " residual = NULL;" << endl + << " if (nlhs >= 1)" << endl + << " {" << endl + << " /* Set the output pointer to the output matrix residual. */" << endl + << " plhs[0] = mxCreateDoubleMatrix(" << equations.size() << ",1, mxREAL);" << endl + << " /* Create a C pointer to a copy of the output matrix residual. */" << endl + << " residual = mxGetPr(plhs[0]);" << endl + << " }" << endl + << endl + << " g1 = NULL;" << endl + << " if (nlhs >= 2)" << endl + << " {" << endl + << " /* Set the output pointer to the output matrix g1. */" << endl + + << " plhs[1] = mxCreateDoubleMatrix(" << equations.size() << ", " << dynJacobianColsNbr << ", mxREAL);" << endl + << " /* Create a C pointer to a copy of the output matrix g1. */" << endl + << " g1 = mxGetPr(plhs[1]);" << endl + << " }" << endl + << endl + << " v2 = NULL;" << endl + << " if (nlhs >= 3)" << endl + << " {" << endl + << " /* Set the output pointer to the output matrix v2. */" << endl + << " plhs[2] = mxCreateDoubleMatrix(" << NNZDerivatives[1] << ", " << 3 + << ", mxREAL);" << endl + << " v2 = mxGetPr(plhs[2]);" << endl + << " }" << endl + << endl + << " if (nlhs >= 4)" << endl + << " {" << endl + << " /* Set the output pointer to the output matrix v3. */" << endl + << " plhs[3] = mxCreateDoubleMatrix(" << NNZDerivatives[2] << ", " << 3 << ", mxREAL);" << endl + << " v3 = mxGetPr(plhs[3]);" << endl + << " }" << endl + << endl + << " /* Call the C subroutines. */" << endl + << " Dynamic(y, x, nb_row_x, params, it_, residual, g1, v2, v3);" << endl + << "}" << endl; + mDynamicModelFile.close(); +} string -DynamicModel::reform(const string name1) const - { - string name=name1; - int pos = name.find("\\", 0); - while (pos >= 0) - { - if (name.substr(pos + 1, 1) != "\\") - { - name = name.insert(pos, "\\"); - pos++; - } - pos++; - pos = name.find("\\", pos); - } - return (name); - } +DynamicModel::reform(const string name1) const +{ + string name = name1; + int pos = name.find("\\", 0); + while (pos >= 0) + { + if (name.substr(pos + 1, 1) != "\\") + { + name = name.insert(pos, "\\"); + pos++; + } + pos++; + pos = name.find("\\", pos); + } + return (name); +} void DynamicModel::Write_Inf_To_Bin_File(const string &dynamic_basename, const string &bin_basename, const int &num, int &u_count_int, bool &file_open, bool is_two_boundaries) const - { - int j; - std::ofstream SaveCode; - if (file_open) - SaveCode.open((bin_basename + "_dynamic.bin").c_str(), ios::out | ios::in | ios::binary | ios ::ate ); - else - SaveCode.open((bin_basename + "_dynamic.bin").c_str(), ios::out | ios::binary); - if (!SaveCode.is_open()) - { - cout << "Error : Can't open file \"" << bin_basename << "_dynamic.bin\" for writing\n"; - exit(EXIT_FAILURE); - } - u_count_int=0; - unsigned int block_size = getBlockSize(num); - unsigned int block_mfs = getBlockMfs(num); - unsigned int block_recursive = block_size - block_mfs; - for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[num].begin(); it != (blocks_derivatives[num]).end(); it++) - { - unsigned int eq = it->first.first; - unsigned int var = it->first.second; - int lag = it->second.first; - if(eq>=block_recursive and var>=block_recursive) - { - int v = eq - block_recursive; - SaveCode.write(reinterpret_cast<char *>(&v), sizeof(v)); - int varr = var - block_recursive + lag * block_mfs; - SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr)); - SaveCode.write(reinterpret_cast<char *>(&lag), sizeof(lag)); - int u = u_count_int + block_mfs; - SaveCode.write(reinterpret_cast<char *>(&u), sizeof(u)); - u_count_int++; - } - } - - if (is_two_boundaries) - u_count_int+=block_mfs; - for (j = block_recursive; j < (int) block_size; j++) - { - unsigned int varr=getBlockVariableID(num, j); - SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr)); - } - for (j = block_recursive; j < (int) block_size; j++) - { - unsigned int eqr=getBlockEquationID(num, j); - SaveCode.write(reinterpret_cast<char *>(&eqr), sizeof(eqr)); - } - SaveCode.close(); - } +{ + int j; + std::ofstream SaveCode; + if (file_open) + SaveCode.open((bin_basename + "_dynamic.bin").c_str(), ios::out | ios::in | ios::binary | ios::ate); + else + SaveCode.open((bin_basename + "_dynamic.bin").c_str(), ios::out | ios::binary); + if (!SaveCode.is_open()) + { + cout << "Error : Can't open file \"" << bin_basename << "_dynamic.bin\" for writing\n"; + exit(EXIT_FAILURE); + } + u_count_int = 0; + unsigned int block_size = getBlockSize(num); + unsigned int block_mfs = getBlockMfs(num); + unsigned int block_recursive = block_size - block_mfs; + for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[num].begin(); it != (blocks_derivatives[num]).end(); it++) + { + unsigned int eq = it->first.first; + unsigned int var = it->first.second; + int lag = it->second.first; + if (eq >= block_recursive and var >= block_recursive) + { + int v = eq - block_recursive; + SaveCode.write(reinterpret_cast<char *>(&v), sizeof(v)); + int varr = var - block_recursive + lag * block_mfs; + SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr)); + SaveCode.write(reinterpret_cast<char *>(&lag), sizeof(lag)); + int u = u_count_int + block_mfs; + SaveCode.write(reinterpret_cast<char *>(&u), sizeof(u)); + u_count_int++; + } + } + + if (is_two_boundaries) + u_count_int += block_mfs; + for (j = block_recursive; j < (int) block_size; j++) + { + unsigned int varr = getBlockVariableID(num, j); + SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr)); + } + for (j = block_recursive; j < (int) block_size; j++) + { + unsigned int eqr = getBlockEquationID(num, j); + SaveCode.write(reinterpret_cast<char *>(&eqr), sizeof(eqr)); + } + SaveCode.close(); +} void DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const string &basename) const - { - string sp; - ofstream mDynamicModelFile; - ostringstream tmp, tmp1, tmp_eq; - int prev_Simulation_Type; - bool OK; - chdir(basename.c_str()); - string filename = dynamic_basename + ".m"; - mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary); - if (!mDynamicModelFile.is_open()) - { - cerr << "Error: Can't open file " << filename << " for writing" << endl; - exit(EXIT_FAILURE); - } - mDynamicModelFile << "%\n"; - mDynamicModelFile << "% " << filename << " : Computes dynamic model for Dynare\n"; - mDynamicModelFile << "%\n"; - mDynamicModelFile << "% Warning : this file is generated automatically by Dynare\n"; - mDynamicModelFile << "% from model file (.mod)\n\n"; - mDynamicModelFile << "%/\n"; - - int Nb_SGE=0; - bool skip_head, open_par=false; - - mDynamicModelFile << "function [varargout] = " << dynamic_basename << "(varargin)\n"; - mDynamicModelFile << " global oo_ options_ M_ ;\n"; - mDynamicModelFile << " g2=[];g3=[];\n"; - //Temporary variables declaration - OK=true; - ostringstream tmp_output; - for (temporary_terms_type::const_iterator it = temporary_terms.begin(); - it != temporary_terms.end(); it++) - { - if (OK) - OK=false; - else - tmp_output << " "; - (*it)->writeOutput(tmp_output, oMatlabStaticModelSparse, temporary_terms); - } - if (tmp_output.str().length()>0) - mDynamicModelFile << " global " << tmp_output.str() << " M_ ;\n"; - - mDynamicModelFile << " T_init=zeros(1,options_.periods+M_.maximum_lag+M_.maximum_lead);\n"; - tmp_output.str(""); - for (temporary_terms_type::const_iterator it = temporary_terms.begin(); - it != temporary_terms.end(); it++) - { - tmp_output << " "; - (*it)->writeOutput(tmp_output, oMatlabDynamicModel, temporary_terms); - tmp_output << "=T_init;\n"; - } - if (tmp_output.str().length()>0) - mDynamicModelFile << tmp_output.str(); - - mDynamicModelFile << " y_kmin=M_.maximum_lag;" << endl - << " y_kmax=M_.maximum_lead;" << endl - << " y_size=M_.endo_nbr;" << endl - << " if(length(varargin)>0)" << endl - << " %it is a simple evaluation of the dynamic model for time _it" << endl - << " params=varargin{3};" << endl - << " it_=varargin{4};" << endl - << " Per_u_=0;" << endl - << " Per_y_=it_*y_size;" << endl - << " y=varargin{1};" << endl - << " ys=y(it_,:);" << endl - << " x=varargin{2};" << endl; - prev_Simulation_Type=-1; - tmp.str(""); - tmp_eq.str(""); - unsigned int nb_blocks = getNbBlocks(); - unsigned int block = 0; - for (int count_call=1; block < nb_blocks; block++, count_call++) - { - unsigned int block_size = getBlockSize(block); - unsigned int block_mfs = getBlockMfs(block); - unsigned int block_recursive = block_size - block_mfs; - BlockSimulationType simulation_type = getBlockSimulationType(block); - - if(simulation_type==EVALUATE_FORWARD || simulation_type==EVALUATE_BACKWARD) - { - for (unsigned int ik=0 ;ik<block_size;ik++) - { - tmp << " " << getBlockVariableID(block, ik)+1; - tmp_eq << " " << getBlockEquationID(block, ik)+1; - } - } - else - { - for (unsigned int ik = block_recursive; ik < block_size; ik++) - { - tmp << " " << getBlockVariableID(block, ik)+1; - tmp_eq << " " << getBlockEquationID(block, ik)+1; - } - } - mDynamicModelFile << " y_index_eq=[" << tmp_eq.str() << "];\n"; - mDynamicModelFile << " y_index=[" << tmp.str() << "];\n"; +{ + string sp; + ofstream mDynamicModelFile; + ostringstream tmp, tmp1, tmp_eq; + int prev_Simulation_Type; + bool OK; + chdir(basename.c_str()); + string filename = dynamic_basename + ".m"; + mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary); + if (!mDynamicModelFile.is_open()) + { + cerr << "Error: Can't open file " << filename << " for writing" << endl; + exit(EXIT_FAILURE); + } + mDynamicModelFile << "%\n"; + mDynamicModelFile << "% " << filename << " : Computes dynamic model for Dynare\n"; + mDynamicModelFile << "%\n"; + mDynamicModelFile << "% Warning : this file is generated automatically by Dynare\n"; + mDynamicModelFile << "% from model file (.mod)\n\n"; + mDynamicModelFile << "%/\n"; + + int Nb_SGE = 0; + bool skip_head, open_par = false; + + mDynamicModelFile << "function [varargout] = " << dynamic_basename << "(varargin)\n"; + mDynamicModelFile << " global oo_ options_ M_ ;\n"; + mDynamicModelFile << " g2=[];g3=[];\n"; + //Temporary variables declaration + OK = true; + ostringstream tmp_output; + for (temporary_terms_type::const_iterator it = temporary_terms.begin(); + it != temporary_terms.end(); it++) + { + if (OK) + OK = false; + else + tmp_output << " "; + (*it)->writeOutput(tmp_output, oMatlabStaticModelSparse, temporary_terms); + } + if (tmp_output.str().length() > 0) + mDynamicModelFile << " global " << tmp_output.str() << " M_ ;\n"; - switch (simulation_type) - { - case EVALUATE_FORWARD: - case EVALUATE_BACKWARD: - mDynamicModelFile << " [y, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << block + 1 << "(y, x, params, 1, it_-1, 1);\n"; - mDynamicModelFile << " residual(y_index_eq)=ys(y_index)-y(it_, y_index);\n"; - break; - case SOLVE_FORWARD_SIMPLE: - case SOLVE_BACKWARD_SIMPLE: - mDynamicModelFile << " [r, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << block + 1 << "(y, x, params, it_, 1);\n"; - mDynamicModelFile << " residual(y_index_eq)=r;\n"; - break; - case SOLVE_FORWARD_COMPLETE: - case SOLVE_BACKWARD_COMPLETE: - mDynamicModelFile << " [r, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << block + 1 << "(y, x, params, it_, 1);\n"; - mDynamicModelFile << " residual(y_index_eq)=r;\n"; - break; - case SOLVE_TWO_BOUNDARIES_COMPLETE: - case SOLVE_TWO_BOUNDARIES_SIMPLE: - mDynamicModelFile << " [r, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, b, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << block + 1 << "(y, x, params, it_-" << max_lag << ", 1, " << max_lag << ", " << block_recursive << ");\n"; - mDynamicModelFile << " residual(y_index_eq)=r(:,M_.maximum_lag+1);\n"; - break; - default: - break; - } - tmp_eq.str(""); - tmp.str(""); - } - if (tmp1.str().length()) - { - mDynamicModelFile << tmp1.str(); - tmp1.str(""); - } - mDynamicModelFile << " varargout{1}=residual;" << endl - << " varargout{2}=dr;" << endl - << " return;" << endl - << " end;" << endl - << " %it is the deterministic simulation of the block decomposed dynamic model" << endl - << " if(options_.stack_solve_algo==1)" << endl - << " mthd='Sparse LU';" << endl - << " elseif(options_.stack_solve_algo==2)" << endl - << " mthd='GMRES';" << endl - << " elseif(options_.stack_solve_algo==3)" << endl - << " mthd='BICGSTAB';" << endl - << " elseif(options_.stack_solve_algo==4)" << endl - << " mthd='OPTIMPATH';" << endl - << " else" << endl - << " mthd='UNKNOWN';" << endl - << " end;" << endl - << " disp (['-----------------------------------------------------']) ;" << endl - << " disp (['MODEL SIMULATION: (method=' mthd ')']) ;" << endl - << " fprintf('\\n') ;" << endl - << " periods=options_.periods;" << endl - << " maxit_=options_.maxit_;" << endl - << " solve_tolf=options_.solve_tolf;" << endl - << " y=oo_.endo_simul';" << endl - << " x=oo_.exo_simul;" << endl; - - prev_Simulation_Type=-1; - mDynamicModelFile << " params=M_.params;\n"; - mDynamicModelFile << " oo_.deterministic_simulation.status = 0;\n"; - for (block = 0;block < nb_blocks; block++) - { - unsigned int block_size = getBlockSize(block); - unsigned int block_mfs = getBlockMfs(block); - unsigned int block_recursive = block_size - block_mfs; - BlockSimulationType simulation_type = getBlockSimulationType(block); - - if (BlockSim(prev_Simulation_Type)==BlockSim(simulation_type) && - (simulation_type==EVALUATE_FORWARD || simulation_type==EVALUATE_BACKWARD )) - skip_head=true; - else - skip_head=false; - if ((simulation_type == EVALUATE_FORWARD ) && (block_size)) - { - if (!skip_head) - { - if (open_par) - { - mDynamicModelFile << " end\n"; - } - mDynamicModelFile << " oo_.deterministic_simulation.status = 1;\n"; - mDynamicModelFile << " oo_.deterministic_simulation.error = 0;\n"; - mDynamicModelFile << " oo_.deterministic_simulation.iterations = 0;\n"; - mDynamicModelFile << " if(isfield(oo_.deterministic_simulation,'block'))\n"; - mDynamicModelFile << " blck_num = length(oo_.deterministic_simulation.block)+1;\n"; - mDynamicModelFile << " else\n"; - mDynamicModelFile << " blck_num = 1;\n"; - mDynamicModelFile << " end;\n"; - mDynamicModelFile << " oo_.deterministic_simulation.block(blck_num).status = 1;\n"; - mDynamicModelFile << " oo_.deterministic_simulation.block(blck_num).error = 0;\n"; - mDynamicModelFile << " oo_.deterministic_simulation.block(blck_num).iterations = 0;\n"; - mDynamicModelFile << " g1=[];g2=[];g3=[];\n"; - mDynamicModelFile << " y=" << dynamic_basename << "_" << block + 1 << "(y, x, params, 0, y_kmin, periods);\n"; - mDynamicModelFile << " tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n"; - mDynamicModelFile << " if(isnan(tmp) | isinf(tmp))\n"; - mDynamicModelFile << " disp(['Inf or Nan value during the evaluation of block " << block <<"']);\n"; - mDynamicModelFile << " return;\n"; - mDynamicModelFile << " end;\n"; - } - } - else if ((simulation_type == EVALUATE_BACKWARD ) && (block_size)) - { - if (!skip_head) - { - if (open_par) - { - mDynamicModelFile << " end\n"; - } - mDynamicModelFile << " oo_.deterministic_simulation.status = 1;\n"; - mDynamicModelFile << " oo_.deterministic_simulation.error = 0;\n"; - mDynamicModelFile << " oo_.deterministic_simulation.iterations = 0;\n"; - mDynamicModelFile << " if(isfield(oo_.deterministic_simulation,'block'))\n"; - mDynamicModelFile << " blck_num = length(oo_.deterministic_simulation.block)+1;\n"; - mDynamicModelFile << " else\n"; - mDynamicModelFile << " blck_num = 1;\n"; - mDynamicModelFile << " end;\n"; - mDynamicModelFile << " oo_.deterministic_simulation.block(blck_num).status = 1;\n"; - mDynamicModelFile << " oo_.deterministic_simulation.block(blck_num).error = 0;\n"; - mDynamicModelFile << " oo_.deterministic_simulation.block(blck_num).iterations = 0;\n"; - mDynamicModelFile << " g1=[];g2=[];g3=[];\n"; - mDynamicModelFile << " " << dynamic_basename << "_" << block + 1 << "(y, x, params, 0, y_kmin, periods);\n"; - mDynamicModelFile << " tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n"; - mDynamicModelFile << " if(isnan(tmp) | isinf(tmp))\n"; - mDynamicModelFile << " disp(['Inf or Nan value during the evaluation of block " << block <<"']);\n"; - mDynamicModelFile << " return;\n"; - mDynamicModelFile << " end;\n"; - } - } - else if ((simulation_type == SOLVE_FORWARD_COMPLETE || simulation_type == SOLVE_FORWARD_SIMPLE) && (block_size)) - { - if (open_par) - mDynamicModelFile << " end\n"; - open_par=false; - mDynamicModelFile << " g1=0;\n"; - mDynamicModelFile << " r=0;\n"; - tmp.str(""); - for (unsigned int ik = block_recursive; ik < block_size; ik++) - { - tmp << " " << getBlockVariableID(block, ik)+1; - } - mDynamicModelFile << " y_index = [" << tmp.str() << "];\n"; - int nze = blocks_derivatives[block].size(); - mDynamicModelFile << " if(isfield(oo_.deterministic_simulation,'block'))\n"; - mDynamicModelFile << " blck_num = length(oo_.deterministic_simulation.block)+1;\n"; - mDynamicModelFile << " else\n"; - mDynamicModelFile << " blck_num = 1;\n"; - mDynamicModelFile << " end;\n"; - mDynamicModelFile << " y = solve_one_boundary('" << dynamic_basename << "_" << block + 1 << "'" << - ", y, x, params, y_index, " << nze << - ", options_.periods, " << blocks_linear[block] << - ", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, " << cutoff << ", options_.stack_solve_algo, 1, 1, 0);\n"; - mDynamicModelFile << " tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n"; - mDynamicModelFile << " if(isnan(tmp) | isinf(tmp))\n"; - mDynamicModelFile << " disp(['Inf or Nan value during the resolution of block " << block <<"']);\n"; - mDynamicModelFile << " return;\n"; - mDynamicModelFile << " end;\n"; - } - else if ((simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_BACKWARD_SIMPLE) && (block_size)) - { - if (open_par) - mDynamicModelFile << " end\n"; - open_par=false; - mDynamicModelFile << " g1=0;\n"; - mDynamicModelFile << " r=0;\n"; - tmp.str(""); - for (unsigned int ik = block_recursive; ik < block_size; ik++) - { - tmp << " " << getBlockVariableID(block, ik)+1; - } - mDynamicModelFile << " y_index = [" << tmp.str() << "];\n"; - int nze = blocks_derivatives[block].size(); - - mDynamicModelFile << " if(isfield(oo_.deterministic_simulation,'block'))\n"; - mDynamicModelFile << " blck_num = length(oo_.deterministic_simulation.block)+1;\n"; - mDynamicModelFile << " else\n"; - mDynamicModelFile << " blck_num = 1;\n"; - mDynamicModelFile << " end;\n"; - mDynamicModelFile << " y = solve_one_boundary('" << dynamic_basename << "_" << block + 1 << "'" << - ", y, x, params, y_index, " << nze << - ", options_.periods, " << blocks_linear[block] << - ", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, " << cutoff << ", options_.stack_solve_algo, 1, 1, 0);\n"; - mDynamicModelFile << " tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n"; - mDynamicModelFile << " if(isnan(tmp) | isinf(tmp))\n"; - mDynamicModelFile << " disp(['Inf or Nan value during the resolution of block " << block <<"']);\n"; - mDynamicModelFile << " return;\n"; - mDynamicModelFile << " end;\n"; - } - else if ((simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) && (block_size)) - { - if (open_par) - mDynamicModelFile << " end\n"; - open_par=false; - Nb_SGE++; - int nze = blocks_derivatives[block].size(); - mDynamicModelFile << " y_index=["; - for (unsigned int ik = block_recursive; ik < block_size; ik++) - { - mDynamicModelFile << " " << getBlockVariableID(block, ik)+1; - } - mDynamicModelFile << " ];\n"; - mDynamicModelFile << " if(isfield(oo_.deterministic_simulation,'block'))\n"; - mDynamicModelFile << " blck_num = length(oo_.deterministic_simulation.block)+1;\n"; - mDynamicModelFile << " else\n"; - mDynamicModelFile << " blck_num = 1;\n"; - mDynamicModelFile << " end;\n"; - mDynamicModelFile << " y = solve_two_boundaries('" << dynamic_basename << "_" << block + 1 << "'" << - ", y, x, params, y_index, " << nze << - ", options_.periods, " << max_leadlag_block[block].first << - ", " << max_leadlag_block[block].second << - ", " << blocks_linear[block] << - ", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, " << cutoff << ", options_.stack_solve_algo);\n"; - mDynamicModelFile << " tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n"; - mDynamicModelFile << " if(isnan(tmp) | isinf(tmp))\n"; - mDynamicModelFile << " disp(['Inf or Nan value during the resolution of block " << block <<"']);\n"; - mDynamicModelFile << " return;\n"; - mDynamicModelFile << " end;\n"; - } - prev_Simulation_Type=simulation_type; - } - if (open_par) - mDynamicModelFile << " end;\n"; - open_par=false; - mDynamicModelFile << " oo_.endo_simul = y';\n"; - mDynamicModelFile << "return;\n"; + mDynamicModelFile << " T_init=zeros(1,options_.periods+M_.maximum_lag+M_.maximum_lead);\n"; + tmp_output.str(""); + for (temporary_terms_type::const_iterator it = temporary_terms.begin(); + it != temporary_terms.end(); it++) + { + tmp_output << " "; + (*it)->writeOutput(tmp_output, oMatlabDynamicModel, temporary_terms); + tmp_output << "=T_init;\n"; + } + if (tmp_output.str().length() > 0) + mDynamicModelFile << tmp_output.str(); + + mDynamicModelFile << " y_kmin=M_.maximum_lag;" << endl + << " y_kmax=M_.maximum_lead;" << endl + << " y_size=M_.endo_nbr;" << endl + << " if(length(varargin)>0)" << endl + << " %it is a simple evaluation of the dynamic model for time _it" << endl + << " params=varargin{3};" << endl + << " it_=varargin{4};" << endl + << " Per_u_=0;" << endl + << " Per_y_=it_*y_size;" << endl + << " y=varargin{1};" << endl + << " ys=y(it_,:);" << endl + << " x=varargin{2};" << endl; + prev_Simulation_Type = -1; + tmp.str(""); + tmp_eq.str(""); + unsigned int nb_blocks = getNbBlocks(); + unsigned int block = 0; + for (int count_call = 1; block < nb_blocks; block++, count_call++) + { + unsigned int block_size = getBlockSize(block); + unsigned int block_mfs = getBlockMfs(block); + unsigned int block_recursive = block_size - block_mfs; + BlockSimulationType simulation_type = getBlockSimulationType(block); + + if (simulation_type == EVALUATE_FORWARD || simulation_type == EVALUATE_BACKWARD) + { + for (unsigned int ik = 0; ik < block_size; ik++) + { + tmp << " " << getBlockVariableID(block, ik)+1; + tmp_eq << " " << getBlockEquationID(block, ik)+1; + } + } + else + { + for (unsigned int ik = block_recursive; ik < block_size; ik++) + { + tmp << " " << getBlockVariableID(block, ik)+1; + tmp_eq << " " << getBlockEquationID(block, ik)+1; + } + } + mDynamicModelFile << " y_index_eq=[" << tmp_eq.str() << "];\n"; + mDynamicModelFile << " y_index=[" << tmp.str() << "];\n"; + + switch (simulation_type) + { + case EVALUATE_FORWARD: + case EVALUATE_BACKWARD: + mDynamicModelFile << " [y, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << block + 1 << "(y, x, params, 1, it_-1, 1);\n"; + mDynamicModelFile << " residual(y_index_eq)=ys(y_index)-y(it_, y_index);\n"; + break; + case SOLVE_FORWARD_SIMPLE: + case SOLVE_BACKWARD_SIMPLE: + mDynamicModelFile << " [r, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << block + 1 << "(y, x, params, it_, 1);\n"; + mDynamicModelFile << " residual(y_index_eq)=r;\n"; + break; + case SOLVE_FORWARD_COMPLETE: + case SOLVE_BACKWARD_COMPLETE: + mDynamicModelFile << " [r, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << block + 1 << "(y, x, params, it_, 1);\n"; + mDynamicModelFile << " residual(y_index_eq)=r;\n"; + break; + case SOLVE_TWO_BOUNDARIES_COMPLETE: + case SOLVE_TWO_BOUNDARIES_SIMPLE: + mDynamicModelFile << " [r, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, b, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << block + 1 << "(y, x, params, it_-" << max_lag << ", 1, " << max_lag << ", " << block_recursive << ");\n"; + mDynamicModelFile << " residual(y_index_eq)=r(:,M_.maximum_lag+1);\n"; + break; + default: + break; + } + tmp_eq.str(""); + tmp.str(""); + } + if (tmp1.str().length()) + { + mDynamicModelFile << tmp1.str(); + tmp1.str(""); + } + mDynamicModelFile << " varargout{1}=residual;" << endl + << " varargout{2}=dr;" << endl + << " return;" << endl + << " end;" << endl + << " %it is the deterministic simulation of the block decomposed dynamic model" << endl + << " if(options_.stack_solve_algo==1)" << endl + << " mthd='Sparse LU';" << endl + << " elseif(options_.stack_solve_algo==2)" << endl + << " mthd='GMRES';" << endl + << " elseif(options_.stack_solve_algo==3)" << endl + << " mthd='BICGSTAB';" << endl + << " elseif(options_.stack_solve_algo==4)" << endl + << " mthd='OPTIMPATH';" << endl + << " else" << endl + << " mthd='UNKNOWN';" << endl + << " end;" << endl + << " disp (['-----------------------------------------------------']) ;" << endl + << " disp (['MODEL SIMULATION: (method=' mthd ')']) ;" << endl + << " fprintf('\\n') ;" << endl + << " periods=options_.periods;" << endl + << " maxit_=options_.maxit_;" << endl + << " solve_tolf=options_.solve_tolf;" << endl + << " y=oo_.endo_simul';" << endl + << " x=oo_.exo_simul;" << endl; + + prev_Simulation_Type = -1; + mDynamicModelFile << " params=M_.params;\n"; + mDynamicModelFile << " oo_.deterministic_simulation.status = 0;\n"; + for (block = 0; block < nb_blocks; block++) + { + unsigned int block_size = getBlockSize(block); + unsigned int block_mfs = getBlockMfs(block); + unsigned int block_recursive = block_size - block_mfs; + BlockSimulationType simulation_type = getBlockSimulationType(block); + + if (BlockSim(prev_Simulation_Type) == BlockSim(simulation_type) + && (simulation_type == EVALUATE_FORWARD || simulation_type == EVALUATE_BACKWARD)) + skip_head = true; + else + skip_head = false; + if ((simulation_type == EVALUATE_FORWARD) && (block_size)) + { + if (!skip_head) + { + if (open_par) + { + mDynamicModelFile << " end\n"; + } + mDynamicModelFile << " oo_.deterministic_simulation.status = 1;\n"; + mDynamicModelFile << " oo_.deterministic_simulation.error = 0;\n"; + mDynamicModelFile << " oo_.deterministic_simulation.iterations = 0;\n"; + mDynamicModelFile << " if(isfield(oo_.deterministic_simulation,'block'))\n"; + mDynamicModelFile << " blck_num = length(oo_.deterministic_simulation.block)+1;\n"; + mDynamicModelFile << " else\n"; + mDynamicModelFile << " blck_num = 1;\n"; + mDynamicModelFile << " end;\n"; + mDynamicModelFile << " oo_.deterministic_simulation.block(blck_num).status = 1;\n"; + mDynamicModelFile << " oo_.deterministic_simulation.block(blck_num).error = 0;\n"; + mDynamicModelFile << " oo_.deterministic_simulation.block(blck_num).iterations = 0;\n"; + mDynamicModelFile << " g1=[];g2=[];g3=[];\n"; + mDynamicModelFile << " y=" << dynamic_basename << "_" << block + 1 << "(y, x, params, 0, y_kmin, periods);\n"; + mDynamicModelFile << " tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n"; + mDynamicModelFile << " if(isnan(tmp) | isinf(tmp))\n"; + mDynamicModelFile << " disp(['Inf or Nan value during the evaluation of block " << block <<"']);\n"; + mDynamicModelFile << " return;\n"; + mDynamicModelFile << " end;\n"; + } + } + else if ((simulation_type == EVALUATE_BACKWARD) && (block_size)) + { + if (!skip_head) + { + if (open_par) + { + mDynamicModelFile << " end\n"; + } + mDynamicModelFile << " oo_.deterministic_simulation.status = 1;\n"; + mDynamicModelFile << " oo_.deterministic_simulation.error = 0;\n"; + mDynamicModelFile << " oo_.deterministic_simulation.iterations = 0;\n"; + mDynamicModelFile << " if(isfield(oo_.deterministic_simulation,'block'))\n"; + mDynamicModelFile << " blck_num = length(oo_.deterministic_simulation.block)+1;\n"; + mDynamicModelFile << " else\n"; + mDynamicModelFile << " blck_num = 1;\n"; + mDynamicModelFile << " end;\n"; + mDynamicModelFile << " oo_.deterministic_simulation.block(blck_num).status = 1;\n"; + mDynamicModelFile << " oo_.deterministic_simulation.block(blck_num).error = 0;\n"; + mDynamicModelFile << " oo_.deterministic_simulation.block(blck_num).iterations = 0;\n"; + mDynamicModelFile << " g1=[];g2=[];g3=[];\n"; + mDynamicModelFile << " " << dynamic_basename << "_" << block + 1 << "(y, x, params, 0, y_kmin, periods);\n"; + mDynamicModelFile << " tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n"; + mDynamicModelFile << " if(isnan(tmp) | isinf(tmp))\n"; + mDynamicModelFile << " disp(['Inf or Nan value during the evaluation of block " << block <<"']);\n"; + mDynamicModelFile << " return;\n"; + mDynamicModelFile << " end;\n"; + } + } + else if ((simulation_type == SOLVE_FORWARD_COMPLETE || simulation_type == SOLVE_FORWARD_SIMPLE) && (block_size)) + { + if (open_par) + mDynamicModelFile << " end\n"; + open_par = false; + mDynamicModelFile << " g1=0;\n"; + mDynamicModelFile << " r=0;\n"; + tmp.str(""); + for (unsigned int ik = block_recursive; ik < block_size; ik++) + { + tmp << " " << getBlockVariableID(block, ik)+1; + } + mDynamicModelFile << " y_index = [" << tmp.str() << "];\n"; + int nze = blocks_derivatives[block].size(); + mDynamicModelFile << " if(isfield(oo_.deterministic_simulation,'block'))\n"; + mDynamicModelFile << " blck_num = length(oo_.deterministic_simulation.block)+1;\n"; + mDynamicModelFile << " else\n"; + mDynamicModelFile << " blck_num = 1;\n"; + mDynamicModelFile << " end;\n"; + mDynamicModelFile << " y = solve_one_boundary('" << dynamic_basename << "_" << block + 1 << "'" + <<", y, x, params, y_index, " << nze + <<", options_.periods, " << blocks_linear[block] + <<", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, " << cutoff << ", options_.stack_solve_algo, 1, 1, 0);\n"; + mDynamicModelFile << " tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n"; + mDynamicModelFile << " if(isnan(tmp) | isinf(tmp))\n"; + mDynamicModelFile << " disp(['Inf or Nan value during the resolution of block " << block <<"']);\n"; + mDynamicModelFile << " return;\n"; + mDynamicModelFile << " end;\n"; + } + else if ((simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_BACKWARD_SIMPLE) && (block_size)) + { + if (open_par) + mDynamicModelFile << " end\n"; + open_par = false; + mDynamicModelFile << " g1=0;\n"; + mDynamicModelFile << " r=0;\n"; + tmp.str(""); + for (unsigned int ik = block_recursive; ik < block_size; ik++) + { + tmp << " " << getBlockVariableID(block, ik)+1; + } + mDynamicModelFile << " y_index = [" << tmp.str() << "];\n"; + int nze = blocks_derivatives[block].size(); + + mDynamicModelFile << " if(isfield(oo_.deterministic_simulation,'block'))\n"; + mDynamicModelFile << " blck_num = length(oo_.deterministic_simulation.block)+1;\n"; + mDynamicModelFile << " else\n"; + mDynamicModelFile << " blck_num = 1;\n"; + mDynamicModelFile << " end;\n"; + mDynamicModelFile << " y = solve_one_boundary('" << dynamic_basename << "_" << block + 1 << "'" + <<", y, x, params, y_index, " << nze + <<", options_.periods, " << blocks_linear[block] + <<", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, " << cutoff << ", options_.stack_solve_algo, 1, 1, 0);\n"; + mDynamicModelFile << " tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n"; + mDynamicModelFile << " if(isnan(tmp) | isinf(tmp))\n"; + mDynamicModelFile << " disp(['Inf or Nan value during the resolution of block " << block <<"']);\n"; + mDynamicModelFile << " return;\n"; + mDynamicModelFile << " end;\n"; + } + else if ((simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) && (block_size)) + { + if (open_par) + mDynamicModelFile << " end\n"; + open_par = false; + Nb_SGE++; + int nze = blocks_derivatives[block].size(); + mDynamicModelFile << " y_index=["; + for (unsigned int ik = block_recursive; ik < block_size; ik++) + { + mDynamicModelFile << " " << getBlockVariableID(block, ik)+1; + } + mDynamicModelFile << " ];\n"; + mDynamicModelFile << " if(isfield(oo_.deterministic_simulation,'block'))\n"; + mDynamicModelFile << " blck_num = length(oo_.deterministic_simulation.block)+1;\n"; + mDynamicModelFile << " else\n"; + mDynamicModelFile << " blck_num = 1;\n"; + mDynamicModelFile << " end;\n"; + mDynamicModelFile << " y = solve_two_boundaries('" << dynamic_basename << "_" << block + 1 << "'" + <<", y, x, params, y_index, " << nze + <<", options_.periods, " << max_leadlag_block[block].first + <<", " << max_leadlag_block[block].second + <<", " << blocks_linear[block] + <<", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, " << cutoff << ", options_.stack_solve_algo);\n"; + mDynamicModelFile << " tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n"; + mDynamicModelFile << " if(isnan(tmp) | isinf(tmp))\n"; + mDynamicModelFile << " disp(['Inf or Nan value during the resolution of block " << block <<"']);\n"; + mDynamicModelFile << " return;\n"; + mDynamicModelFile << " end;\n"; + } + prev_Simulation_Type = simulation_type; + } + if (open_par) + mDynamicModelFile << " end;\n"; + open_par = false; + mDynamicModelFile << " oo_.endo_simul = y';\n"; + mDynamicModelFile << "return;\n"; - mDynamicModelFile.close(); + mDynamicModelFile.close(); - writeModelEquationsOrdered_M(dynamic_basename); + writeModelEquationsOrdered_M(dynamic_basename); - chdir(".."); - } + chdir(".."); +} void DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll) const - { - ostringstream model_output; // Used for storing model equations - ostringstream jacobian_output; // Used for storing jacobian equations - ostringstream hessian_output; // Used for storing Hessian equations - ostringstream third_derivatives_output; +{ + ostringstream model_output; // Used for storing model equations + ostringstream jacobian_output; // Used for storing jacobian equations + ostringstream hessian_output; // Used for storing Hessian equations + ostringstream third_derivatives_output; + + ExprNodeOutputType output_type = (use_dll ? oCDynamicModel : oMatlabDynamicModel); + + writeModelLocalVariables(model_output, output_type); + + writeTemporaryTerms(temporary_terms, model_output, output_type); - ExprNodeOutputType output_type = (use_dll ? oCDynamicModel : oMatlabDynamicModel); + writeModelEquations(model_output, output_type); - writeModelLocalVariables(model_output, output_type); + int nrows = equations.size(); + int hessianColsNbr = dynJacobianColsNbr * dynJacobianColsNbr; - writeTemporaryTerms(temporary_terms, model_output, output_type); + // Writing Jacobian + for (first_derivatives_type::const_iterator it = first_derivatives.begin(); + it != first_derivatives.end(); it++) + { + int eq = it->first.first; + int var = it->first.second; + NodeID d1 = it->second; + + jacobian_output << "g1"; + jacobianHelper(jacobian_output, eq, getDynJacobianCol(var), output_type); + jacobian_output << "="; + d1->writeOutput(jacobian_output, output_type, temporary_terms); + jacobian_output << ";" << endl; + } - writeModelEquations(model_output, output_type); + // Writing Hessian + int k = 0; // Keep the line of a 2nd derivative in v2 + for (second_derivatives_type::const_iterator it = second_derivatives.begin(); + it != second_derivatives.end(); it++) + { + int eq = it->first.first; + int var1 = it->first.second.first; + int var2 = it->first.second.second; + NodeID d2 = it->second; - int nrows = equations.size(); - int hessianColsNbr = dynJacobianColsNbr * dynJacobianColsNbr; + int id1 = getDynJacobianCol(var1); + int id2 = getDynJacobianCol(var2); - // Writing Jacobian - for (first_derivatives_type::const_iterator it = first_derivatives.begin(); - it != first_derivatives.end(); it++) - { - int eq = it->first.first; - int var = it->first.second; - NodeID d1 = it->second; + int col_nb = id1 * dynJacobianColsNbr + id2; + int col_nb_sym = id2 * dynJacobianColsNbr + id1; - jacobian_output << "g1"; - jacobianHelper(jacobian_output, eq, getDynJacobianCol(var), output_type); - jacobian_output << "="; - d1->writeOutput(jacobian_output, output_type, temporary_terms); - jacobian_output << ";" << endl; - } + sparseHelper(2, hessian_output, k, 0, output_type); + hessian_output << "=" << eq + 1 << ";" << endl; - // Writing Hessian - int k = 0; // Keep the line of a 2nd derivative in v2 - for (second_derivatives_type::const_iterator it = second_derivatives.begin(); - it != second_derivatives.end(); it++) - { - int eq = it->first.first; - int var1 = it->first.second.first; - int var2 = it->first.second.second; - NodeID d2 = it->second; + sparseHelper(2, hessian_output, k, 1, output_type); + hessian_output << "=" << col_nb + 1 << ";" << endl; - int id1 = getDynJacobianCol(var1); - int id2 = getDynJacobianCol(var2); + sparseHelper(2, hessian_output, k, 2, output_type); + hessian_output << "="; + d2->writeOutput(hessian_output, output_type, temporary_terms); + hessian_output << ";" << endl; - int col_nb = id1 * dynJacobianColsNbr + id2; - int col_nb_sym = id2 * dynJacobianColsNbr + id1; + k++; - sparseHelper(2, hessian_output, k, 0, output_type); - hessian_output << "=" << eq + 1 << ";" << endl; + // Treating symetric elements + if (id1 != id2) + { + sparseHelper(2, hessian_output, k, 0, output_type); + hessian_output << "=" << eq + 1 << ";" << endl; - sparseHelper(2, hessian_output, k, 1, output_type); - hessian_output << "=" << col_nb + 1 << ";" << endl; + sparseHelper(2, hessian_output, k, 1, output_type); + hessian_output << "=" << col_nb_sym + 1 << ";" << endl; - sparseHelper(2, hessian_output, k, 2, output_type); - hessian_output << "="; - d2->writeOutput(hessian_output, output_type, temporary_terms); - hessian_output << ";" << endl; + sparseHelper(2, hessian_output, k, 2, output_type); + hessian_output << "="; + sparseHelper(2, hessian_output, k-1, 2, output_type); + hessian_output << ";" << endl; - k++; + k++; + } + } - // Treating symetric elements - if (id1 != id2) + // Writing third derivatives + k = 0; // Keep the line of a 3rd derivative in v3 + for (third_derivatives_type::const_iterator it = third_derivatives.begin(); + it != third_derivatives.end(); it++) + { + int eq = it->first.first; + int var1 = it->first.second.first; + int var2 = it->first.second.second.first; + int var3 = it->first.second.second.second; + NodeID d3 = it->second; + + int id1 = getDynJacobianCol(var1); + int id2 = getDynJacobianCol(var2); + int id3 = getDynJacobianCol(var3); + + // Reference column number for the g3 matrix + int ref_col = id1 * hessianColsNbr + id2 * dynJacobianColsNbr + id3; + + sparseHelper(3, third_derivatives_output, k, 0, output_type); + third_derivatives_output << "=" << eq + 1 << ";" << endl; + + sparseHelper(3, third_derivatives_output, k, 1, output_type); + third_derivatives_output << "=" << ref_col + 1 << ";" << endl; + + sparseHelper(3, third_derivatives_output, k, 2, output_type); + third_derivatives_output << "="; + d3->writeOutput(third_derivatives_output, output_type, temporary_terms); + third_derivatives_output << ";" << endl; + + k++; + + // Compute the column numbers for the 5 other permutations of (id1,id2,id3) and store them in a set (to avoid duplicates if two indexes are equal) + set<int> cols; + 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); + + int k2 = 0; // Keeps the offset of the permutation relative to k + for (set<int>::iterator it2 = cols.begin(); it2 != cols.end(); it2++) + if (*it2 != ref_col) { - sparseHelper(2, hessian_output, k, 0, output_type); - hessian_output << "=" << eq + 1 << ";" << endl; + sparseHelper(3, third_derivatives_output, k+k2, 0, output_type); + third_derivatives_output << "=" << eq + 1 << ";" << endl; - sparseHelper(2, hessian_output, k, 1, output_type); - hessian_output << "=" << col_nb_sym + 1 << ";" << endl; + sparseHelper(3, third_derivatives_output, k+k2, 1, output_type); + third_derivatives_output << "=" << *it2 + 1 << ";" << endl; - sparseHelper(2, hessian_output, k, 2, output_type); - hessian_output << "="; - sparseHelper(2, hessian_output, k-1, 2, output_type); - hessian_output << ";" << endl; + sparseHelper(3, third_derivatives_output, k+k2, 2, output_type); + third_derivatives_output << "="; + sparseHelper(3, third_derivatives_output, k, 2, output_type); + third_derivatives_output << ";" << endl; - k++; + k2++; } - } - - // Writing third derivatives - k = 0; // Keep the line of a 3rd derivative in v3 - for (third_derivatives_type::const_iterator it = third_derivatives.begin(); - it != third_derivatives.end(); it++) - { - int eq = it->first.first; - int var1 = it->first.second.first; - int var2 = it->first.second.second.first; - int var3 = it->first.second.second.second; - NodeID d3 = it->second; - - int id1 = getDynJacobianCol(var1); - int id2 = getDynJacobianCol(var2); - int id3 = getDynJacobianCol(var3); - - // Reference column number for the g3 matrix - int ref_col = id1 * hessianColsNbr + id2 * dynJacobianColsNbr + id3; - - sparseHelper(3, third_derivatives_output, k, 0, output_type); - third_derivatives_output << "=" << eq + 1 << ";" << endl; - - sparseHelper(3, third_derivatives_output, k, 1, output_type); - third_derivatives_output << "=" << ref_col + 1 << ";" << endl; - - sparseHelper(3, third_derivatives_output, k, 2, output_type); - third_derivatives_output << "="; - d3->writeOutput(third_derivatives_output, output_type, temporary_terms); - third_derivatives_output << ";" << endl; - - k++; - - // Compute the column numbers for the 5 other permutations of (id1,id2,id3) and store them in a set (to avoid duplicates if two indexes are equal) - set<int> cols; - 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); - - int k2 = 0; // Keeps the offset of the permutation relative to k - for (set<int>::iterator it2 = cols.begin(); it2 != cols.end(); it2++) - if (*it2 != ref_col) - { - sparseHelper(3, third_derivatives_output, k+k2, 0, output_type); - third_derivatives_output << "=" << eq + 1 << ";" << endl; + k += k2; + } - sparseHelper(3, third_derivatives_output, k+k2, 1, output_type); - third_derivatives_output << "=" << *it2 + 1 << ";" << endl; + if (!use_dll) + { + DynamicOutput << "%" << endl + << "% Model equations" << endl + << "%" << endl + << endl + << "residual = zeros(" << nrows << ", 1);" << endl + << model_output.str() + // Writing initialization instruction for matrix g1 + << "if nargout >= 2," << endl + << " g1 = zeros(" << nrows << ", " << dynJacobianColsNbr << ");" << endl + << endl + << "%" << endl + << "% Jacobian matrix" << endl + << "%" << endl + << endl + << jacobian_output.str() + << "end" << endl; + + // Initialize g2 matrix + DynamicOutput << "if nargout >= 3," << endl + << "%" << endl + << "% Hessian matrix" << endl + << "%" << endl + << endl; + if (second_derivatives.size()) + DynamicOutput << " v2 = zeros(" << NNZDerivatives[1] << ",3);" << endl + << hessian_output.str() + << " g2 = sparse(v2(:,1),v2(:,2),v2(:,3)," << nrows << "," << hessianColsNbr << ");" << endl; + else // Either hessian is all zero, or we didn't compute it + DynamicOutput << " g2 = sparse([],[],[]," << nrows << "," << hessianColsNbr << ");" << endl; + DynamicOutput << "end;" << endl; + + // Initialize g3 matrix + DynamicOutput << "if nargout >= 4," << endl + << "%" << endl + << "% Third order derivatives" << endl + << "%" << endl + << endl; + int ncols = hessianColsNbr * dynJacobianColsNbr; + if (third_derivatives.size()) + DynamicOutput << " v3 = zeros(" << NNZDerivatives[2] << ",3);" << 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 + DynamicOutput << " g3 = sparse([],[],[]," << nrows << "," << ncols << ");" << endl; + + DynamicOutput << "end;" << endl; + } + else + { + DynamicOutput << "void Dynamic(double *y, double *x, int nb_row_x, double *params, int it_, double *residual, double *g1, double *v2, double *v3)" << endl + << "{" << endl + << " double lhs, rhs;" << endl + << endl + << " /* Residual equations */" << endl + << model_output.str() + << " /* Jacobian */" << endl + << " if (g1 == NULL)" << endl + << " return;" << endl + << " else" << endl + << " {" << endl + << jacobian_output.str() + << " }" << endl; + + if (second_derivatives.size()) + DynamicOutput << " /* Hessian for endogenous and exogenous variables */" << endl + << " if (v2 == NULL)" << endl + << " return;" << endl + << " else" << endl + << " {" << endl + << hessian_output.str() + << " }" << endl; - sparseHelper(3, third_derivatives_output, k+k2, 2, output_type); - third_derivatives_output << "="; - sparseHelper(3, third_derivatives_output, k, 2, output_type); - third_derivatives_output << ";" << endl; + if (third_derivatives.size()) + DynamicOutput << " /* Third derivatives for endogenous and exogenous variables */" << endl + << " if (v3 == NULL)" << endl + << " return;" << endl + << " else" << endl + << " {" << endl + << third_derivatives_output.str() + << " }" << endl; - k2++; - } - k += k2; - } - - if (!use_dll) - { - DynamicOutput << "%" << endl - << "% Model equations" << endl - << "%" << endl - << endl - << "residual = zeros(" << nrows << ", 1);" << endl - << model_output.str() - // Writing initialization instruction for matrix g1 - << "if nargout >= 2," << endl - << " g1 = zeros(" << nrows << ", " << dynJacobianColsNbr << ");" << endl - << endl - << "%" << endl - << "% Jacobian matrix" << endl - << "%" << endl - << endl - << jacobian_output.str() - << "end" << endl; - - // Initialize g2 matrix - DynamicOutput << "if nargout >= 3," << endl - << "%" << endl - << "% Hessian matrix" << endl - << "%" << endl - << endl; - if (second_derivatives.size()) - DynamicOutput << " v2 = zeros(" << NNZDerivatives[1] << ",3);" << endl - << hessian_output.str() - << " g2 = sparse(v2(:,1),v2(:,2),v2(:,3)," << nrows << "," << hessianColsNbr << ");" << endl; - else // Either hessian is all zero, or we didn't compute it - DynamicOutput << " g2 = sparse([],[],[]," << nrows << "," << hessianColsNbr << ");" << endl; - DynamicOutput << "end;" << endl; - - // Initialize g3 matrix - DynamicOutput << "if nargout >= 4," << endl - << "%" << endl - << "% Third order derivatives" << endl - << "%" << endl - << endl; - int ncols = hessianColsNbr * dynJacobianColsNbr; - if (third_derivatives.size()) - DynamicOutput << " v3 = zeros(" << NNZDerivatives[2] << ",3);" << 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 - DynamicOutput << " g3 = sparse([],[],[]," << nrows << "," << ncols << ");" << endl; - - DynamicOutput << "end;" << endl; - } - else - { - DynamicOutput << "void Dynamic(double *y, double *x, int nb_row_x, double *params, int it_, double *residual, double *g1, double *v2, double *v3)" << endl - << "{" << endl - << " double lhs, rhs;" << endl - << endl - << " /* Residual equations */" << endl - << model_output.str() - << " /* Jacobian */" << endl - << " if (g1 == NULL)" << endl - << " return;" << endl - << " else" << endl - << " {" << endl - << jacobian_output.str() - << " }" << endl; - - if (second_derivatives.size()) - DynamicOutput << " /* Hessian for endogenous and exogenous variables */" << endl - << " if (v2 == NULL)" << endl - << " return;" << endl - << " else" << endl - << " {" << endl - << hessian_output.str() - << " }" << endl; - - if (third_derivatives.size()) - DynamicOutput << " /* Third derivatives for endogenous and exogenous variables */" << endl - << " if (v3 == NULL)" << endl - << " return;" << endl - << " else" << endl - << " {" << endl - << third_derivatives_output.str() - << " }" << endl; - - DynamicOutput << "}" << endl << endl; - } - } + DynamicOutput << "}" << endl << endl; + } +} void DynamicModel::writeOutput(ostream &output, const string &basename, bool block_decomposition, bool byte_code, bool use_dll) const - { - /* Writing initialisation for M_.lead_lag_incidence matrix - M_.lead_lag_incidence is a matrix with as many columns as there are - endogenous variables and as many rows as there are periods in the - models (nbr of rows = M_.max_lag+M_.max_lead+1) - - The matrix elements are equal to zero if a variable isn't present in the - model at a given period. - */ - - output << "M_.lead_lag_incidence = ["; - // Loop on endogenous variables - for (int endoID = 0; endoID < symbol_table.endo_nbr(); endoID++) - { - output << endl; - // Loop on periods - for (int lag = -max_endo_lag; lag <= max_endo_lead; lag++) - { - // Print variableID if exists with current period, otherwise print 0 - try - { - int varID = getDerivID(symbol_table.getID(eEndogenous, endoID), lag); - output << " " << getDynJacobianCol(varID) + 1; - } - catch (UnknownDerivIDException &e) - { - output << " 0"; - } - } - output << ";"; - } - output << "]';" << endl; - - // Write equation tags - output << "M_.equations_tags = {" << endl; - for (unsigned int i = 0; i < equation_tags.size(); i++) - output << " " << equation_tags[i].first + 1 << " , '" - << equation_tags[i].second.first << "' , '" - << equation_tags[i].second.second << "' ;" << endl; - output << "};" << endl; - - //In case of sparse model, writes the block_decomposition structure of the model - if (block_decomposition) - { - int count_lead_lag_incidence = 0; - int max_lead, max_lag, max_lag_endo, max_lead_endo, max_lag_exo, max_lead_exo; - unsigned int nb_blocks = getNbBlocks(); - for (unsigned int block = 0; block < nb_blocks; block++) - { - //For a block composed of a single equation determines wether we have to evaluate or to solve the equation - count_lead_lag_incidence = 0; - BlockSimulationType simulation_type = getBlockSimulationType(block); - int block_size = getBlockSize(block); - max_lag = max_leadlag_block[block].first; - max_lead = max_leadlag_block[block].second; - max_lag_endo = endo_max_leadlag_block[block].first; - max_lead_endo= endo_max_leadlag_block[block].second; - max_lag_exo = max(exo_max_leadlag_block[block].first, exo_det_max_leadlag_block[block].first); - max_lead_exo= max(exo_max_leadlag_block[block].second, exo_det_max_leadlag_block[block].second); - vector<int> exogenous(symbol_table.exo_nbr(), -1); - vector<int>::iterator it_exogenous; - exogenous.clear(); - ostringstream tmp_s, tmp_s_eq; - tmp_s.str(""); - tmp_s_eq.str(""); - for (int i=0;i<block_size;i++) +{ + /* Writing initialisation for M_.lead_lag_incidence matrix + M_.lead_lag_incidence is a matrix with as many columns as there are + endogenous variables and as many rows as there are periods in the + models (nbr of rows = M_.max_lag+M_.max_lead+1) + + The matrix elements are equal to zero if a variable isn't present in the + model at a given period. + */ + + output << "M_.lead_lag_incidence = ["; + // Loop on endogenous variables + for (int endoID = 0; endoID < symbol_table.endo_nbr(); endoID++) + { + output << endl; + // Loop on periods + for (int lag = -max_endo_lag; lag <= max_endo_lead; lag++) + { + // Print variableID if exists with current period, otherwise print 0 + try + { + int varID = getDerivID(symbol_table.getID(eEndogenous, endoID), lag); + output << " " << getDynJacobianCol(varID) + 1; + } + catch (UnknownDerivIDException &e) + { + output << " 0"; + } + } + output << ";"; + } + output << "]';" << endl; + + // Write equation tags + output << "M_.equations_tags = {" << endl; + for (unsigned int i = 0; i < equation_tags.size(); i++) + output << " " << equation_tags[i].first + 1 << " , '" + << equation_tags[i].second.first << "' , '" + << equation_tags[i].second.second << "' ;" << endl; + output << "};" << endl; + + //In case of sparse model, writes the block_decomposition structure of the model + if (block_decomposition) + { + int count_lead_lag_incidence = 0; + int max_lead, max_lag, max_lag_endo, max_lead_endo, max_lag_exo, max_lead_exo; + unsigned int nb_blocks = getNbBlocks(); + for (unsigned int block = 0; block < nb_blocks; block++) + { + //For a block composed of a single equation determines wether we have to evaluate or to solve the equation + count_lead_lag_incidence = 0; + BlockSimulationType simulation_type = getBlockSimulationType(block); + int block_size = getBlockSize(block); + max_lag = max_leadlag_block[block].first; + max_lead = max_leadlag_block[block].second; + max_lag_endo = endo_max_leadlag_block[block].first; + max_lead_endo = endo_max_leadlag_block[block].second; + max_lag_exo = max(exo_max_leadlag_block[block].first, exo_det_max_leadlag_block[block].first); + max_lead_exo = max(exo_max_leadlag_block[block].second, exo_det_max_leadlag_block[block].second); + vector<int> exogenous(symbol_table.exo_nbr(), -1); + vector<int>::iterator it_exogenous; + exogenous.clear(); + ostringstream tmp_s, tmp_s_eq; + tmp_s.str(""); + tmp_s_eq.str(""); + for (int i = 0; i < block_size; i++) + { + tmp_s << " " << getBlockVariableID(block, i)+1; + tmp_s_eq << " " << getBlockEquationID(block, i)+1; + } + it_exogenous = exogenous.begin(); + for (t_lag_var::const_iterator it = exo_block[block].begin(); it != exo_block[block].end(); it++) + it_exogenous = set_union(it->second.begin(), it->second.end(), exogenous.begin(), exogenous.end(), it_exogenous); + output << "M_.block_structure.block(" << block+1 << ").num = " << block+1 << ";\n"; + output << "M_.block_structure.block(" << block+1 << ").Simulation_Type = " << simulation_type << ";\n"; + output << "M_.block_structure.block(" << block+1 << ").maximum_lag = " << max_lag << ";\n"; + output << "M_.block_structure.block(" << block+1 << ").maximum_lead = " << max_lead << ";\n"; + output << "M_.block_structure.block(" << block+1 << ").maximum_endo_lag = " << max_lag_endo << ";\n"; + output << "M_.block_structure.block(" << block+1 << ").maximum_endo_lead = " << max_lead_endo << ";\n"; + output << "M_.block_structure.block(" << block+1 << ").maximum_exo_lag = " << max_lag_exo << ";\n"; + output << "M_.block_structure.block(" << block+1 << ").maximum_exo_lead = " << max_lead_exo << ";\n"; + output << "M_.block_structure.block(" << block+1 << ").endo_nbr = " << block_size << ";\n"; + output << "M_.block_structure.block(" << block+1 << ").equation = [" << tmp_s_eq.str() << "];\n"; + output << "M_.block_structure.block(" << block+1 << ").variable = [" << tmp_s.str() << "];\n"; + output << "M_.block_structure.block(" << block+1 << ").exogenous = ["; + int i = 0; + for (it_exogenous = exogenous.begin(); it_exogenous != exogenous.end(); it_exogenous++) + if (*it_exogenous >= 0) { - tmp_s << " " << getBlockVariableID(block, i)+1; - tmp_s_eq << " " << getBlockEquationID(block, i)+1; + output << " " << *it_exogenous+1; + i++; } - it_exogenous = exogenous.begin(); - for(t_lag_var::const_iterator it = exo_block[block].begin(); it != exo_block[block].end(); it++) - it_exogenous = set_union(it->second.begin(), it->second.end(), exogenous.begin(), exogenous.end(), it_exogenous); - output << "M_.block_structure.block(" << block+1 << ").num = " << block+1 << ";\n"; - output << "M_.block_structure.block(" << block+1 << ").Simulation_Type = " << simulation_type << ";\n"; - output << "M_.block_structure.block(" << block+1 << ").maximum_lag = " << max_lag << ";\n"; - output << "M_.block_structure.block(" << block+1 << ").maximum_lead = " << max_lead << ";\n"; - output << "M_.block_structure.block(" << block+1 << ").maximum_endo_lag = " << max_lag_endo << ";\n"; - output << "M_.block_structure.block(" << block+1 << ").maximum_endo_lead = " << max_lead_endo << ";\n"; - output << "M_.block_structure.block(" << block+1 << ").maximum_exo_lag = " << max_lag_exo << ";\n"; - output << "M_.block_structure.block(" << block+1 << ").maximum_exo_lead = " << max_lead_exo << ";\n"; - output << "M_.block_structure.block(" << block+1 << ").endo_nbr = " << block_size << ";\n"; - output << "M_.block_structure.block(" << block+1 << ").equation = [" << tmp_s_eq.str() << "];\n"; - output << "M_.block_structure.block(" << block+1 << ").variable = [" << tmp_s.str() << "];\n"; - output << "M_.block_structure.block(" << block+1 << ").exogenous = ["; - int i=0; - for (it_exogenous=exogenous.begin();it_exogenous!=exogenous.end();it_exogenous++) - if (*it_exogenous>=0) + output << "];\n"; + output << "M_.block_structure.block(" << block+1 << ").exo_nbr = " << i << ";\n"; + + output << "M_.block_structure.block(" << block+1 << ").exo_det_nbr = " << exo_det_block.size() << ";\n"; + + tmp_s.str(""); + count_lead_lag_incidence = 0; + dynamic_jacob_map reordered_dynamic_jacobian; + for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != blocks_derivatives[block].end(); it++) + reordered_dynamic_jacobian[make_pair(it->second.first, make_pair(it->first.second, it->first.first))] = it->second.second; + output << "M_.block_structure.block(" << block+1 << ").lead_lag_incidence = [];\n"; + int last_var = -1; + for (int lag = -max_lag_endo; lag < max_lead_endo+1; lag++) + { + last_var = 0; + for (dynamic_jacob_map::const_iterator it = reordered_dynamic_jacobian.begin(); it != reordered_dynamic_jacobian.end(); it++) { - output << " " << *it_exogenous+1; - i++; + if (lag == it->first.first && last_var != it->first.second.first) + { + count_lead_lag_incidence++; + for (int i = last_var; i < it->first.second.first-1; i++) + tmp_s << " 0"; + if (tmp_s.str().length()) + tmp_s << " "; + tmp_s << count_lead_lag_incidence; + last_var = it->first.second.first; + } } - output << "];\n"; - output << "M_.block_structure.block(" << block+1 << ").exo_nbr = " << i << ";\n"; - - output << "M_.block_structure.block(" << block+1 << ").exo_det_nbr = " << exo_det_block.size() << ";\n"; - - tmp_s.str(""); - count_lead_lag_incidence = 0; - dynamic_jacob_map reordered_dynamic_jacobian; - for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != blocks_derivatives[block].end(); it++) - reordered_dynamic_jacobian[make_pair(it->second.first, make_pair(it->first.second, it->first.first))] = it->second.second; - output << "M_.block_structure.block(" << block+1 << ").lead_lag_incidence = [];\n"; - int last_var = -1; - for (int lag=-max_lag_endo;lag<max_lead_endo+1;lag++) - { - last_var = 0; - for (dynamic_jacob_map::const_iterator it = reordered_dynamic_jacobian.begin(); it != reordered_dynamic_jacobian.end(); it++) - { - if (lag == it->first.first && last_var != it->first.second.first) - { - count_lead_lag_incidence++; - for( int i = last_var; i < it->first.second.first-1; i++) - tmp_s << " 0"; - if (tmp_s.str().length()) - tmp_s << " "; - tmp_s << count_lead_lag_incidence; - last_var = it->first.second.first; - } - } - for( int i = last_var + 1; i < block_size; i++) - tmp_s << " 0"; - output << "M_.block_structure.block(" << block+1 << ").lead_lag_incidence = [ M_.block_structure.block(" << block+1 << ").lead_lag_incidence; " << tmp_s.str() << "]; %lag = " << lag << "\n"; - tmp_s.str(""); - } - } - string cst_s; - int nb_endo = symbol_table.endo_nbr(); - output << "M_.block_structure.variable_reordered = ["; - for(int i=0; i<nb_endo; i++) - output << " " << variable_reordered[i]+1; - output << "];\n"; - output << "M_.block_structure.equation_reordered = ["; - for(int i=0; i<nb_endo; i++) - output << " " << equation_reordered[i]+1; - output << "];\n"; - map<pair< int, pair<int, int> >, int> lag_row_incidence; - for (first_derivatives_type::const_iterator it = first_derivatives.begin(); - it != first_derivatives.end(); it++) - { - int deriv_id = it->first.second; - if (getTypeByDerivID(deriv_id) == eEndogenous) - { - int eq = it->first.first; - int symb = getSymbIDByDerivID(deriv_id); - int var = symbol_table.getTypeSpecificID(symb); - int lag = getLagByDerivID(deriv_id); - int eqr = inv_equation_reordered[eq]; - int varr = inv_variable_reordered[var]; - lag_row_incidence[make_pair(lag, make_pair(eqr, varr))] = 1; - } - } - int prev_lag=-1000000; - for(map<pair< int, pair<int, int> >, int> ::const_iterator it=lag_row_incidence.begin(); it != lag_row_incidence.end(); it++) - { - if(prev_lag != it->first.first) - { - if(prev_lag != -1000000) - output << "];\n"; - prev_lag = it->first.first; - output << "M_.block_structure.incidence(" << max_endo_lag+it->first.first+1 << ").lead_lag = " << prev_lag << ";\n"; - output << "M_.block_structure.incidence(" << max_endo_lag+it->first.first+1 << ").sparse_IM = ["; - } - output << it->first.second.first << " " << it->first.second.second << ";\n"; - } - output << "];\n"; - } - // Writing initialization for some other variables - output << "M_.exo_names_orig_ord = [1:" << symbol_table.exo_nbr() << "];" << endl - << "M_.maximum_lag = " << max_lag << ";" << endl - << "M_.maximum_lead = " << max_lead << ";" << endl; - if (symbol_table.endo_nbr()) - { - output << "M_.maximum_endo_lag = " << max_endo_lag << ";" << endl - << "M_.maximum_endo_lead = " << max_endo_lead << ";" << endl - << "oo_.steady_state = zeros(" << symbol_table.endo_nbr() << ", 1);" << endl; - } - if (symbol_table.exo_nbr()) - { - output << "M_.maximum_exo_lag = " << max_exo_lag << ";" << endl - << "M_.maximum_exo_lead = " << max_exo_lead << ";" << endl - << "oo_.exo_steady_state = zeros(" << symbol_table.exo_nbr() << ", 1);" << endl; - } - if (symbol_table.exo_det_nbr()) - { - output << "M_.maximum_exo_det_lag = " << max_exo_det_lag << ";" << endl - << "M_.maximum_exo_det_lead = " << max_exo_det_lead << ";" << endl - << "oo_.exo_det_steady_state = zeros(" << symbol_table.exo_det_nbr() << ", 1);" << endl; - } - if (symbol_table.param_nbr()) - output << "M_.params = repmat(NaN," << symbol_table.param_nbr() << ", 1);" << endl; - - // Write number of non-zero derivatives - output << "M_.NNZDerivatives = zeros(3, 1);" << endl - << "M_.NNZDerivatives(1) = " << NNZDerivatives[0] << ";" << endl - << "M_.NNZDerivatives(2) = " << NNZDerivatives[1] << ";" << endl - << "M_.NNZDerivatives(3) = " << NNZDerivatives[2] << ";" << endl; - } - + for (int i = last_var + 1; i < block_size; i++) + tmp_s << " 0"; + output << "M_.block_structure.block(" << block+1 << ").lead_lag_incidence = [ M_.block_structure.block(" << block+1 << ").lead_lag_incidence; " << tmp_s.str() << "]; %lag = " << lag << "\n"; + tmp_s.str(""); + } + } + string cst_s; + int nb_endo = symbol_table.endo_nbr(); + output << "M_.block_structure.variable_reordered = ["; + for (int i = 0; i < nb_endo; i++) + output << " " << variable_reordered[i]+1; + output << "];\n"; + output << "M_.block_structure.equation_reordered = ["; + for (int i = 0; i < nb_endo; i++) + output << " " << equation_reordered[i]+1; + output << "];\n"; + map<pair< int, pair<int, int> >, int> lag_row_incidence; + for (first_derivatives_type::const_iterator it = first_derivatives.begin(); + it != first_derivatives.end(); it++) + { + int deriv_id = it->first.second; + if (getTypeByDerivID(deriv_id) == eEndogenous) + { + int eq = it->first.first; + int symb = getSymbIDByDerivID(deriv_id); + int var = symbol_table.getTypeSpecificID(symb); + int lag = getLagByDerivID(deriv_id); + int eqr = inv_equation_reordered[eq]; + int varr = inv_variable_reordered[var]; + lag_row_incidence[make_pair(lag, make_pair(eqr, varr))] = 1; + } + } + int prev_lag = -1000000; + for (map<pair< int, pair<int, int> >, int>::const_iterator it = lag_row_incidence.begin(); it != lag_row_incidence.end(); it++) + { + if (prev_lag != it->first.first) + { + if (prev_lag != -1000000) + output << "];\n"; + prev_lag = it->first.first; + output << "M_.block_structure.incidence(" << max_endo_lag+it->first.first+1 << ").lead_lag = " << prev_lag << ";\n"; + output << "M_.block_structure.incidence(" << max_endo_lag+it->first.first+1 << ").sparse_IM = ["; + } + output << it->first.second.first << " " << it->first.second.second << ";\n"; + } + output << "];\n"; + } + // Writing initialization for some other variables + output << "M_.exo_names_orig_ord = [1:" << symbol_table.exo_nbr() << "];" << endl + << "M_.maximum_lag = " << max_lag << ";" << endl + << "M_.maximum_lead = " << max_lead << ";" << endl; + if (symbol_table.endo_nbr()) + { + output << "M_.maximum_endo_lag = " << max_endo_lag << ";" << endl + << "M_.maximum_endo_lead = " << max_endo_lead << ";" << endl + << "oo_.steady_state = zeros(" << symbol_table.endo_nbr() << ", 1);" << endl; + } + if (symbol_table.exo_nbr()) + { + output << "M_.maximum_exo_lag = " << max_exo_lag << ";" << endl + << "M_.maximum_exo_lead = " << max_exo_lead << ";" << endl + << "oo_.exo_steady_state = zeros(" << symbol_table.exo_nbr() << ", 1);" << endl; + } + if (symbol_table.exo_det_nbr()) + { + output << "M_.maximum_exo_det_lag = " << max_exo_det_lag << ";" << endl + << "M_.maximum_exo_det_lead = " << max_exo_det_lead << ";" << endl + << "oo_.exo_det_steady_state = zeros(" << symbol_table.exo_det_nbr() << ", 1);" << endl; + } + if (symbol_table.param_nbr()) + output << "M_.params = repmat(NaN," << symbol_table.param_nbr() << ", 1);" << endl; + + // Write number of non-zero derivatives + output << "M_.NNZDerivatives = zeros(3, 1);" << endl + << "M_.NNZDerivatives(1) = " << NNZDerivatives[0] << ";" << endl + << "M_.NNZDerivatives(2) = " << NNZDerivatives[1] << ";" << endl + << "M_.NNZDerivatives(3) = " << NNZDerivatives[2] << ";" << endl; +} map<pair<int, pair<int, int > >, NodeID> DynamicModel::collect_first_order_derivatives_endogenous() @@ -1931,19 +1927,17 @@ DynamicModel::collect_first_order_derivatives_endogenous() for (first_derivatives_type::iterator it2 = first_derivatives.begin(); it2 != first_derivatives.end(); it2++) { - if (getTypeByDerivID(it2->first.second)==eEndogenous) + if (getTypeByDerivID(it2->first.second) == eEndogenous) { int eq = it2->first.first; - int var=symbol_table.getTypeSpecificID(getSymbIDByDerivID(it2->first.second)); - int lag=getLagByDerivID(it2->first.second); + int var = symbol_table.getTypeSpecificID(getSymbIDByDerivID(it2->first.second)); + int lag = getLagByDerivID(it2->first.second); endo_derivatives[make_pair(eq, make_pair(var, lag))] = it2->second; } } - return endo_derivatives; + return endo_derivatives; } - - void DynamicModel::computingPass(bool jacobianExo, bool hessian, bool thirdDerivatives, bool paramsDerivatives, const eval_context_type &eval_context, bool no_tmp_terms, bool block, bool use_dll) @@ -1968,7 +1962,7 @@ DynamicModel::computingPass(bool jacobianExo, bool hessian, bool thirdDerivative // Launch computations cout << "Computing dynamic model derivatives:" << endl - << " - order 1" << endl; + << " - order 1" << endl; computeJacobian(vars); if (hessian) @@ -2043,41 +2037,41 @@ DynamicModel::get_Derivatives(int block) int max_lead = getBlockMaxLead(block); int block_size = getBlockSize(block); int block_nb_recursive = block_size - getBlockMfs(block); - for(int lag = -max_lag; lag <= max_lead; lag++) + for (int lag = -max_lag; lag <= max_lead; lag++) { - for(int eq = 0; eq < block_size; eq++) + for (int eq = 0; eq < block_size; eq++) { int eqr = getBlockEquationID(block, eq); - for(int var = 0; var < block_size; var++) + for (int var = 0; var < block_size; var++) { int varr = getBlockVariableID(block, var); - if(dynamic_jacobian.find(make_pair(lag, make_pair(eqr, varr))) != dynamic_jacobian.end()) + if (dynamic_jacobian.find(make_pair(lag, make_pair(eqr, varr))) != dynamic_jacobian.end()) { bool OK = true; map<pair<pair<int, pair<int, int> >, pair<int, int> >, int>::const_iterator its = Derivatives.find(make_pair(make_pair(lag, make_pair(eq, var)), make_pair(eqr, varr))); - if(its!=Derivatives.end()) + if (its != Derivatives.end()) { - if(its->second == 2) - OK=false; + if (its->second == 2) + OK = false; } - if(OK) + if (OK) { - if (getBlockEquationType(block, eq) == E_EVALUATE_S and eq<block_nb_recursive) + if (getBlockEquationType(block, eq) == E_EVALUATE_S and eq < block_nb_recursive) //It's a normalized equation, we have to recompute the derivative using chain rule derivative function Derivatives[make_pair(make_pair(lag, make_pair(eq, var)), make_pair(eqr, varr))] = 1; else //It's a feedback equation we can use the derivatives Derivatives[make_pair(make_pair(lag, make_pair(eq, var)), make_pair(eqr, varr))] = 0; } - if(var<block_nb_recursive) + if (var < block_nb_recursive) { int eqs = getBlockEquationID(block, var); - for(int vars=block_nb_recursive; vars<block_size; vars++) + for (int vars = block_nb_recursive; vars < block_size; vars++) { int varrs = getBlockVariableID(block, vars); //A new derivative needs to be computed using the chain rule derivative function (a feedback variable appears in a recursive equation) - if(Derivatives.find(make_pair(make_pair(lag, make_pair(var, vars)), make_pair(eqs, varrs)))!=Derivatives.end()) + if (Derivatives.find(make_pair(make_pair(lag, make_pair(var, vars)), make_pair(eqs, varrs))) != Derivatives.end()) Derivatives[make_pair(make_pair(lag, make_pair(eq, vars)), make_pair(eqr, varrs))] = 2; } } @@ -2085,7 +2079,7 @@ DynamicModel::get_Derivatives(int block) } } } - return(Derivatives); + return (Derivatives); } void @@ -2094,7 +2088,7 @@ DynamicModel::computeChainRuleJacobian(t_blocks_derivatives &blocks_derivatives) map<int, NodeID> recursive_variables; unsigned int nb_blocks = getNbBlocks(); blocks_derivatives = t_blocks_derivatives(nb_blocks); - for(unsigned int block = 0; block < nb_blocks; block++) + for (unsigned int block = 0; block < nb_blocks; block++) { t_block_derivatives_equation_variable_laglead_nodeid tmp_derivatives; recursive_variables.clear(); @@ -2102,10 +2096,10 @@ DynamicModel::computeChainRuleJacobian(t_blocks_derivatives &blocks_derivatives) int block_size = getBlockSize(block); int block_nb_mfs = getBlockMfs(block); int block_nb_recursives = block_size - block_nb_mfs; - if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE or simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE) + if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE or simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) { blocks_derivatives.push_back(t_block_derivatives_equation_variable_laglead_nodeid(0)); - for(int i = 0; i < block_nb_recursives; i++) + for (int i = 0; i < block_nb_recursives; i++) { if (getBlockEquationType(block, i) == E_EVALUATE_S) recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block, i)), 0)] = getBlockEquationRenormalizedNodeID(block, i); @@ -2114,7 +2108,7 @@ DynamicModel::computeChainRuleJacobian(t_blocks_derivatives &blocks_derivatives) } map<pair<pair<int, pair<int, int> >, pair<int, int> >, int> Derivatives = get_Derivatives(block); map<pair<pair<int, pair<int, int> >, pair<int, int> >, int>::const_iterator it = Derivatives.begin(); - for(int i=0; i<(int)Derivatives.size(); i++) + for (int i = 0; i < (int) Derivatives.size(); i++) { int Deriv_type = it->second; pair<pair<int, pair<int, int> >, pair<int, int> > it_l(it->first); @@ -2124,35 +2118,35 @@ DynamicModel::computeChainRuleJacobian(t_blocks_derivatives &blocks_derivatives) int var = it_l.first.second.second; int eqr = it_l.second.first; int varr = it_l.second.second; - if(Deriv_type == 0) + if (Deriv_type == 0) first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))] = first_derivatives[make_pair(eqr, getDerivID(symbol_table.getID(eEndogenous, varr), lag))]; else if (Deriv_type == 1) first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))] = (equation_type_and_normalized_equation[eqr].second)->getChainRuleDerivative(getDerivID(symbol_table.getID(eEndogenous, varr), lag), recursive_variables); else if (Deriv_type == 2) { - if(getBlockEquationType(block, eq) == E_EVALUATE_S && eq<block_nb_recursives) + if (getBlockEquationType(block, eq) == E_EVALUATE_S && eq < block_nb_recursives) first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))] = (equation_type_and_normalized_equation[eqr].second)->getChainRuleDerivative(getDerivID(symbol_table.getID(eEndogenous, varr), lag), recursive_variables); else first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))] = equations[eqr]->getChainRuleDerivative(getDerivID(symbol_table.getID(eEndogenous, varr), lag), recursive_variables); } - tmp_derivatives.push_back(make_pair(make_pair(eq, var), make_pair(lag, first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))]) )); + tmp_derivatives.push_back(make_pair(make_pair(eq, var), make_pair(lag, first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))]))); } } - else if( simulation_type==SOLVE_BACKWARD_SIMPLE or simulation_type==SOLVE_FORWARD_SIMPLE - or simulation_type==SOLVE_BACKWARD_COMPLETE or simulation_type==SOLVE_FORWARD_COMPLETE) + else if (simulation_type == SOLVE_BACKWARD_SIMPLE or simulation_type == SOLVE_FORWARD_SIMPLE + or simulation_type == SOLVE_BACKWARD_COMPLETE or simulation_type == SOLVE_FORWARD_COMPLETE) { blocks_derivatives.push_back(t_block_derivatives_equation_variable_laglead_nodeid(0)); - for(int i = 0; i < block_nb_recursives; i++) + for (int i = 0; i < block_nb_recursives; i++) { if (getBlockEquationType(block, i) == E_EVALUATE_S) - recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block,i)), 0)] = getBlockEquationRenormalizedNodeID(block, i); + recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block, i)), 0)] = getBlockEquationRenormalizedNodeID(block, i); else - recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block,i)), 0)] = getBlockEquationNodeID(block, i); + recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block, i)), 0)] = getBlockEquationNodeID(block, i); } - for(int eq = block_nb_recursives; eq < block_size; eq++) + for (int eq = block_nb_recursives; eq < block_size; eq++) { int eqr = getBlockEquationID(block, eq); - for(int var = block_nb_recursives; var < block_size; var++) + for (int var = block_nb_recursives; var < block_size; var++) { int varr = getBlockVariableID(block, var); NodeID d1 = equations[eqr]->getChainRuleDerivative(getDerivID(symbol_table.getID(eEndogenous, varr), 0), recursive_variables); @@ -2160,7 +2154,7 @@ DynamicModel::computeChainRuleJacobian(t_blocks_derivatives &blocks_derivatives) continue; first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, 0))] = d1; tmp_derivatives.push_back( - make_pair(make_pair(eq, var),make_pair(0, first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, 0))]))); + make_pair(make_pair(eq, var), make_pair(0, first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, 0))]))); } } } @@ -2176,10 +2170,10 @@ DynamicModel::collect_block_first_order_derivatives() unsigned int nb_blocks = getNbBlocks(); equation_2_block = vector<int>(equation_reordered.size()); variable_2_block = vector<int>(variable_reordered.size()); - for(unsigned int block = 0; block < nb_blocks; block++) + for (unsigned int block = 0; block < nb_blocks; block++) { unsigned int block_size = getBlockSize(block); - for(unsigned int i = 0; i < block_size; i++) + for (unsigned int i = 0; i < block_size; i++) { equation_2_block[getBlockEquationID(block, i)] = block; variable_2_block[getBlockVariableID(block, i)] = block; @@ -2192,11 +2186,11 @@ DynamicModel::collect_block_first_order_derivatives() derivative_other_endo = vector<t_derivative>(nb_blocks); derivative_exo = vector<t_derivative>(nb_blocks); derivative_exo_det = vector<t_derivative>(nb_blocks); - endo_max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair( 0, 0)); - other_endo_max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair( 0, 0)); - exo_max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair( 0, 0)); - exo_det_max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair( 0, 0)); - max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair( 0, 0)); + endo_max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair(0, 0)); + other_endo_max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair(0, 0)); + exo_max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair(0, 0)); + exo_det_max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair(0, 0)); + max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair(0, 0)); for (first_derivatives_type::iterator it2 = first_derivatives.begin(); it2 != first_derivatives.end(); it2++) { @@ -2205,71 +2199,71 @@ DynamicModel::collect_block_first_order_derivatives() int lag = getLagByDerivID(it2->first.second); int block_eq = equation_2_block[eq]; int block_var = variable_2_block[var]; - t_derivative tmp_derivative ; + t_derivative tmp_derivative; t_lag_var lag_var; - switch(getTypeByDerivID(it2->first.second)) + switch (getTypeByDerivID(it2->first.second)) { - case eEndogenous: - if(block_eq == block_var) - { - if(lag<0 && lag<-endo_max_leadlag_block[block_eq].first) - endo_max_leadlag_block[block_eq] = make_pair(-lag, endo_max_leadlag_block[block_eq].second); - if(lag>0 && lag>endo_max_leadlag_block[block_eq].second) - endo_max_leadlag_block[block_eq] = make_pair(endo_max_leadlag_block[block_eq].first, lag); - tmp_derivative = derivative_endo[block_eq]; - tmp_derivative[make_pair(lag, make_pair(eq, var))] = first_derivatives[make_pair(eq, getDerivID(symbol_table.getID(eEndogenous, var), lag))]; - derivative_endo[block_eq] = tmp_derivative; - } - else - { - if(lag<0 && lag<-other_endo_max_leadlag_block[block_eq].first) - other_endo_max_leadlag_block[block_eq] = make_pair(-lag, other_endo_max_leadlag_block[block_eq].second); - if(lag>0 && lag>other_endo_max_leadlag_block[block_eq].second) - other_endo_max_leadlag_block[block_eq] = make_pair(other_endo_max_leadlag_block[block_eq].first, lag); - tmp_derivative = derivative_other_endo[block_eq]; - tmp_derivative[make_pair(lag, make_pair(eq, var))] = first_derivatives[make_pair(eq, getDerivID(symbol_table.getID(eEndogenous, var), lag))]; - derivative_other_endo[block_eq] = tmp_derivative; - lag_var = other_endo_block[block_eq]; - if(lag_var.find(lag) == lag_var.end()) - lag_var[lag].clear(); - lag_var[lag].insert(var); - other_endo_block[block_eq] = lag_var; - } - break; - case eExogenous: - if(lag<0 && lag<-exo_max_leadlag_block[block_eq].first) - exo_max_leadlag_block[block_eq] = make_pair(-lag, exo_max_leadlag_block[block_eq].second); - if(lag>0 && lag>exo_max_leadlag_block[block_eq].second) - exo_max_leadlag_block[block_eq] = make_pair(exo_max_leadlag_block[block_eq].first, lag); - tmp_derivative = derivative_exo[block_eq]; - tmp_derivative[make_pair(lag, make_pair(eq, var))] = first_derivatives[make_pair(eq, getDerivID(symbol_table.getID(eExogenous, var), lag))]; - derivative_exo[block_eq] = tmp_derivative ; - lag_var = exo_block[block_eq]; - if(lag_var.find(lag) == lag_var.end()) - lag_var[lag].clear(); - lag_var[lag].insert(var); - exo_block[block_eq] = lag_var; - break; - case eExogenousDet: - if(lag<0 && lag<-exo_det_max_leadlag_block[block_eq].first) - exo_det_max_leadlag_block[block_eq] = make_pair(-lag, exo_det_max_leadlag_block[block_eq].second); - if(lag>0 && lag>exo_det_max_leadlag_block[block_eq].second) - exo_det_max_leadlag_block[block_eq] = make_pair(exo_det_max_leadlag_block[block_eq].first, lag); - tmp_derivative = derivative_exo_det[block_eq]; - tmp_derivative[make_pair(lag, make_pair(eq, var))] = first_derivatives[make_pair(eq, getDerivID(symbol_table.getID(eExogenous, var), lag))]; - derivative_exo_det[block_eq] = tmp_derivative ; - lag_var = exo_det_block[block_eq]; - if(lag_var.find(lag) == lag_var.end()) - lag_var[lag].clear(); - lag_var[lag].insert(var); - exo_det_block[block_eq] = lag_var; - break; - default: - break; + case eEndogenous: + if (block_eq == block_var) + { + if (lag < 0 && lag < -endo_max_leadlag_block[block_eq].first) + endo_max_leadlag_block[block_eq] = make_pair(-lag, endo_max_leadlag_block[block_eq].second); + if (lag > 0 && lag > endo_max_leadlag_block[block_eq].second) + endo_max_leadlag_block[block_eq] = make_pair(endo_max_leadlag_block[block_eq].first, lag); + tmp_derivative = derivative_endo[block_eq]; + tmp_derivative[make_pair(lag, make_pair(eq, var))] = first_derivatives[make_pair(eq, getDerivID(symbol_table.getID(eEndogenous, var), lag))]; + derivative_endo[block_eq] = tmp_derivative; + } + else + { + if (lag < 0 && lag < -other_endo_max_leadlag_block[block_eq].first) + other_endo_max_leadlag_block[block_eq] = make_pair(-lag, other_endo_max_leadlag_block[block_eq].second); + if (lag > 0 && lag > other_endo_max_leadlag_block[block_eq].second) + other_endo_max_leadlag_block[block_eq] = make_pair(other_endo_max_leadlag_block[block_eq].first, lag); + tmp_derivative = derivative_other_endo[block_eq]; + tmp_derivative[make_pair(lag, make_pair(eq, var))] = first_derivatives[make_pair(eq, getDerivID(symbol_table.getID(eEndogenous, var), lag))]; + derivative_other_endo[block_eq] = tmp_derivative; + lag_var = other_endo_block[block_eq]; + if (lag_var.find(lag) == lag_var.end()) + lag_var[lag].clear(); + lag_var[lag].insert(var); + other_endo_block[block_eq] = lag_var; + } + break; + case eExogenous: + if (lag < 0 && lag < -exo_max_leadlag_block[block_eq].first) + exo_max_leadlag_block[block_eq] = make_pair(-lag, exo_max_leadlag_block[block_eq].second); + if (lag > 0 && lag > exo_max_leadlag_block[block_eq].second) + exo_max_leadlag_block[block_eq] = make_pair(exo_max_leadlag_block[block_eq].first, lag); + tmp_derivative = derivative_exo[block_eq]; + tmp_derivative[make_pair(lag, make_pair(eq, var))] = first_derivatives[make_pair(eq, getDerivID(symbol_table.getID(eExogenous, var), lag))]; + derivative_exo[block_eq] = tmp_derivative; + lag_var = exo_block[block_eq]; + if (lag_var.find(lag) == lag_var.end()) + lag_var[lag].clear(); + lag_var[lag].insert(var); + exo_block[block_eq] = lag_var; + break; + case eExogenousDet: + if (lag < 0 && lag < -exo_det_max_leadlag_block[block_eq].first) + exo_det_max_leadlag_block[block_eq] = make_pair(-lag, exo_det_max_leadlag_block[block_eq].second); + if (lag > 0 && lag > exo_det_max_leadlag_block[block_eq].second) + exo_det_max_leadlag_block[block_eq] = make_pair(exo_det_max_leadlag_block[block_eq].first, lag); + tmp_derivative = derivative_exo_det[block_eq]; + tmp_derivative[make_pair(lag, make_pair(eq, var))] = first_derivatives[make_pair(eq, getDerivID(symbol_table.getID(eExogenous, var), lag))]; + derivative_exo_det[block_eq] = tmp_derivative; + lag_var = exo_det_block[block_eq]; + if (lag_var.find(lag) == lag_var.end()) + lag_var[lag].clear(); + lag_var[lag].insert(var); + exo_det_block[block_eq] = lag_var; + break; + default: + break; } - if (lag<0 && lag<-max_leadlag_block[block_eq].first) + if (lag < 0 && lag < -max_leadlag_block[block_eq].first) max_leadlag_block[block_eq] = make_pair(-lag, max_leadlag_block[block_eq].second); - if (lag>0 && lag>max_leadlag_block[block_eq].second) + if (lag > 0 && lag > max_leadlag_block[block_eq].second) max_leadlag_block[block_eq] = make_pair(max_leadlag_block[block_eq].first, lag); } @@ -2277,68 +2271,68 @@ DynamicModel::collect_block_first_order_derivatives() void DynamicModel::writeDynamicFile(const string &basename, bool block, bool bytecode, bool use_dll) const - { - int r; - if(block && bytecode) - writeModelEquationsCodeOrdered(basename + "_dynamic", basename, map_idx); - else if(block && !bytecode) - { +{ + int r; + if (block && bytecode) + writeModelEquationsCodeOrdered(basename + "_dynamic", basename, map_idx); + else if (block && !bytecode) + { #ifdef _WIN32 - r = mkdir(basename.c_str()); + r = mkdir(basename.c_str()); #else - r = mkdir(basename.c_str(), 0777); + r = mkdir(basename.c_str(), 0777); #endif - if (r < 0 && errno != EEXIST) - { - perror("ERROR"); - exit(EXIT_FAILURE); - } - writeSparseDynamicMFile(basename + "_dynamic", basename); - } - else if (use_dll) - writeDynamicCFile(basename + "_dynamic"); - else - writeDynamicMFile(basename + "_dynamic"); - } + if (r < 0 && errno != EEXIST) + { + perror("ERROR"); + exit(EXIT_FAILURE); + } + writeSparseDynamicMFile(basename + "_dynamic", basename); + } + else if (use_dll) + writeDynamicCFile(basename + "_dynamic"); + else + writeDynamicMFile(basename + "_dynamic"); +} void DynamicModel::toStatic(StaticModel &static_model) const - { - // Convert model local variables (need to be done first) - for (map<int, NodeID>::const_iterator it = local_variables_table.begin(); - it != local_variables_table.end(); it++) - static_model.AddLocalVariable(symbol_table.getName(it->first), it->second->toStatic(static_model)); - - // Convert equations - for (vector<BinaryOpNode *>::const_iterator it = equations.begin(); - it != equations.end(); it++) - static_model.addEquation((*it)->toStatic(static_model)); - - // Convert auxiliary equations - for (deque<BinaryOpNode *>::const_iterator it = aux_equations.begin(); - it != aux_equations.end(); it++) - static_model.addAuxEquation((*it)->toStatic(static_model)); - } +{ + // Convert model local variables (need to be done first) + for (map<int, NodeID>::const_iterator it = local_variables_table.begin(); + it != local_variables_table.end(); it++) + static_model.AddLocalVariable(symbol_table.getName(it->first), it->second->toStatic(static_model)); + + // Convert equations + for (vector<BinaryOpNode *>::const_iterator it = equations.begin(); + it != equations.end(); it++) + static_model.addEquation((*it)->toStatic(static_model)); + + // Convert auxiliary equations + for (deque<BinaryOpNode *>::const_iterator it = aux_equations.begin(); + it != aux_equations.end(); it++) + static_model.addAuxEquation((*it)->toStatic(static_model)); +} void DynamicModel::computeDerivIDs() { set<pair<int, int> > dynvars; - for(int i = 0; i < (int) equations.size(); i++) + for (int i = 0; i < (int) equations.size(); i++) equations[i]->collectVariables(eEndogenous, dynvars); dynJacobianColsNbr = dynvars.size(); - for(int i = 0; i < (int) equations.size(); i++) + for (int i = 0; i < (int) equations.size(); i++) { equations[i]->collectVariables(eExogenous, dynvars); equations[i]->collectVariables(eExogenousDet, dynvars); equations[i]->collectVariables(eParameter, dynvars); } - for(set<pair<int, int> >::const_iterator it = dynvars.begin(); - it != dynvars.end(); it++) + for (set<pair<int, int> >::const_iterator it = dynvars.begin(); + it != dynvars.end(); it++) { int lag = it->second; SymbolType type = symbol_table.getType(it->first); @@ -2477,7 +2471,6 @@ DynamicModel::getDynJacobianCol(int deriv_id) const throw (UnknownDerivIDExcepti return it->second; } - void DynamicModel::computeParamsDerivatives() { @@ -2529,75 +2522,72 @@ DynamicModel::computeParamsDerivativesTemporaryTerms() void DynamicModel::writeParamsDerivativesFile(const string &basename) const - { - if (!residuals_params_derivatives.size() - && !jacobian_params_derivatives.size()) - return; - - string filename = basename + "_params_derivs.m"; - - ofstream paramsDerivsFile; - paramsDerivsFile.open(filename.c_str(), ios::out | ios::binary); - if (!paramsDerivsFile.is_open()) - { - cerr << "ERROR: Can't open file " << filename << " for writing" << endl; - exit(EXIT_FAILURE); - } - paramsDerivsFile << "function [rp, gp] = " << basename << "_params_derivs(y, x, params, it_)" << endl - << "%" << endl - << "% Warning : this file is generated automatically by Dynare" << endl - << "% from model file (.mod)" << endl << endl; - +{ + if (!residuals_params_derivatives.size() + && !jacobian_params_derivatives.size()) + return; - writeTemporaryTerms(params_derivs_temporary_terms, paramsDerivsFile, oMatlabDynamicModel); + string filename = basename + "_params_derivs.m"; - // Write parameter derivative - paramsDerivsFile << "rp = zeros(" << equation_number() << ", " - << symbol_table.param_nbr() << ");" << endl; + ofstream paramsDerivsFile; + paramsDerivsFile.open(filename.c_str(), ios::out | ios::binary); + if (!paramsDerivsFile.is_open()) + { + cerr << "ERROR: Can't open file " << filename << " for writing" << endl; + exit(EXIT_FAILURE); + } + paramsDerivsFile << "function [rp, gp] = " << basename << "_params_derivs(y, x, params, it_)" << endl + << "%" << endl + << "% Warning : this file is generated automatically by Dynare" << endl + << "% from model file (.mod)" << endl << endl; - for (first_derivatives_type::const_iterator it = residuals_params_derivatives.begin(); - it != residuals_params_derivatives.end(); it++) - { - int eq = it->first.first; - int param = it->first.second; - NodeID d1 = it->second; + writeTemporaryTerms(params_derivs_temporary_terms, paramsDerivsFile, oMatlabDynamicModel); - int param_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param)) + 1; + // Write parameter derivative + paramsDerivsFile << "rp = zeros(" << equation_number() << ", " + << symbol_table.param_nbr() << ");" << endl; - paramsDerivsFile << "rp(" << eq+1 << ", " << param_col << ") = "; - d1->writeOutput(paramsDerivsFile, oMatlabDynamicModel, params_derivs_temporary_terms); - paramsDerivsFile << ";" << endl; - } + for (first_derivatives_type::const_iterator it = residuals_params_derivatives.begin(); + it != residuals_params_derivatives.end(); it++) + { + int eq = it->first.first; + int param = it->first.second; + NodeID d1 = it->second; - // Write jacobian derivatives - paramsDerivsFile << "gp = zeros(" << equation_number() << ", " << dynJacobianColsNbr << ", " - << symbol_table.param_nbr() << ");" << endl; + int param_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param)) + 1; - for (second_derivatives_type::const_iterator it = jacobian_params_derivatives.begin(); - it != jacobian_params_derivatives.end(); it++) - { - int eq = it->first.first; - int var = it->first.second.first; - int param = it->first.second.second; - NodeID d2 = it->second; + paramsDerivsFile << "rp(" << eq+1 << ", " << param_col << ") = "; + d1->writeOutput(paramsDerivsFile, oMatlabDynamicModel, params_derivs_temporary_terms); + paramsDerivsFile << ";" << endl; + } - int var_col = getDynJacobianCol(var) + 1; - int param_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param)) + 1; + // Write jacobian derivatives + paramsDerivsFile << "gp = zeros(" << equation_number() << ", " << dynJacobianColsNbr << ", " + << symbol_table.param_nbr() << ");" << endl; - paramsDerivsFile << "gp(" << eq+1 << ", " << var_col << ", " << param_col << ") = "; - d2->writeOutput(paramsDerivsFile, oMatlabDynamicModel, params_derivs_temporary_terms); - paramsDerivsFile << ";" << endl; - } + for (second_derivatives_type::const_iterator it = jacobian_params_derivatives.begin(); + it != jacobian_params_derivatives.end(); it++) + { + int eq = it->first.first; + int var = it->first.second.first; + int param = it->first.second.second; + NodeID d2 = it->second; - paramsDerivsFile.close(); - } + int var_col = getDynJacobianCol(var) + 1; + int param_col = symbol_table.getTypeSpecificID(getSymbIDByDerivID(param)) + 1; + paramsDerivsFile << "gp(" << eq+1 << ", " << var_col << ", " << param_col << ") = "; + d2->writeOutput(paramsDerivsFile, oMatlabDynamicModel, params_derivs_temporary_terms); + paramsDerivsFile << ";" << endl; + } + paramsDerivsFile.close(); +} void DynamicModel::writeChainRuleDerivative(ostream &output, int eqr, int varr, int lag, - ExprNodeOutputType output_type, - const temporary_terms_type &temporary_terms) const + ExprNodeOutputType output_type, + const temporary_terms_type &temporary_terms) const { map<pair<int, pair<int, int> >, NodeID>::const_iterator it = first_chain_rule_derivatives.find(make_pair(eqr, make_pair(varr, lag))); if (it != first_chain_rule_derivatives.end()) @@ -2606,12 +2596,11 @@ DynamicModel::writeChainRuleDerivative(ostream &output, int eqr, int varr, int l output << 0; } - void DynamicModel::writeLatexFile(const string &basename) const - { - writeLatexModelFile(basename + "_dynamic.tex", oLatexDynamicModel); - } +{ + writeLatexModelFile(basename + "_dynamic.tex", oLatexDynamicModel); +} void DynamicModel::jacobianHelper(ostream &output, int eq_nb, int col_nb, ExprNodeOutputType output_type) const @@ -2620,7 +2609,7 @@ DynamicModel::jacobianHelper(ostream &output, int eq_nb, int col_nb, ExprNodeOut if (IS_MATLAB(output_type)) output << eq_nb + 1 << "," << col_nb + 1; else - output << eq_nb + col_nb * equations.size(); + output << eq_nb + col_nb *equations.size(); output << RIGHT_ARRAY_SUBSCRIPT(output_type); } @@ -2666,11 +2655,11 @@ DynamicModel::substituteLeadLagInternal(aux_var_t type) vector<BinaryOpNode *> neweqs; // Substitute in model local variables - for(map<int, NodeID>::iterator it = local_variables_table.begin(); - it != local_variables_table.end(); it++) + for (map<int, NodeID>::iterator it = local_variables_table.begin(); + it != local_variables_table.end(); it++) { NodeID subst; - switch(type) + switch (type) { case avEndoLead: subst = it->second->substituteEndoLeadGreaterThanTwo(subst_table, neweqs); @@ -2692,10 +2681,10 @@ DynamicModel::substituteLeadLagInternal(aux_var_t type) } // Substitute in equations - for(int i = 0; i < (int) equations.size(); i++) + for (int i = 0; i < (int) equations.size(); i++) { NodeID subst; - switch(type) + switch (type) { case avEndoLead: subst = equations[i]->substituteEndoLeadGreaterThanTwo(subst_table, neweqs); @@ -2719,7 +2708,7 @@ DynamicModel::substituteLeadLagInternal(aux_var_t type) } // Add new equations - for(int i = 0; i < (int) neweqs.size(); i++) + for (int i = 0; i < (int) neweqs.size(); i++) addEquation(neweqs[i]); // Add the new set of equations at the *beginning* of aux_equations @@ -2728,7 +2717,7 @@ DynamicModel::substituteLeadLagInternal(aux_var_t type) if (neweqs.size() > 0) { cout << "Substitution of "; - switch(type) + switch (type) { case avEndoLead: cout << "endo leads >= 2"; @@ -2757,12 +2746,12 @@ DynamicModel::substituteExpectation(bool partial_information_model) vector<BinaryOpNode *> neweqs; // Substitute in model local variables - for(map<int, NodeID>::iterator it = local_variables_table.begin(); - it != local_variables_table.end(); it++) + for (map<int, NodeID>::iterator it = local_variables_table.begin(); + it != local_variables_table.end(); it++) it->second = it->second->substituteExpectation(subst_table, neweqs, partial_information_model); // Substitute in equations - for(int i = 0; i < (int) equations.size(); i++) + for (int i = 0; i < (int) equations.size(); i++) { BinaryOpNode *substeq = dynamic_cast<BinaryOpNode *>(equations[i]->substituteExpectation(subst_table, neweqs, partial_information_model)); assert(substeq != NULL); @@ -2770,7 +2759,7 @@ DynamicModel::substituteExpectation(bool partial_information_model) } // Add new equations - for(int i = 0; i < (int) neweqs.size(); i++) + for (int i = 0; i < (int) neweqs.size(); i++) addEquation(neweqs[i]); // Add the new set of equations at the *beginning* of aux_equations @@ -2788,7 +2777,7 @@ DynamicModel::substituteExpectation(bool partial_information_model) void DynamicModel::transformPredeterminedVariables() { - for(int i = 0; i < (int) equations.size(); i++) + for (int i = 0; i < (int) equations.size(); i++) { BinaryOpNode *substeq = dynamic_cast<BinaryOpNode *>(equations[i]->decreaseLeadsLagsPredeterminedVariables()); assert(substeq != NULL); @@ -2800,8 +2789,8 @@ void DynamicModel::fillEvalContext(eval_context_type &eval_context) const { // First, auxiliary variables - for(deque<BinaryOpNode *>::const_iterator it = aux_equations.begin(); - it != aux_equations.end(); it++) + for (deque<BinaryOpNode *>::const_iterator it = aux_equations.begin(); + it != aux_equations.end(); it++) { assert((*it)->get_op_code() == oEqual); VariableNode *auxvar = dynamic_cast<VariableNode *>((*it)->get_arg1()); @@ -2811,15 +2800,15 @@ DynamicModel::fillEvalContext(eval_context_type &eval_context) const double val = (*it)->get_arg2()->eval(eval_context); eval_context[auxvar->get_symb_id()] = val; } - catch(ExprNode::EvalException &e) + catch (ExprNode::EvalException &e) { // Do nothing } } // Second, model local variables - for(map<int, NodeID>::const_iterator it = local_variables_table.begin(); - it != local_variables_table.end(); it++) + for (map<int, NodeID>::const_iterator it = local_variables_table.begin(); + it != local_variables_table.end(); it++) { try { @@ -2827,7 +2816,7 @@ DynamicModel::fillEvalContext(eval_context_type &eval_context) const double val = expression->eval(eval_context); eval_context[it->first] = val; } - catch(ExprNode::EvalException &e) + catch (ExprNode::EvalException &e) { // Do nothing } diff --git a/DynamicModel.hh b/DynamicModel.hh index be88b45ce477e426dde4c9d287d98f93d7d203eb..32da867a9360619270734040baa585b99fabc32a 100644 --- a/DynamicModel.hh +++ b/DynamicModel.hh @@ -143,7 +143,7 @@ private: //! Helper for writing the sparse Hessian or third derivatives in MATLAB and C /*! If order=2, writes either v2(i+1,j+1) or v2[i+j*NNZDerivatives[1]] - If order=3, writes either v3(i+1,j+1) or v3[i+j*NNZDerivatives[2]] */ + If order=3, writes either v3(i+1,j+1) or v3[i+j*NNZDerivatives[2]] */ void sparseHelper(int order, ostream &output, int row_nb, int col_nb, ExprNodeOutputType output_type) const; //! Write chain rule derivative of a recursive equation w.r. to a variable @@ -152,12 +152,10 @@ private: //! Collecte the derivatives w.r. to endogenous of the block, to endogenous of previouys blocks and to exogenous void collect_block_first_order_derivatives(); - //! Factorized code for substitutions of leads/lags /*! \param[in] type determines which type of variables is concerned */ void substituteLeadLagInternal(aux_var_t type); - private: //! Indicate if the temporary terms are computed for the overall model (true) or not (false). Default value true bool global_temporary_terms; @@ -202,10 +200,10 @@ public: double cutoff; //! Compute the minimum feedback set in the dynamic model: /*! 0 : all endogenous variables are considered as feedback variables - 1 : the variables belonging to non normalized equation are considered as feedback variables - 2 : the variables belonging to a non linear equation are considered as feedback variables - 3 : the variables belonging to a non normalizable non linear equation are considered as feedback variables - default value = 0 */ + 1 : the variables belonging to non normalized equation are considered as feedback variables + 2 : the variables belonging to a non linear equation are considered as feedback variables + 3 : the variables belonging to a non normalizable non linear equation are considered as feedback variables + default value = 0 */ int mfs; //! the file containing the model and the derivatives code ofstream code_file; @@ -241,7 +239,11 @@ public: virtual int getDynJacobianCol(int deriv_id) const throw (UnknownDerivIDException); //! Returns true indicating that this is a dynamic model - virtual bool isDynamic() const { return true; }; + virtual bool + isDynamic() const + { + return true; + }; //! Transforms the model by removing all leads greater or equal than 2 on endos /*! Note that this can create new lags on endos and exos */ @@ -266,38 +268,96 @@ public: //! Fills eval context with values of model local variables and auxiliary variables void fillEvalContext(eval_context_type &eval_context) const; - //! Return the number of blocks - virtual unsigned int getNbBlocks() const {return(block_type_firstequation_size_mfs.size());}; + virtual unsigned int + getNbBlocks() const + { + return (block_type_firstequation_size_mfs.size()); + }; //! Determine the simulation type of each block - virtual BlockSimulationType getBlockSimulationType(int block_number) const {return(block_type_firstequation_size_mfs[block_number].first.first);}; + virtual BlockSimulationType + getBlockSimulationType(int block_number) const + { + return (block_type_firstequation_size_mfs[block_number].first.first); + }; //! Return the first equation number of a block - virtual unsigned int getBlockFirstEquation(int block_number) const {return(block_type_firstequation_size_mfs[block_number].first.second);}; + virtual unsigned int + getBlockFirstEquation(int block_number) const + { + return (block_type_firstequation_size_mfs[block_number].first.second); + }; //! Return the size of the block block_number - virtual unsigned int getBlockSize(int block_number) const {return(block_type_firstequation_size_mfs[block_number].second.first);}; + virtual unsigned int + getBlockSize(int block_number) const + { + return (block_type_firstequation_size_mfs[block_number].second.first); + }; //! Return the number of feedback variable of the block block_number - virtual unsigned int getBlockMfs(int block_number) const {return(block_type_firstequation_size_mfs[block_number].second.second);}; + virtual unsigned int + getBlockMfs(int block_number) const + { + return (block_type_firstequation_size_mfs[block_number].second.second); + }; //! Return the maximum lag in a block - virtual unsigned int getBlockMaxLag(int block_number) const {return(block_lag_lead[block_number].first);}; + virtual unsigned int + getBlockMaxLag(int block_number) const + { + return (block_lag_lead[block_number].first); + }; //! Return the maximum lead in a block - virtual unsigned int getBlockMaxLead(int block_number) const {return(block_lag_lead[block_number].second);}; + virtual unsigned int + getBlockMaxLead(int block_number) const + { + return (block_lag_lead[block_number].second); + }; //! Return the type of equation (equation_number) belonging to the block block_number - virtual EquationType getBlockEquationType(int block_number, int equation_number) const {return( equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].first);}; + virtual EquationType + getBlockEquationType(int block_number, int equation_number) const + { + return (equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].first); + }; //! Return true if the equation has been normalized - virtual bool isBlockEquationRenormalized(int block_number, int equation_number) const {return( equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].first == E_EVALUATE_S);}; + virtual bool + isBlockEquationRenormalized(int block_number, int equation_number) const + { + return (equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].first == E_EVALUATE_S); + }; //! Return the NodeID of the equation equation_number belonging to the block block_number - virtual NodeID getBlockEquationNodeID(int block_number, int equation_number) const {return( equations[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]]);}; + virtual NodeID + getBlockEquationNodeID(int block_number, int equation_number) const + { + return (equations[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]]); + }; //! Return the NodeID of the renormalized equation equation_number belonging to the block block_number - virtual NodeID getBlockEquationRenormalizedNodeID(int block_number, int equation_number) const {return( equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].second);}; + virtual NodeID + getBlockEquationRenormalizedNodeID(int block_number, int equation_number) const + { + return (equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].second); + }; //! Return the original number of equation equation_number belonging to the block block_number - virtual int getBlockEquationID(int block_number, int equation_number) const {return( equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]);}; + virtual int + getBlockEquationID(int block_number, int equation_number) const + { + return (equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]); + }; //! Return the original number of variable variable_number belonging to the block block_number - virtual int getBlockVariableID(int block_number, int variable_number) const {return( variable_reordered[block_type_firstequation_size_mfs[block_number].first.second+variable_number]);}; + virtual int + getBlockVariableID(int block_number, int variable_number) const + { + return (variable_reordered[block_type_firstequation_size_mfs[block_number].first.second+variable_number]); + }; //! Return the position of equation_number in the block number belonging to the block block_number - virtual int getBlockInitialEquationID(int block_number, int equation_number) const {return((int)inv_equation_reordered[equation_number] - (int)block_type_firstequation_size_mfs[block_number].first.second);}; + virtual int + getBlockInitialEquationID(int block_number, int equation_number) const + { + return ((int) inv_equation_reordered[equation_number] - (int) block_type_firstequation_size_mfs[block_number].first.second); + }; //! Return the position of variable_number in the block number belonging to the block block_number - virtual int getBlockInitialVariableID(int block_number, int variable_number) const {return((int)inv_variable_reordered[variable_number] - (int)block_type_firstequation_size_mfs[block_number].first.second);}; - + virtual int + getBlockInitialVariableID(int block_number, int variable_number) const + { + return ((int) inv_variable_reordered[variable_number] - (int) block_type_firstequation_size_mfs[block_number].first.second); + }; }; diff --git a/DynareMain.cc b/DynareMain.cc index 646a290c09fc6bf29c5be6841708396585c7ba92..8969aaadf0768b7b331d84471f3b4fd6eabe80f4 100644 --- a/DynareMain.cc +++ b/DynareMain.cc @@ -26,7 +26,7 @@ using namespace std; #include <cstdlib> #include <cstring> #ifndef PACKAGE_VERSION - #define PACKAGE_VERSION 4. +# define PACKAGE_VERSION 4. #endif #include "macro/MacroDriver.hh" @@ -36,9 +36,9 @@ using namespace std; */ void main2(stringstream &in, string &basename, bool debug, bool clear_all, bool no_tmp_terms, bool warn_uninit #if defined(_WIN32) || defined(__CYGWIN32__) - , bool cygwin, bool msvc + , bool cygwin, bool msvc #endif - ); + ); void usage() @@ -52,7 +52,7 @@ usage() } int -main(int argc, char** argv) +main(int argc, char **argv) { if (argc < 2) { @@ -150,7 +150,7 @@ main(int argc, char** argv) #if defined(_WIN32) || defined(__CYGWIN32__) , cygwin, msvc #endif - ); + ); return EXIT_SUCCESS; } diff --git a/DynareMain2.cc b/DynareMain2.cc index fed8ed98d1307c32ee64f2e6fead14dc6d24454b..1090685139ea76676d36850a49397f452531776c 100644 --- a/DynareMain2.cc +++ b/DynareMain2.cc @@ -51,9 +51,9 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool no_tm // Write outputs mod_file->writeOutputFiles(basename, clear_all #if defined(_WIN32) || defined(__CYGWIN32__) - , cygwin, msvc + , cygwin, msvc #endif - ); + ); delete mod_file; diff --git a/ExprNode.cc b/ExprNode.cc index 820dc9de1d009b4c50787c34d70e26e8712312bb..d9183d7119c77dd44e918ceadc36415b7528ad91 100644 --- a/ExprNode.cc +++ b/ExprNode.cc @@ -72,25 +72,25 @@ ExprNode::getDerivative(int deriv_id) int ExprNode::precedence(ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const - { - // For a constant, a variable, or a unary op, the precedence is maximal - return 100; - } +{ + // For a constant, a variable, or a unary op, the precedence is maximal + return 100; +} int ExprNode::cost(const temporary_terms_type &temporary_terms, bool is_matlab) const - { - // For a terminal node, the cost is null - return 0; - } +{ + // For a terminal node, the cost is null + return 0; +} void ExprNode::collectEndogenous(set<pair<int, int> > &result) const { set<pair<int, int> > symb_ids; collectVariables(eEndogenous, symb_ids); - for(set<pair<int, int> >::const_iterator it = symb_ids.begin(); - it != symb_ids.end(); it++) + for (set<pair<int, int> >::const_iterator it = symb_ids.begin(); + it != symb_ids.end(); it++) result.insert(make_pair(datatree.symbol_table.getTypeSpecificID(it->first), it->second)); } @@ -99,8 +99,8 @@ ExprNode::collectExogenous(set<pair<int, int> > &result) const { set<pair<int, int> > symb_ids; collectVariables(eExogenous, symb_ids); - for(set<pair<int, int> >::const_iterator it = symb_ids.begin(); - it != symb_ids.end(); it++) + for (set<pair<int, int> >::const_iterator it = symb_ids.begin(); + it != symb_ids.end(); it++) result.insert(make_pair(datatree.symbol_table.getTypeSpecificID(it->first), it->second)); } @@ -117,9 +117,9 @@ void ExprNode::computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms, bool is_matlab) const - { - // Nothing to do for a terminal node - } +{ + // Nothing to do for a terminal node +} void ExprNode::computeTemporaryTerms(map<NodeID, int> &reference_count, @@ -128,17 +128,15 @@ ExprNode::computeTemporaryTerms(map<NodeID, int> &reference_count, int Curr_block, vector<vector<temporary_terms_type> > &v_temporary_terms, int equation) const - { - // Nothing to do for a terminal node - } - +{ + // Nothing to do for a terminal node +} pair<int, NodeID > ExprNode::normalizeEquation(int var_endo, vector<pair<int, pair<NodeID, NodeID> > > &List_of_Op_RHS) const - { - return(make_pair(0, (NodeID)NULL)); - } - +{ + return (make_pair(0, (NodeID) NULL)); +} void ExprNode::writeOutput(ostream &output) @@ -161,7 +159,7 @@ ExprNode::createEndoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector // Each iteration tries to create an auxvar such that auxvar(+1)=expr(-lag) // At the beginning (resp. end) of each iteration, substexpr is an expression (possibly an auxvar) equivalent to expr(-lag-1) (resp. expr(-lag)) - while(lag >= 0) + while (lag >= 0) { NodeID orig_expr = decreaseLeadsLags(lag); it = subst_table.find(orig_expr); @@ -197,7 +195,7 @@ ExprNode::createExoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector< // Each iteration tries to create an auxvar such that auxvar(+1)=expr(-lag) // At the beginning (resp. end) of each iteration, substexpr is an expression (possibly an auxvar) equivalent to expr(-lag-1) (resp. expr(-lag)) - while(lag >= 0) + while (lag >= 0) { NodeID orig_expr = decreaseLeadsLags(lag); it = subst_table.find(orig_expr); @@ -219,8 +217,8 @@ ExprNode::createExoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector< } NumConstNode::NumConstNode(DataTree &datatree_arg, int id_arg) : - ExprNode(datatree_arg), - id(id_arg) + ExprNode(datatree_arg), + id(id_arg) { // Add myself to the num const map datatree.num_const_node_map[id] = this; @@ -241,38 +239,38 @@ NumConstNode::computeDerivative(int deriv_id) void NumConstNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, temporary_terms_inuse_type &temporary_terms_inuse, int Curr_Block) const - { - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<NumConstNode *>(this)); - if (it != temporary_terms.end()) - temporary_terms_inuse.insert(idx); - } +{ + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<NumConstNode *>(this)); + if (it != temporary_terms.end()) + temporary_terms_inuse.insert(idx); +} void NumConstNode::writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const - { - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<NumConstNode *>(this)); - if (it != temporary_terms.end()) - if (output_type == oMatlabDynamicModelSparse) - output << "T" << idx << "(it_)"; - else - output << "T" << idx; +{ + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<NumConstNode *>(this)); + if (it != temporary_terms.end()) + if (output_type == oMatlabDynamicModelSparse) + output << "T" << idx << "(it_)"; else - output << datatree.num_constants.get(id); - } + output << "T" << idx; + else + output << datatree.num_constants.get(id); +} double NumConstNode::eval(const eval_context_type &eval_context) const throw (EvalException) { - return(datatree.num_constants.getDouble(id)); + return (datatree.num_constants.getDouble(id)); } void NumConstNode::compile(ostream &CompileCode, bool lhs_rhs, const temporary_terms_type &temporary_terms, map_idx_type &map_idx, bool dynamic, bool steady_dynamic) const - { - FLDC_ fldc(datatree.num_constants.getDouble(id)); - fldc.write(CompileCode); - } +{ + FLDC_ fldc(datatree.num_constants.getDouble(id)); + fldc.write(CompileCode); +} void NumConstNode::collectVariables(SymbolType type_arg, set<pair<int, int> > &result) const @@ -281,9 +279,9 @@ NumConstNode::collectVariables(SymbolType type_arg, set<pair<int, int> > &result pair<int, NodeID > NumConstNode::normalizeEquation(int var_endo, vector<pair<int, pair<NodeID, NodeID> > > &List_of_Op_RHS) const - { - return(make_pair(0, datatree.AddNumConstant(datatree.num_constants.get(id)))); - } +{ + return (make_pair(0, datatree.AddNumConstant(datatree.num_constants.get(id)))); +} NodeID NumConstNode::getChainRuleDerivative(int deriv_id, const map<int, NodeID> &recursive_variables) @@ -293,9 +291,9 @@ NumConstNode::getChainRuleDerivative(int deriv_id, const map<int, NodeID> &recur NodeID NumConstNode::toStatic(DataTree &static_datatree) const - { - return static_datatree.AddNumConstant(datatree.num_constants.get(id)); - } +{ + return static_datatree.AddNumConstant(datatree.num_constants.get(id)); +} int NumConstNode::maxEndoLead() const @@ -352,10 +350,10 @@ NumConstNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOpN } VariableNode::VariableNode(DataTree &datatree_arg, int symb_id_arg, int lag_arg) : - ExprNode(datatree_arg), - symb_id(symb_id_arg), - type(datatree.symbol_table.getType(symb_id_arg)), - lag(lag_arg) + ExprNode(datatree_arg), + symb_id(symb_id_arg), + type(datatree.symbol_table.getType(symb_id_arg)), + lag(lag_arg) { // Add myself to the variable map datatree.variable_node_map[make_pair(symb_id, lag)] = this; @@ -425,189 +423,189 @@ VariableNode::computeDerivative(int deriv_id) void VariableNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, temporary_terms_inuse_type &temporary_terms_inuse, int Curr_Block) const - { - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<VariableNode *>(this)); - if (it != temporary_terms.end()) - temporary_terms_inuse.insert(idx); - if (type== eModelLocalVariable) - datatree.local_variables_table[symb_id]->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); - } +{ + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<VariableNode *>(this)); + if (it != temporary_terms.end()) + temporary_terms_inuse.insert(idx); + if (type == eModelLocalVariable) + datatree.local_variables_table[symb_id]->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); +} void VariableNode::writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const - { - // If node is a temporary term - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<VariableNode *>(this)); - if (it != temporary_terms.end()) - { - if (output_type == oMatlabDynamicModelSparse) - output << "T" << idx << "(it_)"; - else - output << "T" << idx; - return; - } +{ + // If node is a temporary term + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<VariableNode *>(this)); + if (it != temporary_terms.end()) + { + if (output_type == oMatlabDynamicModelSparse) + output << "T" << idx << "(it_)"; + else + output << "T" << idx; + return; + } - if (IS_LATEX(output_type)) - { - if (output_type == oLatexDynamicSteadyStateOperator) - output << "\\bar{"; - output << datatree.symbol_table.getTeXName(symb_id); - if (output_type == oLatexDynamicModel - && (type == eEndogenous || type == eExogenous || type == eExogenousDet || type == eModelLocalVariable)) - { - output << "_{t"; - if (lag != 0) - { - if (lag > 0) - output << "+"; - output << lag; - } - output << "}"; - } - else if (output_type == oLatexDynamicSteadyStateOperator) + if (IS_LATEX(output_type)) + { + if (output_type == oLatexDynamicSteadyStateOperator) + output << "\\bar{"; + output << datatree.symbol_table.getTeXName(symb_id); + if (output_type == oLatexDynamicModel + && (type == eEndogenous || type == eExogenous || type == eExogenousDet || type == eModelLocalVariable)) + { + output << "_{t"; + if (lag != 0) + { + if (lag > 0) + output << "+"; + output << lag; + } output << "}"; - return; - } + } + else if (output_type == oLatexDynamicSteadyStateOperator) + output << "}"; + return; + } - int i; - int tsid = datatree.symbol_table.getTypeSpecificID(symb_id); - switch (type) - { - case eParameter: - if (output_type == oMatlabOutsideModel) - output << "M_.params" << "(" << tsid + 1 << ")"; - else - output << "params" << LEFT_ARRAY_SUBSCRIPT(output_type) << tsid + ARRAY_SUBSCRIPT_OFFSET(output_type) << RIGHT_ARRAY_SUBSCRIPT(output_type); - break; + int i; + int tsid = datatree.symbol_table.getTypeSpecificID(symb_id); + switch (type) + { + case eParameter: + if (output_type == oMatlabOutsideModel) + output << "M_.params" << "(" << tsid + 1 << ")"; + else + output << "params" << LEFT_ARRAY_SUBSCRIPT(output_type) << tsid + ARRAY_SUBSCRIPT_OFFSET(output_type) << RIGHT_ARRAY_SUBSCRIPT(output_type); + break; - case eModelLocalVariable: - case eModFileLocalVariable: - if (output_type==oMatlabDynamicModelSparse || output_type==oMatlabStaticModelSparse || output_type == oMatlabDynamicModelSparseLocalTemporaryTerms) - { - output << "("; - datatree.local_variables_table[symb_id]->writeOutput(output, output_type,temporary_terms); - output << ")"; - } - else - output << datatree.symbol_table.getName(symb_id); - break; + case eModelLocalVariable: + case eModFileLocalVariable: + if (output_type == oMatlabDynamicModelSparse || output_type == oMatlabStaticModelSparse || output_type == oMatlabDynamicModelSparseLocalTemporaryTerms) + { + output << "("; + datatree.local_variables_table[symb_id]->writeOutput(output, output_type, temporary_terms); + output << ")"; + } + else + output << datatree.symbol_table.getName(symb_id); + break; - case eEndogenous: - switch (output_type) - { - case oMatlabDynamicModel: - case oCDynamicModel: - i = datatree.getDynJacobianCol(datatree.getDerivID(symb_id, lag)) + ARRAY_SUBSCRIPT_OFFSET(output_type); - output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << i << RIGHT_ARRAY_SUBSCRIPT(output_type); - break; - case oMatlabStaticModel: - case oMatlabStaticModelSparse: - i = tsid + ARRAY_SUBSCRIPT_OFFSET(output_type); - output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << i << RIGHT_ARRAY_SUBSCRIPT(output_type); - break; - case oMatlabDynamicModelSparse: - case oMatlabDynamicModelSparseLocalTemporaryTerms: - i = tsid + ARRAY_SUBSCRIPT_OFFSET(output_type); - if (lag > 0) - output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << "it_+" << lag << ", " << i << RIGHT_ARRAY_SUBSCRIPT(output_type); - else if (lag < 0) - output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << "it_" << lag << ", " << i << RIGHT_ARRAY_SUBSCRIPT(output_type); - else - output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << "it_, " << i << RIGHT_ARRAY_SUBSCRIPT(output_type); - break; - case oMatlabOutsideModel: - output << "oo_.steady_state(" << tsid + 1 << ")"; - break; - case oMatlabDynamicSteadyStateOperator: - output << "oo_.steady_state(" << tsid + 1 << ")"; - break; - default: - assert(false); - } - break; + case eEndogenous: + switch (output_type) + { + case oMatlabDynamicModel: + case oCDynamicModel: + i = datatree.getDynJacobianCol(datatree.getDerivID(symb_id, lag)) + ARRAY_SUBSCRIPT_OFFSET(output_type); + output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << i << RIGHT_ARRAY_SUBSCRIPT(output_type); + break; + case oMatlabStaticModel: + case oMatlabStaticModelSparse: + i = tsid + ARRAY_SUBSCRIPT_OFFSET(output_type); + output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << i << RIGHT_ARRAY_SUBSCRIPT(output_type); + break; + case oMatlabDynamicModelSparse: + case oMatlabDynamicModelSparseLocalTemporaryTerms: + i = tsid + ARRAY_SUBSCRIPT_OFFSET(output_type); + if (lag > 0) + output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << "it_+" << lag << ", " << i << RIGHT_ARRAY_SUBSCRIPT(output_type); + else if (lag < 0) + output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << "it_" << lag << ", " << i << RIGHT_ARRAY_SUBSCRIPT(output_type); + else + output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << "it_, " << i << RIGHT_ARRAY_SUBSCRIPT(output_type); + break; + case oMatlabOutsideModel: + output << "oo_.steady_state(" << tsid + 1 << ")"; + break; + case oMatlabDynamicSteadyStateOperator: + output << "oo_.steady_state(" << tsid + 1 << ")"; + break; + default: + assert(false); + } + break; - case eExogenous: - i = tsid + ARRAY_SUBSCRIPT_OFFSET(output_type); - switch (output_type) - { - case oMatlabDynamicModel: - case oMatlabDynamicModelSparse: - case oMatlabDynamicModelSparseLocalTemporaryTerms: - if (lag > 0) - output << "x(it_+" << lag << ", " << i << ")"; - else if (lag < 0) - output << "x(it_" << lag << ", " << i << ")"; - else - output << "x(it_, " << i << ")"; - break; - case oCDynamicModel: - if (lag == 0) - output << "x[it_+" << i << "*nb_row_x]"; - else if (lag > 0) - output << "x[it_+" << lag << "+" << i << "*nb_row_x]"; - else - output << "x[it_" << lag << "+" << i << "*nb_row_x]"; - break; - case oMatlabStaticModel: - case oMatlabStaticModelSparse: - output << "x" << LEFT_ARRAY_SUBSCRIPT(output_type) << i << RIGHT_ARRAY_SUBSCRIPT(output_type); - break; - case oMatlabOutsideModel: - assert(lag == 0); - output << "oo_.exo_steady_state(" << i << ")"; - break; - case oMatlabDynamicSteadyStateOperator: - output << "oo_.exo_steady_state(" << i << ")"; - break; - default: - assert(false); - } - break; + case eExogenous: + i = tsid + ARRAY_SUBSCRIPT_OFFSET(output_type); + switch (output_type) + { + case oMatlabDynamicModel: + case oMatlabDynamicModelSparse: + case oMatlabDynamicModelSparseLocalTemporaryTerms: + if (lag > 0) + output << "x(it_+" << lag << ", " << i << ")"; + else if (lag < 0) + output << "x(it_" << lag << ", " << i << ")"; + else + output << "x(it_, " << i << ")"; + break; + case oCDynamicModel: + if (lag == 0) + output << "x[it_+" << i << "*nb_row_x]"; + else if (lag > 0) + output << "x[it_+" << lag << "+" << i << "*nb_row_x]"; + else + output << "x[it_" << lag << "+" << i << "*nb_row_x]"; + break; + case oMatlabStaticModel: + case oMatlabStaticModelSparse: + output << "x" << LEFT_ARRAY_SUBSCRIPT(output_type) << i << RIGHT_ARRAY_SUBSCRIPT(output_type); + break; + case oMatlabOutsideModel: + assert(lag == 0); + output << "oo_.exo_steady_state(" << i << ")"; + break; + case oMatlabDynamicSteadyStateOperator: + output << "oo_.exo_steady_state(" << i << ")"; + break; + default: + assert(false); + } + break; - case eExogenousDet: - i = tsid + datatree.symbol_table.exo_nbr() + ARRAY_SUBSCRIPT_OFFSET(output_type); - switch (output_type) - { - case oMatlabDynamicModel: - case oMatlabDynamicModelSparse: - case oMatlabDynamicModelSparseLocalTemporaryTerms: - if (lag > 0) - output << "x(it_+" << lag << ", " << i << ")"; - else if (lag < 0) - output << "x(it_" << lag << ", " << i << ")"; - else - output << "x(it_, " << i << ")"; - break; - case oCDynamicModel: - if (lag == 0) - output << "x[it_+" << i << "*nb_row_xd]"; - else if (lag > 0) - output << "x[it_+" << lag << "+" << i << "*nb_row_xd]"; - else - output << "x[it_" << lag << "+" << i << "*nb_row_xd]"; - break; - case oMatlabStaticModel: - case oMatlabStaticModelSparse: - output << "x" << LEFT_ARRAY_SUBSCRIPT(output_type) << i << RIGHT_ARRAY_SUBSCRIPT(output_type); - break; - case oMatlabOutsideModel: - assert(lag == 0); - output << "oo_.exo_det_steady_state(" << tsid + 1 << ")"; - break; - case oMatlabDynamicSteadyStateOperator: - output << "oo_.exo_det_steady_state(" << tsid + 1 << ")"; - break; - default: - assert(false); - } - break; + case eExogenousDet: + i = tsid + datatree.symbol_table.exo_nbr() + ARRAY_SUBSCRIPT_OFFSET(output_type); + switch (output_type) + { + case oMatlabDynamicModel: + case oMatlabDynamicModelSparse: + case oMatlabDynamicModelSparseLocalTemporaryTerms: + if (lag > 0) + output << "x(it_+" << lag << ", " << i << ")"; + else if (lag < 0) + output << "x(it_" << lag << ", " << i << ")"; + else + output << "x(it_, " << i << ")"; + break; + case oCDynamicModel: + if (lag == 0) + output << "x[it_+" << i << "*nb_row_xd]"; + else if (lag > 0) + output << "x[it_+" << lag << "+" << i << "*nb_row_xd]"; + else + output << "x[it_" << lag << "+" << i << "*nb_row_xd]"; + break; + case oMatlabStaticModel: + case oMatlabStaticModelSparse: + output << "x" << LEFT_ARRAY_SUBSCRIPT(output_type) << i << RIGHT_ARRAY_SUBSCRIPT(output_type); + break; + case oMatlabOutsideModel: + assert(lag == 0); + output << "oo_.exo_det_steady_state(" << tsid + 1 << ")"; + break; + case oMatlabDynamicSteadyStateOperator: + output << "oo_.exo_det_steady_state(" << tsid + 1 << ")"; + break; + default: + assert(false); + } + break; - case eUnknownFunction: - cerr << "Impossible case" << endl; - exit(EXIT_FAILURE); - } - } + case eUnknownFunction: + cerr << "Impossible case" << endl; + exit(EXIT_FAILURE); + } +} double VariableNode::eval(const eval_context_type &eval_context) const throw (EvalException) @@ -621,74 +619,74 @@ VariableNode::eval(const eval_context_type &eval_context) const throw (EvalExcep void VariableNode::compile(ostream &CompileCode, bool lhs_rhs, const temporary_terms_type &temporary_terms, map_idx_type &map_idx, bool dynamic, bool steady_dynamic) const - { - if(type==eModelLocalVariable || type==eModFileLocalVariable) - datatree.local_variables_table[symb_id]->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); - else - { - int tsid = datatree.symbol_table.getTypeSpecificID(symb_id); - if(type == eExogenousDet) - tsid += datatree.symbol_table.exo_nbr(); - if (!lhs_rhs) - { - if(dynamic) - { - if(steady_dynamic) // steady state values in a dynamic model - { - FLDVS_ fldvs(type, tsid); - fldvs.write(CompileCode); - } - else - { - if (type == eParameter) - { - FLDV_ fldv(type, tsid); - fldv.write(CompileCode); - } - else - { - FLDV_ fldv(type, tsid, lag); - fldv.write(CompileCode); - } - } - } - else - { - FLDSV_ fldsv(type, tsid); - fldsv.write(CompileCode); - } - } - else - { - if(dynamic) - { - if(steady_dynamic) // steady state values in a dynamic model - { - cerr << "Impossible case: steady_state in rhs of equation" << endl; - exit(EXIT_FAILURE); - } - else - { - if (type == eParameter) - { - FSTPV_ fstpv(type, tsid); - fstpv.write(CompileCode); - } - else - { - FSTPV_ fstpv(type, tsid, lag); - fstpv.write(CompileCode); - } - } - } - else - { - FSTPSV_ fstpsv(type, tsid); - fstpsv.write(CompileCode); - } - } - } - } +{ + if (type == eModelLocalVariable || type == eModFileLocalVariable) + datatree.local_variables_table[symb_id]->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); + else + { + int tsid = datatree.symbol_table.getTypeSpecificID(symb_id); + if (type == eExogenousDet) + tsid += datatree.symbol_table.exo_nbr(); + if (!lhs_rhs) + { + if (dynamic) + { + if (steady_dynamic) // steady state values in a dynamic model + { + FLDVS_ fldvs(type, tsid); + fldvs.write(CompileCode); + } + else + { + if (type == eParameter) + { + FLDV_ fldv(type, tsid); + fldv.write(CompileCode); + } + else + { + FLDV_ fldv(type, tsid, lag); + fldv.write(CompileCode); + } + } + } + else + { + FLDSV_ fldsv(type, tsid); + fldsv.write(CompileCode); + } + } + else + { + if (dynamic) + { + if (steady_dynamic) // steady state values in a dynamic model + { + cerr << "Impossible case: steady_state in rhs of equation" << endl; + exit(EXIT_FAILURE); + } + else + { + if (type == eParameter) + { + FSTPV_ fstpv(type, tsid); + fstpv.write(CompileCode); + } + else + { + FSTPV_ fstpv(type, tsid, lag); + fstpv.write(CompileCode); + } + } + } + else + { + FSTPSV_ fstpsv(type, tsid); + fstpsv.write(CompileCode); + } + } + } +} void VariableNode::computeTemporaryTerms(map<NodeID, int> &reference_count, @@ -697,10 +695,10 @@ VariableNode::computeTemporaryTerms(map<NodeID, int> &reference_count, int Curr_block, vector<vector<temporary_terms_type> > &v_temporary_terms, int equation) const - { - if (type== eModelLocalVariable) - datatree.local_variables_table[symb_id]->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); - } +{ + if (type == eModelLocalVariable) + datatree.local_variables_table[symb_id]->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); +} void VariableNode::collectVariables(SymbolType type_arg, set<pair<int, int> > &result) const @@ -713,22 +711,22 @@ VariableNode::collectVariables(SymbolType type_arg, set<pair<int, int> > &result pair<int, NodeID> VariableNode::normalizeEquation(int var_endo, vector<pair<int, pair<NodeID, NodeID> > > &List_of_Op_RHS) const - { - if (type ==eEndogenous) - { - if (datatree.symbol_table.getTypeSpecificID(symb_id)==var_endo && lag==0) - return(make_pair(1, (NodeID)NULL )); - else - return(make_pair(0, datatree.AddVariableInternal(symb_id, lag) )); - } - else - { - if (type == eParameter) - return(make_pair(0, datatree.AddVariableInternal(symb_id, 0) )); - else - return(make_pair(0, datatree.AddVariableInternal(symb_id, lag) )); - } - } +{ + if (type == eEndogenous) + { + if (datatree.symbol_table.getTypeSpecificID(symb_id) == var_endo && lag == 0) + return (make_pair(1, (NodeID) NULL)); + else + return (make_pair(0, datatree.AddVariableInternal(symb_id, lag))); + } + else + { + if (type == eParameter) + return (make_pair(0, datatree.AddVariableInternal(symb_id, 0))); + else + return (make_pair(0, datatree.AddVariableInternal(symb_id, lag))); + } +} NodeID VariableNode::getChainRuleDerivative(int deriv_id, const map<int, NodeID> &recursive_variables) @@ -777,18 +775,16 @@ VariableNode::getChainRuleDerivative(int deriv_id, const map<int, NodeID> &recur exit(EXIT_FAILURE); } - - NodeID VariableNode::toStatic(DataTree &static_datatree) const - { - return static_datatree.AddVariable(datatree.symbol_table.getName(symb_id)); - } +{ + return static_datatree.AddVariable(datatree.symbol_table.getName(symb_id)); +} int VariableNode::maxEndoLead() const { - switch(type) + switch (type) { case eEndogenous: return max(lag, 0); @@ -802,7 +798,7 @@ VariableNode::maxEndoLead() const int VariableNode::maxExoLead() const { - switch(type) + switch (type) { case eExogenous: return max(lag, 0); @@ -816,7 +812,7 @@ VariableNode::maxExoLead() const NodeID VariableNode::decreaseLeadsLags(int n) const { - switch(type) + switch (type) { case eEndogenous: case eExogenous: @@ -842,7 +838,7 @@ NodeID VariableNode::substituteEndoLeadGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const { NodeID value; - switch(type) + switch (type) { case eEndogenous: if (lag <= 1) @@ -866,7 +862,7 @@ VariableNode::substituteEndoLagGreaterThanTwo(subst_table_t &subst_table, vector VariableNode *substexpr; subst_table_t::const_iterator it; int cur_lag; - switch(type) + switch (type) { case eEndogenous: if (lag >= -1) @@ -881,7 +877,7 @@ VariableNode::substituteEndoLagGreaterThanTwo(subst_table_t &subst_table, vector // Each iteration tries to create an auxvar such that auxvar(-1)=curvar(cur_lag) // At the beginning (resp. end) of each iteration, substexpr is an expression (possibly an auxvar) equivalent to curvar(cur_lag+1) (resp. curvar(cur_lag)) - while(cur_lag >= lag) + while (cur_lag >= lag) { VariableNode *orig_expr = datatree.AddVariable(symb_id, cur_lag); it = subst_table.find(orig_expr); @@ -910,7 +906,7 @@ NodeID VariableNode::substituteExoLead(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const { NodeID value; - switch(type) + switch (type) { case eExogenous: if (lag <= 0) @@ -934,7 +930,7 @@ VariableNode::substituteExoLag(subst_table_t &subst_table, vector<BinaryOpNode * VariableNode *substexpr; subst_table_t::const_iterator it; int cur_lag; - switch(type) + switch (type) { case eExogenous: if (lag >= 0) @@ -949,7 +945,7 @@ VariableNode::substituteExoLag(subst_table_t &subst_table, vector<BinaryOpNode * // Each iteration tries to create an auxvar such that auxvar(-1)=curvar(cur_lag) // At the beginning (resp. end) of each iteration, substexpr is an expression (possibly an auxvar) equivalent to curvar(cur_lag+1) (resp. curvar(cur_lag)) - while(cur_lag >= lag) + while (cur_lag >= lag) { VariableNode *orig_expr = datatree.AddVariable(symb_id, cur_lag); it = subst_table.find(orig_expr); @@ -981,10 +977,10 @@ VariableNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOpN } UnaryOpNode::UnaryOpNode(DataTree &datatree_arg, UnaryOpcode op_code_arg, const NodeID arg_arg, const int expectation_information_set_arg) : - ExprNode(datatree_arg), - arg(arg_arg), - expectation_information_set(expectation_information_set_arg), - op_code(op_code_arg) + ExprNode(datatree_arg), + arg(arg_arg), + expectation_information_set(expectation_information_set_arg), + op_code(op_code_arg) { // Add myself to the unary op map datatree.unary_op_node_map[make_pair(arg, op_code)] = this; @@ -1068,10 +1064,10 @@ UnaryOpNode::composeDerivatives(NodeID darg) t11 = datatree.AddPlus(this, this); return datatree.AddDivide(darg, t11); case oSteadyState: - if (datatree.isDynamic()) - return datatree.Zero; - else - return darg; + if (datatree.isDynamic()) + return datatree.Zero; + else + return darg; case oExpectation: assert(0); } @@ -1088,279 +1084,279 @@ UnaryOpNode::computeDerivative(int deriv_id) int UnaryOpNode::cost(const temporary_terms_type &temporary_terms, bool is_matlab) const - { - // For a temporary term, the cost is null - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode *>(this)); - if (it != temporary_terms.end()) - return 0; - - int cost = arg->cost(temporary_terms, is_matlab); - - if (is_matlab) - // Cost for Matlab files - switch (op_code) - { - case oUminus: - return cost + 70; - case oExp: - return cost + 160; - case oLog: - return cost + 300; - case oLog10: - return cost + 16000; - case oCos: - case oSin: - case oCosh: - return cost + 210; - case oTan: - return cost + 230; - case oAcos: - return cost + 300; - case oAsin: - return cost + 310; - case oAtan: - return cost + 140; - case oSinh: - return cost + 240; - case oTanh: - return cost + 190; - case oAcosh: - return cost + 770; - case oAsinh: - return cost + 460; - case oAtanh: - return cost + 350; - case oSqrt: - return cost + 570; - case oSteadyState: - case oExpectation: - return cost; - } - else - // Cost for C files - switch (op_code) - { - case oUminus: - return cost + 3; - case oExp: - case oAcosh: - return cost + 210; - case oLog: - return cost + 137; - case oLog10: - return cost + 139; - case oCos: - case oSin: - return cost + 160; - case oTan: - return cost + 170; - case oAcos: - case oAtan: - return cost + 190; - case oAsin: - return cost + 180; - case oCosh: - case oSinh: - case oTanh: - return cost + 240; - case oAsinh: - return cost + 220; - case oAtanh: - return cost + 150; - case oSqrt: - return cost + 90; - case oSteadyState: - case oExpectation: - return cost; - } - // Suppress GCC warning - exit(EXIT_FAILURE); - } +{ + // For a temporary term, the cost is null + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode *>(this)); + if (it != temporary_terms.end()) + return 0; -void -UnaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count, - temporary_terms_type &temporary_terms, - bool is_matlab) const - { - NodeID this2 = const_cast<UnaryOpNode *>(this); + int cost = arg->cost(temporary_terms, is_matlab); - map<NodeID, int>::iterator it = reference_count.find(this2); - if (it == reference_count.end()) - { - reference_count[this2] = 1; - arg->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); - } - else + if (is_matlab) + // Cost for Matlab files + switch (op_code) { - reference_count[this2]++; - if (reference_count[this2] * cost(temporary_terms, is_matlab) > MIN_COST(is_matlab)) - temporary_terms.insert(this2); - } - } - -void -UnaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count, - temporary_terms_type &temporary_terms, - map<NodeID, pair<int, int> > &first_occurence, - int Curr_block, - vector< vector<temporary_terms_type> > &v_temporary_terms, - int equation) const - { - NodeID this2 = const_cast<UnaryOpNode *>(this); - map<NodeID, int>::iterator it = reference_count.find(this2); - if (it == reference_count.end()) - { - reference_count[this2] = 1; - first_occurence[this2] = make_pair(Curr_block,equation); - arg->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); - } - else - { - reference_count[this2]++; - if (reference_count[this2] * cost(temporary_terms, false) > MIN_COST_C) - { - temporary_terms.insert(this2); - v_temporary_terms[first_occurence[this2].first][first_occurence[this2].second].insert(this2); - } - } - } - -void -UnaryOpNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, temporary_terms_inuse_type &temporary_terms_inuse, int Curr_Block) const - { - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode*>(this)); - if (it != temporary_terms.end()) - temporary_terms_inuse.insert(idx); - else - arg->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); - } - -void -UnaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type, - const temporary_terms_type &temporary_terms) const - { - // If node is a temporary term - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode *>(this)); - if (it != temporary_terms.end()) - { - if (output_type == oMatlabDynamicModelSparse) - output << "T" << idx << "(it_)"; - else - output << "T" << idx; - return; + case oUminus: + return cost + 70; + case oExp: + return cost + 160; + case oLog: + return cost + 300; + case oLog10: + return cost + 16000; + case oCos: + case oSin: + case oCosh: + return cost + 210; + case oTan: + return cost + 230; + case oAcos: + return cost + 300; + case oAsin: + return cost + 310; + case oAtan: + return cost + 140; + case oSinh: + return cost + 240; + case oTanh: + return cost + 190; + case oAcosh: + return cost + 770; + case oAsinh: + return cost + 460; + case oAtanh: + return cost + 350; + case oSqrt: + return cost + 570; + case oSteadyState: + case oExpectation: + return cost; } - - // Always put parenthesis around uminus nodes - if (op_code == oUminus) - output << LEFT_PAR(output_type); - + else + // Cost for C files switch (op_code) { case oUminus: - output << "-"; - break; + return cost + 3; case oExp: - output << "exp"; - break; + case oAcosh: + return cost + 210; case oLog: - output << "log"; - break; + return cost + 137; case oLog10: - if (IS_LATEX(output_type)) - output << "log_{10}"; - else - output << "log10"; - break; + return cost + 139; case oCos: - output << "cos"; - break; case oSin: - output << "sin"; - break; + return cost + 160; case oTan: - output << "tan"; - break; + return cost + 170; case oAcos: - output << "acos"; - break; - case oAsin: - output << "asin"; - break; case oAtan: - output << "atan"; - break; + return cost + 190; + case oAsin: + return cost + 180; case oCosh: - output << "cosh"; - break; case oSinh: - output << "sinh"; - break; case oTanh: - output << "tanh"; - break; - case oAcosh: - output << "acosh"; - break; + return cost + 240; case oAsinh: - output << "asinh"; - break; + return cost + 220; case oAtanh: - output << "atanh"; - break; + return cost + 150; case oSqrt: - output << "sqrt"; - break; + return cost + 90; case oSteadyState: - ExprNodeOutputType new_output_type; - switch(output_type) - { - case oMatlabDynamicModel: - new_output_type = oMatlabDynamicSteadyStateOperator; - break; - case oLatexDynamicModel: - new_output_type = oLatexDynamicSteadyStateOperator; - break; - case oCDynamicModel: - cerr << "Steady State Operator not implemented for oCDynamicModel." << endl; - exit(EXIT_FAILURE); - case oMatlabDynamicModelSparse: - case oMatlabDynamicModelSparseLocalTemporaryTerms: - cerr << "Steady State Operator not implemented for oMatlabDynamicModelSparse." << endl; - exit(EXIT_FAILURE); - default: - new_output_type = output_type; - break; - } - arg->writeOutput(output, new_output_type, temporary_terms); - return; case oExpectation: - assert(0); + return cost; } + // Suppress GCC warning + exit(EXIT_FAILURE); +} - bool close_parenthesis = false; +void +UnaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count, + temporary_terms_type &temporary_terms, + bool is_matlab) const +{ + NodeID this2 = const_cast<UnaryOpNode *>(this); - /* 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); - close_parenthesis = true; - } + map<NodeID, int>::iterator it = reference_count.find(this2); + if (it == reference_count.end()) + { + reference_count[this2] = 1; + arg->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + } + else + { + reference_count[this2]++; + if (reference_count[this2] * cost(temporary_terms, is_matlab) > MIN_COST(is_matlab)) + temporary_terms.insert(this2); + } +} + +void +UnaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count, + temporary_terms_type &temporary_terms, + map<NodeID, pair<int, int> > &first_occurence, + int Curr_block, + vector< vector<temporary_terms_type> > &v_temporary_terms, + int equation) const +{ + NodeID this2 = const_cast<UnaryOpNode *>(this); + map<NodeID, int>::iterator it = reference_count.find(this2); + if (it == reference_count.end()) + { + reference_count[this2] = 1; + first_occurence[this2] = make_pair(Curr_block, equation); + arg->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); + } + else + { + reference_count[this2]++; + if (reference_count[this2] * cost(temporary_terms, false) > MIN_COST_C) + { + temporary_terms.insert(this2); + v_temporary_terms[first_occurence[this2].first][first_occurence[this2].second].insert(this2); + } + } +} + +void +UnaryOpNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, temporary_terms_inuse_type &temporary_terms_inuse, int Curr_Block) const +{ + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode *>(this)); + if (it != temporary_terms.end()) + temporary_terms_inuse.insert(idx); + else + arg->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); +} + +void +UnaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_type &temporary_terms) const +{ + // If node is a temporary term + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode *>(this)); + if (it != temporary_terms.end()) + { + if (output_type == oMatlabDynamicModelSparse) + output << "T" << idx << "(it_)"; + else + output << "T" << idx; + return; + } + + // 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: + if (IS_LATEX(output_type)) + output << "log_{10}"; + else + 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 oSteadyState: + ExprNodeOutputType new_output_type; + switch (output_type) + { + case oMatlabDynamicModel: + new_output_type = oMatlabDynamicSteadyStateOperator; + break; + case oLatexDynamicModel: + new_output_type = oLatexDynamicSteadyStateOperator; + break; + case oCDynamicModel: + cerr << "Steady State Operator not implemented for oCDynamicModel." << endl; + exit(EXIT_FAILURE); + case oMatlabDynamicModelSparse: + case oMatlabDynamicModelSparseLocalTemporaryTerms: + cerr << "Steady State Operator not implemented for oMatlabDynamicModelSparse." << endl; + exit(EXIT_FAILURE); + default: + new_output_type = output_type; + break; + } + arg->writeOutput(output, new_output_type, temporary_terms); + return; + case oExpectation: + assert(0); + } + + bool close_parenthesis = false; - // Write argument - arg->writeOutput(output, output_type, temporary_terms); + /* 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); + close_parenthesis = true; + } + + // Write argument + arg->writeOutput(output, output_type, temporary_terms); - if (close_parenthesis) - output << RIGHT_PAR(output_type); + if (close_parenthesis) + output << RIGHT_PAR(output_type); - // Close parenthesis for uminus - if (op_code == oUminus) - output << RIGHT_PAR(output_type); - } + // Close parenthesis for uminus + if (op_code == oUminus) + output << RIGHT_PAR(output_type); +} double UnaryOpNode::eval_opcode(UnaryOpcode op_code, double v) throw (EvalException) @@ -1368,41 +1364,41 @@ UnaryOpNode::eval_opcode(UnaryOpcode op_code, double v) throw (EvalException) switch (op_code) { case oUminus: - return(-v); + return (-v); case oExp: - return(exp(v)); + return (exp(v)); case oLog: - return(log(v)); + return (log(v)); case oLog10: - return(log10(v)); + return (log10(v)); case oCos: - return(cos(v)); + return (cos(v)); case oSin: - return(sin(v)); + return (sin(v)); case oTan: - return(tan(v)); + return (tan(v)); case oAcos: - return(acos(v)); + return (acos(v)); case oAsin: - return(asin(v)); + return (asin(v)); case oAtan: - return(atan(v)); + return (atan(v)); case oCosh: - return(cosh(v)); + return (cosh(v)); case oSinh: - return(sinh(v)); + return (sinh(v)); case oTanh: - return(tanh(v)); + return (tanh(v)); case oAcosh: - return(acosh(v)); + return (acosh(v)); case oAsinh: - return(asinh(v)); + return (asinh(v)); case oAtanh: - return(atanh(v)); + return (atanh(v)); case oSqrt: - return(sqrt(v)); + return (sqrt(v)); case oSteadyState: - return(v); + return (v); case oExpectation: throw EvalException(); } @@ -1420,31 +1416,31 @@ UnaryOpNode::eval(const eval_context_type &eval_context) const throw (EvalExcept void UnaryOpNode::compile(ostream &CompileCode, bool lhs_rhs, const temporary_terms_type &temporary_terms, map_idx_type &map_idx, bool dynamic, bool steady_dynamic) const - { - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode *>(this)); - if (it != temporary_terms.end()) - { - if(dynamic) - { - FLDT_ fldt(map_idx[idx]); - fldt.write(CompileCode); - } - else - { - FLDST_ fldst(map_idx[idx]); - fldst.write(CompileCode); - } - return; - } - if (op_code == oSteadyState) - arg->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, true); - else - { - arg->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); - FUNARY_ funary(op_code); - funary.write(CompileCode); - } - } +{ + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode *>(this)); + if (it != temporary_terms.end()) + { + if (dynamic) + { + FLDT_ fldt(map_idx[idx]); + fldt.write(CompileCode); + } + else + { + FLDST_ fldst(map_idx[idx]); + fldst.write(CompileCode); + } + return; + } + if (op_code == oSteadyState) + arg->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, true); + else + { + arg->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); + FUNARY_ funary(op_code); + funary.write(CompileCode); + } +} void UnaryOpNode::collectVariables(SymbolType type_arg, set<pair<int, int> > &result) const @@ -1454,109 +1450,108 @@ UnaryOpNode::collectVariables(SymbolType type_arg, set<pair<int, int> > &result) pair<int, NodeID> UnaryOpNode::normalizeEquation(int var_endo, vector<pair<int, pair<NodeID, NodeID> > > &List_of_Op_RHS) const - { - pair<bool, NodeID > res = arg->normalizeEquation(var_endo, List_of_Op_RHS); - int is_endogenous_present = res.first; - NodeID New_NodeID = res.second; - /*if(res.second.second)*/ - if(is_endogenous_present==2) - return(make_pair(2, (NodeID)NULL)); - else if (is_endogenous_present) - { - switch (op_code) - { - case oUminus: - List_of_Op_RHS.push_back(make_pair(oUminus, make_pair((NodeID)NULL, (NodeID)NULL))); - return(make_pair(1, (NodeID)NULL)); - case oExp: - List_of_Op_RHS.push_back(make_pair(oLog, make_pair((NodeID)NULL, (NodeID)NULL))); - return(make_pair(1, (NodeID)NULL)); - case oLog: - List_of_Op_RHS.push_back(make_pair(oExp, make_pair((NodeID)NULL, (NodeID)NULL))); - return(make_pair(1, (NodeID)NULL)); - case oLog10: - List_of_Op_RHS.push_back(make_pair(oPower, make_pair((NodeID)NULL, datatree.AddNumConstant("10")))); - return(make_pair(1, (NodeID)NULL)); - case oCos: - return(make_pair(1, (NodeID)NULL)); - case oSin: - return(make_pair(1, (NodeID)NULL)); - case oTan: - return(make_pair(1, (NodeID)NULL)); - case oAcos: - return(make_pair(1, (NodeID)NULL)); - case oAsin: - return(make_pair(1, (NodeID)NULL)); - case oAtan: - return(make_pair(1, (NodeID)NULL)); - case oCosh: - return(make_pair(1, (NodeID)NULL)); - case oSinh: - return(make_pair(1, (NodeID)NULL)); - case oTanh: - return(make_pair(1, (NodeID)NULL)); - case oAcosh: - return(make_pair(1, (NodeID)NULL)); - case oAsinh: - return(make_pair(1, (NodeID)NULL)); - case oAtanh: - return(make_pair(1, (NodeID)NULL)); - case oSqrt: - List_of_Op_RHS.push_back(make_pair(oPower, make_pair((NodeID)NULL, datatree.AddNumConstant("2")))); - return(make_pair(1, (NodeID)NULL)); - case oSteadyState: - return(make_pair(1, (NodeID)NULL)); - case oExpectation: - assert(0); - } - } - else - { - switch (op_code) - { - case oUminus: - return(make_pair(0, datatree.AddUMinus(New_NodeID))); - case oExp: - return(make_pair(0, datatree.AddExp(New_NodeID))); - case oLog: - return(make_pair(0, datatree.AddLog(New_NodeID))); - case oLog10: - return(make_pair(0, datatree.AddLog10(New_NodeID))); - case oCos: - return(make_pair(0, datatree.AddCos(New_NodeID))); - case oSin: - return(make_pair(0, datatree.AddSin(New_NodeID))); - case oTan: - return(make_pair(0, datatree.AddTan(New_NodeID))); - case oAcos: - return(make_pair(0, datatree.AddAcos(New_NodeID))); - case oAsin: - return(make_pair(0, datatree.AddAsin(New_NodeID))); - case oAtan: - return(make_pair(0, datatree.AddAtan(New_NodeID))); - case oCosh: - return(make_pair(0, datatree.AddCosh(New_NodeID))); - case oSinh: - return(make_pair(0, datatree.AddSinh(New_NodeID))); - case oTanh: - return(make_pair(0, datatree.AddTanh(New_NodeID))); - case oAcosh: - return(make_pair(0, datatree.AddAcosh(New_NodeID))); - case oAsinh: - return(make_pair(0, datatree.AddAsinh(New_NodeID))); - case oAtanh: - return(make_pair(0, datatree.AddAtanh(New_NodeID))); - case oSqrt: - return(make_pair(0, datatree.AddSqrt(New_NodeID))); - case oSteadyState: - return(make_pair(0, datatree.AddSteadyState(New_NodeID))); - case oExpectation: - assert(0); - } - } - return(make_pair(1, (NodeID)NULL)); - } - +{ + pair<bool, NodeID > res = arg->normalizeEquation(var_endo, List_of_Op_RHS); + int is_endogenous_present = res.first; + NodeID New_NodeID = res.second; + /*if(res.second.second)*/ + if (is_endogenous_present == 2) + return (make_pair(2, (NodeID) NULL)); + else if (is_endogenous_present) + { + switch (op_code) + { + case oUminus: + List_of_Op_RHS.push_back(make_pair(oUminus, make_pair((NodeID) NULL, (NodeID) NULL))); + return (make_pair(1, (NodeID) NULL)); + case oExp: + List_of_Op_RHS.push_back(make_pair(oLog, make_pair((NodeID) NULL, (NodeID) NULL))); + return (make_pair(1, (NodeID) NULL)); + case oLog: + List_of_Op_RHS.push_back(make_pair(oExp, make_pair((NodeID) NULL, (NodeID) NULL))); + return (make_pair(1, (NodeID) NULL)); + case oLog10: + List_of_Op_RHS.push_back(make_pair(oPower, make_pair((NodeID) NULL, datatree.AddNumConstant("10")))); + return (make_pair(1, (NodeID) NULL)); + case oCos: + return (make_pair(1, (NodeID) NULL)); + case oSin: + return (make_pair(1, (NodeID) NULL)); + case oTan: + return (make_pair(1, (NodeID) NULL)); + case oAcos: + return (make_pair(1, (NodeID) NULL)); + case oAsin: + return (make_pair(1, (NodeID) NULL)); + case oAtan: + return (make_pair(1, (NodeID) NULL)); + case oCosh: + return (make_pair(1, (NodeID) NULL)); + case oSinh: + return (make_pair(1, (NodeID) NULL)); + case oTanh: + return (make_pair(1, (NodeID) NULL)); + case oAcosh: + return (make_pair(1, (NodeID) NULL)); + case oAsinh: + return (make_pair(1, (NodeID) NULL)); + case oAtanh: + return (make_pair(1, (NodeID) NULL)); + case oSqrt: + List_of_Op_RHS.push_back(make_pair(oPower, make_pair((NodeID) NULL, datatree.AddNumConstant("2")))); + return (make_pair(1, (NodeID) NULL)); + case oSteadyState: + return (make_pair(1, (NodeID) NULL)); + case oExpectation: + assert(0); + } + } + else + { + switch (op_code) + { + case oUminus: + return (make_pair(0, datatree.AddUMinus(New_NodeID))); + case oExp: + return (make_pair(0, datatree.AddExp(New_NodeID))); + case oLog: + return (make_pair(0, datatree.AddLog(New_NodeID))); + case oLog10: + return (make_pair(0, datatree.AddLog10(New_NodeID))); + case oCos: + return (make_pair(0, datatree.AddCos(New_NodeID))); + case oSin: + return (make_pair(0, datatree.AddSin(New_NodeID))); + case oTan: + return (make_pair(0, datatree.AddTan(New_NodeID))); + case oAcos: + return (make_pair(0, datatree.AddAcos(New_NodeID))); + case oAsin: + return (make_pair(0, datatree.AddAsin(New_NodeID))); + case oAtan: + return (make_pair(0, datatree.AddAtan(New_NodeID))); + case oCosh: + return (make_pair(0, datatree.AddCosh(New_NodeID))); + case oSinh: + return (make_pair(0, datatree.AddSinh(New_NodeID))); + case oTanh: + return (make_pair(0, datatree.AddTanh(New_NodeID))); + case oAcosh: + return (make_pair(0, datatree.AddAcosh(New_NodeID))); + case oAsinh: + return (make_pair(0, datatree.AddAsinh(New_NodeID))); + case oAtanh: + return (make_pair(0, datatree.AddAtanh(New_NodeID))); + case oSqrt: + return (make_pair(0, datatree.AddSqrt(New_NodeID))); + case oSteadyState: + return (make_pair(0, datatree.AddSteadyState(New_NodeID))); + case oExpectation: + assert(0); + } + } + return (make_pair(1, (NodeID) NULL)); +} NodeID UnaryOpNode::getChainRuleDerivative(int deriv_id, const map<int, NodeID> &recursive_variables) @@ -1697,7 +1692,7 @@ UnaryOpNode::substituteExoLag(subst_table_t &subst_table, vector<BinaryOpNode *> NodeID UnaryOpNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool partial_information_model) const { - switch(op_code) + switch (op_code) { case oExpectation: { @@ -1710,7 +1705,7 @@ UnaryOpNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNo int symb_id = datatree.symbol_table.addExpectationAuxiliaryVar(expectation_information_set, arg->idx); //AUXE_period_arg.idx NodeID newAuxE = datatree.AddVariable(symb_id, 0); - if (partial_information_model && expectation_information_set==0) + if (partial_information_model && expectation_information_set == 0) { //Ensure x is a single variable as opposed to an expression if (dynamic_cast<VariableNode *>(arg) == NULL) @@ -1736,17 +1731,17 @@ UnaryOpNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNo return newAuxE; } default: - NodeID argsubst = arg->substituteExpectation(subst_table, neweqs, partial_information_model); - return buildSimilarUnaryOpNode(argsubst, datatree); + NodeID argsubst = arg->substituteExpectation(subst_table, neweqs, partial_information_model); + return buildSimilarUnaryOpNode(argsubst, datatree); } } BinaryOpNode::BinaryOpNode(DataTree &datatree_arg, const NodeID arg1_arg, BinaryOpcode op_code_arg, const NodeID arg2_arg) : - ExprNode(datatree_arg), - arg1(arg1_arg), - arg2(arg2_arg), - op_code(op_code_arg) + ExprNode(datatree_arg), + arg1(arg1_arg), + arg2(arg2_arg), + op_code(op_code_arg) { datatree.binary_op_node_map[make_pair(make_pair(arg1, arg2), op_code)] = this; } @@ -1787,7 +1782,7 @@ BinaryOpNode::composeDerivatives(NodeID darg1, NodeID darg2) t12 = datatree.AddTimes(darg2, arg1); return datatree.AddPlus(t11, t12); case oDivide: - if (darg2!=datatree.Zero) + if (darg2 != datatree.Zero) { t11 = datatree.AddTimes(darg1, arg2); t12 = datatree.AddTimes(darg2, arg1); @@ -1827,17 +1822,17 @@ BinaryOpNode::composeDerivatives(NodeID darg1, NodeID darg2) return datatree.AddTimes(t15, this); } case oMax: - t11 = datatree.AddGreater(arg1,arg2); - t12 = datatree.AddTimes(t11,darg1); - t13 = datatree.AddMinus(datatree.One,t11); - t14 = datatree.AddTimes(t13,darg2); - return datatree.AddPlus(t14,t12); + t11 = datatree.AddGreater(arg1, arg2); + t12 = datatree.AddTimes(t11, darg1); + t13 = datatree.AddMinus(datatree.One, t11); + t14 = datatree.AddTimes(t13, darg2); + return datatree.AddPlus(t14, t12); case oMin: - t11 = datatree.AddGreater(arg2,arg1); - t12 = datatree.AddTimes(t11,darg1); - t13 = datatree.AddMinus(datatree.One,t11); - t14 = datatree.AddTimes(t13,darg2); - return datatree.AddPlus(t14,t12); + t11 = datatree.AddGreater(arg2, arg1); + t12 = datatree.AddTimes(t11, darg1); + t13 = datatree.AddMinus(datatree.One, t11); + t14 = datatree.AddTimes(t13, darg2); + return datatree.AddPlus(t14, t12); case oEqual: return datatree.AddMinus(darg1, darg2); } @@ -1855,133 +1850,133 @@ BinaryOpNode::computeDerivative(int deriv_id) int BinaryOpNode::precedence(ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const - { - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this)); - // A temporary term behaves as a variable - if (it != temporary_terms.end()) - return 100; +{ + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(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: - if (IS_C(output_type)) - // In C, power operator is of the form pow(a, b) - return 100; - else - return 5; - case oMin: - case oMax: + 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: + if (IS_C(output_type)) + // In C, power operator is of the form pow(a, b) return 100; - } - // Suppress GCC warning - exit(EXIT_FAILURE); - } + else + return 5; + case oMin: + case oMax: + return 100; + } + // Suppress GCC warning + exit(EXIT_FAILURE); +} int BinaryOpNode::cost(const temporary_terms_type &temporary_terms, bool is_matlab) const - { - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this)); - // For a temporary term, the cost is null - if (it != temporary_terms.end()) - return 0; +{ + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this)); + // For a temporary term, the cost is null + if (it != temporary_terms.end()) + return 0; - int cost = arg1->cost(temporary_terms, is_matlab); - cost += arg2->cost(temporary_terms, is_matlab); + int cost = arg1->cost(temporary_terms, is_matlab); + cost += arg2->cost(temporary_terms, is_matlab); - if (is_matlab) - // Cost for Matlab files - switch (op_code) - { - case oLess: - case oGreater: - case oLessEqual: - case oGreaterEqual: - case oEqualEqual: - case oDifferent: - return cost + 60; - case oPlus: - case oMinus: - case oTimes: - return cost + 90; - case oMax: - case oMin: - return cost + 110; - case oDivide: - return cost + 990; - case oPower: - return cost + 1160; - case oEqual: - return cost; - } - else - // Cost for C files - switch (op_code) - { - case oLess: - case oGreater: - case oLessEqual: - case oGreaterEqual: - case oEqualEqual: - case oDifferent: - return cost + 2; - case oPlus: - case oMinus: - case oTimes: - return cost + 4; - case oMax: - case oMin: - return cost + 5; - case oDivide: - return cost + 15; - case oPower: - return cost + 520; - case oEqual: - return cost; - } - // Suppress GCC warning - exit(EXIT_FAILURE); - } + if (is_matlab) + // Cost for Matlab files + switch (op_code) + { + case oLess: + case oGreater: + case oLessEqual: + case oGreaterEqual: + case oEqualEqual: + case oDifferent: + return cost + 60; + case oPlus: + case oMinus: + case oTimes: + return cost + 90; + case oMax: + case oMin: + return cost + 110; + case oDivide: + return cost + 990; + case oPower: + return cost + 1160; + case oEqual: + return cost; + } + else + // Cost for C files + switch (op_code) + { + case oLess: + case oGreater: + case oLessEqual: + case oGreaterEqual: + case oEqualEqual: + case oDifferent: + return cost + 2; + case oPlus: + case oMinus: + case oTimes: + return cost + 4; + case oMax: + case oMin: + return cost + 5; + case oDivide: + return cost + 15; + case oPower: + return cost + 520; + case oEqual: + return cost; + } + // Suppress GCC warning + exit(EXIT_FAILURE); +} void BinaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms, bool is_matlab) const - { - NodeID this2 = const_cast<BinaryOpNode *>(this); - map<NodeID, int>::iterator it = reference_count.find(this2); - if (it == reference_count.end()) - { - // If this node has never been encountered, set its ref count to one, - // and travel through its children - reference_count[this2] = 1; - arg1->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); - arg2->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); - } - else - { - // If the node has already been encountered, increment its ref count - // and declare it as a temporary term if it is too costly - reference_count[this2]++; - if (reference_count[this2] * cost(temporary_terms, is_matlab) > MIN_COST(is_matlab)) - temporary_terms.insert(this2); - } - } +{ + NodeID this2 = const_cast<BinaryOpNode *>(this); + map<NodeID, int>::iterator it = reference_count.find(this2); + if (it == reference_count.end()) + { + // If this node has never been encountered, set its ref count to one, + // and travel through its children + reference_count[this2] = 1; + arg1->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + arg2->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + } + else + { + // If the node has already been encountered, increment its ref count + // and declare it as a temporary term if it is too costly + reference_count[this2]++; + if (reference_count[this2] * cost(temporary_terms, is_matlab) > MIN_COST(is_matlab)) + temporary_terms.insert(this2); + } +} void BinaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count, @@ -1990,26 +1985,26 @@ BinaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count, int Curr_block, vector<vector<temporary_terms_type> > &v_temporary_terms, int equation) const - { - NodeID this2 = const_cast<BinaryOpNode *>(this); - map<NodeID, int>::iterator it = reference_count.find(this2); - if (it == reference_count.end()) - { - reference_count[this2] = 1; - first_occurence[this2] = make_pair(Curr_block, equation); - arg1->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); - arg2->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); - } - else - { - reference_count[this2]++; - if (reference_count[this2] * cost(temporary_terms, false) > MIN_COST_C) - { - temporary_terms.insert(this2); - v_temporary_terms[first_occurence[this2].first][first_occurence[this2].second].insert(this2); - } - } - } +{ + NodeID this2 = const_cast<BinaryOpNode *>(this); + map<NodeID, int>::iterator it = reference_count.find(this2); + if (it == reference_count.end()) + { + reference_count[this2] = 1; + first_occurence[this2] = make_pair(Curr_block, equation); + arg1->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); + arg2->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); + } + else + { + reference_count[this2]++; + if (reference_count[this2] * cost(temporary_terms, false) > MIN_COST_C) + { + temporary_terms.insert(this2); + v_temporary_terms[first_occurence[this2].first][first_occurence[this2].second].insert(this2); + } + } +} double BinaryOpNode::eval_opcode(double v1, BinaryOpcode op_code, double v2) throw (EvalException) @@ -2017,15 +2012,15 @@ BinaryOpNode::eval_opcode(double v1, BinaryOpcode op_code, double v2) throw (Eva switch (op_code) { case oPlus: - return(v1 + v2); + return (v1 + v2); case oMinus: - return(v1 - v2); + return (v1 - v2); case oTimes: - return(v1 * v2); + return (v1 * v2); case oDivide: - return(v1 / v2); + return (v1 / v2); case oPower: - return(pow(v1, v2)); + return (pow(v1, v2)); case oMax: if (v1 < v2) return v2; @@ -2066,203 +2061,201 @@ BinaryOpNode::eval(const eval_context_type &eval_context) const throw (EvalExcep void BinaryOpNode::compile(ostream &CompileCode, bool lhs_rhs, const temporary_terms_type &temporary_terms, map_idx_type &map_idx, bool dynamic, bool steady_dynamic) const - { - // If current node is a temporary term - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this)); - if (it != temporary_terms.end()) - { - if(dynamic) - { - FLDT_ fldt(map_idx[idx]); - fldt.write(CompileCode); - } - else - { - FLDST_ fldst(map_idx[idx]); - fldst.write(CompileCode); - } - return; - } - arg1->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); - arg2->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); - FBINARY_ fbinary(op_code); - fbinary.write(CompileCode); - } +{ + // If current node is a temporary term + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this)); + if (it != temporary_terms.end()) + { + if (dynamic) + { + FLDT_ fldt(map_idx[idx]); + fldt.write(CompileCode); + } + else + { + FLDST_ fldst(map_idx[idx]); + fldst.write(CompileCode); + } + return; + } + arg1->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); + arg2->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); + FBINARY_ fbinary(op_code); + fbinary.write(CompileCode); +} void BinaryOpNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, temporary_terms_inuse_type &temporary_terms_inuse, int Curr_Block) const - { - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this)); - if (it != temporary_terms.end()) - temporary_terms_inuse.insert(idx); - else - { - arg1->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); - arg2->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); - } - } - +{ + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this)); + if (it != temporary_terms.end()) + temporary_terms_inuse.insert(idx); + else + { + arg1->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); + arg2->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); + } +} void BinaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const - { - // If current node is a temporary term - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this)); - if (it != temporary_terms.end()) - { - if (output_type == oMatlabDynamicModelSparse) - output << "T" << idx << "(it_)"; - else - output << "T" << idx; - return; - } +{ + // If current node is a temporary term + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this)); + if (it != temporary_terms.end()) + { + if (output_type == oMatlabDynamicModelSparse) + output << "T" << idx << "(it_)"; + else + output << "T" << idx; + return; + } - // Treat special case of power operator in C, and case of max and min operators - if ((op_code == oPower && IS_C(output_type)) || op_code == oMax || op_code == oMin ) - { - switch (op_code) - { - case oPower: - output << "pow("; - break; - case oMax: - output << "max("; - break; - case oMin: - output << "min("; - break; - default: - ; - } - arg1->writeOutput(output, output_type, temporary_terms); - output << ","; - arg2->writeOutput(output, output_type, temporary_terms); - output << ")"; - return; - } + // Treat special case of power operator in C, and case of max and min operators + if ((op_code == oPower && IS_C(output_type)) || op_code == oMax || op_code == oMin) + { + switch (op_code) + { + case oPower: + output << "pow("; + break; + case oMax: + output << "max("; + break; + case oMin: + output << "min("; + break; + default: + ; + } + arg1->writeOutput(output, output_type, temporary_terms); + output << ","; + arg2->writeOutput(output, output_type, temporary_terms); + output << ")"; + return; + } - int prec = precedence(output_type, temporary_terms); + int prec = precedence(output_type, temporary_terms); - bool close_parenthesis = false; + bool close_parenthesis = false; - if (IS_LATEX(output_type) && op_code == oDivide) - output << "\\frac{"; - else - { - // 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<BinaryOpNode *>(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->writeOutput(output, output_type, temporary_terms); + if (IS_LATEX(output_type) && op_code == oDivide) + output << "\\frac{"; + else + { + // 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<BinaryOpNode *>(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; + } + } - if (close_parenthesis) - output << RIGHT_PAR(output_type); + // Write left argument + arg1->writeOutput(output, output_type, temporary_terms); - if (IS_LATEX(output_type) && op_code == oDivide) - output << "}"; + if (close_parenthesis) + output << RIGHT_PAR(output_type); + if (IS_LATEX(output_type) && op_code == oDivide) + output << "}"; - // Write current operator symbol - switch (op_code) - { - case oPlus: - output << "+"; - break; - case oMinus: - output << "-"; - break; - case oTimes: - if (IS_LATEX(output_type)) - output << "\\, "; - else - output << "*"; - break; - case oDivide: - if (!IS_LATEX(output_type)) - output << "/"; - break; - case oPower: - output << "^"; - break; - case oLess: - output << "<"; - break; - case oGreater: - output << ">"; - break; - case oLessEqual: - if (IS_LATEX(output_type)) - output << "\\leq "; - else - output << "<="; - break; - case oGreaterEqual: - if (IS_LATEX(output_type)) - output << "\\geq "; - else - output << ">="; - break; - case oEqualEqual: - output << "=="; - break; - case oDifferent: - if (IS_MATLAB(output_type)) - output << "~="; - else - { - if (IS_C(output_type)) - output << "!="; - else - output << "\\neq "; - } - break; - case oEqual: - output << "="; - break; - default: - ; - } + // Write current operator symbol + switch (op_code) + { + case oPlus: + output << "+"; + break; + case oMinus: + output << "-"; + break; + case oTimes: + if (IS_LATEX(output_type)) + output << "\\, "; + else + output << "*"; + break; + case oDivide: + if (!IS_LATEX(output_type)) + output << "/"; + break; + case oPower: + output << "^"; + break; + case oLess: + output << "<"; + break; + case oGreater: + output << ">"; + break; + case oLessEqual: + if (IS_LATEX(output_type)) + output << "\\leq "; + else + output << "<="; + break; + case oGreaterEqual: + if (IS_LATEX(output_type)) + output << "\\geq "; + else + output << ">="; + break; + case oEqualEqual: + output << "=="; + break; + case oDifferent: + if (IS_MATLAB(output_type)) + output << "~="; + else + { + if (IS_C(output_type)) + output << "!="; + else + output << "\\neq "; + } + break; + case oEqual: + output << "="; + break; + default: + ; + } - close_parenthesis = false; + close_parenthesis = false; - if (IS_LATEX(output_type) && (op_code == oPower || op_code == oDivide)) - output << "{"; - else - { - /* 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<BinaryOpNode *>(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; - } - } + if (IS_LATEX(output_type) && (op_code == oPower || op_code == oDivide)) + output << "{"; + else + { + /* 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<BinaryOpNode *>(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->writeOutput(output, output_type, temporary_terms); + // Write right argument + arg2->writeOutput(output, output_type, temporary_terms); - if (IS_LATEX(output_type) && (op_code == oPower || op_code == oDivide)) - output << "}"; + if (IS_LATEX(output_type) && (op_code == oPower || op_code == oDivide)) + output << "}"; - if (close_parenthesis) - output << RIGHT_PAR(output_type); - } + if (close_parenthesis) + output << RIGHT_PAR(output_type); +} void BinaryOpNode::collectVariables(SymbolType type_arg, set<pair<int, int> > &result) const @@ -2275,275 +2268,274 @@ NodeID BinaryOpNode::Compute_RHS(NodeID arg1, NodeID arg2, int op, int op_type) const { temporary_terms_type temp; - switch(op_type) + switch (op_type) { case 0: /*Unary Operator*/ - switch(op) + switch (op) { case oUminus: - return(datatree.AddUMinus(arg1)); + return (datatree.AddUMinus(arg1)); break; case oExp: - return(datatree.AddExp(arg1)); + return (datatree.AddExp(arg1)); break; case oLog: - return(datatree.AddLog(arg1)); + return (datatree.AddLog(arg1)); break; case oLog10: - return(datatree.AddLog10(arg1)); + return (datatree.AddLog10(arg1)); + break; + } + break; + case 1: /*Binary Operator*/ + switch (op) + { + case oPlus: + return (datatree.AddPlus(arg1, arg2)); + break; + case oMinus: + return (datatree.AddMinus(arg1, arg2)); + break; + case oTimes: + return (datatree.AddTimes(arg1, arg2)); + break; + case oDivide: + return (datatree.AddDivide(arg1, arg2)); + break; + case oPower: + return (datatree.AddPower(arg1, arg2)); break; } break; - case 1: /*Binary Operator*/ - switch(op) - { - case oPlus: - return(datatree.AddPlus(arg1, arg2)); - break; - case oMinus: - return(datatree.AddMinus(arg1, arg2)); - break; - case oTimes: - return(datatree.AddTimes(arg1, arg2)); - break; - case oDivide: - return(datatree.AddDivide(arg1, arg2)); - break; - case oPower: - return(datatree.AddPower(arg1, arg2)); - break; - } + } + return ((NodeID) NULL); +} + +pair<int, NodeID> +BinaryOpNode::normalizeEquation(int var_endo, vector<pair<int, pair<NodeID, NodeID> > > &List_of_Op_RHS) const +{ + vector<pair<int, pair<NodeID, NodeID> > > List_of_Op_RHS1, List_of_Op_RHS2; + int is_endogenous_present_1, is_endogenous_present_2; + pair<int, NodeID> res; + NodeID NodeID_1, NodeID_2; + res = arg1->normalizeEquation(var_endo, List_of_Op_RHS1); + is_endogenous_present_1 = res.first; + NodeID_1 = res.second; + + res = arg2->normalizeEquation(var_endo, List_of_Op_RHS2); + is_endogenous_present_2 = res.first; + NodeID_2 = res.second; + if (is_endogenous_present_1 == 2 || is_endogenous_present_2 == 2) + return (make_pair(2, (NodeID) NULL)); + else if (is_endogenous_present_1 && is_endogenous_present_2) + return (make_pair(2, (NodeID) NULL)); + else if (is_endogenous_present_1) + { + if (op_code == oEqual) + { + pair<int, pair<NodeID, NodeID> > it; + int oo = List_of_Op_RHS1.size(); + for (int i = 0; i < oo; i++) + { + it = List_of_Op_RHS1.back(); + List_of_Op_RHS1.pop_back(); + if (it.second.first && !it.second.second) /*Binary operator*/ + NodeID_2 = Compute_RHS(NodeID_2, (BinaryOpNode *) it.second.first, it.first, 1); + else if (it.second.second && !it.second.first) /*Binary operator*/ + NodeID_2 = Compute_RHS(it.second.second, NodeID_2, it.first, 1); + else if (it.second.second && it.second.first) /*Binary operator*/ + NodeID_2 = Compute_RHS(it.second.first, it.second.second, it.first, 1); + else /*Unary operator*/ + NodeID_2 = Compute_RHS((UnaryOpNode *) NodeID_2, (UnaryOpNode *) it.second.first, it.first, 0); + } + } + else + List_of_Op_RHS = List_of_Op_RHS1; + } + else if (is_endogenous_present_2) + { + if (op_code == oEqual) + { + int oo = List_of_Op_RHS2.size(); + for (int i = 0; i < oo; i++) + { + pair<int, pair<NodeID, NodeID> > it; + it = List_of_Op_RHS2.back(); + List_of_Op_RHS2.pop_back(); + if (it.second.first && !it.second.second) /*Binary operator*/ + NodeID_1 = Compute_RHS((BinaryOpNode *) NodeID_1, (BinaryOpNode *) it.second.first, it.first, 1); + else if (it.second.second && !it.second.first) /*Binary operator*/ + NodeID_1 = Compute_RHS((BinaryOpNode *) it.second.second, (BinaryOpNode *) NodeID_1, it.first, 1); + else if (it.second.second && it.second.first) /*Binary operator*/ + NodeID_1 = Compute_RHS(it.second.first, it.second.second, it.first, 1); + else + NodeID_1 = Compute_RHS((UnaryOpNode *) NodeID_1, (UnaryOpNode *) it.second.first, it.first, 0); + } + } + else + List_of_Op_RHS = List_of_Op_RHS2; + } + switch (op_code) + { + case oPlus: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + { + List_of_Op_RHS.push_back(make_pair(oMinus, make_pair(datatree.AddPlus(NodeID_1, NodeID_2), (NodeID) NULL))); + return (make_pair(0, datatree.AddPlus(NodeID_1, NodeID_2))); + } + else if (is_endogenous_present_1 && is_endogenous_present_2) + return (make_pair(1, (NodeID) NULL)); + else if (!is_endogenous_present_1 && is_endogenous_present_2) + { + List_of_Op_RHS.push_back(make_pair(oMinus, make_pair(NodeID_1, (NodeID) NULL))); + return (make_pair(1, NodeID_1)); + } + else if (is_endogenous_present_1 && !is_endogenous_present_2) + { + List_of_Op_RHS.push_back(make_pair(oMinus, make_pair(NodeID_2, (NodeID) NULL))); + return (make_pair(1, NodeID_2)); + } + break; + case oMinus: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + { + List_of_Op_RHS.push_back(make_pair(oMinus, make_pair(datatree.AddMinus(NodeID_1, NodeID_2), (NodeID) NULL))); + return (make_pair(0, datatree.AddMinus(NodeID_1, NodeID_2))); + } + else if (is_endogenous_present_1 && is_endogenous_present_2) + return (make_pair(1, (NodeID) NULL)); + else if (!is_endogenous_present_1 && is_endogenous_present_2) + { + List_of_Op_RHS.push_back(make_pair(oUminus, make_pair((NodeID) NULL, (NodeID) NULL))); + List_of_Op_RHS.push_back(make_pair(oMinus, make_pair(NodeID_1, (NodeID) NULL))); + return (make_pair(1, NodeID_1)); + } + else if (is_endogenous_present_1 && !is_endogenous_present_2) + { + List_of_Op_RHS.push_back(make_pair(oPlus, make_pair(NodeID_2, (NodeID) NULL))); + return (make_pair(1, datatree.AddUMinus(NodeID_2))); + } + break; + case oTimes: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + return (make_pair(0, datatree.AddTimes(NodeID_1, NodeID_2))); + else if (!is_endogenous_present_1 && is_endogenous_present_2) + { + List_of_Op_RHS.push_back(make_pair(oDivide, make_pair(NodeID_1, (NodeID) NULL))); + return (make_pair(1, NodeID_1)); + } + else if (is_endogenous_present_1 && !is_endogenous_present_2) + { + List_of_Op_RHS.push_back(make_pair(oDivide, make_pair(NodeID_2, (NodeID) NULL))); + return (make_pair(1, NodeID_2)); + } + else + return (make_pair(1, (NodeID) NULL)); + break; + case oDivide: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + return (make_pair(0, datatree.AddDivide(NodeID_1, NodeID_2))); + else if (!is_endogenous_present_1 && is_endogenous_present_2) + { + List_of_Op_RHS.push_back(make_pair(oDivide, make_pair((NodeID) NULL, NodeID_1))); + return (make_pair(1, NodeID_1)); + } + else if (is_endogenous_present_1 && !is_endogenous_present_2) + { + List_of_Op_RHS.push_back(make_pair(oTimes, make_pair(NodeID_2, (NodeID) NULL))); + return (make_pair(1, NodeID_2)); + } + else + return (make_pair(1, (NodeID) NULL)); + break; + case oPower: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + return (make_pair(0, datatree.AddPower(NodeID_1, NodeID_2))); + else if (is_endogenous_present_1 && !is_endogenous_present_2) + { + List_of_Op_RHS.push_back(make_pair(oPower, make_pair(datatree.AddDivide(datatree.AddNumConstant("1"), NodeID_2), (NodeID) NULL))); + return (make_pair(1, (NodeID) NULL)); + } + break; + case oEqual: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + { + return (make_pair(0, + datatree.AddEqual(datatree.AddVariable(datatree.symbol_table.getName(datatree.symbol_table.getID(eEndogenous, var_endo)), 0), datatree.AddMinus(NodeID_2, NodeID_1)) + )); + } + else if (is_endogenous_present_1 && is_endogenous_present_2) + { + return (make_pair(0, + datatree.AddEqual(datatree.AddVariable(datatree.symbol_table.getName(datatree.symbol_table.getID(eEndogenous, var_endo)), 0), datatree.Zero) + )); + } + else if (!is_endogenous_present_1 && is_endogenous_present_2) + { + return (make_pair(0, + datatree.AddEqual(datatree.AddVariable(datatree.symbol_table.getName(datatree.symbol_table.getID(eEndogenous, var_endo)), 0), /*datatree.AddUMinus(NodeID_1)*/ NodeID_1) + )); + } + else if (is_endogenous_present_1 && !is_endogenous_present_2) + { + return (make_pair(0, + datatree.AddEqual(datatree.AddVariable(datatree.symbol_table.getName(datatree.symbol_table.getID(eEndogenous, var_endo)), 0), NodeID_2) + )); + } + break; + case oMax: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + return (make_pair(0, datatree.AddMax(NodeID_1, NodeID_2))); + else + return (make_pair(1, (NodeID) NULL)); + break; + case oMin: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + return (make_pair(0, datatree.AddMin(NodeID_1, NodeID_2))); + else + return (make_pair(1, (NodeID) NULL)); + break; + case oLess: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + return (make_pair(0, datatree.AddLess(NodeID_1, NodeID_2))); + else + return (make_pair(1, (NodeID) NULL)); + break; + case oGreater: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + return (make_pair(0, datatree.AddGreater(NodeID_1, NodeID_2))); + else + return (make_pair(1, (NodeID) NULL)); + break; + case oLessEqual: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + return (make_pair(0, datatree.AddLessEqual(NodeID_1, NodeID_2))); + else + return (make_pair(1, (NodeID) NULL)); + break; + case oGreaterEqual: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + return (make_pair(0, datatree.AddGreaterEqual(NodeID_1, NodeID_2))); + else + return (make_pair(1, (NodeID) NULL)); + break; + case oEqualEqual: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + return (make_pair(0, datatree.AddEqualEqual(NodeID_1, NodeID_2))); + else + return (make_pair(1, (NodeID) NULL)); + break; + case oDifferent: + if (!is_endogenous_present_1 && !is_endogenous_present_2) + return (make_pair(0, datatree.AddDifferent(NodeID_1, NodeID_2))); + else + return (make_pair(1, (NodeID) NULL)); break; } - return((NodeID)NULL); + // Suppress GCC warning + exit(EXIT_FAILURE); } -pair<int, NodeID> -BinaryOpNode::normalizeEquation(int var_endo, vector<pair<int, pair<NodeID, NodeID> > > &List_of_Op_RHS) const - { - vector<pair<int, pair<NodeID, NodeID> > > List_of_Op_RHS1, List_of_Op_RHS2; - int is_endogenous_present_1, is_endogenous_present_2; - pair<int, NodeID> res; - NodeID NodeID_1, NodeID_2; - res = arg1->normalizeEquation(var_endo, List_of_Op_RHS1); - is_endogenous_present_1 = res.first; - NodeID_1 = res.second; - - res = arg2->normalizeEquation(var_endo, List_of_Op_RHS2); - is_endogenous_present_2 = res.first; - NodeID_2 = res.second; - if(is_endogenous_present_1==2 || is_endogenous_present_2==2) - return(make_pair(2,(NodeID)NULL)); - else if(is_endogenous_present_1 && is_endogenous_present_2) - return(make_pair(2,(NodeID)NULL)); - else if(is_endogenous_present_1) - { - if(op_code==oEqual) - { - pair<int, pair<NodeID, NodeID> > it; - int oo=List_of_Op_RHS1.size(); - for(int i=0;i<oo;i++) - { - it = List_of_Op_RHS1.back(); - List_of_Op_RHS1.pop_back(); - if(it.second.first && !it.second.second) /*Binary operator*/ - NodeID_2 = Compute_RHS(NodeID_2, (BinaryOpNode*)it.second.first, it.first, 1); - else if(it.second.second && !it.second.first) /*Binary operator*/ - NodeID_2 = Compute_RHS(it.second.second, NodeID_2, it.first, 1); - else if(it.second.second && it.second.first) /*Binary operator*/ - NodeID_2 = Compute_RHS(it.second.first, it.second.second, it.first, 1); - else /*Unary operator*/ - NodeID_2 = Compute_RHS((UnaryOpNode*)NodeID_2, (UnaryOpNode*)it.second.first, it.first, 0); - } - } - else - List_of_Op_RHS = List_of_Op_RHS1; - } - else if(is_endogenous_present_2) - { - if(op_code==oEqual) - { - int oo=List_of_Op_RHS2.size(); - for(int i=0;i<oo;i++) - { - pair<int, pair<NodeID, NodeID> > it; - it = List_of_Op_RHS2.back(); - List_of_Op_RHS2.pop_back(); - if(it.second.first && !it.second.second) /*Binary operator*/ - NodeID_1 = Compute_RHS((BinaryOpNode*)NodeID_1, (BinaryOpNode*)it.second.first, it.first, 1); - else if(it.second.second && !it.second.first) /*Binary operator*/ - NodeID_1 = Compute_RHS((BinaryOpNode*)it.second.second, (BinaryOpNode*)NodeID_1, it.first, 1); - else if(it.second.second && it.second.first) /*Binary operator*/ - NodeID_1 = Compute_RHS(it.second.first, it.second.second, it.first, 1); - else - NodeID_1 = Compute_RHS((UnaryOpNode*)NodeID_1, (UnaryOpNode*)it.second.first, it.first, 0); - } - } - else - List_of_Op_RHS =List_of_Op_RHS2; - } - switch (op_code) - { - case oPlus: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - { - List_of_Op_RHS.push_back(make_pair(oMinus, make_pair(datatree.AddPlus(NodeID_1, NodeID_2), (NodeID)NULL))); - return(make_pair(0, datatree.AddPlus(NodeID_1, NodeID_2))); - } - else if (is_endogenous_present_1 && is_endogenous_present_2) - return(make_pair(1, (NodeID)NULL)); - else if (!is_endogenous_present_1 && is_endogenous_present_2) - { - List_of_Op_RHS.push_back(make_pair(oMinus, make_pair(NodeID_1, (NodeID)NULL))); - return(make_pair(1, NodeID_1)); - } - else if (is_endogenous_present_1 && !is_endogenous_present_2) - { - List_of_Op_RHS.push_back(make_pair(oMinus, make_pair(NodeID_2, (NodeID)NULL) )); - return(make_pair(1, NodeID_2)); - } - break; - case oMinus: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - { - List_of_Op_RHS.push_back(make_pair(oMinus, make_pair(datatree.AddMinus(NodeID_1, NodeID_2), (NodeID)NULL) )); - return(make_pair(0, datatree.AddMinus(NodeID_1, NodeID_2))); - } - else if (is_endogenous_present_1 && is_endogenous_present_2) - return(make_pair(1, (NodeID)NULL)); - else if (!is_endogenous_present_1 && is_endogenous_present_2) - { - List_of_Op_RHS.push_back(make_pair(oUminus, make_pair((NodeID)NULL, (NodeID)NULL))); - List_of_Op_RHS.push_back(make_pair(oMinus, make_pair(NodeID_1, (NodeID)NULL) )); - return(make_pair(1, NodeID_1)); - } - else if (is_endogenous_present_1 && !is_endogenous_present_2) - { - List_of_Op_RHS.push_back(make_pair(oPlus, make_pair(NodeID_2, (NodeID) NULL) )); - return(make_pair(1, datatree.AddUMinus(NodeID_2))); - } - break; - case oTimes: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - return(make_pair(0, datatree.AddTimes(NodeID_1, NodeID_2))); - else if(!is_endogenous_present_1 && is_endogenous_present_2) - { - List_of_Op_RHS.push_back(make_pair(oDivide, make_pair(NodeID_1, (NodeID)NULL) )); - return(make_pair(1, NodeID_1)); - } - else if(is_endogenous_present_1 && !is_endogenous_present_2) - { - List_of_Op_RHS.push_back(make_pair(oDivide, make_pair(NodeID_2, (NodeID)NULL) )); - return(make_pair(1, NodeID_2)); - } - else - return(make_pair(1, (NodeID)NULL)); - break; - case oDivide: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - return(make_pair(0, datatree.AddDivide(NodeID_1, NodeID_2))); - else if(!is_endogenous_present_1 && is_endogenous_present_2) - { - List_of_Op_RHS.push_back(make_pair(oDivide, make_pair((NodeID)NULL, NodeID_1) )); - return(make_pair(1, NodeID_1)); - } - else if(is_endogenous_present_1 && !is_endogenous_present_2) - { - List_of_Op_RHS.push_back(make_pair(oTimes, make_pair(NodeID_2, (NodeID)NULL) )); - return(make_pair(1, NodeID_2)); - } - else - return(make_pair(1, (NodeID)NULL)); - break; - case oPower: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - return(make_pair(0, datatree.AddPower(NodeID_1, NodeID_2))); - else if(is_endogenous_present_1 && !is_endogenous_present_2) - { - List_of_Op_RHS.push_back(make_pair(oPower, make_pair(datatree.AddDivide( datatree.AddNumConstant("1"), NodeID_2), (NodeID)NULL) )); - return(make_pair(1, (NodeID)NULL)); - } - break; - case oEqual: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - { - return( make_pair(0, - datatree.AddEqual(datatree.AddVariable(datatree.symbol_table.getName(datatree.symbol_table.getID(eEndogenous, var_endo)), 0), datatree.AddMinus(NodeID_2, NodeID_1)) - )); - } - else if (is_endogenous_present_1 && is_endogenous_present_2) - { - return(make_pair(0, - datatree.AddEqual(datatree.AddVariable(datatree.symbol_table.getName(datatree.symbol_table.getID(eEndogenous, var_endo)), 0), datatree.Zero) - )); - } - else if (!is_endogenous_present_1 && is_endogenous_present_2) - { - return(make_pair(0, - datatree.AddEqual(datatree.AddVariable(datatree.symbol_table.getName(datatree.symbol_table.getID(eEndogenous, var_endo)), 0), /*datatree.AddUMinus(NodeID_1)*/NodeID_1) - )); - } - else if (is_endogenous_present_1 && !is_endogenous_present_2) - { - return(make_pair(0, - datatree.AddEqual(datatree.AddVariable(datatree.symbol_table.getName(datatree.symbol_table.getID(eEndogenous, var_endo)), 0), NodeID_2) - )); - } - break; - case oMax: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - return(make_pair(0, datatree.AddMax(NodeID_1, NodeID_2) )); - else - return(make_pair(1, (NodeID)NULL )); - break; - case oMin: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - return(make_pair(0, datatree.AddMin(NodeID_1, NodeID_2) )); - else - return(make_pair(1, (NodeID)NULL )); - break; - case oLess: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - return(make_pair(0, datatree.AddLess(NodeID_1, NodeID_2) )); - else - return(make_pair(1, (NodeID)NULL )); - break; - case oGreater: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - return(make_pair(0, datatree.AddGreater(NodeID_1, NodeID_2) )); - else - return(make_pair(1, (NodeID)NULL )); - break; - case oLessEqual: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - return(make_pair(0, datatree.AddLessEqual(NodeID_1, NodeID_2) )); - else - return(make_pair(1, (NodeID)NULL )); - break; - case oGreaterEqual: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - return(make_pair(0, datatree.AddGreaterEqual(NodeID_1, NodeID_2) )); - else - return(make_pair(1, (NodeID)NULL )); - break; - case oEqualEqual: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - return(make_pair(0, datatree.AddEqualEqual(NodeID_1, NodeID_2) )); - else - return(make_pair(1, (NodeID)NULL )); - break; - case oDifferent: - if (!is_endogenous_present_1 && !is_endogenous_present_2) - return(make_pair(0, datatree.AddDifferent(NodeID_1, NodeID_2) )); - else - return(make_pair(1, (NodeID)NULL )); - break; - } - // Suppress GCC warning - exit(EXIT_FAILURE); - } - - NodeID BinaryOpNode::getChainRuleDerivative(int deriv_id, const map<int, NodeID> &recursive_variables) { @@ -2635,7 +2627,7 @@ BinaryOpNode::substituteEndoLeadGreaterThanTwo(subst_table_t &subst_table, vecto if (maxendolead1 < 2 && maxendolead2 < 2) return const_cast<BinaryOpNode *>(this); - switch(op_code) + switch (op_code) { case oPlus: case oMinus: @@ -2679,7 +2671,7 @@ BinaryOpNode::substituteExoLead(subst_table_t &subst_table, vector<BinaryOpNode if (maxexolead1 < 1 && maxexolead2 < 1) return const_cast<BinaryOpNode *>(this); - switch(op_code) + switch (op_code) { case oPlus: case oMinus: @@ -2724,11 +2716,11 @@ BinaryOpNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOpN TrinaryOpNode::TrinaryOpNode(DataTree &datatree_arg, const NodeID arg1_arg, TrinaryOpcode op_code_arg, const NodeID arg2_arg, const NodeID arg3_arg) : - ExprNode(datatree_arg), - arg1(arg1_arg), - arg2(arg2_arg), - arg3(arg3_arg), - op_code(op_code_arg) + ExprNode(datatree_arg), + arg1(arg1_arg), + arg2(arg2_arg), + arg3(arg3_arg), + op_code(op_code_arg) { datatree.trinary_op_node_map[make_pair(make_pair(make_pair(arg1, arg2), arg3), op_code)] = this; } @@ -2774,11 +2766,11 @@ TrinaryOpNode::composeDerivatives(NodeID darg1, NodeID darg2, NodeID darg3) // sqrt(2*pi) t14 = datatree.AddSqrt(datatree.AddTimes(datatree.Two, datatree.Pi)); // x - mu - t12 = datatree.AddMinus(arg1,arg2); + t12 = datatree.AddMinus(arg1, arg2); // y = (x-mu)/sigma - y = datatree.AddDivide(t12,arg3); + y = datatree.AddDivide(t12, arg3); // (x-mu)^2/sigma^2 - t12 = datatree.AddTimes(y,y); + t12 = datatree.AddTimes(y, y); // -(x-mu)^2/sigma^2 t13 = datatree.AddUMinus(t12); // -((x-mu)^2/sigma^2)/2 @@ -2787,18 +2779,18 @@ TrinaryOpNode::composeDerivatives(NodeID darg1, NodeID darg2, NodeID darg3) t13 = datatree.AddExp(t12); // derivative of a standardized normal // t15 = (1/sqrt(2*pi))*exp(-y^2/2) - t15 = datatree.AddDivide(t13,t14); + t15 = datatree.AddDivide(t13, t14); // derivatives thru x - t11 = datatree.AddDivide(darg1,arg3); + t11 = datatree.AddDivide(darg1, arg3); // derivatives thru mu - t12 = datatree.AddDivide(darg2,arg3); + t12 = datatree.AddDivide(darg2, arg3); // intermediary sum - t14 = datatree.AddMinus(t11,t12); + t14 = datatree.AddMinus(t11, t12); // derivatives thru sigma - t11 = datatree.AddDivide(y,arg3); - t12 = datatree.AddTimes(t11,darg3); + t11 = datatree.AddDivide(y, arg3); + t12 = datatree.AddTimes(t11, darg3); //intermediary sum - t11 = datatree.AddMinus(t14,t12); + t11 = datatree.AddMinus(t14, t12); // total derivative: // (darg1/sigma - darg2/sigma - darg3*(x-mu)/sigma^2) * t15 // where t15 is the derivative of a standardized normal @@ -2819,75 +2811,75 @@ TrinaryOpNode::computeDerivative(int deriv_id) int TrinaryOpNode::precedence(ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const - { - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<TrinaryOpNode *>(this)); - // A temporary term behaves as a variable - if (it != temporary_terms.end()) - return 100; +{ + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<TrinaryOpNode *>(this)); + // A temporary term behaves as a variable + if (it != temporary_terms.end()) + return 100; - switch (op_code) - { - case oNormcdf: - return 100; - } - // Suppress GCC warning - exit(EXIT_FAILURE); - } + switch (op_code) + { + case oNormcdf: + return 100; + } + // Suppress GCC warning + exit(EXIT_FAILURE); +} int TrinaryOpNode::cost(const temporary_terms_type &temporary_terms, bool is_matlab) const - { - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<TrinaryOpNode *>(this)); - // For a temporary term, the cost is null - if (it != temporary_terms.end()) - return 0; +{ + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<TrinaryOpNode *>(this)); + // For a temporary term, the cost is null + if (it != temporary_terms.end()) + return 0; - int cost = arg1->cost(temporary_terms, is_matlab); - cost += arg2->cost(temporary_terms, is_matlab); + int cost = arg1->cost(temporary_terms, is_matlab); + cost += arg2->cost(temporary_terms, is_matlab); - if (is_matlab) - // Cost for Matlab files - switch (op_code) - { - case oNormcdf: - return cost+1000; - } - else - // Cost for C files - switch (op_code) - { - case oNormcdf: - return cost+1000; - } - // Suppress GCC warning - exit(EXIT_FAILURE); - } + if (is_matlab) + // Cost for Matlab files + switch (op_code) + { + case oNormcdf: + return cost+1000; + } + else + // Cost for C files + switch (op_code) + { + case oNormcdf: + return cost+1000; + } + // Suppress GCC warning + exit(EXIT_FAILURE); +} void TrinaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms, bool is_matlab) const - { - NodeID this2 = const_cast<TrinaryOpNode *>(this); - map<NodeID, int>::iterator it = reference_count.find(this2); - if (it == reference_count.end()) - { - // If this node has never been encountered, set its ref count to one, - // and travel through its children - reference_count[this2] = 1; - arg1->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); - arg2->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); - arg3->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); - } - else - { - // If the node has already been encountered, increment its ref count - // and declare it as a temporary term if it is too costly - reference_count[this2]++; - if (reference_count[this2] * cost(temporary_terms, is_matlab) > MIN_COST(is_matlab)) - temporary_terms.insert(this2); - } - } +{ + NodeID this2 = const_cast<TrinaryOpNode *>(this); + map<NodeID, int>::iterator it = reference_count.find(this2); + if (it == reference_count.end()) + { + // If this node has never been encountered, set its ref count to one, + // and travel through its children + reference_count[this2] = 1; + arg1->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + arg2->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + arg3->computeTemporaryTerms(reference_count, temporary_terms, is_matlab); + } + else + { + // If the node has already been encountered, increment its ref count + // and declare it as a temporary term if it is too costly + reference_count[this2]++; + if (reference_count[this2] * cost(temporary_terms, is_matlab) > MIN_COST(is_matlab)) + temporary_terms.insert(this2); + } +} void TrinaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count, @@ -2896,27 +2888,27 @@ TrinaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count, int Curr_block, vector<vector<temporary_terms_type> > &v_temporary_terms, int equation) const - { - NodeID this2 = const_cast<TrinaryOpNode *>(this); - map<NodeID, int>::iterator it = reference_count.find(this2); - if (it == reference_count.end()) - { - reference_count[this2] = 1; - first_occurence[this2] = make_pair(Curr_block,equation); - arg1->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); - arg2->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); - arg3->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); - } - else - { - reference_count[this2]++; - if (reference_count[this2] * cost(temporary_terms, false) > MIN_COST_C) - { - temporary_terms.insert(this2); - v_temporary_terms[first_occurence[this2].first][first_occurence[this2].second].insert(this2); - } - } - } +{ + NodeID this2 = const_cast<TrinaryOpNode *>(this); + map<NodeID, int>::iterator it = reference_count.find(this2); + if (it == reference_count.end()) + { + reference_count[this2] = 1; + first_occurence[this2] = make_pair(Curr_block, equation); + arg1->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); + arg2->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); + arg3->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, v_temporary_terms, equation); + } + else + { + reference_count[this2]++; + if (reference_count[this2] * cost(temporary_terms, false) > MIN_COST_C) + { + temporary_terms.insert(this2); + v_temporary_terms[first_occurence[this2].first][first_occurence[this2].second].insert(this2); + } + } +} double TrinaryOpNode::eval_opcode(double v1, TrinaryOpcode op_code, double v2, double v3) throw (EvalException) @@ -2943,73 +2935,72 @@ TrinaryOpNode::eval(const eval_context_type &eval_context) const throw (EvalExce void TrinaryOpNode::compile(ostream &CompileCode, bool lhs_rhs, const temporary_terms_type &temporary_terms, map_idx_type &map_idx, bool dynamic, bool steady_dynamic) const - { - // If current node is a temporary term - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<TrinaryOpNode *>(this)); - if (it != temporary_terms.end()) - { - if(dynamic) - { - FLDT_ fldt(map_idx[idx]); - fldt.write(CompileCode); - } - else - { - FLDST_ fldst(map_idx[idx]); - fldst.write(CompileCode); - } - return; - } - arg1->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); - arg2->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); - arg3->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); - FBINARY_ fbinary(op_code); - fbinary.write(CompileCode); - } +{ + // If current node is a temporary term + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<TrinaryOpNode *>(this)); + if (it != temporary_terms.end()) + { + if (dynamic) + { + FLDT_ fldt(map_idx[idx]); + fldt.write(CompileCode); + } + else + { + FLDST_ fldst(map_idx[idx]); + fldst.write(CompileCode); + } + return; + } + arg1->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); + arg2->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); + arg3->compile(CompileCode, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic); + FBINARY_ fbinary(op_code); + fbinary.write(CompileCode); +} void TrinaryOpNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, temporary_terms_inuse_type &temporary_terms_inuse, int Curr_Block) const - { - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<TrinaryOpNode *>(this)); - if (it != temporary_terms.end()) - temporary_terms_inuse.insert(idx); - else - { - arg1->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); - arg2->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); - arg3->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); - } - } - +{ + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<TrinaryOpNode *>(this)); + if (it != temporary_terms.end()) + temporary_terms_inuse.insert(idx); + else + { + arg1->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); + arg2->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); + arg3->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block); + } +} void TrinaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const - { - // TrinaryOpNode not implemented for C output - assert(!IS_C(output_type)); +{ + // TrinaryOpNode not implemented for C output + assert(!IS_C(output_type)); - // If current node is a temporary term - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<TrinaryOpNode *>(this)); - if (it != temporary_terms.end()) - { - output << "T" << idx; - return; - } + // If current node is a temporary term + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<TrinaryOpNode *>(this)); + if (it != temporary_terms.end()) + { + output << "T" << idx; + return; + } - switch (op_code) - { - case oNormcdf: - output << "normcdf("; - break; - } - arg1->writeOutput(output, output_type, temporary_terms); - output << ","; - arg2->writeOutput(output, output_type, temporary_terms); - output << ","; - arg3->writeOutput(output, output_type, temporary_terms); - output << ")"; - } + switch (op_code) + { + case oNormcdf: + output << "normcdf("; + break; + } + arg1->writeOutput(output, output_type, temporary_terms); + output << ","; + arg2->writeOutput(output, output_type, temporary_terms); + output << ","; + arg3->writeOutput(output, output_type, temporary_terms); + output << ")"; +} void TrinaryOpNode::collectVariables(SymbolType type_arg, set<pair<int, int> > &result) const @@ -3021,21 +3012,21 @@ TrinaryOpNode::collectVariables(SymbolType type_arg, set<pair<int, int> > &resul pair<int, NodeID> TrinaryOpNode::normalizeEquation(int var_endo, vector<pair<int, pair<NodeID, NodeID> > > &List_of_Op_RHS) const - { - pair<int, NodeID> res = arg1->normalizeEquation(var_endo, List_of_Op_RHS); - bool is_endogenous_present_1 = res.first; - NodeID NodeID_1 = res.second; - res = arg2->normalizeEquation(var_endo, List_of_Op_RHS); - bool is_endogenous_present_2 = res.first; - NodeID NodeID_2 = res.second; - res = arg3->normalizeEquation(var_endo, List_of_Op_RHS); - bool is_endogenous_present_3 = res.first; - NodeID NodeID_3 = res.second; - if (!is_endogenous_present_1 && !is_endogenous_present_2 && !is_endogenous_present_3) - return(make_pair(0, datatree.AddNormcdf(NodeID_1, NodeID_2, NodeID_3) )); - else - return(make_pair(1, (NodeID)NULL )); - } +{ + pair<int, NodeID> res = arg1->normalizeEquation(var_endo, List_of_Op_RHS); + bool is_endogenous_present_1 = res.first; + NodeID NodeID_1 = res.second; + res = arg2->normalizeEquation(var_endo, List_of_Op_RHS); + bool is_endogenous_present_2 = res.first; + NodeID NodeID_2 = res.second; + res = arg3->normalizeEquation(var_endo, List_of_Op_RHS); + bool is_endogenous_present_3 = res.first; + NodeID NodeID_3 = res.second; + if (!is_endogenous_present_1 && !is_endogenous_present_2 && !is_endogenous_present_3) + return (make_pair(0, datatree.AddNormcdf(NodeID_1, NodeID_2, NodeID_3))); + else + return (make_pair(1, (NodeID) NULL)); +} NodeID TrinaryOpNode::getChainRuleDerivative(int deriv_id, const map<int, NodeID> &recursive_variables) @@ -3143,11 +3134,11 @@ TrinaryOpNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOp } UnknownFunctionNode::UnknownFunctionNode(DataTree &datatree_arg, - int symb_id_arg, - const vector<NodeID> &arguments_arg) : - ExprNode(datatree_arg), - symb_id(symb_id_arg), - arguments(arguments_arg) + int symb_id_arg, + const vector<NodeID> &arguments_arg) : + ExprNode(datatree_arg), + symb_id(symb_id_arg), + arguments(arguments_arg) { } @@ -3172,42 +3163,42 @@ UnknownFunctionNode::getChainRuleDerivative(int deriv_id, const map<int, NodeID> exit(EXIT_FAILURE); } - void UnknownFunctionNode::computeTemporaryTerms(map<NodeID, int> &reference_count, - temporary_terms_type &temporary_terms, - bool is_matlab) const - { - cerr << "UnknownFunctionNode::computeTemporaryTerms: operation impossible!" << endl; - exit(EXIT_FAILURE); - } - -void UnknownFunctionNode::writeOutput(ostream &output, ExprNodeOutputType output_type, - const temporary_terms_type &temporary_terms) const - { - output << datatree.symbol_table.getName(symb_id) << "("; - for (vector<NodeID>::const_iterator it = arguments.begin(); - it != arguments.end(); it++) - { - if (it != arguments.begin()) - output << ","; + temporary_terms_type &temporary_terms, + bool is_matlab) const +{ + cerr << "UnknownFunctionNode::computeTemporaryTerms: operation impossible!" << endl; + exit(EXIT_FAILURE); +} - (*it)->writeOutput(output, output_type, temporary_terms); - } - output << ")"; - } +void +UnknownFunctionNode::writeOutput(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_type &temporary_terms) const +{ + output << datatree.symbol_table.getName(symb_id) << "("; + for (vector<NodeID>::const_iterator it = arguments.begin(); + it != arguments.end(); it++) + { + if (it != arguments.begin()) + output << ","; + + (*it)->writeOutput(output, output_type, temporary_terms); + } + output << ")"; +} void UnknownFunctionNode::computeTemporaryTerms(map<NodeID, int> &reference_count, - temporary_terms_type &temporary_terms, - map<NodeID, pair<int, int> > &first_occurence, - int Curr_block, - vector< vector<temporary_terms_type> > &v_temporary_terms, - int equation) const - { - cerr << "UnknownFunctionNode::computeTemporaryTerms: not implemented" << endl; - exit(EXIT_FAILURE); - } + temporary_terms_type &temporary_terms, + map<NodeID, pair<int, int> > &first_occurence, + int Curr_block, + vector< vector<temporary_terms_type> > &v_temporary_terms, + int equation) const +{ + cerr << "UnknownFunctionNode::computeTemporaryTerms: not implemented" << endl; + exit(EXIT_FAILURE); +} void UnknownFunctionNode::collectVariables(SymbolType type_arg, set<pair<int, int> > &result) const @@ -3219,16 +3210,15 @@ UnknownFunctionNode::collectVariables(SymbolType type_arg, set<pair<int, int> > void UnknownFunctionNode::collectTemporary_terms(const temporary_terms_type &temporary_terms, temporary_terms_inuse_type &temporary_terms_inuse, int Curr_Block) const - { - temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnknownFunctionNode *>(this)); - if (it != temporary_terms.end()) - temporary_terms_inuse.insert(idx); - else - { - //arg->collectTemporary_terms(temporary_terms, result); - } - } - +{ + temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnknownFunctionNode *>(this)); + if (it != temporary_terms.end()) + temporary_terms_inuse.insert(idx); + else + { + //arg->collectTemporary_terms(temporary_terms, result); + } +} double UnknownFunctionNode::eval(const eval_context_type &eval_context) const throw (EvalException) @@ -3238,46 +3228,46 @@ UnknownFunctionNode::eval(const eval_context_type &eval_context) const throw (Ev void UnknownFunctionNode::compile(ostream &CompileCode, bool lhs_rhs, const temporary_terms_type &temporary_terms, map_idx_type &map_idx, bool dynamic, bool steady_dynamic) const - { - cerr << "UnknownFunctionNode::compile: operation impossible!" << endl; - exit(EXIT_FAILURE); - } +{ + cerr << "UnknownFunctionNode::compile: operation impossible!" << endl; + exit(EXIT_FAILURE); +} pair<int, NodeID> UnknownFunctionNode::normalizeEquation(int var_endo, vector<pair<int, pair<NodeID, NodeID> > > &List_of_Op_RHS) const - { - vector<pair<bool, NodeID> > V_arguments; - vector<NodeID> V_NodeID; - bool present = false; - for (vector<NodeID>::const_iterator it = arguments.begin(); - it != arguments.end(); it++) - { - V_arguments.push_back((*it)->normalizeEquation(var_endo, List_of_Op_RHS)); - present = present || V_arguments[V_arguments.size()-1].first; - V_NodeID.push_back(V_arguments[V_arguments.size()-1].second); - } - if (!present) - return(make_pair(0, datatree.AddUnknownFunction(datatree.symbol_table.getName(symb_id), V_NodeID))); - else - return(make_pair(1, (NodeID)NULL )); - } +{ + vector<pair<bool, NodeID> > V_arguments; + vector<NodeID> V_NodeID; + bool present = false; + for (vector<NodeID>::const_iterator it = arguments.begin(); + it != arguments.end(); it++) + { + V_arguments.push_back((*it)->normalizeEquation(var_endo, List_of_Op_RHS)); + present = present || V_arguments[V_arguments.size()-1].first; + V_NodeID.push_back(V_arguments[V_arguments.size()-1].second); + } + if (!present) + return (make_pair(0, datatree.AddUnknownFunction(datatree.symbol_table.getName(symb_id), V_NodeID))); + else + return (make_pair(1, (NodeID) NULL)); +} NodeID UnknownFunctionNode::toStatic(DataTree &static_datatree) const - { - vector<NodeID> static_arguments; - for (vector<NodeID>::const_iterator it = arguments.begin(); - it != arguments.end(); it++) - static_arguments.push_back((*it)->toStatic(static_datatree)); - return static_datatree.AddUnknownFunction(datatree.symbol_table.getName(symb_id), static_arguments); - } +{ + vector<NodeID> static_arguments; + for (vector<NodeID>::const_iterator it = arguments.begin(); + it != arguments.end(); it++) + static_arguments.push_back((*it)->toStatic(static_datatree)); + return static_datatree.AddUnknownFunction(datatree.symbol_table.getName(symb_id), static_arguments); +} int UnknownFunctionNode::maxEndoLead() const { int val = 0; - for(vector<NodeID>::const_iterator it = arguments.begin(); - it != arguments.end(); it++) + for (vector<NodeID>::const_iterator it = arguments.begin(); + it != arguments.end(); it++) val = max(val, (*it)->maxEndoLead()); return val; } @@ -3286,8 +3276,8 @@ int UnknownFunctionNode::maxExoLead() const { int val = 0; - for(vector<NodeID>::const_iterator it = arguments.begin(); - it != arguments.end(); it++) + for (vector<NodeID>::const_iterator it = arguments.begin(); + it != arguments.end(); it++) val = max(val, (*it)->maxExoLead()); return val; } diff --git a/ExprNode.hh b/ExprNode.hh index 358687c182249f7199bfb6236e3b74ba73e91287..4781dde9500ee6f92eab064d9c7fe72b7dcb8eed 100644 --- a/ExprNode.hh +++ b/ExprNode.hh @@ -47,7 +47,7 @@ typedef set<NodeID, ExprNodeLess> temporary_terms_type; //! set of temporary terms used in a block typedef set<int> temporary_terms_inuse_type; -typedef map<int,int> map_idx_type; +typedef map<int, int> map_idx_type; //! Type for evaluation contexts /*! The key is a symbol id. Lags are assumed to be null */ @@ -63,11 +63,11 @@ enum ExprNodeOutputType oCDynamicModel, //!< C code, dynamic model declarations oMatlabOutsideModel, //!< Matlab code, outside model block (for example in initval) oLatexStaticModel, //!< LaTeX code, static model declarations - oLatexDynamicModel, //!< LaTeX code, dynamic model declarations + oLatexDynamicModel, //!< LaTeX code, dynamic model declarations oLatexDynamicSteadyStateOperator, //!< LaTeX code, dynamic model steady state declarations - oMatlabDynamicSteadyStateOperator, //!< Matlab code, dynamic model steady state declarations - oMatlabDynamicModelSparseSteadyStateOperator, //!< Matlab code, dynamic block decomposed model steady state declarations - oMatlabDynamicModelSparseLocalTemporaryTerms //!< Matlab code, dynamic block decomposed model local temporary_terms + oMatlabDynamicSteadyStateOperator, //!< Matlab code, dynamic model steady state declarations + oMatlabDynamicModelSparseSteadyStateOperator, //!< Matlab code, dynamic block decomposed model steady state declarations + oMatlabDynamicModelSparseLocalTemporaryTerms //!< Matlab code, dynamic block decomposed model local temporary_terms }; #define IS_MATLAB(output_type) ((output_type) == oMatlabStaticModel \ @@ -76,14 +76,14 @@ enum ExprNodeOutputType || (output_type) == oMatlabStaticModelSparse \ || (output_type) == oMatlabDynamicModelSparse \ || (output_type) == oMatlabDynamicModelSparseLocalTemporaryTerms \ - || (output_type) == oMatlabDynamicSteadyStateOperator \ - || (output_type) == oMatlabDynamicModelSparseSteadyStateOperator) + || (output_type) == oMatlabDynamicSteadyStateOperator \ + || (output_type) == oMatlabDynamicModelSparseSteadyStateOperator) #define IS_C(output_type) ((output_type) == oCDynamicModel) #define IS_LATEX(output_type) ((output_type) == oLatexStaticModel \ - || (output_type) == oLatexDynamicModel \ - || (output_type) == oLatexDynamicSteadyStateOperator) + || (output_type) == oLatexDynamicModel \ + || (output_type) == oLatexDynamicSteadyStateOperator) /* Equal to 1 for Matlab langage, or to 0 for C language. Not defined for LaTeX. In Matlab, array indexes begin at 1, while they begin at 0 in C */ @@ -278,7 +278,7 @@ public: - if this expr is not in the table, then it will create an auxiliary endogenous variable, add the substitution in the table and return the substituted expression \return A new equivalent expression where sub-expressions with max endo lead >= 2 have been replaced by auxiliary variables - */ + */ virtual NodeID substituteEndoLeadGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; //! Constructs a new expression where endo variables with max endo lag >= 2 have been replaced by auxiliary variables @@ -316,7 +316,8 @@ public: //! Object used to compare two nodes (using their indexes) struct ExprNodeLess { - bool operator()(NodeID arg1, NodeID arg2) const + bool + operator()(NodeID arg1, NodeID arg2) const { return arg1->idx < arg2->idx; } @@ -332,7 +333,11 @@ private: virtual NodeID computeDerivative(int deriv_id); public: NumConstNode(DataTree &datatree_arg, int id_arg); - int get_id() const { return id; }; + int + get_id() const + { + return id; + }; virtual void prepareForDerivation(); virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const; virtual void collectVariables(SymbolType type_arg, set<pair<int, int> > &result) const; @@ -377,7 +382,11 @@ public: virtual double eval(const eval_context_type &eval_context) const throw (EvalException); virtual void compile(ostream &CompileCode, bool lhs_rhs, const temporary_terms_type &temporary_terms, map_idx_type &map_idx, bool dynamic, bool steady_dynamic) const; virtual NodeID toStatic(DataTree &static_datatree) const; - int get_symb_id() const { return symb_id; }; + int + get_symb_id() const + { + return symb_id; + }; virtual pair<int, NodeID> normalizeEquation(int symb_id_endo, vector<pair<int, pair<NodeID, NodeID> > > &List_of_Op_RHS) const; virtual NodeID getChainRuleDerivative(int deriv_id, const map<int, NodeID> &recursive_variables); virtual int maxEndoLead() const; @@ -420,9 +429,17 @@ public: virtual double eval(const eval_context_type &eval_context) const throw (EvalException); virtual void compile(ostream &CompileCode, bool lhs_rhs, const temporary_terms_type &temporary_terms, map_idx_type &map_idx, bool dynamic, bool steady_dynamic) const; //! Returns operand - NodeID get_arg() const { return(arg); }; + NodeID + get_arg() const + { + return (arg); + }; //! Returns op code - UnaryOpcode get_op_code() const { return(op_code); }; + UnaryOpcode + get_op_code() const + { + return (op_code); + }; virtual NodeID toStatic(DataTree &static_datatree) const; virtual pair<int, NodeID> normalizeEquation(int symb_id_endo, vector<pair<int, pair<NodeID, NodeID> > > &List_of_Op_RHS) const; virtual NodeID getChainRuleDerivative(int deriv_id, const map<int, NodeID> &recursive_variables); @@ -469,11 +486,23 @@ public: virtual void compile(ostream &CompileCode, bool lhs_rhs, const temporary_terms_type &temporary_terms, map_idx_type &map_idx, bool dynamic, bool steady_dynamic) const; virtual NodeID Compute_RHS(NodeID arg1, NodeID arg2, int op, int op_type) const; //! Returns first operand - NodeID get_arg1() const { return(arg1); }; + NodeID + get_arg1() const + { + return (arg1); + }; //! Returns second operand - NodeID get_arg2() const { return(arg2); }; + NodeID + get_arg2() const + { + return (arg2); + }; //! Returns op code - BinaryOpcode get_op_code() const { return(op_code); }; + BinaryOpcode + get_op_code() const + { + return (op_code); + }; virtual NodeID toStatic(DataTree &static_datatree) const; virtual pair<int, NodeID> normalizeEquation(int symb_id_endo, vector<pair<int, pair<NodeID, NodeID> > > &List_of_Op_RHS) const; virtual NodeID getChainRuleDerivative(int deriv_id, const map<int, NodeID> &recursive_variables); @@ -503,7 +532,7 @@ private: NodeID composeDerivatives(NodeID darg1, NodeID darg2, NodeID darg3); public: TrinaryOpNode(DataTree &datatree_arg, const NodeID arg1_arg, - TrinaryOpcode op_code_arg, const NodeID arg2_arg, const NodeID arg3_arg); + TrinaryOpcode op_code_arg, const NodeID arg2_arg, const NodeID arg3_arg); virtual void prepareForDerivation(); virtual int precedence(ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const; virtual void computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms, bool is_matlab) const; diff --git a/MinimumFeedbackSet.cc b/MinimumFeedbackSet.cc index d9d50ee20542afd05306198f7588c0b929667d0e..d31d5fbf62c26033d9dc32e551eb41715017ba25 100644 --- a/MinimumFeedbackSet.cc +++ b/MinimumFeedbackSet.cc @@ -22,477 +22,470 @@ #include "MinimumFeedbackSet.hh" namespace MFS +{ + void + Suppress(AdjacencyList_type::vertex_descriptor vertex_to_eliminate, AdjacencyList_type &G) { - void - Suppress(AdjacencyList_type::vertex_descriptor vertex_to_eliminate, AdjacencyList_type& G) - { - clear_vertex(vertex_to_eliminate, G); - remove_vertex(vertex_to_eliminate, G); - } - + clear_vertex(vertex_to_eliminate, G); + remove_vertex(vertex_to_eliminate, G); + } - void - Suppress(int vertex_num, AdjacencyList_type& G) - { - Suppress(vertex(vertex_num, G), G); - } + void + Suppress(int vertex_num, AdjacencyList_type &G) + { + Suppress(vertex(vertex_num, G), G); + } + void + Eliminate(AdjacencyList_type::vertex_descriptor vertex_to_eliminate, AdjacencyList_type &G) + { + if (in_degree(vertex_to_eliminate, G) > 0 && out_degree(vertex_to_eliminate, G) > 0) + { + AdjacencyList_type::in_edge_iterator it_in, in_end; + AdjacencyList_type::out_edge_iterator it_out, out_end; + for (tie(it_in, in_end) = in_edges(vertex_to_eliminate, G); it_in != in_end; ++it_in) + for (tie(it_out, out_end) = out_edges(vertex_to_eliminate, G); it_out != out_end; ++it_out) + { + AdjacencyList_type::edge_descriptor ed; + bool exist; + tie(ed, exist) = edge(source(*it_in, G), target(*it_out, G), G); + if (!exist) + add_edge(source(*it_in, G), target(*it_out, G), G); + } + } + Suppress(vertex_to_eliminate, G); + } - void - Eliminate(AdjacencyList_type::vertex_descriptor vertex_to_eliminate, AdjacencyList_type& G) - { - if (in_degree (vertex_to_eliminate, G) > 0 && out_degree (vertex_to_eliminate, G) > 0) + bool + has_cycle_dfs(AdjacencyList_type &g, AdjacencyList_type::vertex_descriptor u, color_type &color, vector<int> &circuit_stack) + { + property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, g); + color[u] = gray_color; + graph_traits<AdjacencyList_type>::out_edge_iterator vi, vi_end; + for (tie(vi, vi_end) = out_edges(u, g); vi != vi_end; ++vi) + if (color[target(*vi, g)] == white_color && has_cycle_dfs(g, target(*vi, g), color, circuit_stack)) { - AdjacencyList_type::in_edge_iterator it_in, in_end; - AdjacencyList_type::out_edge_iterator it_out, out_end; - for (tie(it_in, in_end) = in_edges(vertex_to_eliminate, G); it_in != in_end; ++it_in) - for (tie(it_out, out_end) = out_edges(vertex_to_eliminate, G); it_out != out_end; ++it_out) - { - AdjacencyList_type::edge_descriptor ed; - bool exist; - tie(ed, exist) = edge(source(*it_in, G) , target(*it_out, G), G); - if (!exist) - add_edge(source(*it_in, G) , target(*it_out, G), G); - } - } - Suppress(vertex_to_eliminate, G); - } - - - bool - has_cycle_dfs(AdjacencyList_type& g, AdjacencyList_type::vertex_descriptor u, color_type& color, vector<int> &circuit_stack) - { - property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, g); - color[u] = gray_color; - graph_traits<AdjacencyList_type>::out_edge_iterator vi, vi_end; - for (tie(vi, vi_end) = out_edges(u, g); vi != vi_end; ++vi) - if (color[target(*vi, g)] == white_color && has_cycle_dfs(g, target(*vi, g), color, circuit_stack)) - { - // cycle detected, return immediately - circuit_stack.push_back(v_index[target(*vi, g)]); - return true; - } - else if (color[target(*vi, g)] == gray_color) - { - // *vi is an ancestor! - circuit_stack.push_back(v_index[target(*vi, g)]); - return true; - } - color[u] = black_color; - return false; - } - - bool - has_cycle(vector<int> &circuit_stack, AdjacencyList_type& g) - { - // Initialize color map to white - color_type color; - graph_traits<AdjacencyList_type>::vertex_iterator vi, vi_end; - for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) - color[*vi] = white_color; - - // Perform depth-first search - for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) - if (color[*vi] == white_color && has_cycle_dfs(g, *vi, color, circuit_stack)) + // cycle detected, return immediately + circuit_stack.push_back(v_index[target(*vi, g)]); return true; - - return false; - } - - void - Print(AdjacencyList_type& G) - { - AdjacencyList_type::vertex_iterator it, it_end; - property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); - cout << "Graph\n"; - cout << "-----\n"; - for (tie(it, it_end) = vertices(G);it != it_end; ++it) - { - cout << "vertex[" << v_index[*it] + 1 << "] <-"; - AdjacencyList_type::in_edge_iterator it_in, in_end; - for (tie(it_in, in_end) = in_edges(*it, G); it_in != in_end; ++it_in) - cout << v_index[source(*it_in, G)] + 1 << " "; - cout << "\n ->"; - AdjacencyList_type::out_edge_iterator it_out, out_end; - for (tie(it_out, out_end) = out_edges(*it, G); it_out != out_end; ++it_out) - cout << v_index[target(*it_out, G)] + 1 << " "; - cout << "\n"; } - } - - - AdjacencyList_type - AM_2_AdjacencyList(bool* AM, unsigned int n) - { - AdjacencyList_type G(n); - property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); - property_map<AdjacencyList_type, vertex_index1_t>::type v_index1 = get(vertex_index1, G); - for (unsigned int i = 0;i < n;i++) + else if (color[target(*vi, g)] == gray_color) { - put(v_index, vertex(i, G), i); - put(v_index1, vertex(i, G), i); + // *vi is an ancestor! + circuit_stack.push_back(v_index[target(*vi, g)]); + return true; } - for (unsigned int i = 0;i < n;i++) - for (unsigned int j = 0;j < n;j++) - if (AM[i*n+j]) - add_edge(vertex(j, G), vertex(i, G), G); - return G; - } + color[u] = black_color; + return false; + } + bool + has_cycle(vector<int> &circuit_stack, AdjacencyList_type &g) + { + // Initialize color map to white + color_type color; + graph_traits<AdjacencyList_type>::vertex_iterator vi, vi_end; + for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) + color[*vi] = white_color; + + // Perform depth-first search + for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) + if (color[*vi] == white_color && has_cycle_dfs(g, *vi, color, circuit_stack)) + return true; + + return false; + } - void - Print(GraphvizDigraph& G) - { - GraphvizDigraph::vertex_iterator it, it_end; - property_map<GraphvizDigraph, vertex_index_t>::type v_index = get(vertex_index, G); - cout << "Graph\n"; - cout << "-----\n"; - for (tie(it, it_end) = vertices(G);it != it_end; ++it) - { - cout << "vertex[" << v_index[*it] + 1 << "] ->"; - GraphvizDigraph::out_edge_iterator it_out, out_end; - for (tie(it_out, out_end) = out_edges(*it, G); it_out != out_end; ++it_out) - cout << v_index[target(*it_out, G)] + 1 << " "; - cout << "\n"; - } - } + void + Print(AdjacencyList_type &G) + { + AdjacencyList_type::vertex_iterator it, it_end; + property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); + cout << "Graph\n"; + cout << "-----\n"; + for (tie(it, it_end) = vertices(G); it != it_end; ++it) + { + cout << "vertex[" << v_index[*it] + 1 << "] <-"; + AdjacencyList_type::in_edge_iterator it_in, in_end; + for (tie(it_in, in_end) = in_edges(*it, G); it_in != in_end; ++it_in) + cout << v_index[source(*it_in, G)] + 1 << " "; + cout << "\n ->"; + AdjacencyList_type::out_edge_iterator it_out, out_end; + for (tie(it_out, out_end) = out_edges(*it, G); it_out != out_end; ++it_out) + cout << v_index[target(*it_out, G)] + 1 << " "; + cout << "\n"; + } + } + AdjacencyList_type + AM_2_AdjacencyList(bool *AM, unsigned int n) + { + AdjacencyList_type G(n); + property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); + property_map<AdjacencyList_type, vertex_index1_t>::type v_index1 = get(vertex_index1, G); + for (unsigned int i = 0; i < n; i++) + { + put(v_index, vertex(i, G), i); + put(v_index1, vertex(i, G), i); + } + for (unsigned int i = 0; i < n; i++) + for (unsigned int j = 0; j < n; j++) + if (AM[i*n+j]) + add_edge(vertex(j, G), vertex(i, G), G); + return G; + } - GraphvizDigraph - AM_2_GraphvizDigraph(bool* AM, unsigned int n) - { - GraphvizDigraph G(n); - property_map<GraphvizDigraph, vertex_index_t>::type v_index = get(vertex_index, G); - /*for (unsigned int i = 0;i < n;i++) - cout << "v_index[" << i << "] = " << v_index[i] << "\n";*/ - //put(v_index, vertex(i, G), i); - //v_index[/*vertex(i,G)*/i]["v_index"]=i; - for (unsigned int i = 0;i < n;i++) - for (unsigned int j = 0;j < n;j++) - if (AM[i*n+j]) - add_edge(vertex(j, G), vertex(i, G), G); - return G; - } + void + Print(GraphvizDigraph &G) + { + GraphvizDigraph::vertex_iterator it, it_end; + property_map<GraphvizDigraph, vertex_index_t>::type v_index = get(vertex_index, G); + cout << "Graph\n"; + cout << "-----\n"; + for (tie(it, it_end) = vertices(G); it != it_end; ++it) + { + cout << "vertex[" << v_index[*it] + 1 << "] ->"; + GraphvizDigraph::out_edge_iterator it_out, out_end; + for (tie(it_out, out_end) = out_edges(*it, G); it_out != out_end; ++it_out) + cout << v_index[target(*it_out, G)] + 1 << " "; + cout << "\n"; + } + } + GraphvizDigraph + AM_2_GraphvizDigraph(bool *AM, unsigned int n) + { + GraphvizDigraph G(n); + property_map<GraphvizDigraph, vertex_index_t>::type v_index = get(vertex_index, G); + /*for (unsigned int i = 0;i < n;i++) + cout << "v_index[" << i << "] = " << v_index[i] << "\n";*/ + //put(v_index, vertex(i, G), i); + //v_index[/*vertex(i,G)*/i]["v_index"]=i; + for (unsigned int i = 0; i < n; i++) + for (unsigned int j = 0; j < n; j++) + if (AM[i*n+j]) + add_edge(vertex(j, G), vertex(i, G), G); + return G; + } - AdjacencyList_type - GraphvizDigraph_2_AdjacencyList(GraphvizDigraph& G1, set<int> select_index) - { - unsigned int n = select_index.size(); - AdjacencyList_type G(n); - property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); - property_map<AdjacencyList_type, vertex_index1_t>::type v_index1 = get(vertex_index1, G); - property_map<GraphvizDigraph, vertex_index_t>::type v1_index = get(vertex_index, G1); - set<int>::iterator it = select_index.begin(); - map<int,int> reverse_index; - for (unsigned int i = 0;i < n;i++, ++it) - { - reverse_index[v1_index[*it]]=i; - put(v_index, vertex(i, G), v1_index[*it]); - put(v_index1, vertex(i, G), i); - } - unsigned int i; - for (it = select_index.begin(), i = 0;i < n;i++, ++it) - { - GraphvizDigraph::out_edge_iterator it_out, out_end; - GraphvizDigraph::vertex_descriptor vi = vertex(*it, G1); - for (tie(it_out, out_end) = out_edges(vi, G1); it_out != out_end; ++it_out) - { - int ii = target(*it_out, G1); - if (select_index.find(ii) != select_index.end()) - add_edge( vertex(reverse_index[source(*it_out, G1)],G), vertex(reverse_index[target(*it_out, G1)], G), G); - } - } - return G; - } + AdjacencyList_type + GraphvizDigraph_2_AdjacencyList(GraphvizDigraph &G1, set<int> select_index) + { + unsigned int n = select_index.size(); + AdjacencyList_type G(n); + property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); + property_map<AdjacencyList_type, vertex_index1_t>::type v_index1 = get(vertex_index1, G); + property_map<GraphvizDigraph, vertex_index_t>::type v1_index = get(vertex_index, G1); + set<int>::iterator it = select_index.begin(); + map<int, int> reverse_index; + for (unsigned int i = 0; i < n; i++, ++it) + { + reverse_index[v1_index[*it]] = i; + put(v_index, vertex(i, G), v1_index[*it]); + put(v_index1, vertex(i, G), i); + } + unsigned int i; + for (it = select_index.begin(), i = 0; i < n; i++, ++it) + { + GraphvizDigraph::out_edge_iterator it_out, out_end; + GraphvizDigraph::vertex_descriptor vi = vertex(*it, G1); + for (tie(it_out, out_end) = out_edges(vi, G1); it_out != out_end; ++it_out) + { + int ii = target(*it_out, G1); + if (select_index.find(ii) != select_index.end()) + add_edge(vertex(reverse_index[source(*it_out, G1)], G), vertex(reverse_index[target(*it_out, G1)], G), G); + } + } + return G; + } - vector_vertex_descriptor - Collect_Doublet(AdjacencyList_type::vertex_descriptor vertex, AdjacencyList_type& G) - { - AdjacencyList_type::in_edge_iterator it_in, in_end; - AdjacencyList_type::out_edge_iterator it_out, out_end; - vector<AdjacencyList_type::vertex_descriptor> Doublet; - 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 - Doublet.push_back(source(*it_in, G)); - return Doublet; - } + vector_vertex_descriptor + Collect_Doublet(AdjacencyList_type::vertex_descriptor vertex, AdjacencyList_type &G) + { + AdjacencyList_type::in_edge_iterator it_in, in_end; + AdjacencyList_type::out_edge_iterator it_out, out_end; + vector<AdjacencyList_type::vertex_descriptor> Doublet; + 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 + Doublet.push_back(source(*it_in, G)); + return Doublet; + } - bool - Vertex_Belong_to_a_Clique(AdjacencyList_type::vertex_descriptor vertex, AdjacencyList_type& G) - { - vector<AdjacencyList_type::vertex_descriptor> liste; - bool agree = true; - AdjacencyList_type::in_edge_iterator it_in, in_end; - AdjacencyList_type::out_edge_iterator it_out, out_end; - tie(it_in, in_end) = in_edges(vertex, G); - tie(it_out, out_end) = out_edges(vertex, G); - while (it_in != in_end && it_out != out_end && agree) - { - agree = (source(*it_in, G) == target(*it_out, G) && source(*it_in, G) != target(*it_in, G)); //not a loop - liste.push_back(source(*it_in, G)); - ++it_in; - ++it_out; - } - if (agree) - { - if (it_in != in_end || it_out != out_end) - agree = false; - unsigned int i = 1; - while (i < liste.size() && agree) - { - unsigned int j = i + 1; - while (j < liste.size() && agree) - { - AdjacencyList_type::edge_descriptor ed; - bool exist1, exist2; - tie(ed, exist1) = edge(liste[i], liste[j] , G); - tie(ed, exist2) = edge(liste[j], liste[i] , G); - agree = (exist1 && exist2); - j++; - } - i++; - } - } - return agree; - } + bool + Vertex_Belong_to_a_Clique(AdjacencyList_type::vertex_descriptor vertex, AdjacencyList_type &G) + { + vector<AdjacencyList_type::vertex_descriptor> liste; + bool agree = true; + AdjacencyList_type::in_edge_iterator it_in, in_end; + AdjacencyList_type::out_edge_iterator it_out, out_end; + tie(it_in, in_end) = in_edges(vertex, G); + tie(it_out, out_end) = out_edges(vertex, G); + while (it_in != in_end && it_out != out_end && agree) + { + agree = (source(*it_in, G) == target(*it_out, G) && source(*it_in, G) != target(*it_in, G)); //not a loop + liste.push_back(source(*it_in, G)); + ++it_in; + ++it_out; + } + if (agree) + { + if (it_in != in_end || it_out != out_end) + agree = false; + unsigned int i = 1; + while (i < liste.size() && agree) + { + unsigned int j = i + 1; + while (j < liste.size() && agree) + { + AdjacencyList_type::edge_descriptor ed; + bool exist1, exist2; + tie(ed, exist1) = edge(liste[i], liste[j], G); + tie(ed, exist2) = edge(liste[j], liste[i], G); + agree = (exist1 && exist2); + j++; + } + i++; + } + } + return agree; + } - bool - Elimination_of_Vertex_With_One_or_Less_Indegree_or_Outdegree_Step(AdjacencyList_type& G) - { - bool something_has_been_done = false; - bool not_a_loop; - int i; - AdjacencyList_type::vertex_iterator it, it1, ita, it_end; - property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); - for (tie(it, it_end) = vertices(G), i = 0; it != it_end; ++it, i++) - { - int in_degree_n = in_degree(*it, G); - int out_degree_n = out_degree(*it, G); - if (in_degree_n <= 1 || out_degree_n <= 1) - { - not_a_loop = true; - if (in_degree_n >= 1 && out_degree_n >= 1) // Do not eliminate a vertex if it loops on itself! - { - AdjacencyList_type::in_edge_iterator it_in, in_end; - for (tie(it_in, in_end) = in_edges(*it, G); it_in != in_end; ++it_in) - if (source(*it_in, G) == target(*it_in, G)) - { + bool + Elimination_of_Vertex_With_One_or_Less_Indegree_or_Outdegree_Step(AdjacencyList_type &G) + { + bool something_has_been_done = false; + bool not_a_loop; + int i; + AdjacencyList_type::vertex_iterator it, it1, ita, it_end; + property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); + for (tie(it, it_end) = vertices(G), i = 0; it != it_end; ++it, i++) + { + int in_degree_n = in_degree(*it, G); + int out_degree_n = out_degree(*it, G); + if (in_degree_n <= 1 || out_degree_n <= 1) + { + not_a_loop = true; + if (in_degree_n >= 1 && out_degree_n >= 1) // Do not eliminate a vertex if it loops on itself! + { + AdjacencyList_type::in_edge_iterator it_in, in_end; + for (tie(it_in, in_end) = in_edges(*it, G); it_in != in_end; ++it_in) + if (source(*it_in, G) == target(*it_in, G)) + { #ifdef verbose - cout << v_index[source(*it_in, G)] << " == " << v_index[target(*it_in, G)] << "\n"; + cout << v_index[source(*it_in, G)] << " == " << v_index[target(*it_in, G)] << "\n"; #endif - not_a_loop = false; - } - } - if (not_a_loop) - { + not_a_loop = false; + } + } + if (not_a_loop) + { #ifdef verbose - property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); - cout << "->eliminate vertex[" << v_index[*it] + 1 << "]\n"; + property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); + cout << "->eliminate vertex[" << v_index[*it] + 1 << "]\n"; #endif - Eliminate(*it, G); + Eliminate(*it, G); #ifdef verbose - Print(G); + Print(G); #endif - something_has_been_done = true; - if (i > 0) - it = ita; - else - { - tie(it, it_end) = vertices(G); - i--; - } - } - } - ita = it; - } - return something_has_been_done; - } + something_has_been_done = true; + if (i > 0) + it = ita; + else + { + tie(it, it_end) = vertices(G); + i--; + } + } + } + ita = it; + } + return something_has_been_done; + } - bool - Elimination_of_Vertex_belonging_to_a_clique_Step(AdjacencyList_type& G) - { - AdjacencyList_type::vertex_iterator it, it1, ita, it_end; - bool something_has_been_done = false; - int i; - for (tie(it, it_end) = vertices(G), i = 0; it != it_end; ++it, i++) - { - if (Vertex_Belong_to_a_Clique(*it, G)) - { + bool + Elimination_of_Vertex_belonging_to_a_clique_Step(AdjacencyList_type &G) + { + AdjacencyList_type::vertex_iterator it, it1, ita, it_end; + bool something_has_been_done = false; + int i; + for (tie(it, it_end) = vertices(G), i = 0; it != it_end; ++it, i++) + { + if (Vertex_Belong_to_a_Clique(*it, G)) + { #ifdef verbose - property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); - cout << "eliminate vertex[" << v_index[*it] + 1 << "]\n"; + property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); + cout << "eliminate vertex[" << v_index[*it] + 1 << "]\n"; #endif - Eliminate(*it, G); - something_has_been_done = true; - if (i > 0) - it = ita; - else - { - tie(it, it_end) = vertices(G); - i--; - } - } - ita = it; - } - return something_has_been_done; - } + Eliminate(*it, G); + something_has_been_done = true; + if (i > 0) + it = ita; + else + { + tie(it, it_end) = vertices(G); + i--; + } + } + ita = it; + } + return something_has_been_done; + } - bool - Suppression_of_Vertex_X_if_it_loops_store_in_set_of_feedback_vertex_Step(set<int> &feed_back_vertices, AdjacencyList_type& G) - { - bool something_has_been_done = false; - AdjacencyList_type::vertex_iterator it, it_end, ita; - int i = 0; - for (tie(it, it_end) = vertices(G); it != it_end; ++it, i++) - { - AdjacencyList_type::edge_descriptor ed; - bool exist; - tie(ed, exist) = edge(*it, *it , G); - if (exist) - { + bool + Suppression_of_Vertex_X_if_it_loops_store_in_set_of_feedback_vertex_Step(set<int> &feed_back_vertices, AdjacencyList_type &G) + { + bool something_has_been_done = false; + AdjacencyList_type::vertex_iterator it, it_end, ita; + int i = 0; + for (tie(it, it_end) = vertices(G); it != it_end; ++it, i++) + { + AdjacencyList_type::edge_descriptor ed; + bool exist; + tie(ed, exist) = edge(*it, *it, G); + if (exist) + { #ifdef verbose - property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); - cout << "store v[*it] = " << v_index[*it]+1 << "\n"; + property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); + cout << "store v[*it] = " << v_index[*it]+1 << "\n"; #endif - property_map<AdjacencyList_type, vertex_index1_t>::type v_index1 = get(vertex_index1, G); - feed_back_vertices.insert(v_index1[*it] ); - /*property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); + property_map<AdjacencyList_type, vertex_index1_t>::type v_index1 = get(vertex_index1, G); + feed_back_vertices.insert(v_index1[*it]); + /*property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); feed_back_vertices.insert(v_index[*it] );*/ - Suppress(*it, G); - something_has_been_done = true; - if (i > 0) - it = ita; - else - { - tie(it, it_end) = vertices(G); - i--; - } - } - ita = it; - } - return something_has_been_done; - } - + Suppress(*it, G); + something_has_been_done = true; + if (i > 0) + it = ita; + else + { + tie(it, it_end) = vertices(G); + i--; + } + } + ita = it; + } + return something_has_been_done; + } - AdjacencyList_type - Minimal_set_of_feedback_vertex(set<int> &feed_back_vertices,const AdjacencyList_type& G1) - { - bool something_has_been_done = true; - int cut_ = 0; - feed_back_vertices.clear(); - AdjacencyList_type G(G1); - while (num_vertices(G) > 0) - { - while (something_has_been_done && num_vertices(G) > 0) - { - //Rule 1 - something_has_been_done = (Elimination_of_Vertex_With_One_or_Less_Indegree_or_Outdegree_Step(G) /*or something_has_been_done*/); + AdjacencyList_type + Minimal_set_of_feedback_vertex(set<int> &feed_back_vertices, const AdjacencyList_type &G1) + { + bool something_has_been_done = true; + int cut_ = 0; + feed_back_vertices.clear(); + AdjacencyList_type G(G1); + while (num_vertices(G) > 0) + { + while (something_has_been_done && num_vertices(G) > 0) + { + //Rule 1 + something_has_been_done = (Elimination_of_Vertex_With_One_or_Less_Indegree_or_Outdegree_Step(G) /*or something_has_been_done*/); #ifdef verbose - cout << "1 something_has_been_done=" << something_has_been_done << "\n"; + cout << "1 something_has_been_done=" << something_has_been_done << "\n"; #endif - //Rule 2 - something_has_been_done = (Elimination_of_Vertex_belonging_to_a_clique_Step(G) || something_has_been_done); + //Rule 2 + something_has_been_done = (Elimination_of_Vertex_belonging_to_a_clique_Step(G) || something_has_been_done); #ifdef verbose - cout << "2 something_has_been_done=" << something_has_been_done << "\n"; + cout << "2 something_has_been_done=" << something_has_been_done << "\n"; #endif - //Rule 3 - something_has_been_done = (Suppression_of_Vertex_X_if_it_loops_store_in_set_of_feedback_vertex_Step(feed_back_vertices, G) || something_has_been_done); + //Rule 3 + something_has_been_done = (Suppression_of_Vertex_X_if_it_loops_store_in_set_of_feedback_vertex_Step(feed_back_vertices, G) || something_has_been_done); #ifdef verbose - cout << "3 something_has_been_done=" << something_has_been_done << "\n"; + cout << "3 something_has_been_done=" << something_has_been_done << "\n"; #endif - } - vector<int> circuit; - if (!has_cycle(circuit, G)) - { + } + vector<int> circuit; + if (!has_cycle(circuit, G)) + { #ifdef verbose - cout << "has_cycle=false\n"; + cout << "has_cycle=false\n"; #endif - //sort(feed_back_vertices.begin(), feed_back_vertices.end()); - return G; - } - if (num_vertices(G) > 0) - { - /*if nothing has been done in the five previous rule then cut the vertex with the maximum in_degree+out_degree*/ - unsigned int max_degree = 0, num = 0; - AdjacencyList_type::vertex_iterator it, it_end, max_degree_index; - for (tie(it, it_end) = vertices(G);it != it_end; ++it, num++) - { - if (in_degree(*it, G) + out_degree(*it, G) > max_degree) - { - max_degree = in_degree(*it, G) + out_degree(*it, G); - max_degree_index = it; - } - } - property_map<AdjacencyList_type, vertex_index1_t>::type v_index1 = get(vertex_index1, G); - feed_back_vertices.insert(v_index1[*max_degree_index]); - /*property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); + //sort(feed_back_vertices.begin(), feed_back_vertices.end()); + return G; + } + if (num_vertices(G) > 0) + { + /*if nothing has been done in the five previous rule then cut the vertex with the maximum in_degree+out_degree*/ + unsigned int max_degree = 0, num = 0; + AdjacencyList_type::vertex_iterator it, it_end, max_degree_index; + for (tie(it, it_end) = vertices(G); it != it_end; ++it, num++) + { + if (in_degree(*it, G) + out_degree(*it, G) > max_degree) + { + max_degree = in_degree(*it, G) + out_degree(*it, G); + max_degree_index = it; + } + } + property_map<AdjacencyList_type, vertex_index1_t>::type v_index1 = get(vertex_index1, G); + feed_back_vertices.insert(v_index1[*max_degree_index]); + /*property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); feed_back_vertices.insert(v_index[*max_degree_index]);*/ - //cout << "v_index1[*max_degree_index] = " << v_index1[*max_degree_index] << "\n"; - cut_++; + //cout << "v_index1[*max_degree_index] = " << v_index1[*max_degree_index] << "\n"; + cut_++; #ifdef verbose - property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); - cout << "--> cut vertex " << v_index[*max_degree_index] + 1 << "\n"; + property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); + cout << "--> cut vertex " << v_index[*max_degree_index] + 1 << "\n"; #endif - Suppress(*max_degree_index, G); - something_has_been_done = true; - } - } + Suppress(*max_degree_index, G); + something_has_been_done = true; + } + } #ifdef verbose - cout << "cut_=" << cut_ << "\n"; + cout << "cut_=" << cut_ << "\n"; #endif - //sort(feed_back_vertices.begin(), feed_back_vertices.end()); - return G; + //sort(feed_back_vertices.begin(), feed_back_vertices.end()); + return G; + } + + struct rev + { + bool + operator()(const int a, const int b) const + { + return (a > b); } + }; - struct rev + void + Reorder_the_recursive_variables(const AdjacencyList_type &G1, set<int> &feedback_vertices, vector< int> &Reordered_Vertices) + { + AdjacencyList_type G(G1); + property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); + set<int>::iterator its, ita; + set<int, rev> fv; + for (its = feedback_vertices.begin(); its != feedback_vertices.end(); its++) + fv.insert(*its); + int i = 0; + for (its = fv.begin(); its != fv.end(); ++its, i++) + Suppress(*its, G); + bool something_has_been_done = true; + while (something_has_been_done) { - bool operator()(const int a, const int b) const + something_has_been_done = false; + AdjacencyList_type::vertex_iterator it, it_end, ita; + for (tie(it, it_end) = vertices(G), i = 0; it != it_end; ++it, i++) { - return (a>b); + if (in_degree(*it, G) == 0) + { + Reordered_Vertices.push_back(v_index[*it]); + Suppress(*it, G); + something_has_been_done = true; + if (i > 0) + it = ita; + else + { + tie(it, it_end) = vertices(G); + i--; + } + } + ita = it; } - }; - - void - Reorder_the_recursive_variables(const AdjacencyList_type& G1, set<int> &feedback_vertices, vector< int> &Reordered_Vertices) - { - AdjacencyList_type G(G1); - property_map<AdjacencyList_type, vertex_index_t>::type v_index = get(vertex_index, G); - set<int>::iterator its, ita; - set<int, rev> fv; - for (its = feedback_vertices.begin(); its != feedback_vertices.end(); its++) - fv.insert(*its); - int i=0; - for (its = fv.begin(); its != fv.end(); ++its, i++) - Suppress(*its, G); - bool something_has_been_done = true; - while (something_has_been_done) - { - something_has_been_done = false; - AdjacencyList_type::vertex_iterator it, it_end, ita; - for (tie(it, it_end) = vertices(G), i = 0; it != it_end; ++it, i++) - { - if (in_degree(*it, G) == 0) - { - Reordered_Vertices.push_back(v_index[*it]); - Suppress(*it, G); - something_has_been_done = true; - if (i > 0) - it = ita; - else - { - tie(it, it_end) = vertices(G); - i--; - } - } - ita = it; - } - } - if (num_vertices(G)) - cout << "Error in the computation of feedback vertex set\n"; - } + } + if (num_vertices(G)) + cout << "Error in the computation of feedback vertex set\n"; } +} diff --git a/MinimumFeedbackSet.hh b/MinimumFeedbackSet.hh index bac12b38edc3e21bdcca9c1d2b5f49d6a4302882..9801c0643a8795c91f2082fa01f28d8856ad7122 100644 --- a/MinimumFeedbackSet.hh +++ b/MinimumFeedbackSet.hh @@ -31,49 +31,49 @@ using namespace boost; namespace MFS { typedef property<vertex_index_t, int, - property<vertex_index1_t, int, - property<vertex_degree_t, int, - property<vertex_in_degree_t, int, - property<vertex_out_degree_t, int > > > > > VertexProperty; + property<vertex_index1_t, int, + property<vertex_degree_t, int, + property<vertex_in_degree_t, int, + property<vertex_out_degree_t, int > > > > > VertexProperty; typedef adjacency_list<listS, listS, bidirectionalS, VertexProperty> AdjacencyList_type; - typedef map<graph_traits<AdjacencyList_type>::vertex_descriptor,default_color_type> color_type; + typedef map<graph_traits<AdjacencyList_type>::vertex_descriptor, default_color_type> color_type; typedef vector<AdjacencyList_type::vertex_descriptor> vector_vertex_descriptor; //! Eliminate a vertex i /*! For a vertex i replace all edges e_k_i and e_i_j by a shorcut e_k_j and then Suppress the vertex i*/ - void Eliminate(AdjacencyList_type::vertex_descriptor vertex_to_eliminate, AdjacencyList_type& G); + void Eliminate(AdjacencyList_type::vertex_descriptor vertex_to_eliminate, AdjacencyList_type &G); //! Collect all doublets (edges e_i_k such that there is an edge e_k_i with k!=i in the graph) /*! Returns the vector of doublets */ - vector_vertex_descriptor Collect_Doublet(AdjacencyList_type::vertex_descriptor vertex, AdjacencyList_type& G); + vector_vertex_descriptor Collect_Doublet(AdjacencyList_type::vertex_descriptor vertex, AdjacencyList_type &G); //! Detect all the clique (all vertex in a clique are related to each other) in the graph - bool Vertex_Belong_to_a_Clique(AdjacencyList_type::vertex_descriptor vertex, AdjacencyList_type& G); + bool Vertex_Belong_to_a_Clique(AdjacencyList_type::vertex_descriptor vertex, AdjacencyList_type &G); //! Graph reduction: eliminating purely intermediate variables or variables outside of any circuit - bool Elimination_of_Vertex_With_One_or_Less_Indegree_or_Outdegree_Step(AdjacencyList_type& G); + bool Elimination_of_Vertex_With_One_or_Less_Indegree_or_Outdegree_Step(AdjacencyList_type &G); //! Graph reduction: elimination of a vertex inside a clique - bool Elimination_of_Vertex_belonging_to_a_clique_Step(AdjacencyList_type& G); + bool Elimination_of_Vertex_belonging_to_a_clique_Step(AdjacencyList_type &G); //! A vertex belong to the feedback vertex set if the vertex loops on itself. /*! We have to suppress this vertex and store it into the feedback set.*/ - bool Suppression_of_Vertex_X_if_it_loops_store_in_set_of_feedback_vertex_Step(set<int> &feed_back_vertices, AdjacencyList_type& G1); + bool Suppression_of_Vertex_X_if_it_loops_store_in_set_of_feedback_vertex_Step(set<int> &feed_back_vertices, AdjacencyList_type &G1); //! Print the Graph - void Print(GraphvizDigraph& G); - void Print(AdjacencyList_type& G); + void Print(GraphvizDigraph &G); + void Print(AdjacencyList_type &G); //! Create a GraphvizDigraph from a Adjacency Matrix (an incidence Matrix without the diagonal terms) - GraphvizDigraph AM_2_GraphvizDigraph(bool* AM, unsigned int n); + GraphvizDigraph AM_2_GraphvizDigraph(bool *AM, unsigned int n); //! Create an adjacency graph from a Adjacency Matrix (an incidence Matrix without the diagonal terms) - AdjacencyList_type AM_2_AdjacencyList(bool* AMp,unsigned int n); + AdjacencyList_type AM_2_AdjacencyList(bool *AMp, unsigned int n); //! Create an adjacency graph from a GraphvizDigraph - AdjacencyList_type GraphvizDigraph_2_AdjacencyList(GraphvizDigraph& G1, set<int> select_index); + AdjacencyList_type GraphvizDigraph_2_AdjacencyList(GraphvizDigraph &G1, set<int> select_index); //! Check if the graph contains any cycle (true if the model contains at least one cycle, false otherwise) - bool has_cycle(vector<int> &circuit_stack, AdjacencyList_type& g); - bool has_cycle_dfs(AdjacencyList_type& g, AdjacencyList_type::vertex_descriptor u, color_type& color, vector<int> &circuit_stack); + bool has_cycle(vector<int> &circuit_stack, AdjacencyList_type &g); + bool has_cycle_dfs(AdjacencyList_type &g, AdjacencyList_type::vertex_descriptor u, color_type &color, vector<int> &circuit_stack); //! Return the feedback set - AdjacencyList_type Minimal_set_of_feedback_vertex(set<int> &feed_back_vertices, const AdjacencyList_type& G); + AdjacencyList_type Minimal_set_of_feedback_vertex(set<int> &feed_back_vertices, const AdjacencyList_type &G); //! Clear all in and out edges of vertex_to_eliminate and remove vertex_to_eliminate from the graph - void Suppress(AdjacencyList_type::vertex_descriptor vertex_to_eliminate, AdjacencyList_type& G); - void Suppress(int vertex_num, AdjacencyList_type& G); + void Suppress(AdjacencyList_type::vertex_descriptor vertex_to_eliminate, AdjacencyList_type &G); + void Suppress(int vertex_num, AdjacencyList_type &G); //! Reorder the recursive variables /*! They appear first in a quasi triangular form and they are followed by the feedback variables */ - void Reorder_the_recursive_variables(const AdjacencyList_type& G1, set<int> &feedback_vertices, vector< int> &Reordered_Vertices); + void Reorder_the_recursive_variables(const AdjacencyList_type &G1, set<int> &feedback_vertices, vector< int> &Reordered_Vertices); }; #endif // _MINIMUMFEEDBACKSET_HH diff --git a/ModFile.cc b/ModFile.cc index badbad11e7b45e3a26baba094662202bb69a11da..666714e587d1893297dce58b49e90f9e99232255 100644 --- a/ModFile.cc +++ b/ModFile.cc @@ -33,8 +33,8 @@ ModFile::ModFile() : expressions_tree(symbol_table, num_constants), ModFile::~ModFile() { - for(vector<Statement *>::iterator it = statements.begin(); - it != statements.end(); it++) + for (vector<Statement *>::iterator it = statements.begin(); + it != statements.end(); it++) delete (*it); } @@ -44,7 +44,7 @@ ModFile::evalAllExpressions(bool warn_uninit) cout << "Evaluating expressions..."; // Loop over all statements, and fill global eval context if relevant - for(vector<Statement *>::const_iterator it = statements.begin(); it != statements.end(); it++) + for (vector<Statement *>::const_iterator it = statements.begin(); it != statements.end(); it++) { InitParamStatement *ips = dynamic_cast<InitParamStatement *>(*it); if (ips) @@ -65,11 +65,11 @@ ModFile::evalAllExpressions(bool warn_uninit) cout << "done" << endl; // Check if some symbols are not initialized, and give them a zero value then - for(int id = 0; id <= symbol_table.maxID(); id++) + for (int id = 0; id <= symbol_table.maxID(); id++) { SymbolType type = symbol_table.getType(id); if ((type == eEndogenous || type == eExogenous || type == eExogenousDet - || type == eParameter || type == eModelLocalVariable) + || type == eParameter || type == eModelLocalVariable) && global_eval_context.find(id) == global_eval_context.end()) { if (warn_uninit) @@ -88,8 +88,8 @@ ModFile::addStatement(Statement *st) void ModFile::checkPass() { - for(vector<Statement *>::iterator it = statements.begin(); - it != statements.end(); it++) + for (vector<Statement *>::iterator it = statements.begin(); + it != statements.end(); it++) (*it)->checkPass(mod_file_struct); // If order option has not been set, default to 2 @@ -181,7 +181,7 @@ ModFile::computingPass(bool no_tmp_terms) { // Mod file may have no equation (for example in a standalone BVAR estimation) bool dynamic_model_needed = mod_file_struct.simul_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.estimation_present || mod_file_struct.osr_present || mod_file_struct.ramsey_policy_present || mod_file_struct.identification_present; if (dynamic_model.equation_number() > 0) { @@ -210,21 +210,21 @@ ModFile::computingPass(bool no_tmp_terms) dynamic_model.computingPass(true, true, false, false, global_eval_context, no_tmp_terms, false, false); } - for(vector<Statement *>::iterator it = statements.begin(); - it != statements.end(); it++) + for (vector<Statement *>::iterator it = statements.begin(); + it != statements.end(); it++) (*it)->computingPass(); } void ModFile::writeOutputFiles(const string &basename, bool clear_all #if defined(_WIN32) || defined(__CYGWIN32__) - , bool cygwin, bool msvc + , bool cygwin, bool msvc #endif -) const + ) const { ofstream mOutputFile; bool dynamic_model_needed = mod_file_struct.simul_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.estimation_present || mod_file_struct.osr_present || mod_file_struct.ramsey_policy_present || mod_file_struct.identification_present; if (basename.size()) @@ -303,14 +303,14 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all // Some mex commands are enclosed in an eval(), because otherwise it will make Octave fail #if defined(_WIN32) || defined(__CYGWIN32__) if (msvc) - mOutputFile << " eval('mex -O LINKFLAGS=\"$LINKFLAGS /export:Dynamic\" " << basename << "_dynamic.c')" << endl; // MATLAB/Windows + Microsoft Visual C++ + mOutputFile << " eval('mex -O LINKFLAGS=\"$LINKFLAGS /export:Dynamic\" " << basename << "_dynamic.c')" << endl; // MATLAB/Windows + Microsoft Visual C++ else if (cygwin) - mOutputFile << " eval('mex -O PRELINK_CMDS1=\"echo EXPORTS > mex.def & echo mexFunction >> mex.def & echo Dynamic >> mex.def\" " << basename << "_dynamic.c')" << endl; // MATLAB/Windows + Cygwin g++ + mOutputFile << " eval('mex -O PRELINK_CMDS1=\"echo EXPORTS > mex.def & echo mexFunction >> mex.def & echo Dynamic >> mex.def\" " << basename << "_dynamic.c')" << endl; // MATLAB/Windows + Cygwin g++ else - { - cerr << "ERROR: When using the USE_DLL option, you must give either 'cygwin' or 'msvc' option to the 'dynare' command" << endl; - exit(EXIT_FAILURE); - } + { + cerr << "ERROR: When using the USE_DLL option, you must give either 'cygwin' or 'msvc' option to the 'dynare' command" << endl; + exit(EXIT_FAILURE); + } #else # ifdef __linux__ mOutputFile << " eval('mex -O LDFLAGS=''-pthread -shared -Wl,--no-undefined'' " << basename << "_dynamic.c')" << endl; // MATLAB/Linux @@ -319,8 +319,8 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all # endif #endif mOutputFile << "else" << endl - << " mex " << basename << "_dynamic.c" << endl // Octave - << "end" << endl; + << " mex " << basename << "_dynamic.c" << endl // Octave + << "end" << endl; } // Add path for block option with M-files @@ -329,7 +329,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all if (dynamic_model.equation_number() > 0) { - if(dynamic_model_needed) + if (dynamic_model_needed) dynamic_model.writeOutput(mOutputFile, basename, block, byte_code, use_dll); else dynamic_model.writeOutput(mOutputFile, basename, false, false, false); @@ -338,8 +338,8 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all } // Print statements - for(vector<Statement *>::const_iterator it = statements.begin(); - it != statements.end(); it++) + for (vector<Statement *>::const_iterator it = statements.begin(); + it != statements.end(); it++) { (*it)->writeOutput(mOutputFile, basename); @@ -372,7 +372,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all { static_model.writeStaticFile(basename, block, byte_code); - if(dynamic_model_needed) + if (dynamic_model_needed) { dynamic_model.writeDynamicFile(basename, block, byte_code, use_dll); dynamic_model.writeParamsDerivativesFile(basename); diff --git a/ModFile.hh b/ModFile.hh index bf128690849f304b1530fbfb92c47761ec7f462b..def8595ddc8d7a7b3ec87dbdd339f0935480aa5a 100644 --- a/ModFile.hh +++ b/ModFile.hh @@ -92,9 +92,9 @@ public: */ void writeOutputFiles(const string &basename, bool clear_all #if defined(_WIN32) || defined(__CYGWIN32__) - , bool cygwin, bool msvc + , bool cygwin, bool msvc #endif - ) const; + ) const; }; #endif // ! MOD_FILE_HH diff --git a/ModelTree.cc b/ModelTree.cc index 91e205828790b403659a0d5dbfe43d7e44c4c1d3..0b2853159de51a9d8820df22d081d51b413cc1bd 100644 --- a/ModelTree.cc +++ b/ModelTree.cc @@ -50,7 +50,7 @@ ModelTree::computeNormalization(const set<pair<int, int> > &endo_eqs_incidence) // Fill in the graph set<pair<int, int> > endo; - for(set<pair<int, int> >::const_iterator it = endo_eqs_incidence.begin(); it != endo_eqs_incidence.end(); it++) + for (set<pair<int, int> >::const_iterator it = endo_eqs_incidence.begin(); it != endo_eqs_incidence.end(); it++) add_edge(it->first + n, it->second, g); // Compute maximum cardinality matching @@ -64,7 +64,7 @@ ModelTree::computeNormalization(const set<pair<int, int> > &endo_eqs_incidence) multimap<int, int> natural_endo2eqs; computeNormalizedEquations(natural_endo2eqs); - for(int i = 0; i < symbol_table.endo_nbr(); i++) + for (int i = 0; i < symbol_table.endo_nbr(); i++) { if (natural_endo2eqs.count(i) == 0) continue; @@ -77,7 +77,7 @@ ModelTree::computeNormalization(const set<pair<int, int> > &endo_eqs_incidence) edmonds_augmenting_path_finder<BipartiteGraph, size_t *, property_map<BipartiteGraph, vertex_index_t>::type> augmentor(g, &mate_map[0], get(vertex_index, g)); bool not_maximum_yet = true; - while(not_maximum_yet) + while (not_maximum_yet) { not_maximum_yet = augmentor.augment_matching(); } @@ -89,7 +89,7 @@ ModelTree::computeNormalization(const set<pair<int, int> > &endo_eqs_incidence) assert(check); #ifdef DEBUG - for(int i = 0; i < n; i++) + for (int i = 0; i < n; i++) cout << "Endogenous " << symbol_table.getName(symbol_table.getID(eEndogenous, i)) << " matched with equation " << (mate_map[i]-n+1) << endl; #endif @@ -104,7 +104,7 @@ ModelTree::computeNormalization(const set<pair<int, int> > &endo_eqs_incidence) int n1 = 0, n2 = 0; - for(int i = 0; i < symbol_table.endo_nbr(); i++) + for (int i = 0; i < symbol_table.endo_nbr(); i++) { if (natural_endo2eqs.count(i) == 0) continue; @@ -128,7 +128,6 @@ ModelTree::computeNormalization(const set<pair<int, int> > &endo_eqs_incidence) throw NormalizationException(symbol_table.getID(eEndogenous, it - mate_map.begin())); } - void ModelTree::computePossiblySingularNormalization(const jacob_map &contemporaneous_jacobian, bool try_symbolic) { @@ -136,8 +135,8 @@ ModelTree::computePossiblySingularNormalization(const jacob_map &contemporaneous set<pair<int, int> > endo_eqs_incidence; - for(jacob_map::const_iterator it = contemporaneous_jacobian.begin(); - it != contemporaneous_jacobian.end(); it++) + for (jacob_map::const_iterator it = contemporaneous_jacobian.begin(); + it != contemporaneous_jacobian.end(); it++) endo_eqs_incidence.insert(make_pair(it->first.first, it->first.second)); try @@ -145,7 +144,7 @@ ModelTree::computePossiblySingularNormalization(const jacob_map &contemporaneous computeNormalization(endo_eqs_incidence); return; } - catch(NormalizationException &e) + catch (NormalizationException &e) { if (try_symbolic) cout << "Normalization failed with cutoff, trying symbolic normalization..." << endl; @@ -163,11 +162,11 @@ ModelTree::computePossiblySingularNormalization(const jacob_map &contemporaneous { endo_eqs_incidence.clear(); set<pair<int, int> > endo; - for(int i = 0; i < equation_number(); i++) + for (int i = 0; i < equation_number(); i++) { endo.clear(); equations[i]->collectEndogenous(endo); - for(set<pair<int, int> >::const_iterator it = endo.begin(); it != endo.end(); it++) + for (set<pair<int, int> >::const_iterator it = endo.begin(); it != endo.end(); it++) endo_eqs_incidence.insert(make_pair(i, it->first)); } @@ -175,7 +174,7 @@ ModelTree::computePossiblySingularNormalization(const jacob_map &contemporaneous { computeNormalization(endo_eqs_incidence); } - catch(NormalizationException &e) + catch (NormalizationException &e) { cerr << "ERROR: Could not normalize the model even with zero cutoff. Variable " << symbol_table.getName(e.symb_id) @@ -188,7 +187,7 @@ ModelTree::computePossiblySingularNormalization(const jacob_map &contemporaneous void ModelTree::computeNormalizedEquations(multimap<int, int> &endo2eqs) const { - for(int i = 0; i < equation_number(); i++) + for (int i = 0; i < equation_number(); i++) { VariableNode *lhs = dynamic_cast<VariableNode *>(equations[i]->get_arg1()); if (lhs == NULL) @@ -208,7 +207,6 @@ ModelTree::computeNormalizedEquations(multimap<int, int> &endo2eqs) const } } - void ModelTree::evaluateAndReduceJacobian(const eval_context_type &eval_context, jacob_map &contemporaneous_jacobian, jacob_map &static_jacobian, dynamic_jacob_map &dynamic_jacobian, double cutoff, bool verbose) { @@ -249,7 +247,7 @@ ModelTree::evaluateAndReduceJacobian(const eval_context_type &eval_context, jaco if (lag == 0) { nb_elements_contemparenous_Jacobian++; - contemporaneous_jacobian[make_pair(eq,var)] = val; + contemporaneous_jacobian[make_pair(eq, var)] = val; } if (static_jacobian.find(make_pair(eq, var)) != static_jacobian.end()) static_jacobian[make_pair(eq, var)] += val; @@ -261,10 +259,10 @@ ModelTree::evaluateAndReduceJacobian(const eval_context_type &eval_context, jaco } // Get rid of the elements of the Jacobian matrix below the cutoff - for(set<pair<int, int> >::const_iterator it = jacobian_elements_to_delete.begin(); it != jacobian_elements_to_delete.end(); it++) + for (set<pair<int, int> >::const_iterator it = jacobian_elements_to_delete.begin(); it != jacobian_elements_to_delete.end(); it++) first_derivatives.erase(*it); - if (jacobian_elements_to_delete.size()>0) + if (jacobian_elements_to_delete.size() > 0) { cout << jacobian_elements_to_delete.size() << " elements among " << first_derivatives.size() << " in the incidence matrices are below the cutoff (" << cutoff << ") and are discarded" << endl << "The contemporaneous incidence matrix has " << nb_elements_contemparenous_Jacobian << " elements" << endl; @@ -274,20 +272,20 @@ ModelTree::evaluateAndReduceJacobian(const eval_context_type &eval_context, jaco void ModelTree::computePrologueAndEpilogue(jacob_map &static_jacobian_arg, vector<int> &equation_reordered, vector<int> &variable_reordered, unsigned int &prologue, unsigned int &epilogue) { - vector<int> eq2endo(equation_number(),0); + vector<int> eq2endo(equation_number(), 0); equation_reordered.resize(equation_number()); variable_reordered.resize(equation_number()); bool *IM; int n = equation_number(); - IM = (bool*)calloc(n*n,sizeof(bool)); + IM = (bool *) calloc(n*n, sizeof(bool)); int i = 0; - for(vector<int>::const_iterator it=endo2eq.begin(); it != endo2eq.end(); it++, i++) + for (vector<int>::const_iterator it = endo2eq.begin(); it != endo2eq.end(); it++, i++) { eq2endo[*it] = i; equation_reordered[i] = i; variable_reordered[*it] = i; } - for (jacob_map::const_iterator it = static_jacobian_arg.begin(); it != static_jacobian_arg.end(); it ++) + for (jacob_map::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; prologue = 0; @@ -297,18 +295,18 @@ ModelTree::computePrologueAndEpilogue(jacob_map &static_jacobian_arg, vector<int { int tmp_prologue = prologue; something_has_been_done = false; - for(int i = prologue;i < n; i++) + for (int i = prologue; i < n; i++) { int nze = 0; - for(int j = tmp_prologue; j < n; j++) - if(IM[i * n + j]) + for (int j = tmp_prologue; j < n; j++) + if (IM[i * n + j]) { - nze ++; + nze++; k = j; } - if(nze == 1) + if (nze == 1) { - for(int j = 0; j < n; j++) + for (int j = 0; j < n; j++) { bool tmp_bool = IM[tmp_prologue * n + j]; IM[tmp_prologue * n + j] = IM[i * n + j]; @@ -317,7 +315,7 @@ ModelTree::computePrologueAndEpilogue(jacob_map &static_jacobian_arg, vector<int int tmp = equation_reordered[tmp_prologue]; equation_reordered[tmp_prologue] = equation_reordered[i]; equation_reordered[i] = tmp; - for(int j = 0; j < n; j++) + for (int j = 0; j < n; j++) { bool tmp_bool = IM[j * n + tmp_prologue]; IM[j * n + tmp_prologue] = IM[j * n + k]; @@ -340,18 +338,18 @@ ModelTree::computePrologueAndEpilogue(jacob_map &static_jacobian_arg, vector<int { int tmp_epilogue = epilogue; something_has_been_done = false; - for(int i = prologue;i < n - (int) epilogue; i++) + for (int i = prologue; i < n - (int) epilogue; i++) { int nze = 0; - for(int j = prologue; j < n - tmp_epilogue; j++) - if(IM[j * n + i]) + for (int j = prologue; j < n - tmp_epilogue; j++) + if (IM[j * n + i]) { - nze ++; + nze++; k = j; } - if(nze == 1) + if (nze == 1) { - for(int j = 0; j < n; j++) + for (int j = 0; j < n; j++) { bool tmp_bool = IM[(n - 1 - tmp_epilogue) * n + j]; IM[(n - 1 - tmp_epilogue) * n + j] = IM[k * n + j]; @@ -360,7 +358,7 @@ ModelTree::computePrologueAndEpilogue(jacob_map &static_jacobian_arg, vector<int int tmp = equation_reordered[n - 1 - tmp_epilogue]; equation_reordered[n - 1 - tmp_epilogue] = equation_reordered[k]; equation_reordered[k] = tmp; - for(int j = 0; j < n; j++) + for (int j = 0; j < n; j++) { bool tmp_bool = IM[j * n + n - 1 - tmp_epilogue]; IM[j * n + n - 1 - tmp_epilogue] = IM[j * n + i]; @@ -403,7 +401,7 @@ ModelTree::equationTypeDetermination(vector<BinaryOpNode *> &equations, map<pair tmp_s << "y(it_, " << Index_Var_IM[i]+1 << ")"; map<pair<int, pair<int, int> >, NodeID>::iterator derivative = first_order_endo_derivatives.find(make_pair(eq, make_pair(var, 0))); pair<bool, NodeID> res; - if(derivative != first_order_endo_derivatives.end()) + if (derivative != first_order_endo_derivatives.end()) { set<pair<int, int> > result; derivative->second->collectEndogenous(result); @@ -411,22 +409,22 @@ ModelTree::equationTypeDetermination(vector<BinaryOpNode *> &equations, map<pair //Determine whether the equation could be evaluated rather than to be solved ostringstream tt(""); derivative->second->writeOutput(tt, oMatlabDynamicModelSparse, temporary_terms); - if (tmp_output.str() == tmp_s.str() and tt.str()=="1") + if (tmp_output.str() == tmp_s.str() and tt.str() == "1") { Equation_Simulation_Type = E_EVALUATE; } else { - vector<pair<int, pair<NodeID, NodeID> > > List_of_Op_RHS; + vector<pair<int, pair<NodeID, NodeID> > > List_of_Op_RHS; res = equations[eq]->normalizeEquation(var, List_of_Op_RHS); - if(mfs==2) + if (mfs == 2) { - if(d_endo_variable == result.end() && res.second) + if (d_endo_variable == result.end() && res.second) Equation_Simulation_Type = E_EVALUATE_S; } - else if(mfs==3) + else if (mfs == 3) { - if(res.second) // The equation could be solved analytically + if (res.second) // The equation could be solved analytically Equation_Simulation_Type = E_EVALUATE_S; } } @@ -440,8 +438,8 @@ void ModelTree::getVariableLeadLagByBlock(dynamic_jacob_map &dynamic_jacobian, vector<int > &components_set, int nb_blck_sim, int prologue, int epilogue, t_lag_lead_vector &equation_lead_lag, t_lag_lead_vector &variable_lead_lag, vector<int> equation_reordered, vector<int> variable_reordered) const { int nb_endo = symbol_table.endo_nbr(); - variable_lead_lag = t_lag_lead_vector(nb_endo , make_pair(0,0)); - equation_lead_lag = t_lag_lead_vector(nb_endo , make_pair(0,0)); + variable_lead_lag = t_lag_lead_vector(nb_endo, make_pair(0, 0)); + equation_lead_lag = t_lag_lead_vector(nb_endo, make_pair(0, 0)); vector<int> variable_blck(nb_endo), equation_blck(nb_endo); for (int i = 0; i < nb_endo; i++) { @@ -450,7 +448,7 @@ ModelTree::getVariableLeadLagByBlock(dynamic_jacob_map &dynamic_jacobian, vector variable_blck[variable_reordered[i]] = i; equation_blck[equation_reordered[i]] = i; } - else if (i < (int)components_set.size() + prologue) + else if (i < (int) components_set.size() + prologue) { variable_blck[variable_reordered[i]] = components_set[i-prologue] + prologue; equation_blck[equation_reordered[i]] = components_set[i-prologue] + prologue; @@ -480,7 +478,6 @@ ModelTree::getVariableLeadLagByBlock(dynamic_jacob_map &dynamic_jacobian, vector } } - void ModelTree::computeBlockDecompositionAndFeedbackVariablesForEachBlock(jacob_map &static_jacobian, dynamic_jacob_map &dynamic_jacobian, int prologue, int epilogue, vector<int> &equation_reordered, vector<int> &variable_reordered, vector<pair<int, int> > &blocks, t_equation_type_and_normalized_equation &Equation_Type, bool verbose_, bool select_feedback_variable, int mfs, vector<int> &inv_equation_reordered, vector<int> &inv_variable_reordered) const { @@ -492,17 +489,17 @@ ModelTree::computeBlockDecompositionAndFeedbackVariablesForEachBlock(jacob_map & vector<int> reverse_equation_reordered(nb_var), reverse_variable_reordered(nb_var); - for(int i=0; i<nb_var; i++) + for (int i = 0; i < nb_var; i++) { reverse_equation_reordered[equation_reordered[i]] = i; reverse_variable_reordered[variable_reordered[i]] = i; } - for(jacob_map::const_iterator it = static_jacobian.begin(); it != static_jacobian.end(); it++) - if( reverse_equation_reordered[it->first.first]>=prologue && reverse_equation_reordered[it->first.first]<nb_var - epilogue - && reverse_variable_reordered[it->first.second]>=prologue && reverse_variable_reordered[it->first.second]<nb_var - epilogue - && it->first.first != endo2eq[it->first.second]) - add_edge(reverse_equation_reordered[it->first.first]-prologue, reverse_equation_reordered[endo2eq[it->first.second]]-prologue, G2); + for (jacob_map::const_iterator it = static_jacobian.begin(); it != static_jacobian.end(); it++) + if (reverse_equation_reordered[it->first.first] >= prologue && reverse_equation_reordered[it->first.first] < nb_var - epilogue + && reverse_variable_reordered[it->first.second] >= prologue && reverse_variable_reordered[it->first.second] < nb_var - epilogue + && it->first.first != endo2eq[it->first.second]) + add_edge(reverse_equation_reordered[it->first.first]-prologue, reverse_equation_reordered[endo2eq[it->first.second]]-prologue, G2); vector<int> endo2block(num_vertices(G2)), discover_time(num_vertices(G2)); @@ -511,13 +508,11 @@ ModelTree::computeBlockDecompositionAndFeedbackVariablesForEachBlock(jacob_map & blocks = vector<pair<int, int> >(num, make_pair(0, 0)); - // Create directed acyclic graph associated to the strongly connected components typedef adjacency_list<vecS, vecS, directedS> DirectedGraph; DirectedGraph dag(num); - - for (unsigned int i = 0;i < num_vertices(G2);i++) + for (unsigned int i = 0; i < num_vertices(G2); i++) { GraphvizDigraph::out_edge_iterator it_out, out_end; GraphvizDigraph::vertex_descriptor vi = vertex(i, G2); @@ -536,10 +531,9 @@ ModelTree::computeBlockDecompositionAndFeedbackVariablesForEachBlock(jacob_map & // Construct mapping from unordered SCC to ordered SCC vector<int> unordered2ordered(num); - for(int i = 0; i < num; i++) + for (int i = 0; i < num; i++) unordered2ordered[ordered2unordered[i]] = i; - //This vector contains for each block: // - first set = equations belonging to the block, // - second set = the feeback variables, @@ -559,7 +553,7 @@ ModelTree::computeBlockDecompositionAndFeedbackVariablesForEachBlock(jacob_map & vector<int> tmp_equation_reordered(equation_reordered), tmp_variable_reordered(variable_reordered); int order = prologue; //Add a loop on vertices which could not be normalized or vertices related to lead variables => force those vertices to belong to the feedback set - if(select_feedback_variable) + if (select_feedback_variable) { for (int i = 0; i < n; i++) if (Equation_Type[equation_reordered[i+prologue]].first == E_SOLVE @@ -608,14 +602,15 @@ ModelTree::computeBlockDecompositionAndFeedbackVariablesForEachBlock(jacob_map & } inv_equation_reordered = vector<int>(nb_var); inv_variable_reordered = vector<int>(nb_var); - for(int i = 0; i < nb_var ; i++) + for (int i = 0; i < nb_var; i++) { inv_variable_reordered[variable_reordered[i]] = i; inv_equation_reordered[equation_reordered[i]] = i; } } -void ModelTree::printBlockDecomposition(vector<pair<int, int> > blocks) +void +ModelTree::printBlockDecomposition(vector<pair<int, int> > blocks) { int largest_block = 0; int Nb_SimulBlocks = 0; @@ -636,7 +631,6 @@ void ModelTree::printBlockDecomposition(vector<pair<int, int> > blocks) } } - int Nb_RecursBlocks = Nb_TotalBlocks - Nb_SimulBlocks; cout << Nb_TotalBlocks << " block(s) found:" << endl << " " << Nb_RecursBlocks << " recursive block(s) and " << Nb_SimulBlocks << " simultaneous block(s)." << endl @@ -644,8 +638,6 @@ void ModelTree::printBlockDecomposition(vector<pair<int, int> > blocks) << " and " << Nb_feedback_variable << " feedback variable(s)." << endl; } - - t_block_type_firstequation_size_mfs ModelTree::reduceBlocksAndTypeDetermination(dynamic_jacob_map &dynamic_jacobian, int prologue, int epilogue, vector<pair<int, int> > &blocks, vector<BinaryOpNode *> &equations, t_equation_type_and_normalized_equation &Equation_Type, vector<int> &variable_reordered, vector<int> &equation_reordered) { @@ -678,7 +670,7 @@ ModelTree::reduceBlocksAndTypeDetermination(dynamic_jacob_map &dynamic_jacobian, Lag = Lead = 0; set<pair<int, int> > endo; - for(count_equ = first_count_equ; count_equ < Blck_Size+first_count_equ; count_equ++) + for (count_equ = first_count_equ; count_equ < Blck_Size+first_count_equ; count_equ++) { endo.clear(); equations[equation_reordered[count_equ]]->collectEndogenous(endo); @@ -687,7 +679,7 @@ ModelTree::reduceBlocksAndTypeDetermination(dynamic_jacob_map &dynamic_jacobian, int curr_variable = it->first; int curr_lag = it->second; vector<int>::const_iterator it = find(variable_reordered.begin()+first_count_equ, variable_reordered.begin()+(first_count_equ+Blck_Size), curr_variable); - if(it != variable_reordered.begin()+(first_count_equ+Blck_Size)) + if (it != variable_reordered.begin()+(first_count_equ+Blck_Size)) if (dynamic_jacobian.find(make_pair(curr_lag, make_pair(equation_reordered[count_equ], curr_variable))) != dynamic_jacobian.end()) { if (curr_lag > Lead) @@ -737,9 +729,9 @@ ModelTree::reduceBlocksAndTypeDetermination(dynamic_jacob_map &dynamic_jacobian, 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; block_type_size_mfs[block_type_size_mfs.size()-1] = make_pair(make_pair(c_Type, first_equation), make_pair(++c_Size, block_type_size_mfs[block_type_size_mfs.size()-1].second.second)); - if(block_lag_lead[block_type_size_mfs.size()-1].first > Lag) + if (block_lag_lead[block_type_size_mfs.size()-1].first > Lag) Lag = block_lag_lead[block_type_size_mfs.size()-1].first; - if(block_lag_lead[block_type_size_mfs.size()-1].second > Lead) + if (block_lag_lead[block_type_size_mfs.size()-1].second > Lead) Lead = block_lag_lead[block_type_size_mfs.size()-1].second; block_lag_lead[block_type_size_mfs.size()-1] = make_pair(Lag, Lead); } @@ -766,19 +758,18 @@ ModelTree::reduceBlocksAndTypeDetermination(dynamic_jacob_map &dynamic_jacobian, return (block_type_size_mfs); } - vector<bool> ModelTree::BlockLinear(t_blocks_derivatives &blocks_derivatives, vector<int> &variable_reordered) { unsigned int nb_blocks = getNbBlocks(); vector<bool> blocks_linear(nb_blocks, true); - for (unsigned int block = 0;block < nb_blocks; block++) + for (unsigned int block = 0; block < nb_blocks; block++) { BlockSimulationType simulation_type = getBlockSimulationType(block); int block_size = getBlockSize(block); t_block_derivatives_equation_variable_laglead_nodeid derivatives_block = blocks_derivatives[block]; int first_variable_position = getBlockFirstEquation(block); - if (simulation_type==SOLVE_BACKWARD_COMPLETE || simulation_type==SOLVE_FORWARD_COMPLETE) + if (simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE) { for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = derivatives_block.begin(); it != derivatives_block.end(); it++) { @@ -790,7 +781,7 @@ ModelTree::BlockLinear(t_blocks_derivatives &blocks_derivatives, vector<int> &va Id->collectEndogenous(endogenous); if (endogenous.size() > 0) { - for (int l=0;l<block_size;l++) + for (int l = 0; l < block_size; l++) { if (endogenous.find(make_pair(variable_reordered[first_variable_position+l], 0)) != endogenous.end()) { @@ -802,17 +793,17 @@ ModelTree::BlockLinear(t_blocks_derivatives &blocks_derivatives, vector<int> &va } } } - else if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE) + else if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) { for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = derivatives_block.begin(); it != derivatives_block.end(); it++) { int lag = it->second.first; - NodeID Id = it->second.second;// + NodeID Id = it->second.second; // set<pair<int, int> > endogenous; Id->collectEndogenous(endogenous); if (endogenous.size() > 0) { - for (int l=0;l<block_size;l++) + for (int l = 0; l < block_size; l++) { if (endogenous.find(make_pair(variable_reordered[first_variable_position+l], lag)) != endogenous.end()) { @@ -823,25 +814,24 @@ ModelTree::BlockLinear(t_blocks_derivatives &blocks_derivatives, vector<int> &va } } } -the_end:; + the_end: + ; } - return(blocks_linear); + return (blocks_linear); } - - ModelTree::ModelTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg) : DataTree(symbol_table_arg, num_constants_arg) { - for(int i=0; i < 3; i++) + for (int i = 0; i < 3; i++) NNZDerivatives[i] = 0; } int ModelTree::equation_number() const { - return(equations.size()); + return (equations.size()); } void @@ -859,20 +849,18 @@ ModelTree::writeDerivative(ostream &output, int eq, int symb_id, int lag, void ModelTree::computeJacobian(const set<int> &vars) { - for(set<int>::const_iterator it = vars.begin(); - it != vars.end(); it++) + for (set<int>::const_iterator it = vars.begin(); + it != vars.end(); it++) for (int eq = 0; eq < (int) equations.size(); eq++) { NodeID d1 = equations[eq]->getDerivative(*it); if (d1 == Zero) continue; first_derivatives[make_pair(eq, *it)] = d1; - ++NNZDerivatives[0]; + ++NNZDerivatives[0]; } } - - void ModelTree::computeHessian(const set<int> &vars) { @@ -884,8 +872,8 @@ ModelTree::computeHessian(const set<int> &vars) NodeID d1 = it->second; // Store only second derivatives with var2 <= var1 - for(set<int>::const_iterator it2 = vars.begin(); - it2 != vars.end(); it2++) + for (set<int>::const_iterator it2 = vars.begin(); + it2 != vars.end(); it2++) { int var2 = *it2; if (var2 > var1) @@ -895,10 +883,10 @@ ModelTree::computeHessian(const set<int> &vars) if (d2 == Zero) continue; second_derivatives[make_pair(eq, make_pair(var1, var2))] = d2; - if (var2 == var1) - ++NNZDerivatives[1]; - else - NNZDerivatives[1] += 2; + if (var2 == var1) + ++NNZDerivatives[1]; + else + NNZDerivatives[1] += 2; } } } @@ -918,8 +906,8 @@ ModelTree::computeThirdDerivatives(const set<int> &vars) NodeID d2 = it->second; // Store only third derivatives such that var3 <= var2 <= var1 - for(set<int>::const_iterator it2 = vars.begin(); - it2 != vars.end(); it2++) + for (set<int>::const_iterator it2 = vars.begin(); + it2 != vars.end(); it2++) { int var3 = *it2; if (var3 > var2) @@ -929,12 +917,12 @@ ModelTree::computeThirdDerivatives(const set<int> &vars) if (d3 == Zero) continue; third_derivatives[make_pair(eq, make_pair(var1, make_pair(var2, var3)))] = d3; - if (var3 == var2 && var2 == var1) - ++NNZDerivatives[2]; - else if (var3 == var2 || var2 == var1) - NNZDerivatives[2] += 3; - else - NNZDerivatives[2] += 6; + if (var3 == var2 && var2 == var1) + ++NNZDerivatives[2]; + else if (var3 == var2 || var2 == var1) + NNZDerivatives[2] += 3; + else + NNZDerivatives[2] += 6; } } } @@ -1027,11 +1015,11 @@ ModelTree::writeModelEquations(ostream &output, ExprNodeOutputType output_type) { vrhs = rhs->eval(eval_context_type()); } - catch(ExprNode::EvalException &e) + catch (ExprNode::EvalException &e) { } - if (vrhs!=0)// The right hand side of the equation is not empty ==> residual=lhs-rhs; + if (vrhs != 0) // The right hand side of the equation is not empty ==> residual=lhs-rhs; { output << "lhs ="; lhs->writeOutput(output, output_type, temporary_terms); @@ -1041,19 +1029,19 @@ ModelTree::writeModelEquations(ostream &output, ExprNodeOutputType output_type) rhs->writeOutput(output, output_type, temporary_terms); output << ";" << endl; - output << "residual" << LEFT_ARRAY_SUBSCRIPT(output_type) - << eq + ARRAY_SUBSCRIPT_OFFSET(output_type) - << RIGHT_ARRAY_SUBSCRIPT(output_type) + output << "residual" << LEFT_ARRAY_SUBSCRIPT(output_type) + << eq + ARRAY_SUBSCRIPT_OFFSET(output_type) + << RIGHT_ARRAY_SUBSCRIPT(output_type) << "= lhs-rhs;" << endl; } - else// The right hand side of the equation is empty ==> residual=lhs; + else // The right hand side of the equation is empty ==> residual=lhs; { - output << "residual" << LEFT_ARRAY_SUBSCRIPT(output_type) - << eq + ARRAY_SUBSCRIPT_OFFSET(output_type) - << RIGHT_ARRAY_SUBSCRIPT(output_type) - << " = "; + output << "residual" << LEFT_ARRAY_SUBSCRIPT(output_type) + << eq + ARRAY_SUBSCRIPT_OFFSET(output_type) + << RIGHT_ARRAY_SUBSCRIPT(output_type) + << " = "; lhs->writeOutput(output, output_type, temporary_terms); - output << ";" << endl; + output << ";" << endl; } } } diff --git a/ModelTree.hh b/ModelTree.hh index e20e8b9e863f8dffe07a2f8d52a3aff8703033f3..7b1d7036a399d5729d7fc147e1e09dd0f5c2c229 100644 --- a/ModelTree.hh +++ b/ModelTree.hh @@ -30,7 +30,6 @@ using namespace std; #include "DataTree.hh" - //! Vector describing equations: BlockSimulationType, if BlockSimulationType == EVALUATE_s then a NodeID on the new normalized equation typedef vector<pair<EquationType, NodeID > > t_equation_type_and_normalized_equation; @@ -38,10 +37,10 @@ typedef vector<pair<EquationType, NodeID > > t_equation_type_and_normalized_equa typedef vector<pair< int, int> > t_lag_lead_vector; //! for each block contains pair< pair<Simulation_Type, first_equation>, pair < Block_Size, Recursive_part_Size > > -typedef vector<pair< pair< BlockSimulationType, int> , pair<int, int> > > t_block_type_firstequation_size_mfs; +typedef vector<pair< pair< BlockSimulationType, int>, pair<int, int> > > t_block_type_firstequation_size_mfs; //! for a block contains derivatives pair< pair<block_equation_number, block_variable_number> , pair<lead_lag, NodeID> > -typedef vector< pair<pair<int, int> , pair< int, NodeID > > > t_block_derivatives_equation_variable_laglead_nodeid; +typedef vector< pair<pair<int, int>, pair< int, NodeID > > > t_block_derivatives_equation_variable_laglead_nodeid; //! for all blocks derivatives description typedef vector<t_block_derivatives_equation_variable_laglead_nodeid> t_blocks_derivatives; @@ -143,7 +142,9 @@ protected: public: //! A variable missing from the maximum cardinal matching int symb_id; - NormalizationException(int symb_id_arg) : symb_id(symb_id_arg) { } + NormalizationException(int symb_id_arg) : symb_id(symb_id_arg) + { + } }; //! Compute the matching between endogenous and variable using the jacobian contemporaneous_jacobian @@ -172,7 +173,6 @@ protected: //! Determine for each block if it is linear or not vector<bool> BlockLinear(t_blocks_derivatives &blocks_derivatives, vector<int> &variable_reordered); - virtual SymbolType getTypeByDerivID(int deriv_id) const throw (UnknownDerivIDException) = 0; virtual int getLagByDerivID(int deriv_id) const throw (UnknownDerivIDException) = 0; virtual int getSymbIDByDerivID(int deriv_id) const throw (UnknownDerivIDException) = 0; @@ -208,7 +208,6 @@ protected: //! Return the position of variable_number in the block number belonging to the block block_number virtual int getBlockInitialVariableID(int block_number, int variable_number) const = 0; - public: ModelTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants); //! Declare a node as an equation of the model @@ -220,73 +219,76 @@ public: //! Returns the number of equations in the model int equation_number() const; - inline static std::string c_Equation_Type(int type) - { - char c_Equation_Type[4][13]= - { - "E_UNKNOWN ", - "E_EVALUATE ", - "E_EVALUATE_S", - "E_SOLVE " - }; - return(c_Equation_Type[type]); - }; - - inline static std::string BlockType0(BlockType type) - { - switch (type) - { - case SIMULTANS: - return ("SIMULTANEOUS TIME SEPARABLE "); - break; - case PROLOGUE: - return ("PROLOGUE "); - break; - case EPILOGUE: - return ("EPILOGUE "); - break; - case SIMULTAN: - return ("SIMULTANEOUS TIME UNSEPARABLE"); - break; - default: - return ("UNKNOWN "); - break; - } - }; - - inline static std::string BlockSim(int type) - { - switch (type) - { - case EVALUATE_FORWARD: - return ("EVALUATE FORWARD "); - break; - case EVALUATE_BACKWARD: - return ("EVALUATE BACKWARD "); - break; - case SOLVE_FORWARD_SIMPLE: - return ("SOLVE FORWARD SIMPLE "); - break; - case SOLVE_BACKWARD_SIMPLE: - return ("SOLVE BACKWARD SIMPLE "); - break; - case SOLVE_TWO_BOUNDARIES_SIMPLE: - return ("SOLVE TWO BOUNDARIES SIMPLE "); - break; - case SOLVE_FORWARD_COMPLETE: - return ("SOLVE FORWARD COMPLETE "); - break; - case SOLVE_BACKWARD_COMPLETE: - return ("SOLVE BACKWARD COMPLETE "); - break; - case SOLVE_TWO_BOUNDARIES_COMPLETE: - return ("SOLVE TWO BOUNDARIES COMPLETE"); - break; - default: - return ("UNKNOWN "); - break; - } - }; + inline static std::string + c_Equation_Type(int type) + { + char c_Equation_Type[4][13] = + { + "E_UNKNOWN ", + "E_EVALUATE ", + "E_EVALUATE_S", + "E_SOLVE " + }; + return (c_Equation_Type[type]); + }; + + inline static std::string + BlockType0(BlockType type) + { + switch (type) + { + case SIMULTANS: + return ("SIMULTANEOUS TIME SEPARABLE "); + break; + case PROLOGUE: + return ("PROLOGUE "); + break; + case EPILOGUE: + return ("EPILOGUE "); + break; + case SIMULTAN: + return ("SIMULTANEOUS TIME UNSEPARABLE"); + break; + default: + return ("UNKNOWN "); + break; + } + }; + + inline static std::string + BlockSim(int type) + { + switch (type) + { + case EVALUATE_FORWARD: + return ("EVALUATE FORWARD "); + break; + case EVALUATE_BACKWARD: + return ("EVALUATE BACKWARD "); + break; + case SOLVE_FORWARD_SIMPLE: + return ("SOLVE FORWARD SIMPLE "); + break; + case SOLVE_BACKWARD_SIMPLE: + return ("SOLVE BACKWARD SIMPLE "); + break; + case SOLVE_TWO_BOUNDARIES_SIMPLE: + return ("SOLVE TWO BOUNDARIES SIMPLE "); + break; + case SOLVE_FORWARD_COMPLETE: + return ("SOLVE FORWARD COMPLETE "); + break; + case SOLVE_BACKWARD_COMPLETE: + return ("SOLVE BACKWARD COMPLETE "); + break; + case SOLVE_TWO_BOUNDARIES_COMPLETE: + return ("SOLVE TWO BOUNDARIES COMPLETE"); + break; + default: + return ("UNKNOWN "); + break; + } + }; }; #endif diff --git a/NumericalConstants.cc b/NumericalConstants.cc index e27ce1c175713ae326d9c7869a32c8d0f043f728..3d83c1fb060006965f04d44d25b473b5daa275d8 100644 --- a/NumericalConstants.cc +++ b/NumericalConstants.cc @@ -57,5 +57,5 @@ double NumericalConstants::getDouble(int ID) const { assert(ID >= 0 && ID < (int) double_vals.size()); - return(double_vals[ID]); + return (double_vals[ID]); } diff --git a/NumericalInitialization.cc b/NumericalInitialization.cc index f90b2405ddd8fe9caee568173809cf157e70ffe8..357469ead5783306eec1f17e07855ba7267c57dc 100644 --- a/NumericalInitialization.cc +++ b/NumericalInitialization.cc @@ -49,7 +49,7 @@ InitParamStatement::fillEvalContext(eval_context_type &eval_context) const { eval_context[symb_id] = param_value->eval(eval_context); } - catch(ExprNode::EvalException &e) + catch (ExprNode::EvalException &e) { // Do nothing } @@ -65,14 +65,14 @@ InitOrEndValStatement::InitOrEndValStatement(const init_values_type &init_values void InitOrEndValStatement::fillEvalContext(eval_context_type &eval_context) const { - for(init_values_type::const_iterator it = init_values.begin(); - it != init_values.end(); it++) + for (init_values_type::const_iterator it = init_values.begin(); + it != init_values.end(); it++) { try { eval_context[it->first] = (it->second)->eval(eval_context); } - catch(ExprNode::EvalException &e) + catch (ExprNode::EvalException &e) { // Do nothing } @@ -82,8 +82,8 @@ InitOrEndValStatement::fillEvalContext(eval_context_type &eval_context) const void InitOrEndValStatement::writeInitValues(ostream &output) const { - for(init_values_type::const_iterator it = init_values.begin(); - it != init_values.end(); it++) + for (init_values_type::const_iterator it = init_values.begin(); + it != init_values.end(); it++) { const int symb_id = it->first; const NodeID expression = it->second; @@ -134,14 +134,12 @@ InitValStatement::writeOutputPostInit(ostream &output) const <<"end;" << endl; } - EndValStatement::EndValStatement(const init_values_type &init_values_arg, const SymbolTable &symbol_table_arg) : InitOrEndValStatement(init_values_arg, symbol_table_arg) { } - void EndValStatement::checkPass(ModFileStructure &mod_file_struct) { @@ -179,8 +177,8 @@ HistValStatement::writeOutput(ostream &output, const string &basename) const << "% HISTVAL instructions" << endl << "%" << endl; - for(hist_values_type::const_iterator it = hist_values.begin(); - it != hist_values.end(); it++) + for (hist_values_type::const_iterator it = hist_values.begin(); + it != hist_values.end(); it++) { const int &symb_id = it->first.first; const int &lag = it->first.second; @@ -231,8 +229,8 @@ HomotopyStatement::writeOutput(ostream &output, const string &basename) const << "%" << endl << "options_.homotopy_values = [];" << endl; - for(homotopy_values_type::const_iterator it = homotopy_values.begin(); - it != homotopy_values.end(); it++) + for (homotopy_values_type::const_iterator it = homotopy_values.begin(); + it != homotopy_values.end(); it++) { const int &symb_id = it->first; const NodeID expression1 = it->second.first; @@ -277,7 +275,7 @@ LoadParamsAndSteadyStateStatement::LoadParamsAndSteadyStateStatement(const strin exit(EXIT_FAILURE); } - while(true) + while (true) { string symb_name, value; f >> symb_name >> value; @@ -289,7 +287,7 @@ LoadParamsAndSteadyStateStatement::LoadParamsAndSteadyStateStatement(const strin int symb_id = symbol_table.getID(symb_name); content[symb_id] = value; } - catch(SymbolTable::UnknownSymbolNameException &e) + catch (SymbolTable::UnknownSymbolNameException &e) { cerr << "WARNING: Unknown symbol " << symb_name << " in " << filename << endl; } @@ -299,10 +297,10 @@ LoadParamsAndSteadyStateStatement::LoadParamsAndSteadyStateStatement(const strin void LoadParamsAndSteadyStateStatement::writeOutput(ostream &output, const string &basename) const { - for(map<int, string>::const_iterator it = content.begin(); - it != content.end(); it++) + for (map<int, string>::const_iterator it = content.begin(); + it != content.end(); it++) { - switch(symbol_table.getType(it->first)) + switch (symbol_table.getType(it->first)) { case eParameter: output << "M_.params"; @@ -329,7 +327,7 @@ LoadParamsAndSteadyStateStatement::writeOutput(ostream &output, const string &ba void LoadParamsAndSteadyStateStatement::fillEvalContext(eval_context_type &eval_context) const { - for(map<int, string>::const_iterator it = content.begin(); - it != content.end(); it++) + for (map<int, string>::const_iterator it = content.begin(); + it != content.end(); it++) eval_context[it->first] = atof(it->second.c_str()); } diff --git a/ParsingDriver.cc b/ParsingDriver.cc index 72b636504996b030e8733c9c13b2ef044a5bc6c3..3c6bba6c1dcc7e5471cfc02289c35ea29b326bdb 100644 --- a/ParsingDriver.cc +++ b/ParsingDriver.cc @@ -32,7 +32,7 @@ ParsingDriver::symbol_exists_and_is_not_modfile_local_or_unknown_function(const SymbolType type = mod_file->symbol_table.getType(s); - return(type != eModFileLocalVariable && type != eUnknownFunction); + return (type != eModFileLocalVariable && type != eUnknownFunction); } void @@ -107,7 +107,7 @@ ParsingDriver::declare_symbol(string *name, SymbolType type, string *tex_name) else mod_file->symbol_table.addSymbol(*name, type, *tex_name); } - catch(SymbolTable::AlreadyDeclaredException &e) + catch (SymbolTable::AlreadyDeclaredException &e) { if (e.same_type) warning("Symbol " + *name + " declared twice."); @@ -155,7 +155,7 @@ ParsingDriver::add_predetermined_variable(string *name) mod_file->symbol_table.markPredetermined(symb_id); } - catch(SymbolTable::UnknownSymbolNameException &e) + catch (SymbolTable::UnknownSymbolNameException &e) { error("Undeclared symbol name: " + *name); } @@ -267,7 +267,6 @@ ParsingDriver::dsample(string *arg1, string *arg2) delete arg2; } - void ParsingDriver::init_param(string *name, NodeID rhs) { @@ -468,7 +467,7 @@ ParsingDriver::add_det_shock(string *var, bool conditional_forecast) vector<ShocksStatement::DetShockElement> v; - for(unsigned int i = 0; i < det_shocks_periods.size(); i++) + for (unsigned int i = 0; i < det_shocks_periods.size(); i++) { ShocksStatement::DetShockElement dse; dse.period1 = det_shocks_periods[i].first; @@ -608,8 +607,8 @@ ParsingDriver::combine_lag_and_restriction(string *lag) if (it->first.first == current_lag) error("lag " + *lag + " used more than once."); - for(map<int, vector<int> >::const_iterator it = svar_equation_restrictions.begin(); - it != svar_equation_restrictions.end(); it++ ) + for (map<int, vector<int> >::const_iterator it = svar_equation_restrictions.begin(); + it != svar_equation_restrictions.end(); it++) svar_ident_exclusion_values[make_pair(current_lag, it->first)] = it->second; svar_upper_cholesky = false; @@ -640,16 +639,15 @@ ParsingDriver::add_in_svar_restriction_symbols(string *tmp_var) check_symbol_existence(*tmp_var); int symb_id = mod_file->symbol_table.getID(*tmp_var); - for (vector<int>::const_iterator viit=svar_restriction_symbols.begin(); - viit!=svar_restriction_symbols.end(); viit++) - if (symb_id==*viit) + for (vector<int>::const_iterator viit = svar_restriction_symbols.begin(); + viit != svar_restriction_symbols.end(); viit++) + if (symb_id == *viit) error(*tmp_var + " restriction added twice."); svar_restriction_symbols.push_back(symb_id); delete tmp_var; } - void ParsingDriver::add_upper_cholesky() { @@ -673,7 +671,7 @@ ParsingDriver::do_sigma_e() { mod_file->addStatement(new SigmaeStatement(sigmae_matrix)); } - catch(SigmaeStatement::MatrixFormException &e) + catch (SigmaeStatement::MatrixFormException &e) { error("Sigma_e: matrix is neither upper triangular nor lower triangular"); } @@ -791,14 +789,16 @@ ParsingDriver::add_in_symbol_list(string *tmp_var) delete tmp_var; } -void ParsingDriver::rplot() +void +ParsingDriver::rplot() { mod_file->addStatement(new RplotStatement(symbol_list, options_list)); options_list.clear(); symbol_list.clear(); } -void ParsingDriver::stoch_simul() +void +ParsingDriver::stoch_simul() { mod_file->addStatement(new StochSimulStatement(symbol_list, options_list)); symbol_list.clear(); @@ -1124,8 +1124,8 @@ ParsingDriver::run_identification() void ParsingDriver::add_mc_filename(string *filename, string *prior) { - for(ModelComparisonStatement::filename_list_type::iterator it = filename_list.begin(); - it != filename_list.end(); it++) + for (ModelComparisonStatement::filename_list_type::iterator it = filename_list.begin(); + it != filename_list.end(); it++) if ((*it).first == *filename) error("model_comparison: filename " + *filename + " declared twice"); filename_list.push_back(make_pair(*filename, *prior)); @@ -1218,17 +1218,17 @@ ParsingDriver::svar() it0 = options_list.string_options.find("ms.coefficients"); it1 = options_list.string_options.find("ms.variances"); it2 = options_list.string_options.find("ms.constants"); - if (it0 == options_list.string_options.end() && - it1 == options_list.string_options.end() && - it2 == options_list.string_options.end()) + if (it0 == options_list.string_options.end() + && it1 == options_list.string_options.end() + && it2 == options_list.string_options.end()) error("You must pass one of 'coefficients', 'variances', or 'constants'."); - if ((it0 != options_list.string_options.end() && - it1 != options_list.string_options.end()) || - (it1 != options_list.string_options.end() && - it2 != options_list.string_options.end()) || - (it0 != options_list.string_options.end() && - it2 != options_list.string_options.end())) + if ((it0 != options_list.string_options.end() + && it1 != options_list.string_options.end()) + || (it1 != options_list.string_options.end() + && it2 != options_list.string_options.end()) + || (it0 != options_list.string_options.end() + && it2 != options_list.string_options.end())) error("You may only pass one 'coefficients', 'variances', or 'constants' option."); it0 = options_list.num_options.find("ms.chain"); @@ -1239,7 +1239,7 @@ ParsingDriver::svar() itv = options_list.vector_int_options.find("ms.equations"); if (itv != options_list.vector_int_options.end()) - for (vector<int>::const_iterator viit=itv->second.begin(); viit != itv->second.end(); viit++) + for (vector<int>::const_iterator viit = itv->second.begin(); viit != itv->second.end(); viit++) if (*viit <= 0) error("The value(s) passed to the equation option must be greater than zero."); @@ -1258,14 +1258,14 @@ ParsingDriver::markov_switching() else if (atoi(it0->second.c_str()) <= 0) error("The value passed to the chain option must be greater than zero."); - it0=options_list.num_options.find("ms.state"); - it1=options_list.num_options.find("ms.number_of_states"); - if ((it0 == options_list.num_options.end()) && - (it1 == options_list.num_options.end())) + it0 = options_list.num_options.find("ms.state"); + it1 = options_list.num_options.find("ms.number_of_states"); + if ((it0 == options_list.num_options.end()) + && (it1 == options_list.num_options.end())) error("Either a state option or a number_of_states option must be passed to the markov_switching statement."); - if ((it0 != options_list.num_options.end()) && - (it1 != options_list.num_options.end())) + if ((it0 != options_list.num_options.end()) + && (it1 != options_list.num_options.end())) error("You cannot pass both a state option and a number_of_states option to the markov_switching statement."); if (it0 != options_list.num_options.end()) @@ -1276,7 +1276,7 @@ ParsingDriver::markov_switching() if (atoi(it1->second.c_str()) <= 0) error("The value passed to the number_of_states option must be greater than zero."); - string infStr ("Inf"); + string infStr("Inf"); it0 = options_list.num_options.find("ms.duration"); if (it0 == options_list.num_options.end()) error("A duration option must be passed to the markov_switching statement."); @@ -1346,7 +1346,7 @@ ParsingDriver::declare_and_init_model_local_variable(string *name, NodeID rhs) { mod_file->symbol_table.addSymbol(*name, eModelLocalVariable); } - catch(SymbolTable::AlreadyDeclaredException &e) + catch (SymbolTable::AlreadyDeclaredException &e) { error("Local model variable " + *name + " declared twice."); } @@ -1358,15 +1358,15 @@ ParsingDriver::declare_and_init_model_local_variable(string *name, NodeID rhs) void ParsingDriver::change_type(SymbolType new_type, vector<string *> *var_list) { - for(vector<string *>::iterator it = var_list->begin(); - it != var_list->end(); it++) + for (vector<string *>::iterator it = var_list->begin(); + it != var_list->end(); it++) { int id; try { id = mod_file->symbol_table.getID(**it); } - catch(SymbolTable::UnknownSymbolNameException &e) + catch (SymbolTable::UnknownSymbolNameException &e) { error("Unknown variable " + **it); } @@ -1562,19 +1562,19 @@ ParsingDriver::add_sqrt(NodeID arg1) NodeID ParsingDriver::add_max(NodeID arg1, NodeID arg2) { - return data_tree->AddMax(arg1,arg2); + return data_tree->AddMax(arg1, arg2); } NodeID ParsingDriver::add_min(NodeID arg1, NodeID arg2) { - return data_tree->AddMin(arg1,arg2); + return data_tree->AddMin(arg1, arg2); } NodeID ParsingDriver::add_normcdf(NodeID arg1, NodeID arg2, NodeID arg3) { - return data_tree->AddNormcdf(arg1,arg2,arg3); + return data_tree->AddNormcdf(arg1, arg2, arg3); } NodeID diff --git a/ParsingDriver.hh b/ParsingDriver.hh index bd9fe763c341374b59afaaf9949ec63a301a4cbb..f4ed5fb807ff702dfcea38e884bc1b95b3d9edc1 100644 --- a/ParsingDriver.hh +++ b/ParsingDriver.hh @@ -50,7 +50,6 @@ using namespace std; # undef yyFlexLexer #endif - //! The lexer class /*! Actually it was necessary to subclass the DynareFlexLexer class generated by Flex, since the prototype for DynareFlexLexer::yylex() was not convenient. @@ -58,7 +57,7 @@ using namespace std; class DynareFlex : public DynareFlexLexer { public: - DynareFlex(istream* in = 0, ostream* out = 0); + DynareFlex(istream *in = 0, ostream *out = 0); //! The main lexing function Dynare::parser::token_type lex(Dynare::parser::semantic_type *yylval, @@ -210,7 +209,7 @@ public: //! Changes type of a symbol void change_type(SymbolType new_type, vector<string *> *var_list); //! Adds a list of tags for the current equation - void add_equation_tags(string *key, string *value); + void add_equation_tags(string *key, string *value); //! Adds a constant to DataTree NodeID add_constant(string *constant); //! Adds a NaN constant to DataTree diff --git a/Shocks.cc b/Shocks.cc index 79e19de7e8141e918ab9258ddbb4376a345b785f..509c315da086db3dca00cec11483c468d3499b20 100644 --- a/Shocks.cc +++ b/Shocks.cc @@ -39,8 +39,8 @@ AbstractShocksStatement::writeDetShocks(ostream &output) const { int exo_det_length = 0; - for(det_shocks_type::const_iterator it = det_shocks.begin(); - it != det_shocks.end(); it++) + for (det_shocks_type::const_iterator it = det_shocks.begin(); + it != det_shocks.end(); it++) { int id = symbol_table.getTypeSpecificID(it->first) + 1; bool exo_det = (symbol_table.getType(it->first) == eExogenousDet); @@ -80,7 +80,6 @@ AbstractShocksStatement::checkPass(ModFileStructure &mod_file_struct) mod_file_struct.shocks_present = true; } - ShocksStatement::ShocksStatement(const det_shocks_type &det_shocks_arg, const var_and_std_shocks_type &var_shocks_arg, const var_and_std_shocks_type &std_shocks_arg, @@ -119,7 +118,7 @@ ShocksStatement::writeVarAndStdShocks(ostream &output) const { var_and_std_shocks_type::const_iterator it; - for(it = var_shocks.begin(); it != var_shocks.end(); it++) + for (it = var_shocks.begin(); it != var_shocks.end(); it++) { int id = symbol_table.getTypeSpecificID(it->first) + 1; const NodeID value = it->second; @@ -128,7 +127,7 @@ ShocksStatement::writeVarAndStdShocks(ostream &output) const output << ";" << endl; } - for(it = std_shocks.begin(); it != std_shocks.end(); it++) + for (it = std_shocks.begin(); it != std_shocks.end(); it++) { int id = symbol_table.getTypeSpecificID(it->first) + 1; const NodeID value = it->second; @@ -143,7 +142,7 @@ ShocksStatement::writeCovarAndCorrShocks(ostream &output) const { covar_and_corr_shocks_type::const_iterator it; - for(it = covar_shocks.begin(); it != covar_shocks.end(); it++) + for (it = covar_shocks.begin(); it != covar_shocks.end(); it++) { int id1 = symbol_table.getTypeSpecificID(it->first.first) + 1; int id2 = symbol_table.getTypeSpecificID(it->first.second) + 1; @@ -154,7 +153,7 @@ ShocksStatement::writeCovarAndCorrShocks(ostream &output) const << id1 << ", " << id2 << ");\n"; } - for(it = corr_shocks.begin(); it != corr_shocks.end(); it++) + for (it = corr_shocks.begin(); it != corr_shocks.end(); it++) { int id1 = symbol_table.getTypeSpecificID(it->first.first) + 1; int id2 = symbol_table.getTypeSpecificID(it->first.second) + 1; @@ -196,12 +195,12 @@ ConditionalForecastPathsStatement::ConditionalForecastPathsStatement(const Abstr void ConditionalForecastPathsStatement::checkPass(ModFileStructure &mod_file_struct) { - for(AbstractShocksStatement::det_shocks_type::const_iterator it = paths.begin(); - it != paths.end(); it++) + for (AbstractShocksStatement::det_shocks_type::const_iterator it = paths.begin(); + it != paths.end(); it++) { int this_path_length = 0; const vector<AbstractShocksStatement::DetShockElement> &elems = it->second; - for(int i = 0; i < (int) elems.size(); i++) + for (int i = 0; i < (int) elems.size(); i++) // Period1 < Period2, as enforced in ParsingDriver::add_period() this_path_length = max(this_path_length, elems[i].period2); if (path_length == -1) @@ -223,13 +222,13 @@ ConditionalForecastPathsStatement::writeOutput(ostream &output, const string &ba int k = 1; - for(AbstractShocksStatement::det_shocks_type::const_iterator it = paths.begin(); - it != paths.end(); it++) + for (AbstractShocksStatement::det_shocks_type::const_iterator it = paths.begin(); + it != paths.end(); it++) { output << "constrained_vars_ = strvcat(constrained_vars_, '" << it->first << "');" << endl; const vector<AbstractShocksStatement::DetShockElement> &elems = it->second; - for(int i = 0; i < (int) elems.size(); i++) - for(int j = elems[i].period1; j <= elems[i].period2; j++) + for (int i = 0; i < (int) elems.size(); i++) + for (int j = elems[i].period1; j <= elems[i].period2; j++) { output << "constrained_paths_(" << k << "," << j << ")="; elems[i].value->writeOutput(output); diff --git a/SigmaeInitialization.cc b/SigmaeInitialization.cc index d9bd2d284b0b61c6540b9106b4f2de07c48283fb..82173323f591585fd9950a6a6913990c6419452a 100644 --- a/SigmaeInitialization.cc +++ b/SigmaeInitialization.cc @@ -51,7 +51,7 @@ SigmaeStatement::determineMatrixForm(const matrix_type &matrix) throw (MatrixFor // each row has one element more or less than the previous one // and first or last one has one element. matrix_type::const_iterator ir; - for (ir = matrix.begin(), ir++; ir != matrix.end(); ir++, nbe += inc ) + for (ir = matrix.begin(), ir++; ir != matrix.end(); ir++, nbe += inc) if (ir->size() != nbe) throw MatrixFormException(); diff --git a/SigmaeInitialization.hh b/SigmaeInitialization.hh index 0f7695fc91838dcf6e7ae7817e27558d1fd18d58..1b6ff18d90cc77e763c0744a82cda106d95d1135 100644 --- a/SigmaeInitialization.hh +++ b/SigmaeInitialization.hh @@ -57,7 +57,7 @@ private: /*! Throws an exception if it is neither upper triangular nor lower triangular */ static matrix_form_type determineMatrixForm(const matrix_type &matrix) throw (MatrixFormException); -public : +public: SigmaeStatement(const matrix_type &matrix_arg) throw (MatrixFormException); virtual void writeOutput(ostream &output, const string &basename) const; }; diff --git a/Statement.cc b/Statement.cc index 1e48a4daf4ae6bbcafa87a0320ab1f12f72fad52..08295127f5409c18ad63bc2a728e682edda3a8ac 100644 --- a/Statement.cc +++ b/Statement.cc @@ -64,32 +64,32 @@ NativeStatement::writeOutput(ostream &output, const string &basename) const void OptionsList::writeOutput(ostream &output) const { - for(num_options_type::const_iterator it = num_options.begin(); - it != num_options.end(); it++) + for (num_options_type::const_iterator it = num_options.begin(); + it != num_options.end(); it++) output << "options_." << it->first << " = " << it->second << ";" << endl; - for(paired_num_options_type::const_iterator it = paired_num_options.begin(); - it != paired_num_options.end(); it++) + for (paired_num_options_type::const_iterator it = paired_num_options.begin(); + it != paired_num_options.end(); it++) output << "options_." << it->first << " = [" << it->second.first << "; " << it->second.second << "];" << endl; - for(string_options_type::const_iterator it = string_options.begin(); - it != string_options.end(); it++) + for (string_options_type::const_iterator it = string_options.begin(); + it != string_options.end(); it++) output << "options_." << it->first << " = '" << it->second << "';" << endl; - for(symbol_list_options_type::const_iterator it = symbol_list_options.begin(); - it != symbol_list_options.end(); it++) + for (symbol_list_options_type::const_iterator it = symbol_list_options.begin(); + it != symbol_list_options.end(); it++) it->second.writeOutput("options_." + it->first, output); - for(vec_int_options_type::const_iterator it = vector_int_options.begin(); - it != vector_int_options.end(); it++) + for (vec_int_options_type::const_iterator it = vector_int_options.begin(); + it != vector_int_options.end(); it++) { output << "options_." << it->first << " = "; if (it->second.size() > 1) { output << "["; - for (vector<int>::const_iterator viit=it->second.begin(); - viit!=it->second.end(); viit++) + for (vector<int>::const_iterator viit = it->second.begin(); + viit != it->second.end(); viit++) output << *viit << ";"; output << "];" << endl; } @@ -103,32 +103,32 @@ OptionsList::writeOutput(ostream &output, const string &option_group) const { output << option_group << " = struct();" << endl; - for(num_options_type::const_iterator it = num_options.begin(); - it != num_options.end(); it++) + for (num_options_type::const_iterator it = num_options.begin(); + it != num_options.end(); it++) output << option_group << "." << it->first << " = " << it->second << ";" << endl; - for(paired_num_options_type::const_iterator it = paired_num_options.begin(); - it != paired_num_options.end(); it++) + for (paired_num_options_type::const_iterator it = paired_num_options.begin(); + it != paired_num_options.end(); it++) output << option_group << "." << it->first << " = [" << it->second.first << "; " << it->second.second << "];" << endl; - for(string_options_type::const_iterator it = string_options.begin(); - it != string_options.end(); it++) + for (string_options_type::const_iterator it = string_options.begin(); + it != string_options.end(); it++) output << option_group << "." << it->first << " = '" << it->second << "';" << endl; - for(symbol_list_options_type::const_iterator it = symbol_list_options.begin(); - it != symbol_list_options.end(); it++) + for (symbol_list_options_type::const_iterator it = symbol_list_options.begin(); + it != symbol_list_options.end(); it++) it->second.writeOutput(option_group + "." + it->first, output); - for(vec_int_options_type::const_iterator it = vector_int_options.begin(); - it != vector_int_options.end(); it++) + for (vec_int_options_type::const_iterator it = vector_int_options.begin(); + it != vector_int_options.end(); it++) { output << option_group << "." << it->first << " = "; if (it->second.size() > 1) { output << "["; - for (vector<int>::const_iterator viit=it->second.begin(); - viit!=it->second.end(); viit++) + for (vector<int>::const_iterator viit = it->second.begin(); + viit != it->second.end(); viit++) output << *viit << ";"; output << "];" << endl; } diff --git a/StaticModel.cc b/StaticModel.cc index 941f5279743a8386547bc987d3f2f48e3745dfd4..784403e72fdbe767d50d7e67f6e9fd2b14e15b1a 100644 --- a/StaticModel.cc +++ b/StaticModel.cc @@ -36,11 +36,11 @@ #endif StaticModel::StaticModel(SymbolTable &symbol_table_arg, - NumericalConstants &num_constants_arg) : - ModelTree(symbol_table_arg, num_constants_arg), - global_temporary_terms(true), - cutoff(1e-15), - mfs(0) + NumericalConstants &num_constants_arg) : + ModelTree(symbol_table_arg, num_constants_arg), + global_temporary_terms(true), + cutoff(1e-15), + mfs(0) { } @@ -57,7 +57,6 @@ StaticModel::compileDerivative(ofstream &code_file, int eq, int symb_id, int lag } } - void StaticModel::compileChainRuleDerivative(ofstream &code_file, int eqr, int varr, int lag, map_idx_type &map_idx) const { @@ -86,10 +85,10 @@ StaticModel::computeTemporaryTermsOrdered() unsigned int nb_blocks = getNbBlocks(); v_temporary_terms = vector< vector<temporary_terms_type> >(nb_blocks); - v_temporary_terms_inuse = vector<temporary_terms_inuse_type> (nb_blocks); + v_temporary_terms_inuse = vector<temporary_terms_inuse_type>(nb_blocks); temporary_terms.clear(); - if(!global_temporary_terms) + if (!global_temporary_terms) { for (unsigned int block = 0; block < nb_blocks; block++) { @@ -102,17 +101,17 @@ StaticModel::computeTemporaryTermsOrdered() v_temporary_terms[block] = vector<temporary_terms_type>(block_size); for (unsigned int i = 0; i < block_size; i++) { - if (i<block_nb_recursives && isBlockEquationRenormalized( block, i)) - getBlockEquationRenormalizedNodeID( block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); + if (i < block_nb_recursives && isBlockEquationRenormalized(block, i)) + getBlockEquationRenormalizedNodeID(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); else { - eq_node = (BinaryOpNode*)getBlockEquationNodeID(block, i); + eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i); eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); } } for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) { - NodeID id=it->second.second; + NodeID id = it->second.second; id->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1); } set<int> temporary_terms_in_use; @@ -131,17 +130,17 @@ StaticModel::computeTemporaryTermsOrdered() v_temporary_terms[block] = vector<temporary_terms_type>(block_size); for (unsigned int i = 0; i < block_size; i++) { - if (i<block_nb_recursives && isBlockEquationRenormalized( block, i)) - getBlockEquationRenormalizedNodeID( block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); + if (i < block_nb_recursives && isBlockEquationRenormalized(block, i)) + getBlockEquationRenormalizedNodeID(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); else { - eq_node = (BinaryOpNode*)getBlockEquationNodeID(block, i); + eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i); eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i); } } for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) { - NodeID id=it->second.second; + NodeID id = it->second.second; id->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1); } @@ -155,533 +154,529 @@ StaticModel::computeTemporaryTermsOrdered() set<int> temporary_terms_in_use; for (unsigned int i = 0; i < block_size; i++) { - if (i<block_nb_recursives && isBlockEquationRenormalized( block, i)) - getBlockEquationRenormalizedNodeID( block, i)->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block); + if (i < block_nb_recursives && isBlockEquationRenormalized(block, i)) + getBlockEquationRenormalizedNodeID(block, i)->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block); else { - eq_node = (BinaryOpNode*)getBlockEquationNodeID(block, i); + eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i); eq_node->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block); } } for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) { - NodeID id=it->second.second; + NodeID id = it->second.second; id->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block); } - for(int i = 0; i < (int) getBlockSize(block); i++) + for (int i = 0; i < (int) getBlockSize(block); i++) for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); - it != v_temporary_terms[block][i].end(); it++) - (*it)->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block); + it != v_temporary_terms[block][i].end(); it++) + (*it)->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block); v_temporary_terms_inuse[block] = temporary_terms_in_use; } } // Add a mapping form node ID to temporary terms order - int j=0; + int j = 0; for (temporary_terms_type::const_iterator it = temporary_terms.begin(); - it != temporary_terms.end(); it++) - map_idx[(*it)->idx]=j++; + it != temporary_terms.end(); it++) + map_idx[(*it)->idx] = j++; } - void StaticModel::writeModelEquationsOrdered_M(const string &static_basename) const - { - string tmp_s, sps; - ostringstream tmp_output, tmp1_output, global_output; - NodeID lhs=NULL, rhs=NULL; - BinaryOpNode *eq_node; - map<NodeID, int> reference_count; - temporary_terms_type local_temporary_terms; - ofstream output; - int nze; - vector<int> feedback_variables; - ExprNodeOutputType local_output_type; - - if(global_temporary_terms) - { - local_output_type = oMatlabStaticModelSparse; - local_temporary_terms = temporary_terms; - } - else - local_output_type = oMatlabDynamicModelSparseLocalTemporaryTerms; - - //---------------------------------------------------------------------- - //For each block - for (unsigned int block = 0; block < getNbBlocks(); block++) - { - //recursive_variables.clear(); - feedback_variables.clear(); - //For a block composed of a single equation determines wether we have to evaluate or to solve the equation - nze = derivative_endo[block].size(); - BlockSimulationType simulation_type = getBlockSimulationType(block); - unsigned int block_size = getBlockSize(block); - unsigned int block_mfs = getBlockMfs(block); - unsigned int block_recursive = block_size - block_mfs; - - tmp1_output.str(""); - tmp1_output << static_basename << "_" << block+1 << ".m"; - output.open(tmp1_output.str().c_str(), ios::out | ios::binary); - output << "%\n"; - output << "% " << tmp1_output.str() << " : Computes static model for Dynare\n"; - output << "%\n"; - output << "% Warning : this file is generated automatically by Dynare\n"; - output << "% from model file (.mod)\n\n"; - output << "%/\n"; - if (simulation_type == EVALUATE_BACKWARD || simulation_type ==EVALUATE_FORWARD) - output << "function y = " << static_basename << "_" << block+1 << "(y, x, params)\n"; - else - output << "function [residual, y, g1] = " << static_basename << "_" << block+1 << "(y, x, params)\n"; - - BlockType block_type; - if(simulation_type == SOLVE_FORWARD_COMPLETE ||simulation_type == SOLVE_BACKWARD_COMPLETE) - block_type = SIMULTANS; - else if((simulation_type == SOLVE_FORWARD_SIMPLE ||simulation_type == SOLVE_BACKWARD_SIMPLE || - simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) - && getBlockFirstEquation(block) < prologue) - block_type = PROLOGUE; - else if((simulation_type == SOLVE_FORWARD_SIMPLE ||simulation_type == SOLVE_BACKWARD_SIMPLE || - simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) - && getBlockFirstEquation(block) >= equations.size() - epilogue) - block_type = EPILOGUE; - else - block_type = SIMULTANS; - output << " % ////////////////////////////////////////////////////////////////////////" << endl - << " % //" << string(" Block ").substr(int(log10(block + 1))) << block + 1 << " " << BlockType0(block_type) - << " //" << endl - << " % // Simulation type " - << BlockSim(simulation_type) << " //" << endl - << " % ////////////////////////////////////////////////////////////////////////" << endl; - output << " global options_;" << endl; - //The Temporary terms - if (simulation_type != EVALUATE_BACKWARD && simulation_type != EVALUATE_FORWARD) - output << " g1 = zeros(" << block_mfs << ", " << block_mfs << ");" << endl; - - - if (v_temporary_terms_inuse[block].size()) - { - tmp_output.str(""); - for (temporary_terms_inuse_type::const_iterator it = v_temporary_terms_inuse[block].begin(); - it != v_temporary_terms_inuse[block].end(); it++) - tmp_output << " T" << *it; - output << " global" << tmp_output.str() << ";\n"; - } - - if (simulation_type!=EVALUATE_BACKWARD && simulation_type!=EVALUATE_FORWARD) - output << " residual=zeros(" << block_mfs << ",1);\n"; - - - // The equations - for (unsigned int i = 0; i < block_size; i++) - { - if(!global_temporary_terms) - local_temporary_terms = v_temporary_terms[block][i]; - temporary_terms_type tt2; - tt2.clear(); - if (v_temporary_terms[block].size()) - { - output << " " << "% //Temporary variables" << endl; - for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); - it != v_temporary_terms[block][i].end(); it++) - { - output << " " << sps; - (*it)->writeOutput(output, local_output_type, local_temporary_terms); - output << " = "; - (*it)->writeOutput(output, local_output_type, tt2); - // Insert current node into tt2 - tt2.insert(*it); - output << ";" << endl; - } - } +{ + string tmp_s, sps; + ostringstream tmp_output, tmp1_output, global_output; + NodeID lhs = NULL, rhs = NULL; + BinaryOpNode *eq_node; + map<NodeID, int> reference_count; + temporary_terms_type local_temporary_terms; + ofstream output; + int nze; + vector<int> feedback_variables; + ExprNodeOutputType local_output_type; - int variable_ID = getBlockVariableID(block, i); - int equation_ID = getBlockEquationID(block, i); - EquationType equ_type = getBlockEquationType(block, i); - string sModel = symbol_table.getName(symbol_table.getID(eEndogenous, variable_ID)) ; - eq_node = (BinaryOpNode*)getBlockEquationNodeID(block,i); - lhs = eq_node->get_arg1(); - rhs = eq_node->get_arg2(); - tmp_output.str(""); - lhs->writeOutput(tmp_output, local_output_type, local_temporary_terms); - switch (simulation_type) - { - case EVALUATE_BACKWARD: - case EVALUATE_FORWARD: -evaluation: - output << " % equation " << getBlockEquationID(block, i)+1 << " variable : " << sModel - << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl; - output << " "; - if (equ_type == E_EVALUATE) - { - output << tmp_output.str(); - output << " = "; - rhs->writeOutput(output, local_output_type, local_temporary_terms); - } - else if (equ_type == E_EVALUATE_S) - { - output << "%" << tmp_output.str(); - output << " = "; - if (isBlockEquationRenormalized(block, i)) - { - rhs->writeOutput(output, local_output_type, local_temporary_terms); - output << "\n "; - tmp_output.str(""); - eq_node = (BinaryOpNode *)getBlockEquationRenormalizedNodeID(block, i); - lhs = eq_node->get_arg1(); - rhs = eq_node->get_arg2(); - lhs->writeOutput(output, local_output_type, local_temporary_terms); - output << " = "; - rhs->writeOutput(output, local_output_type, local_temporary_terms); - } - } - else - { - cerr << "Type missmatch for equation " << equation_ID+1 << "\n"; - exit(EXIT_FAILURE); - } - output << ";\n"; - break; - case SOLVE_BACKWARD_SIMPLE: - case SOLVE_FORWARD_SIMPLE: - case SOLVE_BACKWARD_COMPLETE: - case SOLVE_FORWARD_COMPLETE: - if (i<block_recursive) - goto evaluation; - feedback_variables.push_back(variable_ID); - output << " % equation " << equation_ID+1 << " variable : " << sModel - << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl; - output << " " << "residual(" << i+1-block_recursive << ") = ("; - goto end; - default: -end: - output << tmp_output.str(); - output << ") - ("; - rhs->writeOutput(output, local_output_type, local_temporary_terms); - output << ");\n"; - } - } - // The Jacobian if we have to solve the block - if (simulation_type==SOLVE_BACKWARD_SIMPLE || simulation_type==SOLVE_FORWARD_SIMPLE || - simulation_type==SOLVE_BACKWARD_COMPLETE || simulation_type==SOLVE_FORWARD_COMPLETE) - output << " " << sps << "% Jacobian " << endl; - switch (simulation_type) - { - case SOLVE_BACKWARD_SIMPLE: - case SOLVE_FORWARD_SIMPLE: - case SOLVE_BACKWARD_COMPLETE: - case SOLVE_FORWARD_COMPLETE: - for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) - { - unsigned int eq = it->first.first; - unsigned int var = it->first.second; - unsigned int eqr = getBlockEquationID(block, eq); - unsigned int varr = getBlockVariableID(block, var); - NodeID id = it->second.second; - output << " g1(" << eq+1-block_recursive << ", " << var+1-block_recursive << ") = "; - id->writeOutput(output, local_output_type, local_temporary_terms); - output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr)) - << "(" << 0 - << ") " << varr+1 - << ", equation=" << eqr+1 << endl; - } - break; - default: - break; - } - output.close(); - } - } + if (global_temporary_terms) + { + local_output_type = oMatlabStaticModelSparse; + local_temporary_terms = temporary_terms; + } + else + local_output_type = oMatlabDynamicModelSparseLocalTemporaryTerms; + + //---------------------------------------------------------------------- + //For each block + for (unsigned int block = 0; block < getNbBlocks(); block++) + { + //recursive_variables.clear(); + feedback_variables.clear(); + //For a block composed of a single equation determines wether we have to evaluate or to solve the equation + nze = derivative_endo[block].size(); + BlockSimulationType simulation_type = getBlockSimulationType(block); + unsigned int block_size = getBlockSize(block); + unsigned int block_mfs = getBlockMfs(block); + unsigned int block_recursive = block_size - block_mfs; + + tmp1_output.str(""); + tmp1_output << static_basename << "_" << block+1 << ".m"; + output.open(tmp1_output.str().c_str(), ios::out | ios::binary); + output << "%\n"; + output << "% " << tmp1_output.str() << " : Computes static model for Dynare\n"; + output << "%\n"; + output << "% Warning : this file is generated automatically by Dynare\n"; + output << "% from model file (.mod)\n\n"; + output << "%/\n"; + if (simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + output << "function y = " << static_basename << "_" << block+1 << "(y, x, params)\n"; + else + output << "function [residual, y, g1] = " << static_basename << "_" << block+1 << "(y, x, params)\n"; + + BlockType block_type; + if (simulation_type == SOLVE_FORWARD_COMPLETE || simulation_type == SOLVE_BACKWARD_COMPLETE) + block_type = SIMULTANS; + else if ((simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_SIMPLE + || simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + && getBlockFirstEquation(block) < prologue) + block_type = PROLOGUE; + else if ((simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_SIMPLE + || simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + && getBlockFirstEquation(block) >= equations.size() - epilogue) + block_type = EPILOGUE; + else + block_type = SIMULTANS; + output << " % ////////////////////////////////////////////////////////////////////////" << endl + << " % //" << string(" Block ").substr(int (log10(block + 1))) << block + 1 << " " << BlockType0(block_type) + << " //" << endl + << " % // Simulation type " + << BlockSim(simulation_type) << " //" << endl + << " % ////////////////////////////////////////////////////////////////////////" << endl; + output << " global options_;" << endl; + //The Temporary terms + if (simulation_type != EVALUATE_BACKWARD && simulation_type != EVALUATE_FORWARD) + output << " g1 = zeros(" << block_mfs << ", " << block_mfs << ");" << endl; + + if (v_temporary_terms_inuse[block].size()) + { + tmp_output.str(""); + for (temporary_terms_inuse_type::const_iterator it = v_temporary_terms_inuse[block].begin(); + it != v_temporary_terms_inuse[block].end(); it++) + tmp_output << " T" << *it; + output << " global" << tmp_output.str() << ";\n"; + } + + if (simulation_type != EVALUATE_BACKWARD && simulation_type != EVALUATE_FORWARD) + output << " residual=zeros(" << block_mfs << ",1);\n"; + + // The equations + for (unsigned int i = 0; i < block_size; i++) + { + if (!global_temporary_terms) + local_temporary_terms = v_temporary_terms[block][i]; + temporary_terms_type tt2; + tt2.clear(); + if (v_temporary_terms[block].size()) + { + output << " " << "% //Temporary variables" << endl; + for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); + it != v_temporary_terms[block][i].end(); it++) + { + output << " " << sps; + (*it)->writeOutput(output, local_output_type, local_temporary_terms); + output << " = "; + (*it)->writeOutput(output, local_output_type, tt2); + // Insert current node into tt2 + tt2.insert(*it); + output << ";" << endl; + } + } + + int variable_ID = getBlockVariableID(block, i); + int equation_ID = getBlockEquationID(block, i); + EquationType equ_type = getBlockEquationType(block, i); + string sModel = symbol_table.getName(symbol_table.getID(eEndogenous, variable_ID)); + eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i); + lhs = eq_node->get_arg1(); + rhs = eq_node->get_arg2(); + tmp_output.str(""); + lhs->writeOutput(tmp_output, local_output_type, local_temporary_terms); + switch (simulation_type) + { + case EVALUATE_BACKWARD: + case EVALUATE_FORWARD: + evaluation: + output << " % equation " << getBlockEquationID(block, i)+1 << " variable : " << sModel + << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl; + output << " "; + if (equ_type == E_EVALUATE) + { + output << tmp_output.str(); + output << " = "; + rhs->writeOutput(output, local_output_type, local_temporary_terms); + } + else if (equ_type == E_EVALUATE_S) + { + output << "%" << tmp_output.str(); + output << " = "; + if (isBlockEquationRenormalized(block, i)) + { + rhs->writeOutput(output, local_output_type, local_temporary_terms); + output << "\n "; + tmp_output.str(""); + eq_node = (BinaryOpNode *) getBlockEquationRenormalizedNodeID(block, i); + lhs = eq_node->get_arg1(); + rhs = eq_node->get_arg2(); + lhs->writeOutput(output, local_output_type, local_temporary_terms); + output << " = "; + rhs->writeOutput(output, local_output_type, local_temporary_terms); + } + } + else + { + cerr << "Type missmatch for equation " << equation_ID+1 << "\n"; + exit(EXIT_FAILURE); + } + output << ";\n"; + break; + case SOLVE_BACKWARD_SIMPLE: + case SOLVE_FORWARD_SIMPLE: + case SOLVE_BACKWARD_COMPLETE: + case SOLVE_FORWARD_COMPLETE: + if (i < block_recursive) + goto evaluation; + feedback_variables.push_back(variable_ID); + output << " % equation " << equation_ID+1 << " variable : " << sModel + << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl; + output << " " << "residual(" << i+1-block_recursive << ") = ("; + goto end; + default: + end: + output << tmp_output.str(); + output << ") - ("; + rhs->writeOutput(output, local_output_type, local_temporary_terms); + output << ");\n"; + } + } + // The Jacobian if we have to solve the block + if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE + || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE) + output << " " << sps << "% Jacobian " << endl; + switch (simulation_type) + { + case SOLVE_BACKWARD_SIMPLE: + case SOLVE_FORWARD_SIMPLE: + case SOLVE_BACKWARD_COMPLETE: + case SOLVE_FORWARD_COMPLETE: + for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) + { + unsigned int eq = it->first.first; + unsigned int var = it->first.second; + unsigned int eqr = getBlockEquationID(block, eq); + unsigned int varr = getBlockVariableID(block, var); + NodeID id = it->second.second; + output << " g1(" << eq+1-block_recursive << ", " << var+1-block_recursive << ") = "; + id->writeOutput(output, local_output_type, local_temporary_terms); + output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr)) + << "(" << 0 + << ") " << varr+1 + << ", equation=" << eqr+1 << endl; + } + break; + default: + break; + } + output.close(); + } +} void StaticModel::writeModelEquationsCodeOrdered(const string file_name, const string bin_basename, map_idx_type map_idx) const +{ + struct Uff_l { - struct Uff_l - { - int u, var, lag; - Uff_l *pNext; - }; - - struct Uff - { - Uff_l *Ufl, *Ufl_First; - }; - - int i,v; - string tmp_s; - ostringstream tmp_output; - ofstream code_file; - NodeID lhs=NULL, rhs=NULL; - BinaryOpNode *eq_node; - Uff Uf[symbol_table.endo_nbr()]; - map<NodeID, int> reference_count; - vector<int> feedback_variables; - bool file_open=false; - - string main_name=file_name; - main_name+=".cod"; - code_file.open(main_name.c_str(), ios::out | ios::binary | ios::ate ); - if (!code_file.is_open()) - { - cout << "Error : Can't open file \"" << main_name << "\" for writing\n"; - exit(EXIT_FAILURE); - } - //Temporary variables declaration - - FDIMT_ fdimt(temporary_terms.size()); - fdimt.write(code_file); - - for (unsigned int block = 0; block < getNbBlocks(); block++) - { - feedback_variables.clear(); - if (block>0) - { - FENDBLOCK_ fendblock; - fendblock.write(code_file); - } - int count_u; - int u_count_int=0; - BlockSimulationType simulation_type = getBlockSimulationType(block); - unsigned int block_size = getBlockSize(block); - unsigned int block_mfs = getBlockMfs(block); - unsigned int block_recursive = block_size - block_mfs; - - if (simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || - simulation_type==SOLVE_BACKWARD_COMPLETE || simulation_type==SOLVE_FORWARD_COMPLETE) - { - Write_Inf_To_Bin_File(file_name, bin_basename, block, u_count_int,file_open); - file_open=true; - } - - FBEGINBLOCK_ fbeginblock(block_mfs, - simulation_type, - getBlockFirstEquation(block), - block_size, - variable_reordered, - equation_reordered, - blocks_linear[block], - symbol_table.endo_nbr(), - 0, - 0, - u_count_int - ); - fbeginblock.write(code_file); - - // The equations - for (i = 0;i < (int) block_size;i++) - { - //The Temporary terms - temporary_terms_type tt2; - tt2.clear(); - if (v_temporary_terms[block].size()) - { - for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); - it != v_temporary_terms[block][i].end(); it++) - { - (*it)->compile(code_file, false, tt2, map_idx, false, false); - FSTPST_ fstpst((int)(map_idx.find((*it)->idx)->second)); - fstpst.write(code_file); - // Insert current node into tt2 - tt2.insert(*it); - } - } + int u, var, lag; + Uff_l *pNext; + }; - int variable_ID, equation_ID; - EquationType equ_type; - switch (simulation_type) - { -evaluation: - case EVALUATE_BACKWARD: - case EVALUATE_FORWARD: - equ_type = getBlockEquationType(block, i); - if (equ_type == E_EVALUATE) - { - eq_node = (BinaryOpNode*)getBlockEquationNodeID(block,i); - lhs = eq_node->get_arg1(); - rhs = eq_node->get_arg2(); - rhs->compile(code_file, false, temporary_terms, map_idx, false, false); - lhs->compile(code_file, true, temporary_terms, map_idx, false, false); - } - else if (equ_type == E_EVALUATE_S) - { - eq_node = (BinaryOpNode*)getBlockEquationRenormalizedNodeID(block,i); - lhs = eq_node->get_arg1(); - rhs = eq_node->get_arg2(); - rhs->compile(code_file, false, temporary_terms, map_idx, false, false); - lhs->compile(code_file, true, temporary_terms, map_idx, false, false); - } - break; - case SOLVE_BACKWARD_COMPLETE: - case SOLVE_FORWARD_COMPLETE: - if (i< (int) block_recursive) - goto evaluation; - variable_ID = getBlockVariableID(block, i); - equation_ID = getBlockEquationID(block, i); - feedback_variables.push_back(variable_ID); - Uf[equation_ID].Ufl=NULL; - goto end; - default: -end: - eq_node = (BinaryOpNode*)getBlockEquationNodeID(block, i); - lhs = eq_node->get_arg1(); - rhs = eq_node->get_arg2(); - lhs->compile(code_file, false, temporary_terms, map_idx, false, false); - rhs->compile(code_file, false, temporary_terms, map_idx, false, false); - - FBINARY_ fbinary(oMinus); - fbinary.write(code_file); - - FSTPR_ fstpr(i - block_recursive); - fstpr.write(code_file); - } - } - FENDEQU_ fendequ; - fendequ.write(code_file); - // The Jacobian if we have to solve the block - if (simulation_type != EVALUATE_BACKWARD - && simulation_type != EVALUATE_FORWARD) - { - switch (simulation_type) + struct Uff + { + Uff_l *Ufl, *Ufl_First; + }; + + int i, v; + string tmp_s; + ostringstream tmp_output; + ofstream code_file; + NodeID lhs = NULL, rhs = NULL; + BinaryOpNode *eq_node; + Uff Uf[symbol_table.endo_nbr()]; + map<NodeID, int> reference_count; + vector<int> feedback_variables; + bool file_open = false; + + string main_name = file_name; + main_name += ".cod"; + code_file.open(main_name.c_str(), ios::out | ios::binary | ios::ate); + if (!code_file.is_open()) + { + cout << "Error : Can't open file \"" << main_name << "\" for writing\n"; + exit(EXIT_FAILURE); + } + //Temporary variables declaration + + FDIMT_ fdimt(temporary_terms.size()); + fdimt.write(code_file); + + for (unsigned int block = 0; block < getNbBlocks(); block++) + { + feedback_variables.clear(); + if (block > 0) + { + FENDBLOCK_ fendblock; + fendblock.write(code_file); + } + int count_u; + int u_count_int = 0; + BlockSimulationType simulation_type = getBlockSimulationType(block); + unsigned int block_size = getBlockSize(block); + unsigned int block_mfs = getBlockMfs(block); + unsigned int block_recursive = block_size - block_mfs; + + if (simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE + || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE) + { + Write_Inf_To_Bin_File(file_name, bin_basename, block, u_count_int, file_open); + file_open = true; + } + + FBEGINBLOCK_ fbeginblock(block_mfs, + simulation_type, + getBlockFirstEquation(block), + block_size, + variable_reordered, + equation_reordered, + blocks_linear[block], + symbol_table.endo_nbr(), + 0, + 0, + u_count_int + ); + fbeginblock.write(code_file); + + // The equations + for (i = 0; i < (int) block_size; i++) + { + //The Temporary terms + temporary_terms_type tt2; + tt2.clear(); + if (v_temporary_terms[block].size()) + { + for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin(); + it != v_temporary_terms[block][i].end(); it++) + { + (*it)->compile(code_file, false, tt2, map_idx, false, false); + FSTPST_ fstpst((int)(map_idx.find((*it)->idx)->second)); + fstpst.write(code_file); + // Insert current node into tt2 + tt2.insert(*it); + } + } + + int variable_ID, equation_ID; + EquationType equ_type; + switch (simulation_type) + { + evaluation: + case EVALUATE_BACKWARD: + case EVALUATE_FORWARD: + equ_type = getBlockEquationType(block, i); + if (equ_type == E_EVALUATE) + { + eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i); + lhs = eq_node->get_arg1(); + rhs = eq_node->get_arg2(); + rhs->compile(code_file, false, temporary_terms, map_idx, false, false); + lhs->compile(code_file, true, temporary_terms, map_idx, false, false); + } + else if (equ_type == E_EVALUATE_S) + { + eq_node = (BinaryOpNode *) getBlockEquationRenormalizedNodeID(block, i); + lhs = eq_node->get_arg1(); + rhs = eq_node->get_arg2(); + rhs->compile(code_file, false, temporary_terms, map_idx, false, false); + lhs->compile(code_file, true, temporary_terms, map_idx, false, false); + } + break; + case SOLVE_BACKWARD_COMPLETE: + case SOLVE_FORWARD_COMPLETE: + if (i < (int) block_recursive) + goto evaluation; + variable_ID = getBlockVariableID(block, i); + equation_ID = getBlockEquationID(block, i); + feedback_variables.push_back(variable_ID); + Uf[equation_ID].Ufl = NULL; + goto end; + default: + end: + eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i); + lhs = eq_node->get_arg1(); + rhs = eq_node->get_arg2(); + lhs->compile(code_file, false, temporary_terms, map_idx, false, false); + rhs->compile(code_file, false, temporary_terms, map_idx, false, false); + + FBINARY_ fbinary(oMinus); + fbinary.write(code_file); + + FSTPR_ fstpr(i - block_recursive); + fstpr.write(code_file); + } + } + FENDEQU_ fendequ; + fendequ.write(code_file); + // The Jacobian if we have to solve the block + if (simulation_type != EVALUATE_BACKWARD + && simulation_type != EVALUATE_FORWARD) + { + switch (simulation_type) + { + case SOLVE_BACKWARD_SIMPLE: + case SOLVE_FORWARD_SIMPLE: + compileDerivative(code_file, getBlockEquationID(block, 0), getBlockVariableID(block, 0), 0, map_idx); { - case SOLVE_BACKWARD_SIMPLE: - case SOLVE_FORWARD_SIMPLE: - compileDerivative(code_file, getBlockEquationID(block, 0), getBlockVariableID(block, 0), 0, map_idx); - { - FSTPG_ fstpg(0); - fstpg.write(code_file); - } - break; - - case SOLVE_BACKWARD_COMPLETE: - case SOLVE_FORWARD_COMPLETE: - count_u = feedback_variables.size(); - for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) - { - unsigned int eq = it->first.first; - unsigned int var = it->first.second; - unsigned int eqr = getBlockEquationID(block, eq); - unsigned int varr = getBlockVariableID(block, var); - if(eq>=block_recursive and var>=block_recursive) - { - if (!Uf[eqr].Ufl) - { - Uf[eqr].Ufl=(Uff_l*)malloc(sizeof(Uff_l)); - Uf[eqr].Ufl_First=Uf[eqr].Ufl; - } - else - { - Uf[eqr].Ufl->pNext=(Uff_l*)malloc(sizeof(Uff_l)); - Uf[eqr].Ufl=Uf[eqr].Ufl->pNext; - } - Uf[eqr].Ufl->pNext=NULL; - Uf[eqr].Ufl->u=count_u; - Uf[eqr].Ufl->var=varr; - compileChainRuleDerivative(code_file, eqr, varr, 0, map_idx); - FSTPSU_ fstpsu(count_u); - fstpsu.write(code_file); - count_u++; - } - } - for (i = 0;i < (int) block_size;i++) - { - if(i>= (int) block_recursive) - { - FLDR_ fldr(i-block_recursive); - fldr.write(code_file); - - FLDZ_ fldz; - fldz.write(code_file); - - v=getBlockEquationID(block, i); - for (Uf[v].Ufl=Uf[v].Ufl_First; Uf[v].Ufl; Uf[v].Ufl=Uf[v].Ufl->pNext) - { - FLDSU_ fldsu(Uf[v].Ufl->u); - fldsu.write(code_file); - FLDSV_ fldsv(eEndogenous, Uf[v].Ufl->var); - fldsv.write(code_file); - - FBINARY_ fbinary(oTimes); - fbinary.write(code_file); - - FCUML_ fcuml; - fcuml.write(code_file); - } - Uf[v].Ufl=Uf[v].Ufl_First; - while (Uf[v].Ufl) - { - Uf[v].Ufl_First=Uf[v].Ufl->pNext; - free(Uf[v].Ufl); - Uf[v].Ufl=Uf[v].Ufl_First; - } - FBINARY_ fbinary(oMinus); - fbinary.write(code_file); - - FSTPSU_ fstpsu(i - block_recursive); - fstpsu.write(code_file); - - } - } - break; - default: - break; + FSTPG_ fstpg(0); + fstpg.write(code_file); } - } - } - FENDBLOCK_ fendblock; - fendblock.write(code_file); - FEND_ fend; - fend.write(code_file); - code_file.close(); - } + break; + case SOLVE_BACKWARD_COMPLETE: + case SOLVE_FORWARD_COMPLETE: + count_u = feedback_variables.size(); + for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++) + { + unsigned int eq = it->first.first; + unsigned int var = it->first.second; + unsigned int eqr = getBlockEquationID(block, eq); + unsigned int varr = getBlockVariableID(block, var); + if (eq >= block_recursive and var >= block_recursive) + { + if (!Uf[eqr].Ufl) + { + Uf[eqr].Ufl = (Uff_l *) malloc(sizeof(Uff_l)); + Uf[eqr].Ufl_First = Uf[eqr].Ufl; + } + else + { + Uf[eqr].Ufl->pNext = (Uff_l *) malloc(sizeof(Uff_l)); + Uf[eqr].Ufl = Uf[eqr].Ufl->pNext; + } + Uf[eqr].Ufl->pNext = NULL; + Uf[eqr].Ufl->u = count_u; + Uf[eqr].Ufl->var = varr; + compileChainRuleDerivative(code_file, eqr, varr, 0, map_idx); + FSTPSU_ fstpsu(count_u); + fstpsu.write(code_file); + count_u++; + } + } + for (i = 0; i < (int) block_size; i++) + { + if (i >= (int) block_recursive) + { + FLDR_ fldr(i-block_recursive); + fldr.write(code_file); + + FLDZ_ fldz; + fldz.write(code_file); + + v = getBlockEquationID(block, i); + for (Uf[v].Ufl = Uf[v].Ufl_First; Uf[v].Ufl; Uf[v].Ufl = Uf[v].Ufl->pNext) + { + FLDSU_ fldsu(Uf[v].Ufl->u); + fldsu.write(code_file); + FLDSV_ fldsv(eEndogenous, Uf[v].Ufl->var); + fldsv.write(code_file); + + FBINARY_ fbinary(oTimes); + fbinary.write(code_file); + + FCUML_ fcuml; + fcuml.write(code_file); + } + Uf[v].Ufl = Uf[v].Ufl_First; + while (Uf[v].Ufl) + { + Uf[v].Ufl_First = Uf[v].Ufl->pNext; + free(Uf[v].Ufl); + Uf[v].Ufl = Uf[v].Ufl_First; + } + FBINARY_ fbinary(oMinus); + fbinary.write(code_file); + + FSTPSU_ fstpsu(i - block_recursive); + fstpsu.write(code_file); + + } + } + break; + default: + break; + } + } + } + FENDBLOCK_ fendblock; + fendblock.write(code_file); + FEND_ fend; + fend.write(code_file); + code_file.close(); +} void StaticModel::Write_Inf_To_Bin_File(const string &static_basename, const string &bin_basename, const int &num, - int &u_count_int, bool &file_open) const - { - int j; - std::ofstream SaveCode; - if (file_open) - SaveCode.open((bin_basename + "_static.bin").c_str(), ios::out | ios::in | ios::binary | ios ::ate ); - else - SaveCode.open((bin_basename + "_static.bin").c_str(), ios::out | ios::binary); - if (!SaveCode.is_open()) - { - cout << "Error : Can't open file \"" << bin_basename << "_static.bin\" for writing\n"; - exit(EXIT_FAILURE); - } - u_count_int=0; - unsigned int block_size = getBlockSize(num); - unsigned int block_mfs = getBlockMfs(num); - unsigned int block_recursive = block_size - block_mfs; - for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[num].begin(); it != (blocks_derivatives[num]).end(); it++) - { - unsigned int eq = it->first.first; - unsigned int var = it->first.second; - int lag = 0; - if(eq>=block_recursive and var>=block_recursive) - { - int v = eq - block_recursive; - SaveCode.write(reinterpret_cast<char *>(&v), sizeof(v)); - int varr = var - block_recursive; - SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr)); - SaveCode.write(reinterpret_cast<char *>(&lag), sizeof(lag)); - int u = u_count_int + block_mfs; - SaveCode.write(reinterpret_cast<char *>(&u), sizeof(u)); - u_count_int++; - } - } - - for (j = block_recursive; j < (int) block_size; j++) - { - unsigned int varr=getBlockVariableID(num, j); - SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr)); - } - for (j = block_recursive; j < (int) block_size; j++) - { - unsigned int eqr=getBlockEquationID(num, j); - SaveCode.write(reinterpret_cast<char *>(&eqr), sizeof(eqr)); - } - SaveCode.close(); - } + int &u_count_int, bool &file_open) const +{ + int j; + std::ofstream SaveCode; + if (file_open) + SaveCode.open((bin_basename + "_static.bin").c_str(), ios::out | ios::in | ios::binary | ios::ate); + else + SaveCode.open((bin_basename + "_static.bin").c_str(), ios::out | ios::binary); + if (!SaveCode.is_open()) + { + cout << "Error : Can't open file \"" << bin_basename << "_static.bin\" for writing\n"; + exit(EXIT_FAILURE); + } + u_count_int = 0; + unsigned int block_size = getBlockSize(num); + unsigned int block_mfs = getBlockMfs(num); + unsigned int block_recursive = block_size - block_mfs; + for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[num].begin(); it != (blocks_derivatives[num]).end(); it++) + { + unsigned int eq = it->first.first; + unsigned int var = it->first.second; + int lag = 0; + if (eq >= block_recursive and var >= block_recursive) + { + int v = eq - block_recursive; + SaveCode.write(reinterpret_cast<char *>(&v), sizeof(v)); + int varr = var - block_recursive; + SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr)); + SaveCode.write(reinterpret_cast<char *>(&lag), sizeof(lag)); + int u = u_count_int + block_mfs; + SaveCode.write(reinterpret_cast<char *>(&u), sizeof(u)); + u_count_int++; + } + } + + for (j = block_recursive; j < (int) block_size; j++) + { + unsigned int varr = getBlockVariableID(num, j); + SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr)); + } + for (j = block_recursive; j < (int) block_size; j++) + { + unsigned int eqr = getBlockEquationID(num, j); + SaveCode.write(reinterpret_cast<char *>(&eqr), sizeof(eqr)); + } + SaveCode.close(); +} map<pair<int, pair<int, int > >, NodeID> StaticModel::collect_first_order_derivatives_endogenous() @@ -690,29 +685,29 @@ StaticModel::collect_first_order_derivatives_endogenous() for (first_derivatives_type::iterator it2 = first_derivatives.begin(); it2 != first_derivatives.end(); it2++) { - if (getTypeByDerivID(it2->first.second)==eEndogenous) + if (getTypeByDerivID(it2->first.second) == eEndogenous) { int eq = it2->first.first; - int var=symbol_table.getTypeSpecificID(it2->first.second); + int var = symbol_table.getTypeSpecificID(it2->first.second); int lag = 0; endo_derivatives[make_pair(eq, make_pair(var, lag))] = it2->second; } } - return endo_derivatives; + return endo_derivatives; } void StaticModel::computingPass(const eval_context_type &eval_context, bool no_tmp_terms, bool hessian, bool block) { - // Compute derivatives w.r. to all endogenous, and possibly exogenous and exogenous deterministic + // Compute derivatives w.r. to all endogenous, and possibly exogenous and exogenous deterministic set<int> vars; - for(int i = 0; i < symbol_table.endo_nbr(); i++) + for (int i = 0; i < symbol_table.endo_nbr(); i++) vars.insert(symbol_table.getID(eEndogenous, i)); // Launch computations cout << "Computing static model derivatives:" << endl - << " - order 1" << endl; + << " - order 1" << endl; first_derivatives.clear(); computeJacobian(vars); @@ -723,7 +718,6 @@ StaticModel::computingPass(const eval_context_type &eval_context, bool no_tmp_te computeHessian(vars); } - if (block) { jacob_map contemporaneous_jacobian, static_jacobian; @@ -882,42 +876,40 @@ StaticModel::writeStaticMFile(const string &func_name) const output.close(); } - - void StaticModel::writeStaticFile(const string &basename, bool block, bool bytecode) const - { - int r; +{ + int r; - //assert(block); + //assert(block); #ifdef _WIN32 - r = mkdir(basename.c_str()); + r = mkdir(basename.c_str()); #else - r = mkdir(basename.c_str(), 0777); + r = mkdir(basename.c_str(), 0777); #endif - if (r < 0 && errno != EEXIST) - { - perror("ERROR"); - exit(EXIT_FAILURE); - } - if(block && bytecode) - writeModelEquationsCodeOrdered(basename + "_static", basename, map_idx); - else if(block && !bytecode) - { - chdir(basename.c_str()); - writeModelEquationsOrdered_M(basename + "_static"); - chdir(".."); - writeStaticBlockMFSFile(basename); - } - else - writeStaticMFile(basename); - } + if (r < 0 && errno != EEXIST) + { + perror("ERROR"); + exit(EXIT_FAILURE); + } + if (block && bytecode) + writeModelEquationsCodeOrdered(basename + "_static", basename, map_idx); + else if (block && !bytecode) + { + chdir(basename.c_str()); + writeModelEquationsOrdered_M(basename + "_static"); + chdir(".."); + writeStaticBlockMFSFile(basename); + } + else + writeStaticMFile(basename); +} void StaticModel::writeStaticBlockMFSFile(const string &basename) const { - string filename = basename + "_static.m"; + string filename = basename + "_static.m"; ofstream output; output.open(filename.c_str(), ios::out | ios::binary); @@ -936,8 +928,7 @@ StaticModel::writeStaticBlockMFSFile(const string &basename) const unsigned int nb_blocks = getNbBlocks(); - - for(int b = 0; b < (int) nb_blocks; b++) + for (int b = 0; b < (int) nb_blocks; b++) { set<int> local_var; @@ -946,10 +937,10 @@ StaticModel::writeStaticBlockMFSFile(const string &basename) const BlockSimulationType simulation_type = getBlockSimulationType(b); - if (simulation_type == EVALUATE_BACKWARD || simulation_type ==EVALUATE_FORWARD) - output << " y = " << func_name << "_" << b+1 << "(y, x, params);\n"; - else - output << " [residual, y, g1] = " << func_name << "_" << b+1 << "(y, x, params);\n"; + if (simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD) + output << " y = " << func_name << "_" << b+1 << "(y, x, params);\n"; + else + output << " [residual, y, g1] = " << func_name << "_" << b+1 << "(y, x, params);\n"; } output << " end" << endl << "end" << endl; @@ -957,8 +948,6 @@ StaticModel::writeStaticBlockMFSFile(const string &basename) const } - - void StaticModel::writeOutput(ostream &output, bool block) const { @@ -967,7 +956,7 @@ StaticModel::writeOutput(ostream &output, bool block) const unsigned int nb_blocks = getNbBlocks(); output << "M_.blocksMFS = cell(" << nb_blocks << ", 1);" << endl; - for(int b = 0; b < (int) nb_blocks; b++) + for (int b = 0; b < (int) nb_blocks; b++) { output << "M_.blocksMFS{" << b+1 << "} = [ "; unsigned int block_size = getBlockSize(b); @@ -976,14 +965,13 @@ StaticModel::writeOutput(ostream &output, bool block) const BlockSimulationType simulation_type = getBlockSimulationType(b); if (simulation_type != EVALUATE_BACKWARD && simulation_type != EVALUATE_FORWARD) - for(int i= block_recursive; i< (int) block_size; i++) + for (int i = block_recursive; i < (int) block_size; i++) output << getBlockVariableID(b, i)+1 << "; "; output << "];" << endl; } } - SymbolType StaticModel::getTypeByDerivID(int deriv_id) const throw (UnknownDerivIDException) { @@ -1011,7 +999,6 @@ StaticModel::getDerivID(int symb_id, int lag) const throw (UnknownDerivIDExcepti return -1; } - map<pair<pair<int, pair<int, int> >, pair<int, int> >, int> StaticModel::get_Derivatives(int block) { @@ -1020,39 +1007,39 @@ StaticModel::get_Derivatives(int block) int block_size = getBlockSize(block); int block_nb_recursive = block_size - getBlockMfs(block); int lag = 0; - for(int eq = 0; eq < block_size; eq++) + for (int eq = 0; eq < block_size; eq++) { int eqr = getBlockEquationID(block, eq); - for(int var = 0; var < block_size; var++) + for (int var = 0; var < block_size; var++) { int varr = getBlockVariableID(block, var); - if(dynamic_jacobian.find(make_pair(lag, make_pair(eqr, varr))) != dynamic_jacobian.end()) + if (dynamic_jacobian.find(make_pair(lag, make_pair(eqr, varr))) != dynamic_jacobian.end()) { bool OK = true; map<pair<pair<int, pair<int, int> >, pair<int, int> >, int>::const_iterator its = Derivatives.find(make_pair(make_pair(lag, make_pair(eq, var)), make_pair(eqr, varr))); - if(its!=Derivatives.end()) + if (its != Derivatives.end()) { - if(its->second == 2) - OK=false; + if (its->second == 2) + OK = false; } - if(OK) + if (OK) { - if (getBlockEquationType(block, eq) == E_EVALUATE_S and eq<block_nb_recursive) + if (getBlockEquationType(block, eq) == E_EVALUATE_S and eq < block_nb_recursive) //It's a normalized equation, we have to recompute the derivative using chain rule derivative function Derivatives[make_pair(make_pair(lag, make_pair(eq, var)), make_pair(eqr, varr))] = 1; else //It's a feedback equation we can use the derivatives Derivatives[make_pair(make_pair(lag, make_pair(eq, var)), make_pair(eqr, varr))] = 0; } - if(var<block_nb_recursive) + if (var < block_nb_recursive) { int eqs = getBlockEquationID(block, var); - for(int vars=block_nb_recursive; vars<block_size; vars++) + for (int vars = block_nb_recursive; vars < block_size; vars++) { int varrs = getBlockVariableID(block, vars); //A new derivative needs to be computed using the chain rule derivative function (a feedback variable appears in a recursive equation) - if(Derivatives.find(make_pair(make_pair(lag, make_pair(var, vars)), make_pair(eqs, varrs)))!=Derivatives.end()) + if (Derivatives.find(make_pair(make_pair(lag, make_pair(var, vars)), make_pair(eqs, varrs))) != Derivatives.end()) Derivatives[make_pair(make_pair(lag, make_pair(eq, vars)), make_pair(eqr, varrs))] = 2; } } @@ -1060,17 +1047,16 @@ StaticModel::get_Derivatives(int block) } } - return(Derivatives); + return (Derivatives); } - void StaticModel::computeChainRuleJacobian(t_blocks_derivatives &blocks_derivatives) { map<int, NodeID> recursive_variables; unsigned int nb_blocks = getNbBlocks(); blocks_derivatives = t_blocks_derivatives(nb_blocks); - for(unsigned int block = 0; block < nb_blocks; block++) + for (unsigned int block = 0; block < nb_blocks; block++) { t_block_derivatives_equation_variable_laglead_nodeid tmp_derivatives; recursive_variables.clear(); @@ -1078,10 +1064,10 @@ StaticModel::computeChainRuleJacobian(t_blocks_derivatives &blocks_derivatives) int block_size = getBlockSize(block); int block_nb_mfs = getBlockMfs(block); int block_nb_recursives = block_size - block_nb_mfs; - if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE or simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE) + if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE or simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE) { blocks_derivatives.push_back(t_block_derivatives_equation_variable_laglead_nodeid(0)); - for(int i = 0; i < block_nb_recursives; i++) + for (int i = 0; i < block_nb_recursives; i++) { if (getBlockEquationType(block, i) == E_EVALUATE_S) recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block, i)), 0)] = getBlockEquationRenormalizedNodeID(block, i); @@ -1090,7 +1076,7 @@ StaticModel::computeChainRuleJacobian(t_blocks_derivatives &blocks_derivatives) } map<pair<pair<int, pair<int, int> >, pair<int, int> >, int> Derivatives = get_Derivatives(block); map<pair<pair<int, pair<int, int> >, pair<int, int> >, int>::const_iterator it = Derivatives.begin(); - for(int i=0; i<(int)Derivatives.size(); i++) + for (int i = 0; i < (int) Derivatives.size(); i++) { int Deriv_type = it->second; pair<pair<int, pair<int, int> >, pair<int, int> > it_l(it->first); @@ -1100,35 +1086,35 @@ StaticModel::computeChainRuleJacobian(t_blocks_derivatives &blocks_derivatives) int var = it_l.first.second.second; int eqr = it_l.second.first; int varr = it_l.second.second; - if(Deriv_type == 0) + if (Deriv_type == 0) first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))] = first_derivatives[make_pair(eqr, getDerivID(symbol_table.getID(eEndogenous, varr), lag))]; else if (Deriv_type == 1) first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))] = (equation_type_and_normalized_equation[eqr].second)->getChainRuleDerivative(getDerivID(symbol_table.getID(eEndogenous, varr), lag), recursive_variables); else if (Deriv_type == 2) { - if(getBlockEquationType(block, eq) == E_EVALUATE_S && eq<block_nb_recursives) + if (getBlockEquationType(block, eq) == E_EVALUATE_S && eq < block_nb_recursives) first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))] = (equation_type_and_normalized_equation[eqr].second)->getChainRuleDerivative(getDerivID(symbol_table.getID(eEndogenous, varr), lag), recursive_variables); else first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))] = equations[eqr]->getChainRuleDerivative(getDerivID(symbol_table.getID(eEndogenous, varr), lag), recursive_variables); } - tmp_derivatives.push_back(make_pair(make_pair(eq, var), make_pair(lag, first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))]) )); + tmp_derivatives.push_back(make_pair(make_pair(eq, var), make_pair(lag, first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))]))); } } - else if( simulation_type==SOLVE_BACKWARD_SIMPLE or simulation_type==SOLVE_FORWARD_SIMPLE - or simulation_type==SOLVE_BACKWARD_COMPLETE or simulation_type==SOLVE_FORWARD_COMPLETE) + else if (simulation_type == SOLVE_BACKWARD_SIMPLE or simulation_type == SOLVE_FORWARD_SIMPLE + or simulation_type == SOLVE_BACKWARD_COMPLETE or simulation_type == SOLVE_FORWARD_COMPLETE) { blocks_derivatives.push_back(t_block_derivatives_equation_variable_laglead_nodeid(0)); - for(int i = 0; i < block_nb_recursives; i++) + for (int i = 0; i < block_nb_recursives; i++) { if (getBlockEquationType(block, i) == E_EVALUATE_S) - recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block,i)), 0)] = getBlockEquationRenormalizedNodeID(block, i); + recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block, i)), 0)] = getBlockEquationRenormalizedNodeID(block, i); else - recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block,i)), 0)] = getBlockEquationNodeID(block, i); + recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block, i)), 0)] = getBlockEquationNodeID(block, i); } - for(int eq = block_nb_recursives; eq < block_size; eq++) + for (int eq = block_nb_recursives; eq < block_size; eq++) { int eqr = getBlockEquationID(block, eq); - for(int var = block_nb_recursives; var < block_size; var++) + for (int var = block_nb_recursives; var < block_size; var++) { int varr = getBlockVariableID(block, var); NodeID d1 = equations[eqr]->getChainRuleDerivative(getDerivID(symbol_table.getID(eEndogenous, varr), 0), recursive_variables); @@ -1136,7 +1122,7 @@ StaticModel::computeChainRuleJacobian(t_blocks_derivatives &blocks_derivatives) continue; first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, 0))] = d1; tmp_derivatives.push_back( - make_pair(make_pair(eq, var),make_pair(0, first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, 0))]))); + make_pair(make_pair(eq, var), make_pair(0, first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, 0))]))); } } } @@ -1144,7 +1130,6 @@ StaticModel::computeChainRuleJacobian(t_blocks_derivatives &blocks_derivatives) } } - void StaticModel::collect_block_first_order_derivatives() { @@ -1153,18 +1138,18 @@ StaticModel::collect_block_first_order_derivatives() unsigned int nb_blocks = getNbBlocks(); equation_2_block = vector<int>(equation_reordered.size()); variable_2_block = vector<int>(variable_reordered.size()); - for(unsigned int block = 0; block < nb_blocks; block++) + for (unsigned int block = 0; block < nb_blocks; block++) { unsigned int block_size = getBlockSize(block); - for(unsigned int i = 0; i < block_size; i++) + for (unsigned int i = 0; i < block_size; i++) { equation_2_block[getBlockEquationID(block, i)] = block; variable_2_block[getBlockVariableID(block, i)] = block; } } derivative_endo = vector<t_derivative>(nb_blocks); - endo_max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair( 0, 0)); - max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair( 0, 0)); + endo_max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair(0, 0)); + max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair(0, 0)); for (first_derivatives_type::iterator it2 = first_derivatives.begin(); it2 != first_derivatives.end(); it2++) { @@ -1177,7 +1162,7 @@ StaticModel::collect_block_first_order_derivatives() max_leadlag_block[block_eq] = make_pair(0, 0); endo_max_leadlag_block[block_eq] = make_pair(0, 0); endo_max_leadlag_block[block_eq] = make_pair(0, 0); - t_derivative tmp_derivative ; + t_derivative tmp_derivative; t_lag_var lag_var; if (getTypeByDerivID(it2->first.second) == eEndogenous && block_eq == block_var) { @@ -1190,8 +1175,8 @@ StaticModel::collect_block_first_order_derivatives() void StaticModel::writeChainRuleDerivative(ostream &output, int eqr, int varr, int lag, - ExprNodeOutputType output_type, - const temporary_terms_type &temporary_terms) const + ExprNodeOutputType output_type, + const temporary_terms_type &temporary_terms) const { map<pair<int, pair<int, int> >, NodeID>::const_iterator it = first_chain_rule_derivatives.find(make_pair(eqr, make_pair(varr, lag))); if (it != first_chain_rule_derivatives.end()) @@ -1200,12 +1185,11 @@ StaticModel::writeChainRuleDerivative(ostream &output, int eqr, int varr, int la output << 0; } - void StaticModel::writeLatexFile(const string &basename) const - { - writeLatexModelFile(basename + "_static.tex", oLatexStaticModel); - } +{ + writeLatexModelFile(basename + "_static.tex", oLatexStaticModel); +} void StaticModel::jacobianHelper(ostream &output, int eq_nb, int col_nb, ExprNodeOutputType output_type) const @@ -1232,7 +1216,7 @@ StaticModel::hessianHelper(ostream &output, int row_nb, int col_nb, ExprNodeOutp void StaticModel::writeAuxVarInitval(ostream &output) const { - for(int i = 0; i < (int) aux_equations.size(); i++) + for (int i = 0; i < (int) aux_equations.size(); i++) { dynamic_cast<ExprNode *>(aux_equations[i])->writeOutput(output); output << ";" << endl; diff --git a/StaticModel.hh b/StaticModel.hh index ae2da07418d69dbe44f0d0526fd70a0ba1702af6..5b82ab54107d8c02ad812c62677be33ff44c22ca 100644 --- a/StaticModel.hh +++ b/StaticModel.hh @@ -44,7 +44,6 @@ private: vector<temporary_terms_inuse_type> v_temporary_terms_inuse; - typedef map< pair< int, pair< int, int> >, NodeID> first_chain_rule_derivatives_type; first_chain_rule_derivatives_type first_chain_rule_derivatives; @@ -54,7 +53,6 @@ private: //! Writes the static function calling the block to solve (Matlab version) void writeStaticBlockMFSFile(const string &basename) const; - //! Writes static model file (C version) /*! \todo add third derivatives handling */ void writeStaticCFile(const string &static_basename) const; @@ -154,9 +152,9 @@ public: double cutoff; //! Compute the minimum feedback set in the static model: /*! 0 : all endogenous variables are considered as feedback variables - 1 : the variables belonging to a non linear equation are considered as feedback variables - 2 : the variables belonging to a non normalizable non linear equation are considered as feedback variables - default value = 0 */ + 1 : the variables belonging to a non linear equation are considered as feedback variables + 2 : the variables belonging to a non normalizable non linear equation are considered as feedback variables + default value = 0 */ int mfs; //! the file containing the model and the derivatives code ofstream code_file; @@ -187,36 +185,95 @@ public: virtual int getDerivID(int symb_id, int lag) const throw (UnknownDerivIDException); //! Return the number of blocks - virtual unsigned int getNbBlocks() const {return(block_type_firstequation_size_mfs.size());}; + virtual unsigned int + getNbBlocks() const + { + return (block_type_firstequation_size_mfs.size()); + }; //! Determine the simulation type of each block - virtual BlockSimulationType getBlockSimulationType(int block_number) const {return(block_type_firstequation_size_mfs[block_number].first.first);}; + virtual BlockSimulationType + getBlockSimulationType(int block_number) const + { + return (block_type_firstequation_size_mfs[block_number].first.first); + }; //! Return the first equation number of a block - virtual unsigned int getBlockFirstEquation(int block_number) const {return(block_type_firstequation_size_mfs[block_number].first.second);}; + virtual unsigned int + getBlockFirstEquation(int block_number) const + { + return (block_type_firstequation_size_mfs[block_number].first.second); + }; //! Return the size of the block block_number - virtual unsigned int getBlockSize(int block_number) const {return(block_type_firstequation_size_mfs[block_number].second.first);}; + virtual unsigned int + getBlockSize(int block_number) const + { + return (block_type_firstequation_size_mfs[block_number].second.first); + }; //! Return the number of feedback variable of the block block_number - virtual unsigned int getBlockMfs(int block_number) const {return(block_type_firstequation_size_mfs[block_number].second.second);}; + virtual unsigned int + getBlockMfs(int block_number) const + { + return (block_type_firstequation_size_mfs[block_number].second.second); + }; //! Return the maximum lag in a block - virtual unsigned int getBlockMaxLag(int block_number) const {return(block_lag_lead[block_number].first);}; + virtual unsigned int + getBlockMaxLag(int block_number) const + { + return (block_lag_lead[block_number].first); + }; //! Return the maximum lead in a block - virtual unsigned int getBlockMaxLead(int block_number) const {return(block_lag_lead[block_number].second);}; + virtual unsigned int + getBlockMaxLead(int block_number) const + { + return (block_lag_lead[block_number].second); + }; //! Return the type of equation (equation_number) belonging to the block block_number - virtual EquationType getBlockEquationType(int block_number, int equation_number) const {return( equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].first);}; + virtual EquationType + getBlockEquationType(int block_number, int equation_number) const + { + return (equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].first); + }; //! Return true if the equation has been normalized - virtual bool isBlockEquationRenormalized(int block_number, int equation_number) const {return( equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].first == E_EVALUATE_S);}; + virtual bool + isBlockEquationRenormalized(int block_number, int equation_number) const + { + return (equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].first == E_EVALUATE_S); + }; //! Return the NodeID of the equation equation_number belonging to the block block_number - virtual NodeID getBlockEquationNodeID(int block_number, int equation_number) const {return( equations[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]]);}; + virtual NodeID + getBlockEquationNodeID(int block_number, int equation_number) const + { + return (equations[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]]); + }; //! Return the NodeID of the renormalized equation equation_number belonging to the block block_number - virtual NodeID getBlockEquationRenormalizedNodeID(int block_number, int equation_number) const {return( equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].second);}; + virtual NodeID + getBlockEquationRenormalizedNodeID(int block_number, int equation_number) const + { + return (equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].second); + }; //! Return the original number of equation equation_number belonging to the block block_number - virtual int getBlockEquationID(int block_number, int equation_number) const {return( equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]);}; + virtual int + getBlockEquationID(int block_number, int equation_number) const + { + return (equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]); + }; //! Return the original number of variable variable_number belonging to the block block_number - virtual int getBlockVariableID(int block_number, int variable_number) const {return( variable_reordered[block_type_firstequation_size_mfs[block_number].first.second+variable_number]);}; + virtual int + getBlockVariableID(int block_number, int variable_number) const + { + return (variable_reordered[block_type_firstequation_size_mfs[block_number].first.second+variable_number]); + }; //! Return the position of equation_number in the block number belonging to the block block_number - virtual int getBlockInitialEquationID(int block_number, int equation_number) const {return((int)inv_equation_reordered[equation_number] - (int)block_type_firstequation_size_mfs[block_number].first.second);}; + virtual int + getBlockInitialEquationID(int block_number, int equation_number) const + { + return ((int) inv_equation_reordered[equation_number] - (int) block_type_firstequation_size_mfs[block_number].first.second); + }; //! Return the position of variable_number in the block number belonging to the block block_number - virtual int getBlockInitialVariableID(int block_number, int variable_number) const {return((int)inv_variable_reordered[variable_number] - (int)block_type_firstequation_size_mfs[block_number].first.second);}; - + virtual int + getBlockInitialVariableID(int block_number, int variable_number) const + { + return ((int) inv_variable_reordered[variable_number] - (int) block_type_firstequation_size_mfs[block_number].first.second); + }; }; diff --git a/SymbolTable.cc b/SymbolTable.cc index 38d3c46bd7f92cfe8c6eeaf0d88868377b1acae5..74ae98165f5f68f400a0429b69132a361732ef1f 100644 --- a/SymbolTable.cc +++ b/SymbolTable.cc @@ -58,7 +58,7 @@ SymbolTable::addSymbol(const string &name, SymbolType type) throw (AlreadyDeclar // Construct "tex_name" by prepending an antislash to all underscores in "name" string tex_name = name; size_t pos = 0; - while((pos = tex_name.find('_', pos)) != string::npos) + while ((pos = tex_name.find('_', pos)) != string::npos) { tex_name.insert(pos, "\\"); pos += 2; @@ -74,10 +74,10 @@ SymbolTable::freeze() throw (FrozenException) frozen = true; - for(int i = 0; i < size; i++) + for (int i = 0; i < size; i++) { int tsi; - switch(getType(i)) + switch (getType(i)) { case eEndogenous: tsi = endo_ids.size(); @@ -121,7 +121,7 @@ SymbolTable::getID(SymbolType type, int tsid) const throw (UnknownTypeSpecificID if (!frozen) throw NotYetFrozenException(); - switch(type) + switch (type) { case eEndogenous: if (tsid < 0 || tsid >= (int) endo_ids.size()) @@ -207,11 +207,11 @@ SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException) if (aux_vars.size() == 0) output << "M_.aux_vars = [];" << endl; else - for(int i = 0; i < (int) aux_vars.size(); i++) + for (int i = 0; i < (int) aux_vars.size(); i++) { output << "M_.aux_vars(" << i+1 << ").endo_index = " << getTypeSpecificID(aux_vars[i].symb_id)+1 << ";" << endl << "M_.aux_vars(" << i+1 << ").type = " << aux_vars[i].type << ";" << endl; - switch(aux_vars[i].type) + switch (aux_vars[i].type) { case avEndoLead: case avExoLead: @@ -228,8 +228,8 @@ SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException) if (predeterminedNbr() > 0) { output << "M_.predetermined_variables = [ "; - for(set<int>::const_iterator it = predetermined_variables.begin(); - it != predetermined_variables.end(); it++) + for (set<int>::const_iterator it = predetermined_variables.begin(); + it != predetermined_variables.end(); it++) output << getTypeSpecificID(*it)+1 << " "; output << "];" << endl; } @@ -249,7 +249,7 @@ SymbolTable::addLeadAuxiliaryVarInternal(bool endo, int index) throw (FrozenExce { symb_id = addSymbol(varname.str(), eEndogenous); } - catch(AlreadyDeclaredException &e) + catch (AlreadyDeclaredException &e) { cerr << "ERROR: you should rename your variable called " << varname.str() << ", this name is internally used by Dynare" << endl; exit(EXIT_FAILURE); @@ -278,7 +278,7 @@ SymbolTable::addLagAuxiliaryVarInternal(bool endo, int orig_symb_id, int orig_le { symb_id = addSymbol(varname.str(), eEndogenous); } - catch(AlreadyDeclaredException &e) + catch (AlreadyDeclaredException &e) { cerr << "ERROR: you should rename your variable called " << varname.str() << ", this name is internally used by Dynare" << endl; exit(EXIT_FAILURE); @@ -329,7 +329,7 @@ SymbolTable::addExpectationAuxiliaryVar(int information_set, int index) throw (F { symb_id = addSymbol(varname.str(), eEndogenous); } - catch(AlreadyDeclaredException &e) + catch (AlreadyDeclaredException &e) { cerr << "ERROR: you should rename your variable called " << varname.str() << ", this name is internally used by Dynare" << endl; exit(EXIT_FAILURE); @@ -362,11 +362,11 @@ SymbolTable::isPredetermined(int symb_id) const throw (UnknownSymbolIDException) if (symb_id < 0 || symb_id >= size) throw UnknownSymbolIDException(symb_id); - return(predetermined_variables.find(symb_id) != predetermined_variables.end()); + return (predetermined_variables.find(symb_id) != predetermined_variables.end()); } int SymbolTable::predeterminedNbr() const { - return(predetermined_variables.size()); + return (predetermined_variables.size()); } diff --git a/SymbolTable.hh b/SymbolTable.hh index b9395e4c1cf96314ec597ff5a8be4127b1231d7e..7346e679bfa4ccf355c64076c524469ad8351269 100644 --- a/SymbolTable.hh +++ b/SymbolTable.hh @@ -104,7 +104,9 @@ public: public: //! Symbol name string name; - UnknownSymbolNameException(const string &name_arg) : name(name_arg) {} + UnknownSymbolNameException(const string &name_arg) : name(name_arg) + { + } }; //! Thrown when trying to access an unknown symbol (by id) class UnknownSymbolIDException @@ -112,7 +114,9 @@ public: public: //! Symbol ID int id; - UnknownSymbolIDException(int id_arg) : id(id_arg) {} + UnknownSymbolIDException(int id_arg) : id(id_arg) + { + } }; //! Thrown when trying to access an unknown type specific ID class UnknownTypeSpecificIDException @@ -120,7 +124,9 @@ public: public: int tsid; SymbolType type; - UnknownTypeSpecificIDException(int tsid_arg, SymbolType type_arg) : tsid(tsid_arg), type(type_arg) {} + UnknownTypeSpecificIDException(int tsid_arg, SymbolType type_arg) : tsid(tsid_arg), type(type_arg) + { + } }; //! Thrown when trying to declare a symbol twice class AlreadyDeclaredException @@ -130,7 +136,9 @@ public: string name; //! Was the previous declaration done with the same symbol type ? bool same_type; - AlreadyDeclaredException(const string &name_arg, bool same_type_arg) : name(name_arg), same_type(same_type_arg) {} + AlreadyDeclaredException(const string &name_arg, bool same_type_arg) : name(name_arg), same_type(same_type_arg) + { + } }; //! Thrown when table is frozen and trying to modify it class FrozenException @@ -332,7 +340,7 @@ SymbolTable::param_nbr() const throw (NotYetFrozenException) inline int SymbolTable::maxID() { - return(size-1); + return (size-1); } #endif diff --git a/macro/MacroDriver.cc b/macro/MacroDriver.cc index e294cddb299b46e2931c531293758d66239be034..fd05edee9fb5cd15ead143abc427b9ce06373412 100644 --- a/macro/MacroDriver.cc +++ b/macro/MacroDriver.cc @@ -29,8 +29,8 @@ MacroDriver::MacroDriver() MacroDriver::~MacroDriver() { - for(set<const MacroValue *>::iterator it = values.begin(); - it != values.end(); it++) + for (set<const MacroValue *>::iterator it = values.begin(); + it != values.end(); it++) delete *it; } diff --git a/macro/MacroDriver.hh b/macro/MacroDriver.hh index 1a6ce998770fc131d265735e36d5cfedaf9cdb3b..345c8e51b7fadeb1d1b31ef146b23457df6af0b5 100644 --- a/macro/MacroDriver.hh +++ b/macro/MacroDriver.hh @@ -64,7 +64,9 @@ private: const string &for_body_arg, Macro::parser::location_type &for_body_loc_arg) : input(input_arg), buffer(buffer_arg), yylloc(yylloc_arg), is_for_context(is_for_context_arg), - for_body(for_body_arg), for_body_loc(for_body_loc_arg) { } + for_body(for_body_arg), for_body_loc(for_body_loc_arg) + { + } }; //! The stack used to keep track of nested scanning contexts @@ -134,7 +136,7 @@ private: void new_loop_body_buffer(Macro::parser::location_type *yylloc); public: - MacroFlex(istream* in, ostream* out, bool no_line_macro_arg); + MacroFlex(istream *in, ostream *out, bool no_line_macro_arg); //! The main lexing function Macro::parser::token_type lex(Macro::parser::semantic_type *yylval, @@ -162,7 +164,9 @@ public: { public: const string name; - UnknownVariable(const string &name_arg) : name(name_arg) {} + UnknownVariable(const string &name_arg) : name(name_arg) + { + } }; //! Constructor diff --git a/macro/MacroValue.cc b/macro/MacroValue.cc index be509f6785d098286f51c9cae82bbcdff159cca3..d2118075606d9fd2d68abb4412e4705035ccb4cd 100644 --- a/macro/MacroValue.cc +++ b/macro/MacroValue.cc @@ -302,8 +302,8 @@ IntMV::in(const MacroValue *array) const throw (TypeError) throw TypeError("Type mismatch for 'in' operator"); int result = 0; - for(vector<int>::const_iterator it = array2->values.begin(); - it != array2->values.end(); it++) + for (vector<int>::const_iterator it = array2->values.begin(); + it != array2->values.end(); it++) if (*it == value) { result = 1; @@ -331,7 +331,7 @@ IntMV::new_range(MacroDriver &driver, const MacroValue *mv1, const MacroValue *m v2 = v1; v1 = x; } - for(; v1 <= v2; v1++) + for (; v1 <= v2; v1++) result.push_back(v1); return new ArrayMV<int>(driver, result); } @@ -381,8 +381,8 @@ StringMV::operator[](const MacroValue &mv) const throw (TypeError, OutOfBoundsEr if (mv2 == NULL) throw TypeError("Expression inside [] must be an integer array"); string result; - for(vector<int>::const_iterator it = mv2->values.begin(); - it != mv2->values.end(); it++) + for (vector<int>::const_iterator it = mv2->values.begin(); + it != mv2->values.end(); it++) { if (*it < 1 || *it > (int) value.length()) throw OutOfBoundsError(); @@ -426,8 +426,8 @@ StringMV::in(const MacroValue *array) const throw (TypeError) throw TypeError("Type mismatch for 'in' operator"); int result = 0; - for(vector<string>::const_iterator it = array2->values.begin(); - it != array2->values.end(); it++) + for (vector<string>::const_iterator it = array2->values.begin(); + it != array2->values.end(); it++) if (*it == value) { result = 1; diff --git a/macro/MacroValue.hh b/macro/MacroValue.hh index 054dd10503ae65271b60cadd0deca14caef74e5c..52b566f4c4f7f3cd0fc40c86327268a141c0a49e 100644 --- a/macro/MacroValue.hh +++ b/macro/MacroValue.hh @@ -40,7 +40,9 @@ public: { public: const string message; - TypeError(const string &message_arg) : message(message_arg) {}; + TypeError(const string &message_arg) : message(message_arg) + { + }; }; //! Exception thrown when doing an out-of-bounds access through [] operator class OutOfBoundsError @@ -251,11 +253,11 @@ ArrayMV<T>::operator-(const MacroValue &mv) const throw (TypeError) /* Highly inefficient algorithm for computing set difference (but vector<T> is not suited for that...) */ vector<T> new_values; - for(typename vector<T>::const_iterator it = values.begin(); - it != values.end(); it++) + for (typename vector<T>::const_iterator it = values.begin(); + it != values.end(); it++) { typename vector<T>::const_iterator it2; - for(it2 = mv2->values.begin(); it2 != mv2->values.end(); it2++) + for (it2 = mv2->values.begin(); it2 != mv2->values.end(); it2++) if (*it == *it2) break; if (it2 == mv2->values.end()) @@ -295,8 +297,8 @@ ArrayMV<T>::operator[](const MacroValue &mv) const throw (TypeError, OutOfBounds if (mv2 == NULL) throw TypeError("Expression inside [] must be an integer array"); vector<T> result; - for(vector<int>::const_iterator it = mv2->values.begin(); - it != mv2->values.end(); it++) + for (vector<int>::const_iterator it = mv2->values.begin(); + it != mv2->values.end(); it++) { if (*it < 1 || *it > (int) values.size()) throw OutOfBoundsError(); @@ -314,8 +316,8 @@ string ArrayMV<T>::toString() const { ostringstream ss; - for(typename vector<T>::const_iterator it = values.begin(); - it != values.end(); it++) + for (typename vector<T>::const_iterator it = values.begin(); + it != values.end(); it++) ss << *it; return ss.str(); }