diff --git a/mex/sources/bytecode/ErrorHandling.hh b/mex/sources/bytecode/ErrorHandling.hh index 39c9f1b5b963a5d4f9a1ddd1303948873f5962f0..36f6da7db8a12c619ecffb19f4461beac46a7082 100644 --- a/mex/sources/bytecode/ErrorHandling.hh +++ b/mex/sources/bytecode/ErrorHandling.hh @@ -25,8 +25,8 @@ #include <sstream> #include "CodeInterpreter.hh" #ifdef DEBUG_EX -# include <math> -# include "mex_interface.hh" +# include <math> +# include "mex_interface.hh" #endif //#define DEBUG using namespace std; @@ -41,38 +41,40 @@ class GeneralExceptionHandling { string ErrorMsg; public: - GeneralExceptionHandling(string ErrorMsg_arg) : ErrorMsg(ErrorMsg_arg){}; + GeneralExceptionHandling(string ErrorMsg_arg) : ErrorMsg(ErrorMsg_arg) + { + }; inline string GetErrorMsg() - { - return ErrorMsg; - } + { + return ErrorMsg; + } inline void completeErrorMsg(string ErrorMsg_arg) - { - ErrorMsg += ErrorMsg_arg; - } + { + ErrorMsg += ErrorMsg_arg; + } }; class FloatingPointExceptionHandling : public GeneralExceptionHandling { public: FloatingPointExceptionHandling(string value) : GeneralExceptionHandling(string("Floating point error in bytecode: " + value)) - {}; + { + }; }; - class LogExceptionHandling : public FloatingPointExceptionHandling { double value; public: LogExceptionHandling(double value_arg) : FloatingPointExceptionHandling("log(X)"), value(value_arg) - { - ostringstream tmp; - tmp << " with X=" << value << "\n"; - completeErrorMsg(tmp.str()); - }; + { + ostringstream tmp; + tmp << " with X=" << value << "\n"; + completeErrorMsg(tmp.str()); + }; }; class Log10ExceptionHandling : public FloatingPointExceptionHandling @@ -80,12 +82,12 @@ class Log10ExceptionHandling : public FloatingPointExceptionHandling double value; public: Log10ExceptionHandling(double value_arg) : FloatingPointExceptionHandling("log10(X)"), - value(value_arg) - { - ostringstream tmp; - tmp << " with X=" << value << "\n"; - completeErrorMsg(tmp.str()); - }; + value(value_arg) + { + ostringstream tmp; + tmp << " with X=" << value << "\n"; + completeErrorMsg(tmp.str()); + }; }; class DivideExceptionHandling : public FloatingPointExceptionHandling @@ -93,163 +95,157 @@ class DivideExceptionHandling : public FloatingPointExceptionHandling double value1, value2; public: DivideExceptionHandling(double value1_arg, double value2_arg) : FloatingPointExceptionHandling("a/X"), - value1(value1_arg), - value2(value2_arg) - { - ostringstream tmp; - tmp << " with X=" << value2 << "\n"; - completeErrorMsg(tmp.str()); - }; + value1(value1_arg), + value2(value2_arg) + { + ostringstream tmp; + tmp << " with X=" << value2 << "\n"; + completeErrorMsg(tmp.str()); + }; }; - class PowExceptionHandling : public FloatingPointExceptionHandling { double value1, value2; public: PowExceptionHandling(double value1_arg, double value2_arg) : FloatingPointExceptionHandling("X^a"), - value1(value1_arg), - value2(value2_arg) - { - ostringstream tmp; - tmp << " with X=" << value1 << "\n"; - completeErrorMsg(tmp.str()); - }; + value1(value1_arg), + value2(value2_arg) + { + ostringstream tmp; + tmp << " with X=" << value1 << "\n"; + completeErrorMsg(tmp.str()); + }; }; - class FatalExceptionHandling : public GeneralExceptionHandling { public: FatalExceptionHandling(string ErrorMsg_arg) : GeneralExceptionHandling("Fatal error in bytecode:") - { - completeErrorMsg(ErrorMsg_arg); - }; + { + completeErrorMsg(ErrorMsg_arg); + }; FatalExceptionHandling() : GeneralExceptionHandling("") - { - }; + { + }; }; - - class ErrorMsg { public: -double *T; -int nb_row_xd, nb_row_x, y_size; -int y_kmin, y_kmax, periods; -double *x, *params; -double *u, *y, *ya; -double *steady_y, *steady_x; -double *g2, *g1, *r; -vector<mxArray*> jacobian_block, jacobian_other_endo_block, jacobian_exo_block, jacobian_det_exo_block; -map<unsigned int,double> TEF; -map<pair<unsigned int, unsigned int>, double > TEFD; -map<pair<unsigned int, pair<unsigned int, unsigned int> >, double > TEFDD; + double *T; + int nb_row_xd, nb_row_x, y_size; + int y_kmin, y_kmax, periods; + double *x, *params; + double *u, *y, *ya; + double *steady_y, *steady_x; + double *g2, *g1, *r; + vector<mxArray *> jacobian_block, jacobian_other_endo_block, jacobian_exo_block, jacobian_det_exo_block; + map<unsigned int, double> TEF; + map<pair<unsigned int, unsigned int>, double > TEFD; + map<pair<unsigned int, pair<unsigned int, unsigned int> >, double > TEFDD; -ExpressionType EQN_type; -it_code_type it_code_expr; -unsigned int nb_endo, nb_exo, nb_param; -char *P_endo_names, *P_exo_names, *P_param_names; -unsigned int endo_name_length, exo_name_length, param_name_length; -unsigned int EQN_equation, EQN_block, EQN_block_number; -unsigned int EQN_dvar1, EQN_dvar2, EQN_dvar3; + ExpressionType EQN_type; + it_code_type it_code_expr; + unsigned int nb_endo, nb_exo, nb_param; + char *P_endo_names, *P_exo_names, *P_param_names; + unsigned int endo_name_length, exo_name_length, param_name_length; + unsigned int EQN_equation, EQN_block, EQN_block_number; + unsigned int EQN_dvar1, EQN_dvar2, EQN_dvar3; + inline + ErrorMsg() + { + mxArray *M_ = mexGetVariable("global", "M_"); + nb_endo = mxGetM(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "endo_names"))); + endo_name_length = mxGetN(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "endo_names"))); + P_endo_names = (char *) mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "endo_names"))); + nb_exo = mxGetM(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "exo_names"))); + exo_name_length = mxGetN(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "exo_names"))); + P_exo_names = (char *) mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "exo_names"))); + nb_param = mxGetM(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "param_names"))); + param_name_length = mxGetN(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "param_names"))); + P_param_names = (char *) mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "param_names"))); + } -inline ErrorMsg() -{ - mxArray *M_ = mexGetVariable("global", "M_"); - nb_endo = mxGetM(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "endo_names"))); - endo_name_length = mxGetN(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "endo_names"))); - P_endo_names = (char*) mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "endo_names"))); - nb_exo = mxGetM(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "exo_names"))); - exo_name_length = mxGetN(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "exo_names"))); - P_exo_names = (char*) mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "exo_names"))); - nb_param = mxGetM(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "param_names"))); - param_name_length = mxGetN(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "param_names"))); - P_param_names = (char*) mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "param_names"))); -} - -inline string -add_underscore_to_fpe(const string &str) -{ - string temp; - int pos1 = -1, pos2 = -1; - string tmp_n(str.length(), ' '); - for (unsigned int i = 0; i < str.length(); i++) - { - if (str[i] != '$' && str[i] != '�') - temp += str[i]; - else - { - if (str[i] == '$') - pos1 = temp.length(); - else - pos2 = temp.length(); - if (pos1>=0 && pos2 >=0) - { - tmp_n.erase(pos1, pos2-pos1+1); - tmp_n.insert(pos1, pos2-pos1, '~'); - pos1 = pos2 = -1; - } - } - } - temp += "\n" + tmp_n ; - return temp; -} + inline string + add_underscore_to_fpe(const string &str) + { + string temp; + int pos1 = -1, pos2 = -1; + string tmp_n(str.length(), ' '); + for (unsigned int i = 0; i < str.length(); i++) + { + if (str[i] != '$' && str[i] != '�') + temp += str[i]; + else + { + if (str[i] == '$') + pos1 = temp.length(); + else + pos2 = temp.length(); + if (pos1 >= 0 && pos2 >= 0) + { + tmp_n.erase(pos1, pos2-pos1+1); + tmp_n.insert(pos1, pos2-pos1, '~'); + pos1 = pos2 = -1; + } + } + } + temp += "\n" + tmp_n; + return temp; + } + inline string + get_variable(const SymbolType variable_type, const unsigned int variable_num) const + { + ostringstream res; + switch (variable_type) + { + case eEndogenous: + if (variable_num < nb_endo) + { + for (unsigned int i = 0; i < endo_name_length; i++) + if (P_endo_names[CHAR_LENGTH*(variable_num+i*nb_endo)] != ' ') + res << P_endo_names[CHAR_LENGTH*(variable_num+i*nb_endo)]; + } + else + mexPrintf("=> Unknown endogenous variable n� %d", variable_num); + break; + case eExogenous: + case eExogenousDet: + if (variable_num < nb_exo) + { + for (unsigned int i = 0; i < exo_name_length; i++) + if (P_exo_names[CHAR_LENGTH*(variable_num+i*nb_exo)] != ' ') + res << P_exo_names[CHAR_LENGTH*(variable_num+i*nb_exo)]; + } + else + mexPrintf("=> Unknown exogenous variable n� %d", variable_num); + break; + case eParameter: + if (variable_num < nb_param) + { + for (unsigned int i = 0; i < param_name_length; i++) + if (P_param_names[CHAR_LENGTH*(variable_num+i*nb_param)] != ' ') + res << P_param_names[CHAR_LENGTH*(variable_num+i*nb_param)]; + } + else + mexPrintf("=> Unknown parameter n� %d", variable_num); + break; + default: + break; + } + return (res.str()); + } -inline string -get_variable(const SymbolType variable_type, const unsigned int variable_num) const -{ - ostringstream res; - switch(variable_type) - { - case eEndogenous: - if (variable_num < nb_endo) - { - for (unsigned int i = 0; i < endo_name_length; i++) - if (P_endo_names[CHAR_LENGTH*(variable_num+i*nb_endo)] != ' ') - res << P_endo_names[CHAR_LENGTH*(variable_num+i*nb_endo)]; - } - else - mexPrintf("=> Unknown endogenous variable n� %d",variable_num); - break; - case eExogenous: - case eExogenousDet: - if (variable_num < nb_exo) - { - for (unsigned int i = 0; i < exo_name_length; i++) - if (P_exo_names[CHAR_LENGTH*(variable_num+i*nb_exo)] != ' ') - res << P_exo_names[CHAR_LENGTH*(variable_num+i*nb_exo)]; - } - else - mexPrintf("=> Unknown exogenous variable n� %d",variable_num); - break; - case eParameter: - if (variable_num < nb_param) + inline string + error_location(bool evaluate, bool steady_state, int size, int block_num, int it_, int Per_u_) + { + stringstream Error_loc(""); + if (!steady_state) + switch (EQN_type) { - for (unsigned int i = 0; i < param_name_length; i++) - if (P_param_names[CHAR_LENGTH*(variable_num+i*nb_param)] != ' ') - res << P_param_names[CHAR_LENGTH*(variable_num+i*nb_param)]; - } - else - mexPrintf("=> Unknown parameter n� %d",variable_num); - break; - default: - break; - } - return(res.str()); -} - - -inline string -error_location(bool evaluate, bool steady_state, int size, int block_num, int it_, int Per_u_) -{ - stringstream Error_loc(""); - if (!steady_state) - switch(EQN_type) - { case TemporaryTerm: if (EQN_block_number > 1) Error_loc << "temporary term " << EQN_equation+1 << " in block " << EQN_block+1 << " at time " << it_; @@ -293,12 +289,12 @@ error_location(bool evaluate, bool steady_state, int size, int block_num, int it Error_loc << "first order derivative of equation " << EQN_equation+1 << " with respect to parameter " << get_variable(eEndogenous, EQN_dvar1) << " at time " << it_; break; default: - return("???"); + return ("???"); break; - } - else - switch(EQN_type) - { + } + else + switch (EQN_type) + { case TemporaryTerm: if (EQN_block_number > 1) Error_loc << "temporary term " << EQN_equation+1 << " in block " << EQN_block+1; @@ -342,1826 +338,1825 @@ error_location(bool evaluate, bool steady_state, int size, int block_num, int it Error_loc << "first order derivative of equation " << EQN_equation+1 << " with respect to parameter " << get_variable(eEndogenous, EQN_dvar1); break; default: - return("???"); + return ("???"); break; - } - it_code_type it_code_ret; - Error_loc << endl << add_underscore_to_fpe(" " + print_expression(it_code_expr, evaluate, size, block_num, steady_state, Per_u_, it_, it_code_ret, true)); - return(Error_loc.str()); -} + } + it_code_type it_code_ret; + Error_loc << endl << add_underscore_to_fpe(" " + print_expression(it_code_expr, evaluate, size, block_num, steady_state, Per_u_, it_, it_code_ret, true)); + return (Error_loc.str()); + } -inline string -print_expression(it_code_type it_code, bool evaluate, int size, int block_num, bool steady_state, int Per_u_, int it_, it_code_type &it_code_ret, bool compute) const -{ - int var, lag = 0, op, eq; - stack<string> Stack; - stack<double> Stackf; - ostringstream tmp_out, tmp_out2; - string v1, v2, v3; - double v1f, v2f, v3f =0.0; - bool go_on = true; - double ll; - ExpressionType equation_type = TemporaryTerm; - unsigned int equation_num; - unsigned int dvar1, dvar2, dvar3; - int lag1, lag2, lag3; - size_t found; - double *jacob = NULL, *jacob_other_endo = NULL, *jacob_exo = NULL, *jacob_exo_det = NULL; - external_function_type function_type = ExternalFunctionWithoutDerivative; + inline string + print_expression(it_code_type it_code, bool evaluate, int size, int block_num, bool steady_state, int Per_u_, int it_, it_code_type &it_code_ret, bool compute) const + { + int var, lag = 0, op, eq; + stack<string> Stack; + stack<double> Stackf; + ostringstream tmp_out, tmp_out2; + string v1, v2, v3; + double v1f, v2f, v3f = 0.0; + bool go_on = true; + double ll; + ExpressionType equation_type = TemporaryTerm; + unsigned int equation_num; + unsigned int dvar1, dvar2, dvar3; + int lag1, lag2, lag3; + size_t found; + double *jacob = NULL, *jacob_other_endo = NULL, *jacob_exo = NULL, *jacob_exo_det = NULL; + external_function_type function_type = ExternalFunctionWithoutDerivative; - if (evaluate) - { - jacob = mxGetPr(jacobian_block[block_num]); - if (!steady_state) - { - jacob_other_endo = mxGetPr(jacobian_other_endo_block[block_num]); - jacob_exo = mxGetPr(jacobian_exo_block[block_num]); - jacob_exo_det = mxGetPr(jacobian_det_exo_block[block_num]); - } - } + if (evaluate) + { + jacob = mxGetPr(jacobian_block[block_num]); + if (!steady_state) + { + jacob_other_endo = mxGetPr(jacobian_other_endo_block[block_num]); + jacob_exo = mxGetPr(jacobian_exo_block[block_num]); + jacob_exo_det = mxGetPr(jacobian_det_exo_block[block_num]); + } + } - while (go_on) - { - switch (it_code->first) - { - case FNUMEXPR: - switch (((FNUMEXPR_ *) it_code->second)->get_expression_type()) - { - case TemporaryTerm: - equation_type = TemporaryTerm; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - break; - case ModelEquation: - equation_type = ModelEquation; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - break; - case FirstEndoDerivative: - equation_type = FirstEndoDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); - break; - case FirstOtherEndoDerivative: - equation_type = FirstOtherEndoDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); - break; - case FirstExoDerivative: - equation_type = FirstExoDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); - break; - case FirstExodetDerivative: - equation_type = FirstExodetDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); - break; - case FirstParamDerivative: - equation_type = FirstParamDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - break; - case SecondEndoDerivative: - equation_type = SecondEndoDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); - dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); - lag2 = ((FNUMEXPR_ *) it_code->second)->get_lag2(); - break; - case SecondExoDerivative: - equation_type = SecondExoDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); - dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); - lag2 = ((FNUMEXPR_ *) it_code->second)->get_lag2(); - break; - case SecondExodetDerivative: - equation_type = SecondExodetDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); - dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); - lag2 = ((FNUMEXPR_ *) it_code->second)->get_lag2(); - break; - case SecondParamDerivative: - equation_type = SecondExodetDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); - break; - case ThirdEndoDerivative: - equation_type = ThirdEndoDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); - dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); - lag2 = ((FNUMEXPR_ *) it_code->second)->get_lag2(); - dvar3 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); - lag3 = ((FNUMEXPR_ *) it_code->second)->get_lag3(); - break; - case ThirdExoDerivative: - equation_type = ThirdExoDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); - dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); - lag2 = ((FNUMEXPR_ *) it_code->second)->get_lag2(); - dvar3 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); - lag3 = ((FNUMEXPR_ *) it_code->second)->get_lag3(); - break; - case ThirdExodetDerivative: - equation_type = ThirdExodetDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); - dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); - lag2 = ((FNUMEXPR_ *) it_code->second)->get_lag2(); - dvar3 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); - lag3 = ((FNUMEXPR_ *) it_code->second)->get_lag3(); - break; - case ThirdParamDerivative: - equation_type = ThirdExodetDerivative; - equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); - dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); - dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); - dvar3 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); - break; - default: - ostringstream tmp; - tmp << " in print_expression, expression type " << ((FNUMEXPR_ *) it_code->second)->get_expression_type() << " not implemented yet\n"; - throw FatalExceptionHandling(tmp.str()); - } - break; - case FLDV: - //load a variable in the processor - switch (((FLDV_ *) it_code->second)->get_type()) - { - case eParameter: - var = ((FLDV_ *) it_code->second)->get_pos(); + while (go_on) + { + switch (it_code->first) + { + case FNUMEXPR: + switch (((FNUMEXPR_ *) it_code->second)->get_expression_type()) + { + case TemporaryTerm: + equation_type = TemporaryTerm; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + break; + case ModelEquation: + equation_type = ModelEquation; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + break; + case FirstEndoDerivative: + equation_type = FirstEndoDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); + break; + case FirstOtherEndoDerivative: + equation_type = FirstOtherEndoDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); + break; + case FirstExoDerivative: + equation_type = FirstExoDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); + break; + case FirstExodetDerivative: + equation_type = FirstExodetDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); + break; + case FirstParamDerivative: + equation_type = FirstParamDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + break; + case SecondEndoDerivative: + equation_type = SecondEndoDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); + dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); + lag2 = ((FNUMEXPR_ *) it_code->second)->get_lag2(); + break; + case SecondExoDerivative: + equation_type = SecondExoDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); + dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); + lag2 = ((FNUMEXPR_ *) it_code->second)->get_lag2(); + break; + case SecondExodetDerivative: + equation_type = SecondExodetDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); + dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); + lag2 = ((FNUMEXPR_ *) it_code->second)->get_lag2(); + break; + case SecondParamDerivative: + equation_type = SecondExodetDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); + break; + case ThirdEndoDerivative: + equation_type = ThirdEndoDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); + dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); + lag2 = ((FNUMEXPR_ *) it_code->second)->get_lag2(); + dvar3 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); + lag3 = ((FNUMEXPR_ *) it_code->second)->get_lag3(); + break; + case ThirdExoDerivative: + equation_type = ThirdExoDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); + dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); + lag2 = ((FNUMEXPR_ *) it_code->second)->get_lag2(); + dvar3 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); + lag3 = ((FNUMEXPR_ *) it_code->second)->get_lag3(); + break; + case ThirdExodetDerivative: + equation_type = ThirdExodetDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + lag1 = ((FNUMEXPR_ *) it_code->second)->get_lag1(); + dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); + lag2 = ((FNUMEXPR_ *) it_code->second)->get_lag2(); + dvar3 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); + lag3 = ((FNUMEXPR_ *) it_code->second)->get_lag3(); + break; + case ThirdParamDerivative: + equation_type = ThirdExodetDerivative; + equation_num = ((FNUMEXPR_ *) it_code->second)->get_equation(); + dvar1 = ((FNUMEXPR_ *) it_code->second)->get_dvariable1(); + dvar2 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); + dvar3 = ((FNUMEXPR_ *) it_code->second)->get_dvariable2(); + break; + default: + ostringstream tmp; + tmp << " in print_expression, expression type " << ((FNUMEXPR_ *) it_code->second)->get_expression_type() << " not implemented yet\n"; + throw FatalExceptionHandling(tmp.str()); + } + break; + case FLDV: + //load a variable in the processor + switch (((FLDV_ *) it_code->second)->get_type()) + { + case eParameter: + var = ((FLDV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDV_ Param var=%d",var); + mexPrintf("FLDV_ Param var=%d", var); #endif - Stack.push(get_variable(eParameter, var)); - if (compute) - Stackf.push(params[var]); + Stack.push(get_variable(eParameter, var)); + if (compute) + Stackf.push(params[var]); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case eEndogenous: - var = ((FLDV_ *) it_code->second)->get_pos(); - lag = ((FLDV_ *) it_code->second)->get_lead_lag(); + break; + case eEndogenous: + var = ((FLDV_ *) it_code->second)->get_pos(); + lag = ((FLDV_ *) it_code->second)->get_lead_lag(); #ifdef DEBUG - mexPrintf("FLDV_ endo var=%d, lag=%d",var, lag); + mexPrintf("FLDV_ endo var=%d, lag=%d", var, lag); #endif - tmp_out.str(""); - if(lag > 0) - tmp_out << get_variable(eEndogenous, var) << "(+" << lag << ")"; - else if(lag < 0) - tmp_out << get_variable(eEndogenous, var) << "(" << lag << ")"; - else - tmp_out << get_variable(eEndogenous, var); - Stack.push(tmp_out.str()); - if (compute) - { - if (evaluate) - Stackf.push(ya[(it_+lag)*y_size+var]); - else - Stackf.push(y[(it_+lag)*y_size+var]); - } + tmp_out.str(""); + if (lag > 0) + tmp_out << get_variable(eEndogenous, var) << "(+" << lag << ")"; + else if (lag < 0) + tmp_out << get_variable(eEndogenous, var) << "(" << lag << ")"; + else + tmp_out << get_variable(eEndogenous, var); + Stack.push(tmp_out.str()); + if (compute) + { + if (evaluate) + Stackf.push(ya[(it_+lag)*y_size+var]); + else + Stackf.push(y[(it_+lag)*y_size+var]); + } #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case eExogenous: - var = ((FLDV_ *) it_code->second)->get_pos(); - lag = ((FLDV_ *) it_code->second)->get_lead_lag(); + break; + case eExogenous: + var = ((FLDV_ *) it_code->second)->get_pos(); + lag = ((FLDV_ *) it_code->second)->get_lead_lag(); #ifdef DEBUG - mexPrintf("FLDV_ exo var=%d, lag=%d",var, lag); + mexPrintf("FLDV_ exo var=%d, lag=%d", var, lag); #endif - tmp_out.str(""); - if(lag != 0) - tmp_out << get_variable(eExogenous, var) << "(" << lag << ")"; - else - tmp_out << get_variable(eExogenous, var); - Stack.push(tmp_out.str()); - if (compute) - Stackf.push(x[it_+lag+var*nb_row_x]); + tmp_out.str(""); + if (lag != 0) + tmp_out << get_variable(eExogenous, var) << "(" << lag << ")"; + else + tmp_out << get_variable(eExogenous, var); + Stack.push(tmp_out.str()); + if (compute) + Stackf.push(x[it_+lag+var*nb_row_x]); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case eExogenousDet: - var = ((FLDV_ *) it_code->second)->get_pos(); - lag = ((FLDV_ *) it_code->second)->get_lead_lag(); + break; + case eExogenousDet: + var = ((FLDV_ *) it_code->second)->get_pos(); + lag = ((FLDV_ *) it_code->second)->get_lead_lag(); #ifdef DEBUG - mexPrintf("FLDV_ exo_det var=%d, lag=%d",var, lag); + mexPrintf("FLDV_ exo_det var=%d, lag=%d", var, lag); #endif - tmp_out.str(""); - if(lag != 0) - tmp_out << get_variable(eExogenousDet, var) << "(" << lag << ")"; - else - tmp_out << get_variable(eExogenousDet, var); - Stack.push(tmp_out.str()); - if (compute) - Stackf.push(x[it_+lag+var*nb_row_xd]); + tmp_out.str(""); + if (lag != 0) + tmp_out << get_variable(eExogenousDet, var) << "(" << lag << ")"; + else + tmp_out << get_variable(eExogenousDet, var); + Stack.push(tmp_out.str()); + if (compute) + Stackf.push(x[it_+lag+var*nb_row_xd]); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case eModelLocalVariable: - break; - default: - mexPrintf("FLDV: Unknown variable type\n"); - } - break; - case FLDSV: - case FLDVS: - //load a variable in the processor - switch (((FLDSV_ *) it_code->second)->get_type()) - { - case eParameter: - var = ((FLDSV_ *) it_code->second)->get_pos(); + break; + case eModelLocalVariable: + break; + default: + mexPrintf("FLDV: Unknown variable type\n"); + } + break; + case FLDSV: + case FLDVS: + //load a variable in the processor + switch (((FLDSV_ *) it_code->second)->get_type()) + { + case eParameter: + var = ((FLDSV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDSV_ param var=%d",var); + mexPrintf("FLDSV_ param var=%d", var); #endif - Stack.push(get_variable(eParameter, var)); - if (compute) - Stackf.push(params[var]); + Stack.push(get_variable(eParameter, var)); + if (compute) + Stackf.push(params[var]); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case eEndogenous: - var = ((FLDSV_ *) it_code->second)->get_pos(); + break; + case eEndogenous: + var = ((FLDSV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDSV_ endo var=%d",var); + mexPrintf("FLDSV_ endo var=%d", var); #endif - Stack.push(get_variable(eEndogenous, var)); - if (compute) - { - if (it_code->first == FLDSV) - { - if (evaluate) - Stackf.push(ya[var]); - else - Stackf.push(y[var]); - } - else - Stackf.push(steady_y[var]); - } + Stack.push(get_variable(eEndogenous, var)); + if (compute) + { + if (it_code->first == FLDSV) + { + if (evaluate) + Stackf.push(ya[var]); + else + Stackf.push(y[var]); + } + else + Stackf.push(steady_y[var]); + } #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case eExogenous: - var = ((FLDSV_ *) it_code->second)->get_pos(); + break; + case eExogenous: + var = ((FLDSV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDSV_ exo var=%d",var); + mexPrintf("FLDSV_ exo var=%d", var); #endif - Stack.push(get_variable(eExogenous, var)); + Stack.push(get_variable(eExogenous, var)); #ifdef DEBUG - mexPrintf("oka var=%d, Stack.size()=%d x=%x\n", var, Stack.size(), x); + mexPrintf("oka var=%d, Stack.size()=%d x=%x\n", var, Stack.size(), x); #endif - if (compute) - Stackf.push(x[var]); + if (compute) + Stackf.push(x[var]); #ifdef DEBUG - mexPrintf("okb\n"); + mexPrintf("okb\n"); #endif - break; - case eExogenousDet: - var = ((FLDSV_ *) it_code->second)->get_pos(); + break; + case eExogenousDet: + var = ((FLDSV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDSV_ exo_det var=%d",var); + mexPrintf("FLDSV_ exo_det var=%d", var); #endif - Stack.push(get_variable(eExogenousDet, var)); - if (compute) - Stackf.push(x[var]); + Stack.push(get_variable(eExogenousDet, var)); + if (compute) + Stackf.push(x[var]); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case eModelLocalVariable: - break; - default: - mexPrintf("FLDSV: Unknown variable type\n"); - } - break; - case FLDT: - //load a temporary variable in the processor - var = ((FLDT_ *) it_code->second)->get_pos(); + break; + case eModelLocalVariable: + break; + default: + mexPrintf("FLDSV: Unknown variable type\n"); + } + break; + case FLDT: + //load a temporary variable in the processor + var = ((FLDT_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDT_ var=%d",var); + mexPrintf("FLDT_ var=%d", var); #endif - tmp_out.str(""); - tmp_out << "T" << var+1; - Stack.push(tmp_out.str()); - if (compute) - Stackf.push(T[var*(periods+y_kmin+y_kmax)+it_]); + tmp_out.str(""); + tmp_out << "T" << var+1; + Stack.push(tmp_out.str()); + if (compute) + Stackf.push(T[var*(periods+y_kmin+y_kmax)+it_]); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case FLDST: - //load a temporary variable in the processor - var = ((FLDST_ *) it_code->second)->get_pos(); + break; + case FLDST: + //load a temporary variable in the processor + var = ((FLDST_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDST_ var=%d",var); + mexPrintf("FLDST_ var=%d", var); #endif - tmp_out.str(""); - tmp_out << "T" << var+1; - Stack.push(tmp_out.str()); - if (compute) - Stackf.push(T[var]); + tmp_out.str(""); + tmp_out << "T" << var+1; + Stack.push(tmp_out.str()); + if (compute) + Stackf.push(T[var]); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case FLDU: - //load u variable in the processor - var = ((FLDU_ *) it_code->second)->get_pos(); + break; + case FLDU: + //load u variable in the processor + var = ((FLDU_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDU_ var=%d",var); + mexPrintf("FLDU_ var=%d", var); #endif - tmp_out.str(""); - tmp_out << "u(" << var+1 << " + it_)"; - Stack.push(tmp_out.str()); - var += Per_u_; - if (compute) - Stackf.push(u[var]); + tmp_out.str(""); + tmp_out << "u(" << var+1 << " + it_)"; + Stack.push(tmp_out.str()); + var += Per_u_; + if (compute) + Stackf.push(u[var]); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case FLDSU: - //load u variable in the processor - var = ((FLDSU_ *) it_code->second)->get_pos(); + break; + case FLDSU: + //load u variable in the processor + var = ((FLDSU_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDSU_ var=%d",var); + mexPrintf("FLDSU_ var=%d", var); #endif - tmp_out.str(""); - tmp_out << "u(" << var+1 << ")"; - Stack.push(tmp_out.str()); - if (compute) - Stackf.push(u[var]); + tmp_out.str(""); + tmp_out << "u(" << var+1 << ")"; + Stack.push(tmp_out.str()); + if (compute) + Stackf.push(u[var]); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case FLDR: - var = ((FLDR_ *) it_code->second)->get_pos(); + break; + case FLDR: + var = ((FLDR_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDSR_ var=%d",var); + mexPrintf("FLDSR_ var=%d", var); #endif - tmp_out.str(""); - tmp_out << "residual(" << var+1 << ")"; - Stack.push(tmp_out.str()); - if (compute) - Stackf.push(r[var]); + tmp_out.str(""); + tmp_out << "residual(" << var+1 << ")"; + Stack.push(tmp_out.str()); + if (compute) + Stackf.push(r[var]); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case FLDZ: - //load 0 in the processor + break; + case FLDZ: + //load 0 in the processor #ifdef DEBUG - mexPrintf("FLDZ_"); + mexPrintf("FLDZ_"); #endif - tmp_out.str(""); - tmp_out << 0; - Stack.push(tmp_out.str()); - if (compute) - Stackf.push(0.0); + tmp_out.str(""); + tmp_out << 0; + Stack.push(tmp_out.str()); + if (compute) + Stackf.push(0.0); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case FLDC: - //load a numerical constant in the processor - ll = ((FLDC_ *) it_code->second)->get_value(); - tmp_out.str(""); + break; + case FLDC: + //load a numerical constant in the processor + ll = ((FLDC_ *) it_code->second)->get_value(); + tmp_out.str(""); #ifdef DEBUG - mexPrintf("FLDC_ ll=%f",ll); + mexPrintf("FLDC_ ll=%f", ll); #endif - tmp_out << ll; - Stack.push(tmp_out.str()); - if (compute) - Stackf.push(ll); + tmp_out << ll; + Stack.push(tmp_out.str()); + if (compute) + Stackf.push(ll); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case FSTPV: - //load a variable in the processor - go_on = false; - switch (((FSTPV_ *) it_code->second)->get_type()) - { - case eParameter: - var = ((FSTPV_ *) it_code->second)->get_pos(); + break; + case FSTPV: + //load a variable in the processor + go_on = false; + switch (((FSTPV_ *) it_code->second)->get_type()) + { + case eParameter: + var = ((FSTPV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FSTPV_ param var=%d",var); + mexPrintf("FSTPV_ param var=%d", var); #endif - tmp_out2.str(""); - tmp_out2 << Stack.top(); - tmp_out.str(""); - tmp_out << get_variable(eParameter, var) << " = " << tmp_out2.str(); - Stack.pop(); - if (compute) - { - params[var] = Stackf.top(); - Stackf.pop(); - } + tmp_out2.str(""); + tmp_out2 << Stack.top(); + tmp_out.str(""); + tmp_out << get_variable(eParameter, var) << " = " << tmp_out2.str(); + Stack.pop(); + if (compute) + { + params[var] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("ok\n"); -#endif - break; - case eEndogenous: - var = ((FSTPV_ *) it_code->second)->get_pos(); - lag = ((FSTPV_ *) it_code->second)->get_lead_lag(); -#ifdef DEBUG - mexPrintf("FSTPV_ endo var=%d, lag=%d",var, lag); + mexPrintf("ok\n"); #endif - tmp_out2.str(""); - tmp_out2 << Stack.top(); - tmp_out.str(""); - tmp_out << get_variable(eEndogenous, var); - if(lag > 0) - tmp_out << "(+" << lag << ")"; - else if(lag < 0) - tmp_out << "(" << lag << ")"; - tmp_out << " = " << tmp_out2.str(); - Stack.pop(); - if (compute) - { - y[(it_+lag)*y_size+var] = Stackf.top(); - Stackf.pop(); - } + break; + case eEndogenous: + var = ((FSTPV_ *) it_code->second)->get_pos(); + lag = ((FSTPV_ *) it_code->second)->get_lead_lag(); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("FSTPV_ endo var=%d, lag=%d", var, lag); #endif - break; - case eExogenous: - var = ((FSTPV_ *) it_code->second)->get_pos(); - lag = ((FSTPV_ *) it_code->second)->get_lead_lag(); + tmp_out2.str(""); + tmp_out2 << Stack.top(); + tmp_out.str(""); + tmp_out << get_variable(eEndogenous, var); + if (lag > 0) + tmp_out << "(+" << lag << ")"; + else if (lag < 0) + tmp_out << "(" << lag << ")"; + tmp_out << " = " << tmp_out2.str(); + Stack.pop(); + if (compute) + { + y[(it_+lag)*y_size+var] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("FSTPV_ exo var=%d, lag=%d",var, lag); + mexPrintf("ok\n"); #endif - tmp_out2.str(""); - tmp_out2 << Stack.top(); - tmp_out.str(""); - tmp_out << get_variable(eExogenous, var); - if (lag != 0) - tmp_out << "(" << lag << ")"; - tmp_out << " = " << tmp_out2.str(); - Stack.pop(); - if (compute) - { - x[it_+lag+var*nb_row_x] = Stackf.top(); - Stackf.pop(); - } + break; + case eExogenous: + var = ((FSTPV_ *) it_code->second)->get_pos(); + lag = ((FSTPV_ *) it_code->second)->get_lead_lag(); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("FSTPV_ exo var=%d, lag=%d", var, lag); #endif - break; - case eExogenousDet: - var = ((FSTPV_ *) it_code->second)->get_pos(); - lag = ((FSTPV_ *) it_code->second)->get_lead_lag(); + tmp_out2.str(""); + tmp_out2 << Stack.top(); + tmp_out.str(""); + tmp_out << get_variable(eExogenous, var); + if (lag != 0) + tmp_out << "(" << lag << ")"; + tmp_out << " = " << tmp_out2.str(); + Stack.pop(); + if (compute) + { + x[it_+lag+var*nb_row_x] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("FSTPV_ exodet var=%d, lag=%d",var, lag); + mexPrintf("ok\n"); #endif - tmp_out2.str(""); - tmp_out2 << Stack.top(); - tmp_out.str(""); - tmp_out << get_variable(eExogenousDet, var); - if (lag != 0) - tmp_out << "(" << lag << ")"; - tmp_out << " = " << tmp_out2.str(); - Stack.pop(); - if (compute) - { - x[it_+lag+var*nb_row_xd] = Stackf.top(); - Stackf.pop(); - } + break; + case eExogenousDet: + var = ((FSTPV_ *) it_code->second)->get_pos(); + lag = ((FSTPV_ *) it_code->second)->get_lead_lag(); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("FSTPV_ exodet var=%d, lag=%d", var, lag); #endif - break; - default: - mexPrintf("FSTPV: Unknown variable type\n"); - } - break; - case FSTPSV: - go_on = false; - //load a variable in the processor - switch (((FSTPSV_ *) it_code->second)->get_type()) - { - case eParameter: - var = ((FSTPSV_ *) it_code->second)->get_pos(); + tmp_out2.str(""); + tmp_out2 << Stack.top(); + tmp_out.str(""); + tmp_out << get_variable(eExogenousDet, var); + if (lag != 0) + tmp_out << "(" << lag << ")"; + tmp_out << " = " << tmp_out2.str(); + Stack.pop(); + if (compute) + { + x[it_+lag+var*nb_row_xd] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("FSTPSV_ param var=%d",var); + mexPrintf("ok\n"); #endif - tmp_out2.str(""); - tmp_out2 << Stack.top(); - tmp_out.str(""); - tmp_out << get_variable(eParameter, var); - tmp_out << " = " << tmp_out2.str(); - Stack.pop(); - if (compute) - { - params[var] = Stackf.top(); - Stackf.pop(); - } + break; + default: + mexPrintf("FSTPV: Unknown variable type\n"); + } + break; + case FSTPSV: + go_on = false; + //load a variable in the processor + switch (((FSTPSV_ *) it_code->second)->get_type()) + { + case eParameter: + var = ((FSTPSV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("FSTPSV_ param var=%d", var); #endif - break; - case eEndogenous: - var = ((FSTPSV_ *) it_code->second)->get_pos(); + tmp_out2.str(""); + tmp_out2 << Stack.top(); + tmp_out.str(""); + tmp_out << get_variable(eParameter, var); + tmp_out << " = " << tmp_out2.str(); + Stack.pop(); + if (compute) + { + params[var] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("FSTPSV_ endo var=%d",var); + mexPrintf("ok\n"); #endif - tmp_out2.str(""); - tmp_out2 << Stack.top(); - tmp_out.str(""); - tmp_out << get_variable(eEndogenous, var); - tmp_out << " = " << tmp_out2.str(); - Stack.pop(); - if (compute) - { - y[var] = Stackf.top(); - Stackf.pop(); - } + break; + case eEndogenous: + var = ((FSTPSV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("FSTPSV_ endo var=%d", var); #endif - break; - case eExogenous: - case eExogenousDet: - var = ((FSTPSV_ *) it_code->second)->get_pos(); + tmp_out2.str(""); + tmp_out2 << Stack.top(); + tmp_out.str(""); + tmp_out << get_variable(eEndogenous, var); + tmp_out << " = " << tmp_out2.str(); + Stack.pop(); + if (compute) + { + y[var] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("FSTPSV_ exo var=%d",var); + mexPrintf("ok\n"); #endif - tmp_out2.str(""); - tmp_out2 << Stack.top(); - tmp_out.str(""); - tmp_out << get_variable(eExogenous, var); - tmp_out << " = " << tmp_out2.str(); - Stack.pop(); - if (compute) - { - x[var] = Stackf.top(); - Stackf.pop(); - } + break; + case eExogenous: + case eExogenousDet: + var = ((FSTPSV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("FSTPSV_ exo var=%d", var); #endif - break; - default: - mexPrintf("FSTPSV: Unknown variable type\n"); - } - break; - case FSTPT: - go_on = false; - //store in a temporary variable from the processor - var = ((FSTPT_ *) it_code->second)->get_pos(); + tmp_out2.str(""); + tmp_out2 << Stack.top(); + tmp_out.str(""); + tmp_out << get_variable(eExogenous, var); + tmp_out << " = " << tmp_out2.str(); + Stack.pop(); + if (compute) + { + x[var] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("FSTPT_ var=%d",var); + mexPrintf("ok\n"); #endif - tmp_out.str(""); - tmp_out << "T" << var+1 << " = " << Stack.top(); - Stack.pop(); - if (compute) - { - T[var*(periods+y_kmin+y_kmax)+it_] = Stackf.top(); - Stackf.pop(); - } + break; + default: + mexPrintf("FSTPSV: Unknown variable type\n"); + } + break; + case FSTPT: + go_on = false; + //store in a temporary variable from the processor + var = ((FSTPT_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("FSTPT_ var=%d", var); #endif - break; - case FSTPST: - go_on = false; - //store in a temporary variable from the processor - var = ((FSTPST_ *) it_code->second)->get_pos(); + tmp_out.str(""); + tmp_out << "T" << var+1 << " = " << Stack.top(); + Stack.pop(); + if (compute) + { + T[var*(periods+y_kmin+y_kmax)+it_] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("FSTPST_ var=%d",var); + mexPrintf("ok\n"); #endif - tmp_out.str(""); - tmp_out << "T" << var+1 << " = " << Stack.top(); - Stack.pop(); - if (compute) - { - T[var] = Stackf.top(); - Stackf.pop(); - } + break; + case FSTPST: + go_on = false; + //store in a temporary variable from the processor + var = ((FSTPST_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("FSTPST_ var=%d", var); #endif - break; - case FSTPU: - go_on = false; - //store in u variable from the processor - var = ((FSTPU_ *) it_code->second)->get_pos(); -#ifdef DEBUG - mexPrintf("FSTPU_ var=%d",var); -#endif - tmp_out.str(""); - tmp_out << "u(" << var+1 << " + it_) = " << Stack.top(); - var += Per_u_; - Stack.pop(); - if (compute) - { - u[var] = Stackf.top(); - Stackf.pop(); - } + tmp_out.str(""); + tmp_out << "T" << var+1 << " = " << Stack.top(); + Stack.pop(); + if (compute) + { + T[var] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case FSTPSU: - go_on = false; - //store in u variable from the processor - var = ((FSTPSU_ *) it_code->second)->get_pos(); + break; + case FSTPU: + go_on = false; + //store in u variable from the processor + var = ((FSTPU_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FSTPSU_ var=%d",var); + mexPrintf("FSTPU_ var=%d", var); #endif - tmp_out.str(""); - tmp_out << "u(" << var+1 << ") = " << Stack.top(); - Stack.pop(); - if (compute) - { - u[var] = Stackf.top(); - Stackf.pop(); - } + tmp_out.str(""); + tmp_out << "u(" << var+1 << " + it_) = " << Stack.top(); + var += Per_u_; + Stack.pop(); + if (compute) + { + u[var] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case FSTPR: - go_on = false; - //store in residual variable from the processor - var = ((FSTPR_ *) it_code->second)->get_pos(); + break; + case FSTPSU: + go_on = false; + //store in u variable from the processor + var = ((FSTPSU_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FSTPR_ var=%d",var); + mexPrintf("FSTPSU_ var=%d", var); #endif - tmp_out.str(""); - tmp_out << "residual(" << var+1 << ") = " << Stack.top(); - Stack.pop(); - if (compute) - { - r[var] = Stackf.top(); - Stackf.pop(); - } + tmp_out.str(""); + tmp_out << "u(" << var+1 << ") = " << Stack.top(); + Stack.pop(); + if (compute) + { + u[var] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case FSTPG: - go_on = false; - //store in derivative (g) variable from the processor - var = ((FSTPG_ *) it_code->second)->get_pos(); + break; + case FSTPR: + go_on = false; + //store in residual variable from the processor + var = ((FSTPR_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FSTG_ var=%d",var); + mexPrintf("FSTPR_ var=%d", var); #endif - tmp_out.str(""); - tmp_out << "g1[" << var+1 << "] = " << Stack.top(); - Stack.pop(); - if (compute) - { - g1[var] = Stackf.top(); - Stackf.pop(); - } + tmp_out.str(""); + tmp_out << "residual(" << var+1 << ") = " << Stack.top(); + Stack.pop(); + if (compute) + { + r[var] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case FSTPG2: - go_on = false; - //store in derivative (g) variable from the processor - eq = ((FSTPG2_ *) it_code->second)->get_row(); - var = ((FSTPG2_ *) it_code->second)->get_col(); -#ifdef DEBUG - mexPrintf("FSTG2_ eq=%d var=%d",eq, var); -#endif - tmp_out.str(""); - tmp_out << "jacob(" << eq+size*var+1 << ") = " << Stack.top(); - Stack.pop(); - if (compute) - { - jacob[eq + size*var] = Stackf.top(); - Stackf.pop(); - } + break; + case FSTPG: + go_on = false; + //store in derivative (g) variable from the processor + var = ((FSTPG_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("FSTG_ var=%d", var); #endif - break; - case FSTPG3: - //store in derivative (g) variable from the processor + tmp_out.str(""); + tmp_out << "g1[" << var+1 << "] = " << Stack.top(); + Stack.pop(); + if (compute) + { + g1[var] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("FSTPG3\n"); - mexEvalString("drawnow;"); + mexPrintf("ok\n"); #endif - double r; - unsigned int pos_col; - go_on = false; - if (compute) - { - r = Stackf.top(); - Stackf.pop(); - } - eq = ((FSTPG3_ *) it_code->second)->get_row(); - var = ((FSTPG3_ *) it_code->second)->get_col(); - lag = ((FSTPG3_ *) it_code->second)->get_lag(); - pos_col = ((FSTPG3_ *) it_code->second)->get_col_pos(); - switch(equation_type) - { - case FirstEndoDerivative: + break; + case FSTPG2: + go_on = false; + //store in derivative (g) variable from the processor + eq = ((FSTPG2_ *) it_code->second)->get_row(); + var = ((FSTPG2_ *) it_code->second)->get_col(); #ifdef DEBUG - mexPrintf("Endo eq=%d, pos_col=%d, size=%d\n",eq, pos_col,size); + mexPrintf("FSTG2_ eq=%d var=%d", eq, var); #endif - if (compute) - jacob[eq + size*pos_col] = r; - tmp_out.str(""); - tmp_out << "jacob(" << eq+size*pos_col+1 << ") = " << Stack.top(); - Stack.pop(); - break; - case FirstOtherEndoDerivative: - if (compute) - jacob_other_endo[eq + size*pos_col] = r; - tmp_out.str(""); - tmp_out << "jacob_other_endo(" << eq+size*pos_col+1 << ") = " << Stack.top(); - Stack.pop(); - break; - case FirstExoDerivative: + tmp_out.str(""); + tmp_out << "jacob(" << eq+size*var+1 << ") = " << Stack.top(); + Stack.pop(); + if (compute) + { + jacob[eq + size*var] = Stackf.top(); + Stackf.pop(); + } #ifdef DEBUG - mexPrintf("Exo eq=%d, pos_col=%d, size=%d\n",eq, pos_col,size); + mexPrintf("ok\n"); #endif - if (compute) - jacob_exo[eq + size*pos_col] = r; - tmp_out.str(""); - tmp_out << "jacob_exo(" << eq+size*pos_col+1 << ") = " << Stack.top(); - Stack.pop(); - break; - case FirstExodetDerivative: - if (compute) - jacob_exo_det[eq + size*pos_col] = r; - tmp_out.str(""); - tmp_out << "jacob_exo_det(" << eq+size*pos_col+1 << ") = " << Stack.top(); - Stack.pop(); - break; - default: - ostringstream tmp; - tmp << " in compute_block_time, variable " << EQN_type << " not used yet\n"; - //throw FatalExceptionHandling(tmp.str()); - mexPrintf("%s",tmp.str().c_str()); - } + break; + case FSTPG3: + //store in derivative (g) variable from the processor #ifdef DEBUG - tmp_out << "=>"; - mexPrintf(" g1[%d](%f)=%s\n", var, g1[var], tmp_out.str().c_str()); - tmp_out.str(""); + mexPrintf("FSTPG3\n"); + mexEvalString("drawnow;"); #endif - break; - case FBINARY: - op = ((FBINARY_ *) it_code->second)->get_op_type(); - v2 = Stack.top(); - Stack.pop(); - v1 = Stack.top(); - Stack.pop(); - if (compute) - { - v2f = Stackf.top(); - Stackf.pop(); - v1f = Stackf.top(); - Stackf.pop(); - } - switch (op) - { - case oPlus: + double r; + unsigned int pos_col; + go_on = false; + if (compute) + { + r = Stackf.top(); + Stackf.pop(); + } + eq = ((FSTPG3_ *) it_code->second)->get_row(); + var = ((FSTPG3_ *) it_code->second)->get_col(); + lag = ((FSTPG3_ *) it_code->second)->get_lag(); + pos_col = ((FSTPG3_ *) it_code->second)->get_col_pos(); + switch (equation_type) + { + case FirstEndoDerivative: #ifdef DEBUG - mexPrintf("+"); + mexPrintf("Endo eq=%d, pos_col=%d, size=%d\n", eq, pos_col, size); #endif - if (compute) - Stackf.push(v1f + v2f); - tmp_out.str(""); - tmp_out << v1 << " + " << v2; - Stack.push(tmp_out.str()); + if (compute) + jacob[eq + size*pos_col] = r; + tmp_out.str(""); + tmp_out << "jacob(" << eq+size*pos_col+1 << ") = " << Stack.top(); + Stack.pop(); + break; + case FirstOtherEndoDerivative: + if (compute) + jacob_other_endo[eq + size*pos_col] = r; + tmp_out.str(""); + tmp_out << "jacob_other_endo(" << eq+size*pos_col+1 << ") = " << Stack.top(); + Stack.pop(); + break; + case FirstExoDerivative: #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("Exo eq=%d, pos_col=%d, size=%d\n", eq, pos_col, size); #endif - break; - case oMinus: + if (compute) + jacob_exo[eq + size*pos_col] = r; + tmp_out.str(""); + tmp_out << "jacob_exo(" << eq+size*pos_col+1 << ") = " << Stack.top(); + Stack.pop(); + break; + case FirstExodetDerivative: + if (compute) + jacob_exo_det[eq + size*pos_col] = r; + tmp_out.str(""); + tmp_out << "jacob_exo_det(" << eq+size*pos_col+1 << ") = " << Stack.top(); + Stack.pop(); + break; + default: + ostringstream tmp; + tmp << " in compute_block_time, variable " << EQN_type << " not used yet\n"; + //throw FatalExceptionHandling(tmp.str()); + mexPrintf("%s", tmp.str().c_str()); + } #ifdef DEBUG - mexPrintf("-"); + tmp_out << "=>"; + mexPrintf(" g1[%d](%f)=%s\n", var, g1[var], tmp_out.str().c_str()); + tmp_out.str(""); #endif - if (compute) - Stackf.push(v1f - v2f); - tmp_out.str(""); - found = v1.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v1; - if (found != string::npos) - tmp_out << ")"; - tmp_out << " - "; - found = v2.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v2; - if (found != string::npos) - tmp_out << ")"; - Stack.push(tmp_out.str()); + break; + case FBINARY: + op = ((FBINARY_ *) it_code->second)->get_op_type(); + v2 = Stack.top(); + Stack.pop(); + v1 = Stack.top(); + Stack.pop(); + if (compute) + { + v2f = Stackf.top(); + Stackf.pop(); + v1f = Stackf.top(); + Stackf.pop(); + } + switch (op) + { + case oPlus: #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("+"); #endif - break; - case oTimes: + if (compute) + Stackf.push(v1f + v2f); + tmp_out.str(""); + tmp_out << v1 << " + " << v2; + Stack.push(tmp_out.str()); #ifdef DEBUG - mexPrintf("*"); + mexPrintf("ok\n"); #endif - if (compute) - Stackf.push(v1f * v2f); - tmp_out.str(""); - found = v1.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v1; - if (found != string::npos) - tmp_out << ")"; - tmp_out << " * "; - found = v2.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v2; - if (found != string::npos) - tmp_out << ")"; - Stack.push(tmp_out.str()); + break; + case oMinus: #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("-"); #endif - break; - case oDivide: + if (compute) + Stackf.push(v1f - v2f); + tmp_out.str(""); + found = v1.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v1; + if (found != string::npos) + tmp_out << ")"; + tmp_out << " - "; + found = v2.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v2; + if (found != string::npos) + tmp_out << ")"; + Stack.push(tmp_out.str()); #ifdef DEBUG - mexPrintf("/"); + mexPrintf("ok\n"); #endif - if (compute) - { - r = v1f / v2f; - Stackf.push(r); - } - tmp_out.str(""); - found = v1.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v1; - if (found != string::npos) - tmp_out << ")"; - if (compute) - { - if (isinf(r)) - tmp_out << "$"; - tmp_out << " / "; - if (isinf(r)) - tmp_out << "�"; - } - else - tmp_out << " / "; - found = v2.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v2; - if (found != string::npos) - tmp_out << ")"; - Stack.push(tmp_out.str()); + break; + case oTimes: #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("*"); #endif - break; - case oLess: + if (compute) + Stackf.push(v1f * v2f); + tmp_out.str(""); + found = v1.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v1; + if (found != string::npos) + tmp_out << ")"; + tmp_out << " * "; + found = v2.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v2; + if (found != string::npos) + tmp_out << ")"; + Stack.push(tmp_out.str()); #ifdef DEBUG - mexPrintf("<"); + mexPrintf("ok\n"); #endif - if (compute) - Stackf.push(double (v1f < v2f)); - tmp_out.str(""); - found = v1.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v1; - if (found != string::npos) - tmp_out << ")"; - tmp_out << " < "; - found = v2.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v2; - if (found != string::npos) - tmp_out << ")"; - Stack.push(tmp_out.str()); -#ifdef DEBUG - mexPrintf("ok\n"); -#endif - break; - case oGreater: -#ifdef DEBUG - mexPrintf(">"); -#endif - if (compute) - Stackf.push(double (v1f > v2f)); - tmp_out.str(""); - found = v1.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v1; - if (found != string::npos) - tmp_out << ")"; - tmp_out << " > "; - found = v2.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v2; - if (found != string::npos) - tmp_out << ")"; - Stack.push(tmp_out.str()); -#ifdef DEBUG - mexPrintf("ok\n"); -#endif - break; - case oLessEqual: -#ifdef DEBUG - mexPrintf("<="); -#endif - if (compute) - Stackf.push(double (v1f <= v2f)); - tmp_out.str(""); - found = v1.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v1; - if (found != string::npos) - tmp_out << ")"; - tmp_out << " <= "; - found = v2.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v2; - if (found != string::npos) - tmp_out << ")"; - Stack.push(tmp_out.str()); - #ifdef DEBUG - mexPrintf("ok\n"); -#endif - break; - case oGreaterEqual: -#ifdef DEBUG - mexPrintf(">="); -#endif - if (compute) - Stackf.push(double (v1f >= v2f)); - tmp_out.str(""); - found = v1.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v1; - if (found != string::npos) - tmp_out << ")"; - tmp_out << " >= "; - found = v2.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v2; - if (found != string::npos) - tmp_out << ")"; - Stack.push(tmp_out.str()); -#ifdef DEBUG - mexPrintf("ok\n"); -#endif - break; - case oEqualEqual: -#ifdef DEBUG - mexPrintf("=="); -#endif - if (compute) - Stackf.push(double (v1f == v2f)); - tmp_out.str(""); - found = v1.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v1; - if (found != string::npos) - tmp_out << ")"; - tmp_out << " == "; - found = v2.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v2; - if (found != string::npos) - tmp_out << ")"; - Stack.push(tmp_out.str()); -#ifdef DEBUG - mexPrintf("ok\n"); -#endif - break; - case oDifferent: -#ifdef DEBUG - mexPrintf("!="); -#endif - if (compute) - Stackf.push(double (v1f != v2f)); - tmp_out.str(""); - found = v1.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v1; - if (found != string::npos) - tmp_out << ")"; - tmp_out << " != "; - found = v2.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v2; - if (found != string::npos) - tmp_out << ")"; - Stack.push(tmp_out.str()); -#ifdef DEBUG - mexPrintf("ok\n"); -#endif - break; - case oPower: -#ifdef DEBUG - mexPrintf("^"); -#endif - if (compute) - { - r = pow(v1f, v2f); - Stackf.push(r); - } - tmp_out.str(""); - found = v1.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v1; - if (found != string::npos) - tmp_out << ")"; - if (compute) - { - if (isnan(r)) - tmp_out << "$ ^ �"; - else - tmp_out << " ^ "; - } - else - tmp_out << " ^ "; - found = v2.find(" "); - if (found != string::npos) - tmp_out << "("; - tmp_out << v2; - if (found != string::npos) - tmp_out << ")"; - Stack.push(tmp_out.str()); + break; + case oDivide: #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("/"); #endif - break; - case oPowerDeriv: - { - v3 = Stack.top(); - Stack.pop(); if (compute) { - int derivOrder = nearbyint(Stackf.top()); - Stackf.pop(); - if (fabs(v1f) < NEAR_ZERO && v2f > 0 && - derivOrder >= v2f && - fabs(v2f-nearbyint(v2f)) < NEAR_ZERO) - { - r = 0.0; - Stackf.push(r); - } - else - { - double dxp = pow(v1f, v2f-derivOrder); - for (int i=0; i<derivOrder; i++) - dxp *= v2f--; - Stackf.push(dxp); - r = dxp; - } + r = v1f / v2f; + Stackf.push(r); } tmp_out.str(""); + found = v1.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v1; + if (found != string::npos) + tmp_out << ")"; if (compute) { - if (isnan(r)) - tmp_out << "$ PowerDeriv �"; - else - tmp_out << "PowerDeriv"; + if (isinf(r)) + tmp_out << "$"; + tmp_out << " / "; + if (isinf(r)) + tmp_out << "�"; } else - tmp_out << "PowerDeriv"; - tmp_out << "(" << v1 << ", " << v2 << ", " << v3 << ")"; + tmp_out << " / "; + found = v2.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v2; + if (found != string::npos) + tmp_out << ")"; Stack.push(tmp_out.str()); - } #ifdef DEBUG - tmp_out << " |PowerDeriv(" << v1 << ", " << v2 << v3 << ")|"; + mexPrintf("ok\n"); #endif - break; - case oMax: + break; + case oLess: #ifdef DEBUG - mexPrintf("max"); + mexPrintf("<"); #endif - if (compute) - Stackf.push(max(v1f, v2f)); - tmp_out.str(""); - tmp_out << "max(" << v1 << ", " << v2 << ")"; - Stack.push(tmp_out.str()); + if (compute) + Stackf.push(double (v1f < v2f)); + tmp_out.str(""); + found = v1.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v1; + if (found != string::npos) + tmp_out << ")"; + tmp_out << " < "; + found = v2.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v2; + if (found != string::npos) + tmp_out << ")"; + Stack.push(tmp_out.str()); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); #endif - break; - case oMin: + break; + case oGreater: #ifdef DEBUG - mexPrintf("min"); + mexPrintf(">"); #endif - if (compute) - Stackf.push(min(v1f, v2f)); - tmp_out.str(""); - tmp_out << "min(" << v1 << ", " << v2 << ")"; - Stack.push(tmp_out.str()); + if (compute) + Stackf.push(double (v1f > v2f)); + tmp_out.str(""); + found = v1.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v1; + if (found != string::npos) + tmp_out << ")"; + tmp_out << " > "; + found = v2.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v2; + if (found != string::npos) + tmp_out << ")"; + Stack.push(tmp_out.str()); #ifdef DEBUG - mexPrintf("ok\n"); + mexPrintf("ok\n"); +#endif + break; + case oLessEqual: +#ifdef DEBUG + mexPrintf("<="); #endif - break; - case oEqual: - default: - mexPrintf("Error unknown Unary operator=%d\n",op);mexEvalString("drawnow;"); - ; - } - break; - case FUNARY: - op = ((FUNARY_ *) it_code->second)->get_op_type(); - v1 = Stack.top(); - Stack.pop(); - if (compute) - { - v1f = Stackf.top(); - Stackf.pop(); - } - switch (op) - { - case oUminus: - if (compute) - Stackf.push(-v1f); - tmp_out.str(""); - tmp_out << " -" << v1; - Stack.push(tmp_out.str()); - break; - case oExp: - if (compute) - Stackf.push(exp(v1f)); - tmp_out.str(""); - tmp_out << "exp(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oLog: - if (compute) - { - r = log(v1f); - Stackf.push(r); - } - tmp_out.str(""); - if (compute) - { - if (isnan(r)) - tmp_out << "$log�(" << v1 << ")"; - else - tmp_out << "log(" << v1 << ")"; - } - else - tmp_out << "log(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oLog10: - if (compute) - { - r = log10(v1f); - Stackf.push(r); - } - tmp_out.str(""); - if (compute) - { - if (isnan(r)) - tmp_out << "$log10�(" << v1 << ")"; - else - tmp_out << "log10(" << v1 << ")"; - } - else - tmp_out << "log10(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oCos: - if (compute) - Stackf.push(cos(v1f)); - tmp_out.str(""); - tmp_out << "cos(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oSin: - if (compute) - Stackf.push(sin(v1f)); - tmp_out.str(""); - tmp_out << "sin(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oTan: - if (compute) - Stackf.push(tan(v1f)); - tmp_out.str(""); - tmp_out << "tan(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oAcos: - if (compute) - Stackf.push(acos(v1f)); - tmp_out.str(""); - tmp_out << "acos(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oAsin: - if (compute) - Stackf.push(asin(v1f)); - tmp_out.str(""); - tmp_out << "asin(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oAtan: - if (compute) - Stackf.push(atan(v1f)); - tmp_out.str(""); - tmp_out << "atan(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oCosh: - if (compute) - Stackf.push(cosh(v1f)); - tmp_out.str(""); - tmp_out << "cosh(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oSinh: - if (compute) - Stackf.push(sinh(v1f)); - tmp_out.str(""); - tmp_out << "sinh(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oTanh: - if (compute) - Stackf.push(tanh(v1f)); - tmp_out.str(""); - tmp_out << "tanh(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oAcosh: - if (compute) - Stackf.push(acosh(v1f)); - tmp_out.str(""); - tmp_out << "acosh(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oAsinh: - if (compute) - Stackf.push(asinh(v1f)); - tmp_out.str(""); - tmp_out << "asinh(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oAtanh: - if (compute) - Stackf.push(atanh(v1f)); - tmp_out.str(""); - tmp_out << "atanh(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oSqrt: - if (compute) - Stackf.push(sqrt(v1f)); - tmp_out.str(""); - tmp_out << "sqrt(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - case oErf: - if (compute) - Stackf.push(erf(v1f)); - tmp_out.str(""); - tmp_out << "erf(" << v1 << ")"; - Stack.push(tmp_out.str()); - break; - default: - mexPrintf("Error unknown Binary operator=%d\n",op);mexEvalString("drawnow;"); - ; - } - break; - case FTRINARY: - op = ((FTRINARY_ *) it_code->second)->get_op_type(); - v3 = Stack.top(); - Stack.pop(); - v2 = Stack.top(); - Stack.pop(); - v1 = Stack.top(); - Stack.pop(); - if (compute) - { - v3f = Stackf.top(); - Stackf.pop(); - v2f = Stackf.top(); - Stackf.pop(); - v1f = Stackf.top(); - Stackf.pop(); - } - switch (op) - { - case oNormcdf: if (compute) - Stackf.push(0.5*(1+erf((v1f-v2f)/v3f/M_SQRT2))); + Stackf.push(double (v1f <= v2f)); tmp_out.str(""); - tmp_out << "normcdf(" << v1 << ", " << v2 << ", " << v3 << ")"; + found = v1.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v1; + if (found != string::npos) + tmp_out << ")"; + tmp_out << " <= "; + found = v2.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v2; + if (found != string::npos) + tmp_out << ")"; Stack.push(tmp_out.str()); +#ifdef DEBUG + mexPrintf("ok\n"); +#endif break; - case oNormpdf: + case oGreaterEqual: +#ifdef DEBUG + mexPrintf(">="); +#endif if (compute) - Stackf.push(1/(v3f*sqrt(2*M_PI)*exp(pow((v1f-v2f)/v3f,2)/2))); + Stackf.push(double (v1f >= v2f)); tmp_out.str(""); - tmp_out << "normpdf(" << v1 << ", " << v2 << ", " << v3 << ")"; + found = v1.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v1; + if (found != string::npos) + tmp_out << ")"; + tmp_out << " >= "; + found = v2.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v2; + if (found != string::npos) + tmp_out << ")"; Stack.push(tmp_out.str()); +#ifdef DEBUG + mexPrintf("ok\n"); +#endif break; - default: - mexPrintf("Error unknown Trinary operator=%d\n",op);mexEvalString("drawnow;"); - } - break; - case FCALL: - { + case oEqualEqual: #ifdef DEBUG - mexPrintf("------------------------------\n"); - mexPrintf("CALL ");mexEvalString("drawnow;"); + mexPrintf("=="); #endif - FCALL_ *fc = (FCALL_ *) it_code->second; - string function_name = fc->get_function_name(); + if (compute) + Stackf.push(double (v1f == v2f)); + tmp_out.str(""); + found = v1.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v1; + if (found != string::npos) + tmp_out << ")"; + tmp_out << " == "; + found = v2.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v2; + if (found != string::npos) + tmp_out << ")"; + Stack.push(tmp_out.str()); #ifdef DEBUG - mexPrintf("function_name=%s ", function_name.c_str());mexEvalString("drawnow;"); + mexPrintf("ok\n"); #endif - unsigned int nb_input_arguments = fc->get_nb_input_arguments(); + break; + case oDifferent: #ifdef DEBUG - mexPrintf("nb_input_arguments=%d ", nb_input_arguments);mexEvalString("drawnow;"); + mexPrintf("!="); #endif - unsigned int nb_output_arguments = fc->get_nb_output_arguments(); + if (compute) + Stackf.push(double (v1f != v2f)); + tmp_out.str(""); + found = v1.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v1; + if (found != string::npos) + tmp_out << ")"; + tmp_out << " != "; + found = v2.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v2; + if (found != string::npos) + tmp_out << ")"; + Stack.push(tmp_out.str()); #ifdef DEBUG - mexPrintf("nb_output_arguments=%d\n", nb_output_arguments);mexEvalString("drawnow;"); + mexPrintf("ok\n"); #endif - - - mxArray *output_arguments[3]; - string arg_func_name = fc->get_arg_func_name(); + break; + case oPower: #ifdef DEBUG - mexPrintf("arg_func_name.length() = %d\n",arg_func_name.length()); - mexPrintf("arg_func_name.c_str() = %s\n",arg_func_name.c_str()); + mexPrintf("^"); #endif - unsigned int nb_add_input_arguments = fc->get_nb_add_input_arguments(); - function_type = fc->get_function_type(); + if (compute) + { + r = pow(v1f, v2f); + Stackf.push(r); + } + tmp_out.str(""); + found = v1.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v1; + if (found != string::npos) + tmp_out << ")"; + if (compute) + { + if (isnan(r)) + tmp_out << "$ ^ �"; + else + tmp_out << " ^ "; + } + else + tmp_out << " ^ "; + found = v2.find(" "); + if (found != string::npos) + tmp_out << "("; + tmp_out << v2; + if (found != string::npos) + tmp_out << ")"; + Stack.push(tmp_out.str()); #ifdef DEBUG - mexPrintf("function_type=%d ExternalFunctionWithoutDerivative=%d\n",function_type, ExternalFunctionWithoutDerivative); - mexEvalString("drawnow;"); + mexPrintf("ok\n"); #endif - mxArray **input_arguments; - switch (function_type) - { - case ExternalFunctionWithoutDerivative: - case ExternalFunctionWithFirstDerivative: - case ExternalFunctionWithFirstandSecondDerivative: + break; + case oPowerDeriv: { + v3 = Stack.top(); + Stack.pop(); if (compute) { - input_arguments = (mxArray**)mxMalloc(nb_input_arguments * sizeof(mxArray*)); -#ifdef DEBUG - mexPrintf("Stack.size()=%d\n",Stack.size()); - mexEvalString("drawnow;"); -#endif - for (unsigned int i = 0; i < nb_input_arguments ; i++) + int derivOrder = nearbyint(Stackf.top()); + Stackf.pop(); + if (fabs(v1f) < NEAR_ZERO && v2f > 0 + && derivOrder >= v2f + && fabs(v2f-nearbyint(v2f)) < NEAR_ZERO) { - mxArray *vv = mxCreateDoubleScalar(Stackf.top()); - input_arguments[nb_input_arguments - i - 1] = vv; - Stackf.pop(); + r = 0.0; + Stackf.push(r); + } + else + { + double dxp = pow(v1f, v2f-derivOrder); + for (int i = 0; i < derivOrder; i++) + dxp *= v2f--; + Stackf.push(dxp); + r = dxp; } - mexCallMATLAB(nb_output_arguments, output_arguments, nb_input_arguments, input_arguments, function_name.c_str()); - double *rr = mxGetPr(output_arguments[0]); - Stackf.push(*rr); } tmp_out.str(""); - tmp_out << function_name << "("; - string ss[nb_input_arguments]; - for (unsigned int i = 0; i < nb_input_arguments; i++) - { - ss[nb_input_arguments-i-1] = Stack.top(); - Stack.pop(); - } - for (unsigned int i = 0; i < nb_input_arguments; i++) + if (compute) { - tmp_out << ss[i]; - if (i < nb_input_arguments - 1) - tmp_out << ", "; + if (isnan(r)) + tmp_out << "$ PowerDeriv �"; + else + tmp_out << "PowerDeriv"; } - tmp_out << ")"; + else + tmp_out << "PowerDeriv"; + tmp_out << "(" << v1 << ", " << v2 << ", " << v3 << ")"; Stack.push(tmp_out.str()); } - break; - case ExternalFunctionNumericalFirstDerivative: - { - if (compute) - { - input_arguments = (mxArray**)mxMalloc((nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray*)); - mxArray *vv = mxCreateString(arg_func_name.c_str()); - input_arguments[0] = vv; - vv = mxCreateDoubleScalar(fc->get_row()); - input_arguments[1] = vv; - vv = mxCreateCellMatrix(1, nb_add_input_arguments); - for (unsigned int i = 0; i < nb_add_input_arguments; i++) - { - double rr = Stackf.top(); #ifdef DEBUG - mexPrintf("i=%d rr = %f Stack.size()=%d\n",i, rr, Stack.size()); + tmp_out << " |PowerDeriv(" << v1 << ", " << v2 << v3 << ")|"; #endif - mxSetCell(vv, nb_add_input_arguments - (i+1), mxCreateDoubleScalar(rr)); - Stackf.pop(); - } - input_arguments[nb_input_arguments+nb_add_input_arguments] = vv; + break; + case oMax: #ifdef DEBUG - mexCallMATLAB(0, NULL, 1, & input_arguments[0], "disp"); - mexCallMATLAB(0, NULL, 1, & input_arguments[1], "disp"); - mexCallMATLAB(0, NULL, 1, & input_arguments[2], "celldisp"); - mexPrintf("OK\n"); - mexEvalString("drawnow;"); + mexPrintf("max"); #endif - nb_input_arguments = 3; - mexCallMATLAB(nb_output_arguments, output_arguments, nb_input_arguments, input_arguments, function_name.c_str()); - double *rr = mxGetPr(output_arguments[0]); + if (compute) + Stackf.push(max(v1f, v2f)); + tmp_out.str(""); + tmp_out << "max(" << v1 << ", " << v2 << ")"; + Stack.push(tmp_out.str()); #ifdef DEBUG - mexPrintf("*rr=%f\n",*rr); + mexPrintf("ok\n"); #endif - Stackf.push(*rr); - } - tmp_out.str(""); - tmp_out << function_name << "("; - tmp_out << arg_func_name.c_str() << ", " << fc->get_row() << ", {"; - string ss[nb_add_input_arguments]; - for (unsigned int i = 0; i < nb_add_input_arguments; i++) - { - ss[nb_add_input_arguments-i-1] = Stack.top(); - Stack.pop(); - } - for (unsigned int i = 0; i < nb_add_input_arguments; i++) - { - tmp_out << ss[i]; - if (i < nb_add_input_arguments - 1) - tmp_out << ", "; - } - tmp_out << "})"; - Stack.push(tmp_out.str()); - } - break; - case ExternalFunctionFirstDerivative: - { - if (compute) - { - input_arguments = (mxArray**)mxMalloc(nb_input_arguments * sizeof(mxArray*)); - for (unsigned int i = 0; i < nb_input_arguments; i++) - { - mxArray *vv = mxCreateDoubleScalar(Stackf.top()); - input_arguments[(nb_input_arguments - 1) - i] = vv; - Stackf.pop(); - } - mexCallMATLAB(nb_output_arguments, output_arguments, nb_input_arguments, input_arguments, function_name.c_str()); - } - tmp_out.str(""); - tmp_out << function_name << "("; - string ss[nb_input_arguments]; - for (unsigned int i = 0; i < nb_input_arguments; i++) - { - ss[nb_input_arguments-i-1] = Stack.top(); - Stack.pop(); - } - for (unsigned int i = 0; i < nb_input_arguments; i++) - { - tmp_out << ss[i]; - if (i < nb_input_arguments - 1) - tmp_out << ", "; - } - tmp_out << ")"; - Stack.push(tmp_out.str()); - } break; - case ExternalFunctionNumericalSecondDerivative: - { - if (compute) - { - input_arguments = (mxArray**)mxMalloc((nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray*)); - mxArray *vv = mxCreateString(arg_func_name.c_str()); - input_arguments[0] = vv; - vv = mxCreateDoubleScalar(fc->get_row()); - input_arguments[1] = vv; - vv = mxCreateDoubleScalar(fc->get_col()); - input_arguments[2] = vv; - vv = mxCreateCellMatrix(1, nb_add_input_arguments); - for (unsigned int i = 0; i < nb_add_input_arguments; i++) - { - double rr = Stackf.top(); + case oMin: #ifdef DEBUG - mexPrintf("i=%d rr = %f\n",i, rr); + mexPrintf("min"); +#endif + if (compute) + Stackf.push(min(v1f, v2f)); + tmp_out.str(""); + tmp_out << "min(" << v1 << ", " << v2 << ")"; + Stack.push(tmp_out.str()); +#ifdef DEBUG + mexPrintf("ok\n"); #endif - mxSetCell(vv, (nb_add_input_arguments - 1) - i, mxCreateDoubleScalar(rr)); - Stackf.pop(); - } - input_arguments[nb_input_arguments+nb_add_input_arguments] = vv; -#ifdef DEBUG - mexCallMATLAB(0, NULL, 1, & input_arguments[0], "disp"); - mexCallMATLAB(0, NULL, 1, & input_arguments[1], "disp"); - mexCallMATLAB(0, NULL, 1, & input_arguments[2], "celldisp"); - mexPrintf("OK\n"); - mexEvalString("drawnow;"); -#endif - nb_input_arguments = 3; - mexCallMATLAB(nb_output_arguments, output_arguments, nb_input_arguments, input_arguments, function_name.c_str()); - double *rr = mxGetPr(output_arguments[0]); - Stackf.push(*rr); - } - tmp_out.str(""); - tmp_out << function_name << "("; - tmp_out << arg_func_name.c_str() << ", " << fc->get_row() << ", " << fc->get_col() << ", {"; - string ss[nb_add_input_arguments]; - for (unsigned int i = 0; i < nb_add_input_arguments; i++) - { - ss[nb_add_input_arguments-i-1] = Stack.top(); - Stack.pop(); - } - for (unsigned int i = 0; i < nb_add_input_arguments; i++) - { - tmp_out << ss[i]; - if (i < nb_add_input_arguments - 1) - tmp_out << ", "; - } - tmp_out << "})"; - Stack.push(tmp_out.str()); - } break; - case ExternalFunctionSecondDerivative: - { - if (compute) - { - input_arguments = (mxArray**)mxMalloc(nb_input_arguments * sizeof(mxArray*)); - for (unsigned int i = 0; i < nb_input_arguments ; i++) - { - mxArray *vv = mxCreateDoubleScalar(Stackf.top()); - input_arguments[i] = vv; - Stackf.pop(); - } - mexCallMATLAB(nb_output_arguments, output_arguments, nb_input_arguments, input_arguments, function_name.c_str()); - } - tmp_out.str(""); - tmp_out << function_name << "("; - string ss[nb_input_arguments]; - for (unsigned int i = 0; i < nb_input_arguments; i++) - { - ss[nb_input_arguments-i-1] = Stack.top(); - Stack.pop(); - } - for (unsigned int i = 0; i < nb_input_arguments; i++) - { - tmp_out << ss[i]; - if (i < nb_input_arguments - 1) - tmp_out << ", "; - } - tmp_out << ")"; - Stack.push(tmp_out.str()); - } + case oEqual: + default: + mexPrintf("Error unknown Unary operator=%d\n", op); mexEvalString("drawnow;"); + ; + } + break; + case FUNARY: + op = ((FUNARY_ *) it_code->second)->get_op_type(); + v1 = Stack.top(); + Stack.pop(); + if (compute) + { + v1f = Stackf.top(); + Stackf.pop(); + } + switch (op) + { + case oUminus: + if (compute) + Stackf.push(-v1f); + tmp_out.str(""); + tmp_out << " -" << v1; + Stack.push(tmp_out.str()); + break; + case oExp: + if (compute) + Stackf.push(exp(v1f)); + tmp_out.str(""); + tmp_out << "exp(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oLog: + if (compute) + { + r = log(v1f); + Stackf.push(r); + } + tmp_out.str(""); + if (compute) + { + if (isnan(r)) + tmp_out << "$log�(" << v1 << ")"; + else + tmp_out << "log(" << v1 << ")"; + } + else + tmp_out << "log(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oLog10: + if (compute) + { + r = log10(v1f); + Stackf.push(r); + } + tmp_out.str(""); + if (compute) + { + if (isnan(r)) + tmp_out << "$log10�(" << v1 << ")"; + else + tmp_out << "log10(" << v1 << ")"; + } + else + tmp_out << "log10(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oCos: + if (compute) + Stackf.push(cos(v1f)); + tmp_out.str(""); + tmp_out << "cos(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oSin: + if (compute) + Stackf.push(sin(v1f)); + tmp_out.str(""); + tmp_out << "sin(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oTan: + if (compute) + Stackf.push(tan(v1f)); + tmp_out.str(""); + tmp_out << "tan(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oAcos: + if (compute) + Stackf.push(acos(v1f)); + tmp_out.str(""); + tmp_out << "acos(" << v1 << ")"; + Stack.push(tmp_out.str()); break; + case oAsin: + if (compute) + Stackf.push(asin(v1f)); + tmp_out.str(""); + tmp_out << "asin(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oAtan: + if (compute) + Stackf.push(atan(v1f)); + tmp_out.str(""); + tmp_out << "atan(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oCosh: + if (compute) + Stackf.push(cosh(v1f)); + tmp_out.str(""); + tmp_out << "cosh(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oSinh: + if (compute) + Stackf.push(sinh(v1f)); + tmp_out.str(""); + tmp_out << "sinh(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oTanh: + if (compute) + Stackf.push(tanh(v1f)); + tmp_out.str(""); + tmp_out << "tanh(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oAcosh: + if (compute) + Stackf.push(acosh(v1f)); + tmp_out.str(""); + tmp_out << "acosh(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oAsinh: + if (compute) + Stackf.push(asinh(v1f)); + tmp_out.str(""); + tmp_out << "asinh(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oAtanh: + if (compute) + Stackf.push(atanh(v1f)); + tmp_out.str(""); + tmp_out << "atanh(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oSqrt: + if (compute) + Stackf.push(sqrt(v1f)); + tmp_out.str(""); + tmp_out << "sqrt(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + case oErf: + if (compute) + Stackf.push(erf(v1f)); + tmp_out.str(""); + tmp_out << "erf(" << v1 << ")"; + Stack.push(tmp_out.str()); + break; + default: + mexPrintf("Error unknown Binary operator=%d\n", op); mexEvalString("drawnow;"); + ; } + break; + case FTRINARY: + op = ((FTRINARY_ *) it_code->second)->get_op_type(); + v3 = Stack.top(); + Stack.pop(); + v2 = Stack.top(); + Stack.pop(); + v1 = Stack.top(); + Stack.pop(); + if (compute) + { + v3f = Stackf.top(); + Stackf.pop(); + v2f = Stackf.top(); + Stackf.pop(); + v1f = Stackf.top(); + Stackf.pop(); + } + switch (op) + { + case oNormcdf: + if (compute) + Stackf.push(0.5*(1+erf((v1f-v2f)/v3f/M_SQRT2))); + tmp_out.str(""); + tmp_out << "normcdf(" << v1 << ", " << v2 << ", " << v3 << ")"; + Stack.push(tmp_out.str()); + break; + case oNormpdf: + if (compute) + Stackf.push(1/(v3f*sqrt(2*M_PI)*exp(pow((v1f-v2f)/v3f, 2)/2))); + tmp_out.str(""); + tmp_out << "normpdf(" << v1 << ", " << v2 << ", " << v3 << ")"; + Stack.push(tmp_out.str()); + break; + default: + mexPrintf("Error unknown Trinary operator=%d\n", op); mexEvalString("drawnow;"); + } + break; + case FCALL: + { #ifdef DEBUG - mexPrintf("end CALL\n"); - mexEvalString("drawnow;"); + mexPrintf("------------------------------\n"); + mexPrintf("CALL "); mexEvalString("drawnow;"); #endif - break; - } - case FSTPTEF: - go_on = false; - var = ((FSTPTEF_ *) it_code->second)->get_number(); + FCALL_ *fc = (FCALL_ *) it_code->second; + string function_name = fc->get_function_name(); #ifdef DEBUG - mexPrintf("FSTPTEF\n"); - mexPrintf("var=%d Stack.size()=%d\n",var, Stack.size()); + mexPrintf("function_name=%s ", function_name.c_str()); mexEvalString("drawnow;"); #endif - if (compute) - { + unsigned int nb_input_arguments = fc->get_nb_input_arguments(); #ifdef DEBUG - double rr = Stackf.top(); - mexPrintf("FSTP TEF(var-1)=%f done\n",rr); - mexEvalString("drawnow;"); + mexPrintf("nb_input_arguments=%d ", nb_input_arguments); mexEvalString("drawnow;"); #endif - Stackf.pop(); - } - tmp_out.str(""); - switch (function_type) - { - case ExternalFunctionWithoutDerivative: - tmp_out << "TEF(" << var << ") = " << Stack.top(); - break; - case ExternalFunctionWithFirstDerivative: - tmp_out << "[TEF(" << var << "), TEFD(" << var << ") ]= " << Stack.top(); - break; - case ExternalFunctionWithFirstandSecondDerivative: - tmp_out << "[TEF(" << var << "), TEFD(" << var << "), TEFDD(" << var << ") ]= " << Stack.top(); - break; - default: - break; - } - Stack.pop(); + unsigned int nb_output_arguments = fc->get_nb_output_arguments(); #ifdef DEBUG - mexPrintf("end FSTPEF\n"); - mexEvalString("drawnow;"); + mexPrintf("nb_output_arguments=%d\n", nb_output_arguments); mexEvalString("drawnow;"); #endif - break; - case FLDTEF: - var = ((FLDTEF_ *) it_code->second)->get_number(); + + mxArray *output_arguments[3]; + string arg_func_name = fc->get_arg_func_name(); #ifdef DEBUG - mexPrintf("FLDTEF\n"); - mexPrintf("var=%d Stack.size()=%d\n",var, Stackf.size()); - { - map<unsigned int, double>::const_iterator it = TEF.find(var-1); - mexPrintf("FLD TEF[var-1]=%f done\n",it->second); - } - mexEvalString("drawnow;"); + mexPrintf("arg_func_name.length() = %d\n", arg_func_name.length()); + mexPrintf("arg_func_name.c_str() = %s\n", arg_func_name.c_str()); #endif - if (compute) - { - map<unsigned int, double>::const_iterator it = TEF.find(var-1); - Stackf.push(it->second); - } - tmp_out.str(""); - tmp_out << "TEF(" << var << ")"; - Stack.push(tmp_out.str()); + unsigned int nb_add_input_arguments = fc->get_nb_add_input_arguments(); + function_type = fc->get_function_type(); #ifdef DEBUG - mexPrintf("end FLDTEF\n"); - mexEvalString("drawnow;"); + mexPrintf("function_type=%d ExternalFunctionWithoutDerivative=%d\n", function_type, ExternalFunctionWithoutDerivative); + mexEvalString("drawnow;"); #endif - - break; - case FSTPTEFD: - { + mxArray **input_arguments; + switch (function_type) + { + case ExternalFunctionWithoutDerivative: + case ExternalFunctionWithFirstDerivative: + case ExternalFunctionWithFirstandSecondDerivative: + { + if (compute) + { + input_arguments = (mxArray **) mxMalloc(nb_input_arguments * sizeof(mxArray *)); +#ifdef DEBUG + mexPrintf("Stack.size()=%d\n", Stack.size()); + mexEvalString("drawnow;"); +#endif + for (unsigned int i = 0; i < nb_input_arguments; i++) + { + mxArray *vv = mxCreateDoubleScalar(Stackf.top()); + input_arguments[nb_input_arguments - i - 1] = vv; + Stackf.pop(); + } + mexCallMATLAB(nb_output_arguments, output_arguments, nb_input_arguments, input_arguments, function_name.c_str()); + double *rr = mxGetPr(output_arguments[0]); + Stackf.push(*rr); + } + tmp_out.str(""); + tmp_out << function_name << "("; + string ss[nb_input_arguments]; + for (unsigned int i = 0; i < nb_input_arguments; i++) + { + ss[nb_input_arguments-i-1] = Stack.top(); + Stack.pop(); + } + for (unsigned int i = 0; i < nb_input_arguments; i++) + { + tmp_out << ss[i]; + if (i < nb_input_arguments - 1) + tmp_out << ", "; + } + tmp_out << ")"; + Stack.push(tmp_out.str()); + } + break; + case ExternalFunctionNumericalFirstDerivative: + { + if (compute) + { + input_arguments = (mxArray **) mxMalloc((nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray *)); + mxArray *vv = mxCreateString(arg_func_name.c_str()); + input_arguments[0] = vv; + vv = mxCreateDoubleScalar(fc->get_row()); + input_arguments[1] = vv; + vv = mxCreateCellMatrix(1, nb_add_input_arguments); + for (unsigned int i = 0; i < nb_add_input_arguments; i++) + { + double rr = Stackf.top(); +#ifdef DEBUG + mexPrintf("i=%d rr = %f Stack.size()=%d\n", i, rr, Stack.size()); +#endif + mxSetCell(vv, nb_add_input_arguments - (i+1), mxCreateDoubleScalar(rr)); + Stackf.pop(); + } + input_arguments[nb_input_arguments+nb_add_input_arguments] = vv; +#ifdef DEBUG + mexCallMATLAB(0, NULL, 1, &input_arguments[0], "disp"); + mexCallMATLAB(0, NULL, 1, &input_arguments[1], "disp"); + mexCallMATLAB(0, NULL, 1, &input_arguments[2], "celldisp"); + mexPrintf("OK\n"); + mexEvalString("drawnow;"); +#endif + nb_input_arguments = 3; + mexCallMATLAB(nb_output_arguments, output_arguments, nb_input_arguments, input_arguments, function_name.c_str()); + double *rr = mxGetPr(output_arguments[0]); +#ifdef DEBUG + mexPrintf("*rr=%f\n", *rr); +#endif + Stackf.push(*rr); + } + tmp_out.str(""); + tmp_out << function_name << "("; + tmp_out << arg_func_name.c_str() << ", " << fc->get_row() << ", {"; + string ss[nb_add_input_arguments]; + for (unsigned int i = 0; i < nb_add_input_arguments; i++) + { + ss[nb_add_input_arguments-i-1] = Stack.top(); + Stack.pop(); + } + for (unsigned int i = 0; i < nb_add_input_arguments; i++) + { + tmp_out << ss[i]; + if (i < nb_add_input_arguments - 1) + tmp_out << ", "; + } + tmp_out << "})"; + Stack.push(tmp_out.str()); + } + break; + case ExternalFunctionFirstDerivative: + { + if (compute) + { + input_arguments = (mxArray **) mxMalloc(nb_input_arguments * sizeof(mxArray *)); + for (unsigned int i = 0; i < nb_input_arguments; i++) + { + mxArray *vv = mxCreateDoubleScalar(Stackf.top()); + input_arguments[(nb_input_arguments - 1) - i] = vv; + Stackf.pop(); + } + mexCallMATLAB(nb_output_arguments, output_arguments, nb_input_arguments, input_arguments, function_name.c_str()); + } + tmp_out.str(""); + tmp_out << function_name << "("; + string ss[nb_input_arguments]; + for (unsigned int i = 0; i < nb_input_arguments; i++) + { + ss[nb_input_arguments-i-1] = Stack.top(); + Stack.pop(); + } + for (unsigned int i = 0; i < nb_input_arguments; i++) + { + tmp_out << ss[i]; + if (i < nb_input_arguments - 1) + tmp_out << ", "; + } + tmp_out << ")"; + Stack.push(tmp_out.str()); + } + break; + case ExternalFunctionNumericalSecondDerivative: + { + if (compute) + { + input_arguments = (mxArray **) mxMalloc((nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray *)); + mxArray *vv = mxCreateString(arg_func_name.c_str()); + input_arguments[0] = vv; + vv = mxCreateDoubleScalar(fc->get_row()); + input_arguments[1] = vv; + vv = mxCreateDoubleScalar(fc->get_col()); + input_arguments[2] = vv; + vv = mxCreateCellMatrix(1, nb_add_input_arguments); + for (unsigned int i = 0; i < nb_add_input_arguments; i++) + { + double rr = Stackf.top(); +#ifdef DEBUG + mexPrintf("i=%d rr = %f\n", i, rr); +#endif + mxSetCell(vv, (nb_add_input_arguments - 1) - i, mxCreateDoubleScalar(rr)); + Stackf.pop(); + } + input_arguments[nb_input_arguments+nb_add_input_arguments] = vv; +#ifdef DEBUG + mexCallMATLAB(0, NULL, 1, &input_arguments[0], "disp"); + mexCallMATLAB(0, NULL, 1, &input_arguments[1], "disp"); + mexCallMATLAB(0, NULL, 1, &input_arguments[2], "celldisp"); + mexPrintf("OK\n"); + mexEvalString("drawnow;"); +#endif + nb_input_arguments = 3; + mexCallMATLAB(nb_output_arguments, output_arguments, nb_input_arguments, input_arguments, function_name.c_str()); + double *rr = mxGetPr(output_arguments[0]); + Stackf.push(*rr); + } + tmp_out.str(""); + tmp_out << function_name << "("; + tmp_out << arg_func_name.c_str() << ", " << fc->get_row() << ", " << fc->get_col() << ", {"; + string ss[nb_add_input_arguments]; + for (unsigned int i = 0; i < nb_add_input_arguments; i++) + { + ss[nb_add_input_arguments-i-1] = Stack.top(); + Stack.pop(); + } + for (unsigned int i = 0; i < nb_add_input_arguments; i++) + { + tmp_out << ss[i]; + if (i < nb_add_input_arguments - 1) + tmp_out << ", "; + } + tmp_out << "})"; + Stack.push(tmp_out.str()); + } + break; + case ExternalFunctionSecondDerivative: + { + if (compute) + { + input_arguments = (mxArray **) mxMalloc(nb_input_arguments * sizeof(mxArray *)); + for (unsigned int i = 0; i < nb_input_arguments; i++) + { + mxArray *vv = mxCreateDoubleScalar(Stackf.top()); + input_arguments[i] = vv; + Stackf.pop(); + } + mexCallMATLAB(nb_output_arguments, output_arguments, nb_input_arguments, input_arguments, function_name.c_str()); + } + tmp_out.str(""); + tmp_out << function_name << "("; + string ss[nb_input_arguments]; + for (unsigned int i = 0; i < nb_input_arguments; i++) + { + ss[nb_input_arguments-i-1] = Stack.top(); + Stack.pop(); + } + for (unsigned int i = 0; i < nb_input_arguments; i++) + { + tmp_out << ss[i]; + if (i < nb_input_arguments - 1) + tmp_out << ", "; + } + tmp_out << ")"; + Stack.push(tmp_out.str()); + } + break; + } +#ifdef DEBUG + mexPrintf("end CALL\n"); + mexEvalString("drawnow;"); +#endif + break; + } + case FSTPTEF: go_on = false; - unsigned int indx = ((FSTPTEFD_ *) it_code->second)->get_indx(); - unsigned int row = ((FSTPTEFD_ *) it_code->second)->get_row(); + var = ((FSTPTEF_ *) it_code->second)->get_number(); #ifdef DEBUG - mexPrintf("FSTPTEFD\n"); - mexPrintf("indx=%d Stack.size()=%d\n",indx, Stack.size()); + mexPrintf("FSTPTEF\n"); + mexPrintf("var=%d Stack.size()=%d\n", var, Stack.size()); #endif if (compute) { #ifdef DEBUG double rr = Stackf.top(); - mexPrintf("FSTP TEFD[make_pair(indx, row)]=%f done\n",rr); + mexPrintf("FSTP TEF(var-1)=%f done\n", rr); mexEvalString("drawnow;"); #endif Stackf.pop(); } tmp_out.str(""); - if (function_type == ExternalFunctionNumericalFirstDerivative) - tmp_out << "TEFD(" << indx << ", " << row << ") = " << Stack.top(); - else if (function_type == ExternalFunctionFirstDerivative) - tmp_out << "TEFD(" << indx << ") = " << Stack.top(); + switch (function_type) + { + case ExternalFunctionWithoutDerivative: + tmp_out << "TEF(" << var << ") = " << Stack.top(); + break; + case ExternalFunctionWithFirstDerivative: + tmp_out << "[TEF(" << var << "), TEFD(" << var << ") ]= " << Stack.top(); + break; + case ExternalFunctionWithFirstandSecondDerivative: + tmp_out << "[TEF(" << var << "), TEFD(" << var << "), TEFDD(" << var << ") ]= " << Stack.top(); + break; + default: + break; + } Stack.pop(); - } - break; - case FLDTEFD: - { - unsigned int indx = ((FLDTEFD_ *) it_code->second)->get_indx(); - unsigned int row = ((FLDTEFD_ *) it_code->second)->get_row(); #ifdef DEBUG - mexPrintf("FLDTEFD\n"); - mexPrintf("indx=%d row=%d Stack.size()=%d\n",indx, row, Stack.size()); - map<pair<unsigned int, unsigned int>, double>::const_iterator it = TEFD.find(make_pair(indx, row-1)); - mexPrintf("FLD TEFD[make_pair(indx, row)]=%f done\n",it->second); + mexPrintf("end FSTPEF\n"); + mexEvalString("drawnow;"); +#endif + break; + case FLDTEF: + var = ((FLDTEF_ *) it_code->second)->get_number(); +#ifdef DEBUG + mexPrintf("FLDTEF\n"); + mexPrintf("var=%d Stack.size()=%d\n", var, Stackf.size()); + { + map<unsigned int, double>::const_iterator it = TEF.find(var-1); + mexPrintf("FLD TEF[var-1]=%f done\n", it->second); + } mexEvalString("drawnow;"); #endif if (compute) { - map<pair<unsigned int, unsigned int>, double>::const_iterator it = TEFD.find(make_pair(indx, row-1)); + map<unsigned int, double>::const_iterator it = TEF.find(var-1); Stackf.push(it->second); } tmp_out.str(""); - tmp_out << "TEFD(" << indx << ", " << row << ")"; + tmp_out << "TEF(" << var << ")"; Stack.push(tmp_out.str()); - } - break; - case FSTPTEFDD: - { - go_on = false; - unsigned int indx = ((FSTPTEFDD_ *) it_code->second)->get_indx(); - unsigned int row = ((FSTPTEFDD_ *) it_code->second)->get_row(); - unsigned int col = ((FSTPTEFDD_ *) it_code->second)->get_col(); #ifdef DEBUG - mexPrintf("FSTPTEFD\n"); - mexPrintf("indx=%d Stack.size()=%d\n",indx, Stack.size()); + mexPrintf("end FLDTEF\n"); + mexEvalString("drawnow;"); #endif - if (compute) - { + + break; + case FSTPTEFD: + { + go_on = false; + unsigned int indx = ((FSTPTEFD_ *) it_code->second)->get_indx(); + unsigned int row = ((FSTPTEFD_ *) it_code->second)->get_row(); #ifdef DEBUG - double rr = Stackf.top(); - mexPrintf("rr=%f\n",rr); - map<pair<unsigned int, pair<unsigned int, unsigned int> >, double>::const_iterator it = TEFDD.find(make_pair(indx, make_pair(row-1, col-1))); - mexPrintf("FSTP TEFDD[make_pair(indx, make_pair(row, col))]=%f done\n",it->second); - mexEvalString("drawnow;"); + mexPrintf("FSTPTEFD\n"); + mexPrintf("indx=%d Stack.size()=%d\n", indx, Stack.size()); #endif - Stackf.pop(); - } - tmp_out.str(""); - if (function_type == ExternalFunctionNumericalSecondDerivative) - tmp_out << "TEFDD(" << indx << ", " << row << ", " << col << ") = " << Stack.top(); - else if (function_type == ExternalFunctionSecondDerivative) - tmp_out << "TEFDD(" << indx << ") = " << Stack.top(); - Stack.pop(); - } + if (compute) + { +#ifdef DEBUG + double rr = Stackf.top(); + mexPrintf("FSTP TEFD[make_pair(indx, row)]=%f done\n", rr); + mexEvalString("drawnow;"); +#endif + Stackf.pop(); + } + tmp_out.str(""); + if (function_type == ExternalFunctionNumericalFirstDerivative) + tmp_out << "TEFD(" << indx << ", " << row << ") = " << Stack.top(); + else if (function_type == ExternalFunctionFirstDerivative) + tmp_out << "TEFD(" << indx << ") = " << Stack.top(); + Stack.pop(); + } + break; + case FLDTEFD: + { + unsigned int indx = ((FLDTEFD_ *) it_code->second)->get_indx(); + unsigned int row = ((FLDTEFD_ *) it_code->second)->get_row(); +#ifdef DEBUG + mexPrintf("FLDTEFD\n"); + mexPrintf("indx=%d row=%d Stack.size()=%d\n", indx, row, Stack.size()); + map<pair<unsigned int, unsigned int>, double>::const_iterator it = TEFD.find(make_pair(indx, row-1)); + mexPrintf("FLD TEFD[make_pair(indx, row)]=%f done\n", it->second); + mexEvalString("drawnow;"); +#endif + if (compute) + { + map<pair<unsigned int, unsigned int>, double>::const_iterator it = TEFD.find(make_pair(indx, row-1)); + Stackf.push(it->second); + } + tmp_out.str(""); + tmp_out << "TEFD(" << indx << ", " << row << ")"; + Stack.push(tmp_out.str()); + } + break; + case FSTPTEFDD: + { + go_on = false; + unsigned int indx = ((FSTPTEFDD_ *) it_code->second)->get_indx(); + unsigned int row = ((FSTPTEFDD_ *) it_code->second)->get_row(); + unsigned int col = ((FSTPTEFDD_ *) it_code->second)->get_col(); +#ifdef DEBUG + mexPrintf("FSTPTEFD\n"); + mexPrintf("indx=%d Stack.size()=%d\n", indx, Stack.size()); +#endif + if (compute) + { +#ifdef DEBUG + double rr = Stackf.top(); + mexPrintf("rr=%f\n", rr); + map<pair<unsigned int, pair<unsigned int, unsigned int> >, double>::const_iterator it = TEFDD.find(make_pair(indx, make_pair(row-1, col-1))); + mexPrintf("FSTP TEFDD[make_pair(indx, make_pair(row, col))]=%f done\n", it->second); + mexEvalString("drawnow;"); +#endif + Stackf.pop(); + } + tmp_out.str(""); + if (function_type == ExternalFunctionNumericalSecondDerivative) + tmp_out << "TEFDD(" << indx << ", " << row << ", " << col << ") = " << Stack.top(); + else if (function_type == ExternalFunctionSecondDerivative) + tmp_out << "TEFDD(" << indx << ") = " << Stack.top(); + Stack.pop(); + } - break; - case FLDTEFDD: - { - unsigned int indx = ((FLDTEFDD_ *) it_code->second)->get_indx(); - unsigned int row = ((FLDTEFDD_ *) it_code->second)->get_row(); - unsigned int col = ((FSTPTEFDD_ *) it_code->second)->get_col(); -#ifdef DEBUG - mexPrintf("FLDTEFD\n"); - mexPrintf("indx=%d Stack.size()=%d\n",indx, Stack.size()); - map<pair<unsigned int, pair<unsigned int, unsigned int> >, double>::const_iterator it = TEFDD.find(make_pair(indx, make_pair(row-1, col-1))); - mexPrintf("FLD TEFD[make_pair(indx, make_pair(row, col))]=%f done\n",it->second); - mexEvalString("drawnow;"); + break; + case FLDTEFDD: + { + unsigned int indx = ((FLDTEFDD_ *) it_code->second)->get_indx(); + unsigned int row = ((FLDTEFDD_ *) it_code->second)->get_row(); + unsigned int col = ((FSTPTEFDD_ *) it_code->second)->get_col(); +#ifdef DEBUG + mexPrintf("FLDTEFD\n"); + mexPrintf("indx=%d Stack.size()=%d\n", indx, Stack.size()); + map<pair<unsigned int, pair<unsigned int, unsigned int> >, double>::const_iterator it = TEFDD.find(make_pair(indx, make_pair(row-1, col-1))); + mexPrintf("FLD TEFD[make_pair(indx, make_pair(row, col))]=%f done\n", it->second); + mexEvalString("drawnow;"); #endif + if (compute) + { + map<pair<unsigned int, pair<unsigned int, unsigned int> >, double>::const_iterator it = TEFDD.find(make_pair(indx, make_pair(row-1, col-1))); + Stackf.push(it->second); + } + tmp_out.str(""); + tmp_out << "TEFDD(" << indx << ", " << row << ", " << col << ")"; + Stack.push(tmp_out.str()); + } + break; + case FJMPIFEVAL: + tmp_out.str(""); + tmp_out << "if (~evaluate)"; + go_on = false; + break; + case FJMP: + tmp_out.str(""); + tmp_out << "else"; + go_on = false; + break; + case FCUML: if (compute) { - map<pair<unsigned int, pair<unsigned int, unsigned int> >, double>::const_iterator it = TEFDD.find(make_pair(indx, make_pair(row-1, col-1))); - Stackf.push(it->second); + v1f = Stackf.top(); + Stackf.pop(); + v2f = Stackf.top(); + Stackf.pop(); + Stackf.push(v1f+v2f); } + v1 = Stack.top(); + Stack.pop(); + v2 = Stack.top(); + Stack.pop(); tmp_out.str(""); - tmp_out << "TEFDD(" << indx << ", " << row << ", " << col << ")"; + tmp_out << v1 << " + " << v2; Stack.push(tmp_out.str()); + break; + case FENDBLOCK: + case FENDEQU: + go_on = false; + break; + case FOK: + break; + default: + ostringstream tmp; + mexPrintf("Error it_code->first=%d unknown\n", it_code->first); mexEvalString("drawnow;"); + tmp << " in print_expression, unknown opcode " << it_code->first << "!! FENDEQU=" << FENDEQU << "\n"; + throw FatalExceptionHandling(tmp.str()); } - break; - case FJMPIFEVAL: - tmp_out.str(""); - tmp_out << "if (~evaluate)"; - go_on = false; - break; - case FJMP: - tmp_out.str(""); - tmp_out << "else"; - go_on = false; - break; - case FCUML: - if (compute) - { - v1f = Stackf.top(); - Stackf.pop(); - v2f = Stackf.top(); - Stackf.pop(); - Stackf.push(v1f+v2f); - } - v1 = Stack.top(); - Stack.pop(); - v2 = Stack.top(); - Stack.pop(); - tmp_out.str(""); - tmp_out << v1 << " + " << v2; - Stack.push(tmp_out.str()); - break; - case FENDBLOCK: - case FENDEQU: - go_on = false; - break; - case FOK: - break; - default: - ostringstream tmp; - mexPrintf("Error it_code->first=%d unknown\n",it_code->first);mexEvalString("drawnow;"); - tmp << " in print_expression, unknown opcode " << it_code->first << "!! FENDEQU=" << FENDEQU << "\n"; - throw FatalExceptionHandling(tmp.str()); - } - it_code++; - } + it_code++; + } #ifdef DEBUG - mexPrintf("print_expression end\n");mexEvalString("drawnow;"); + mexPrintf("print_expression end\n"); mexEvalString("drawnow;"); #endif - it_code_ret = it_code; - return(tmp_out.str()); -} + it_code_ret = it_code; + return (tmp_out.str()); + } }; diff --git a/mex/sources/bytecode/Interpreter.cc b/mex/sources/bytecode/Interpreter.cc index f13b2339939dc6033e16aa5dd943a38cf9376ada..5bedb53bfe0644382ee715c5cbb19fb0e1c8f90c 100644 --- a/mex/sources/bytecode/Interpreter.cc +++ b/mex/sources/bytecode/Interpreter.cc @@ -33,7 +33,7 @@ Interpreter::Interpreter(double *params_arg, double *y_arg, double *ya_arg, doub int nb_row_x_arg, int nb_row_xd_arg, int periods_arg, int y_kmin_arg, int y_kmax_arg, int maxit_arg_, double solve_tolf_arg, int size_of_direction_arg, double slowc_arg, int y_decal_arg, double markowitz_c_arg, string &filename_arg, int minimal_solving_periods_arg, int stack_solve_algo_arg, int solve_algo_arg, - bool global_temporary_terms_arg, bool print_arg, mxArray* GlobalTemporaryTerms_arg) + bool global_temporary_terms_arg, bool print_arg, mxArray *GlobalTemporaryTerms_arg) { params = params_arg; y = y_arg; @@ -118,8 +118,6 @@ Interpreter::log10_1(double a) return r; } - - void Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int size, bool steady_state) { @@ -167,7 +165,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si EQN_type = TemporaryTerm; EQN_equation = ((FNUMEXPR_ *) it_code->second)->get_equation(); #ifdef DEBUG - mexPrintf("EQN_equation=%d\n",EQN_equation);mexEvalString("drawnow;"); + mexPrintf("EQN_equation=%d\n", EQN_equation); mexEvalString("drawnow;"); #endif break; case ModelEquation: @@ -321,7 +319,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si case eParameter: var = ((FLDV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDV Param[var=%d]\n",var); + mexPrintf("FLDV Param[var=%d]\n", var); tmp_out << " params[" << var << "](" << params[var] << ")"; #endif Stack.push(params[var]); @@ -330,7 +328,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si var = ((FLDV_ *) it_code->second)->get_pos(); lag = ((FLDV_ *) it_code->second)->get_lead_lag(); #ifdef DEBUG - mexPrintf("FLDV y[var=%d, lag=%d, it_=%d], y_size=%d evaluate=%d\n",var, lag, it_, y_size, evaluate); + mexPrintf("FLDV y[var=%d, lag=%d, it_=%d], y_size=%d evaluate=%d\n", var, lag, it_, y_size, evaluate); #endif if (evaluate) Stack.push(ya[(it_+lag)*y_size+var]); @@ -344,7 +342,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si var = ((FLDV_ *) it_code->second)->get_pos(); lag = ((FLDV_ *) it_code->second)->get_lead_lag(); #ifdef DEBUG - mexPrintf("FLDV x[var=%d, lag=%d, it_=%d], nb_row_x=%d evaluate=%d\n",var, lag, it_, nb_row_x, evaluate); + mexPrintf("FLDV x[var=%d, lag=%d, it_=%d], nb_row_x=%d evaluate=%d\n", var, lag, it_, nb_row_x, evaluate); tmp_out << " x[" << it_+lag << ", " << var << "](" << x[it_+lag+var*nb_row_x] << ")"; #endif Stack.push(x[it_+lag+var*nb_row_x]); @@ -371,7 +369,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si case eParameter: var = ((FLDSV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDSV Param[var=%d]=%f\n",var, params[var]); + mexPrintf("FLDSV Param[var=%d]=%f\n", var, params[var]); tmp_out << " params[" << var << "](" << params[var] << ")"; #endif Stack.push(params[var]); @@ -379,7 +377,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si case eEndogenous: var = ((FLDSV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDSV y[var=%d]=%f\n",var, ya[var]); + mexPrintf("FLDSV y[var=%d]=%f\n", var, ya[var]); tmp_out << " y[" << var << "](" << y[var] << ")"; #endif if (evaluate) @@ -390,7 +388,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si case eExogenous: var = ((FLDSV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDSV x[var=%d]\n",var); + mexPrintf("FLDSV x[var=%d]\n", var); tmp_out << " x[" << var << "](" << x[var] << ")"; #endif Stack.push(x[var]); @@ -398,7 +396,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si case eExogenousDet: var = ((FLDSV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDSV xd[var=%d]\n",var); + mexPrintf("FLDSV xd[var=%d]\n", var); #endif Stack.push(x[var]); break; @@ -467,7 +465,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si //load a temporary variable in the processor var = ((FLDST_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDST T[%d]",var); + mexPrintf("FLDST T[%d]", var); #endif Stack.push(T[var]); #ifdef DEBUG @@ -480,7 +478,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si var = ((FLDU_ *) it_code->second)->get_pos(); var += Per_u_; #ifdef DEBUG - mexPrintf("FLDU u[%d]\n",var); + mexPrintf("FLDU u[%d]\n", var); tmp_out << " u[" << var << "](" << u[var] << ")"; #endif Stack.push(u[var]); @@ -489,7 +487,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si //load u variable in the processor var = ((FLDSU_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDSU u[%d]\n",var); + mexPrintf("FLDSU u[%d]\n", var); tmp_out << " u[" << var << "](" << u[var] << ")"; #endif Stack.push(u[var]); @@ -498,7 +496,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si //load u variable in the processor var = ((FLDR_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FLDR r[%d]\n",var); + mexPrintf("FLDR r[%d]\n", var); #endif Stack.push(r[var]); break; @@ -516,7 +514,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si //load a numerical constant in the processor ll = ((FLDC_ *) it_code->second)->get_value(); #ifdef DEBUG - mexPrintf("FLDC = %f\n",ll); + mexPrintf("FLDC = %f\n", ll); tmp_out << " " << ll; #endif @@ -529,7 +527,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si case eParameter: var = ((FSTPV_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("FSTPV params[%d]\n",var); + mexPrintf("FSTPV params[%d]\n", var); #endif params[var] = Stack.top(); Stack.pop(); @@ -628,7 +626,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si #endif var = ((FSTPST_ *) it_code->second)->get_pos(); #ifdef DEBUG - mexPrintf("var=%d\n",var); + mexPrintf("var=%d\n", var); #endif T[var] = Stack.top(); #ifdef DEBUG @@ -644,7 +642,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si var += Per_u_; #ifdef DEBUG mexPrintf("FSTPU\n"); - mexPrintf("var=%d\n",var); + mexPrintf("var=%d\n", var); #endif u[var] = Stack.top(); #ifdef DEBUG @@ -658,8 +656,8 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si //store in u variable from the processor var = ((FSTPSU_ *) it_code->second)->get_pos(); #ifdef DEBUG - if(var>=u_count_alloc || var<0) - mexPrintf("Erreur var=%d\n",var); + if (var >= u_count_alloc || var < 0) + mexPrintf("Erreur var=%d\n", var); #endif u[var] = Stack.top(); #ifdef DEBUG @@ -702,7 +700,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si break; case FSTPG2: - //store in the jacobian matrix + //store in the jacobian matrix rr = Stack.top(); if (EQN_type != FirstEndoDerivative) { @@ -725,7 +723,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si mexEvalString("drawnow;"); #endif rr = Stack.top(); - switch(EQN_type) + switch (EQN_type) { case FirstEndoDerivative: eq = ((FSTPG3_ *) it_code->second)->get_row(); @@ -733,7 +731,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si lag = ((FSTPG3_ *) it_code->second)->get_lag(); pos_col = ((FSTPG3_ *) it_code->second)->get_col_pos(); #ifdef DEBUG - mexPrintf("Endo eq=%d, pos_col=%d, size=%d\n",eq, pos_col,size); + mexPrintf("Endo eq=%d, pos_col=%d, size=%d\n", eq, pos_col, size); #endif jacob[eq + size*pos_col] = rr; break; @@ -752,7 +750,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si lag = ((FSTPG3_ *) it_code->second)->get_lag(); pos_col = ((FSTPG3_ *) it_code->second)->get_col_pos(); #ifdef DEBUG - mexPrintf("Exo eq=%d, pos_col=%d, size=%d\n",eq, pos_col,size); + mexPrintf("Exo eq=%d, pos_col=%d, size=%d\n", eq, pos_col, size); #endif jacob_exo[eq + size*pos_col] = rr; break; @@ -813,11 +811,11 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si #endif try { - tmp = divide(v1 , v2); + tmp = divide(v1, v2); } - catch(FloatingPointExceptionHandling &fpeh) + catch (FloatingPointExceptionHandling &fpeh) { - mexPrintf("%s %s\n",fpeh.GetErrorMsg().c_str(),error_location(evaluate, steady_state, size, block_num, it_, Per_u_).c_str()); + mexPrintf("%s %s\n", fpeh.GetErrorMsg().c_str(), error_location(evaluate, steady_state, size, block_num, it_, Per_u_).c_str()); go_on = false; } Stack.push(tmp); @@ -869,9 +867,9 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si { tmp = pow1(v1, v2); } - catch(FloatingPointExceptionHandling &fpeh) + catch (FloatingPointExceptionHandling &fpeh) { - mexPrintf("%s %s\n",fpeh.GetErrorMsg().c_str(),error_location(evaluate, steady_state, size, block_num, it_, Per_u_).c_str()); + mexPrintf("%s %s\n", fpeh.GetErrorMsg().c_str(), error_location(evaluate, steady_state, size, block_num, it_, Per_u_).c_str()); go_on = false; } Stack.push(tmp); @@ -886,29 +884,29 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si Stack.pop(); try { - if (fabs(v1) < NEAR_ZERO && v2 > 0 && - derivOrder >= v2 && - fabs(v2-nearbyint(v2)) < NEAR_ZERO) + if (fabs(v1) < NEAR_ZERO && v2 > 0 + && derivOrder >= v2 + && fabs(v2-nearbyint(v2)) < NEAR_ZERO) Stack.push(0.0); else { double dxp = pow1(v1, v2-derivOrder); - for (int i=0; i<derivOrder; i++) + for (int i = 0; i < derivOrder; i++) dxp *= v2--; Stack.push(dxp); } } - catch(FloatingPointExceptionHandling &fpeh) + catch (FloatingPointExceptionHandling &fpeh) { - mexPrintf("%s %s\n",fpeh.GetErrorMsg().c_str(),error_location(evaluate, steady_state, size, block_num, it_, Per_u_).c_str()); + mexPrintf("%s %s\n", fpeh.GetErrorMsg().c_str(), error_location(evaluate, steady_state, size, block_num, it_, Per_u_).c_str()); go_on = false; } } #ifdef DEBUG - tmp_out << " |PowerDeriv(" << v1 << ", " << v2 << ")|"; + tmp_out << " |PowerDeriv(" << v1 << ", " << v2 << ")|"; #endif - break; + break; case oMax: Stack.push(max(v1, v2)); #ifdef DEBUG @@ -961,9 +959,9 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si { tmp = log1(v1); } - catch(FloatingPointExceptionHandling &fpeh) + catch (FloatingPointExceptionHandling &fpeh) { - mexPrintf("%s %s\n",fpeh.GetErrorMsg().c_str(),error_location(evaluate, steady_state, size, block_num, it_, Per_u_).c_str()); + mexPrintf("%s %s\n", fpeh.GetErrorMsg().c_str(), error_location(evaluate, steady_state, size, block_num, it_, Per_u_).c_str()); go_on = false; } Stack.push(tmp); @@ -978,9 +976,9 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si { tmp = log10_1(v1); } - catch(FloatingPointExceptionHandling &fpeh) + catch (FloatingPointExceptionHandling &fpeh) { - mexPrintf("%s %s\n",fpeh.GetErrorMsg().c_str(),error_location(evaluate, steady_state, size, block_num, it_, Per_u_).c_str()); + mexPrintf("%s %s\n", fpeh.GetErrorMsg().c_str(), error_location(evaluate, steady_state, size, block_num, it_, Per_u_).c_str()); go_on = false; } Stack.push(tmp); @@ -1071,7 +1069,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si #ifdef DEBUG tmp_out << " |erf(" << v1 << ")|"; -# endif +#endif break; default: { @@ -1092,25 +1090,25 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si Stack.pop(); switch (op) { - case oNormcdf: - Stack.push(0.5*(1+erf((v1-v2)/v3/M_SQRT2))); + case oNormcdf: + Stack.push(0.5*(1+erf((v1-v2)/v3/M_SQRT2))); #ifdef DEBUG - tmp_out << " |normcdf(" << v1 << ", " << v2 << ", " << v3 << ")|"; + tmp_out << " |normcdf(" << v1 << ", " << v2 << ", " << v3 << ")|"; #endif - break; - case oNormpdf: - Stack.push(1/(v3*sqrt(2*M_PI)*exp(pow((v1-v2)/v3,2)/2))); + break; + case oNormpdf: + Stack.push(1/(v3*sqrt(2*M_PI)*exp(pow((v1-v2)/v3, 2)/2))); #ifdef DEBUG - tmp_out << " |normpdf(" << v1 << ", " << v2 << ", " << v3 << ")|"; + tmp_out << " |normpdf(" << v1 << ", " << v2 << ", " << v3 << ")|"; #endif - break; - default: - { - mexPrintf("Error\n"); - ostringstream tmp; - tmp << " in compute_block_time, unknown trinary operator " << op << "\n"; - throw FatalExceptionHandling(tmp.str()); - } + break; + default: + { + mexPrintf("Error\n"); + ostringstream tmp; + tmp << " in compute_block_time, unknown trinary operator " << op << "\n"; + throw FatalExceptionHandling(tmp.str()); + } } break; @@ -1121,33 +1119,32 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si { #ifdef DEBUG mexPrintf("------------------------------\n"); - mexPrintf("CALL ");mexEvalString("drawnow;"); + mexPrintf("CALL "); mexEvalString("drawnow;"); #endif FCALL_ *fc = (FCALL_ *) it_code->second; string function_name = fc->get_function_name(); #ifdef DEBUG - mexPrintf("function_name=%s ", function_name.c_str());mexEvalString("drawnow;"); + mexPrintf("function_name=%s ", function_name.c_str()); mexEvalString("drawnow;"); #endif unsigned int nb_input_arguments = fc->get_nb_input_arguments(); #ifdef DEBUG - mexPrintf("nb_input_arguments=%d ", nb_input_arguments);mexEvalString("drawnow;"); + mexPrintf("nb_input_arguments=%d ", nb_input_arguments); mexEvalString("drawnow;"); #endif unsigned int nb_output_arguments = fc->get_nb_output_arguments(); #ifdef DEBUG - mexPrintf("nb_output_arguments=%d\n", nb_output_arguments);mexEvalString("drawnow;"); + mexPrintf("nb_output_arguments=%d\n", nb_output_arguments); mexEvalString("drawnow;"); #endif - mxArray *output_arguments[3]; string arg_func_name = fc->get_arg_func_name(); #ifdef DEBUG - mexPrintf("arg_func_name.length() = %d\n",arg_func_name.length()); - mexPrintf("arg_func_name.c_str() = %s\n",arg_func_name.c_str()); + mexPrintf("arg_func_name.length() = %d\n", arg_func_name.length()); + mexPrintf("arg_func_name.c_str() = %s\n", arg_func_name.c_str()); #endif unsigned int nb_add_input_arguments = fc->get_nb_add_input_arguments(); function_type = fc->get_function_type(); #ifdef DEBUG - mexPrintf("function_type=%d ExternalFunctionWithoutDerivative=%d\n",function_type, ExternalFunctionWithoutDerivative); + mexPrintf("function_type=%d ExternalFunctionWithoutDerivative=%d\n", function_type, ExternalFunctionWithoutDerivative); mexEvalString("drawnow;"); #endif mxArray **input_arguments; @@ -1157,12 +1154,12 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si case ExternalFunctionWithFirstDerivative: case ExternalFunctionWithFirstandSecondDerivative: { - input_arguments = (mxArray**)mxMalloc(nb_input_arguments * sizeof(mxArray*)); + input_arguments = (mxArray **) mxMalloc(nb_input_arguments * sizeof(mxArray *)); #ifdef DEBUG - mexPrintf("Stack.size()=%d\n",Stack.size()); + mexPrintf("Stack.size()=%d\n", Stack.size()); mexEvalString("drawnow;"); #endif - for (unsigned int i = 0; i < nb_input_arguments ; i++) + for (unsigned int i = 0; i < nb_input_arguments; i++) { mxArray *vv = mxCreateDoubleScalar(Stack.top()); input_arguments[nb_input_arguments - i - 1] = vv; @@ -1176,7 +1173,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si unsigned int indx = fc->get_indx(); double *FD1 = mxGetPr(output_arguments[1]); unsigned int rows = mxGetN(output_arguments[1]); - for(unsigned int i = 0; i < rows; i++) + for (unsigned int i = 0; i < rows; i++) TEFD[make_pair(indx, i)] = FD1[i]; } if (function_type == ExternalFunctionWithFirstandSecondDerivative) @@ -1194,7 +1191,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si break; case ExternalFunctionNumericalFirstDerivative: { - input_arguments = (mxArray**)mxMalloc((nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray*)); + input_arguments = (mxArray **) mxMalloc((nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray *)); mxArray *vv = mxCreateString(arg_func_name.c_str()); input_arguments[0] = vv; vv = mxCreateDoubleScalar(fc->get_row()); @@ -1204,16 +1201,16 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si { double rr = Stack.top(); #ifdef DEBUG - mexPrintf("i=%d rr = %f Stack.size()=%d\n",i, rr, Stack.size()); + mexPrintf("i=%d rr = %f Stack.size()=%d\n", i, rr, Stack.size()); #endif mxSetCell(vv, nb_add_input_arguments - (i+1), mxCreateDoubleScalar(rr)); Stack.pop(); } input_arguments[nb_input_arguments+nb_add_input_arguments] = vv; #ifdef DEBUG - mexCallMATLAB(0, NULL, 1, & input_arguments[0], "disp"); - mexCallMATLAB(0, NULL, 1, & input_arguments[1], "disp"); - mexCallMATLAB(0, NULL, 1, & input_arguments[2], "celldisp"); + mexCallMATLAB(0, NULL, 1, &input_arguments[0], "disp"); + mexCallMATLAB(0, NULL, 1, &input_arguments[1], "disp"); + mexCallMATLAB(0, NULL, 1, &input_arguments[2], "celldisp"); mexPrintf("OK\n"); mexEvalString("drawnow;"); #endif @@ -1221,14 +1218,14 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si mexCallMATLAB(nb_output_arguments, output_arguments, nb_input_arguments, input_arguments, function_name.c_str()); double *rr = mxGetPr(output_arguments[0]); #ifdef DEBUG - mexPrintf("*rr=%f\n",*rr); + mexPrintf("*rr=%f\n", *rr); #endif Stack.push(*rr); } break; case ExternalFunctionFirstDerivative: { - input_arguments = (mxArray**)mxMalloc(nb_input_arguments * sizeof(mxArray*)); + input_arguments = (mxArray **) mxMalloc(nb_input_arguments * sizeof(mxArray *)); for (unsigned int i = 0; i < nb_input_arguments; i++) { mxArray *vv = mxCreateDoubleScalar(Stack.top()); @@ -1246,7 +1243,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si break; case ExternalFunctionNumericalSecondDerivative: { - input_arguments = (mxArray**)mxMalloc((nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray*)); + input_arguments = (mxArray **) mxMalloc((nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray *)); mxArray *vv = mxCreateString(arg_func_name.c_str()); input_arguments[0] = vv; vv = mxCreateDoubleScalar(fc->get_row()); @@ -1258,16 +1255,16 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si { double rr = Stack.top(); #ifdef DEBUG - mexPrintf("i=%d rr = %f\n",i, rr); + mexPrintf("i=%d rr = %f\n", i, rr); #endif mxSetCell(vv, (nb_add_input_arguments - 1) - i, mxCreateDoubleScalar(rr)); Stack.pop(); } input_arguments[nb_input_arguments+nb_add_input_arguments] = vv; #ifdef DEBUG - mexCallMATLAB(0, NULL, 1, & input_arguments[0], "disp"); - mexCallMATLAB(0, NULL, 1, & input_arguments[1], "disp"); - mexCallMATLAB(0, NULL, 1, & input_arguments[2], "celldisp"); + mexCallMATLAB(0, NULL, 1, &input_arguments[0], "disp"); + mexCallMATLAB(0, NULL, 1, &input_arguments[1], "disp"); + mexCallMATLAB(0, NULL, 1, &input_arguments[2], "celldisp"); mexPrintf("OK\n"); mexEvalString("drawnow;"); #endif @@ -1279,8 +1276,8 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si break; case ExternalFunctionSecondDerivative: { - input_arguments = (mxArray**)mxMalloc(nb_input_arguments * sizeof(mxArray*)); - for (unsigned int i = 0; i < nb_input_arguments ; i++) + input_arguments = (mxArray **) mxMalloc(nb_input_arguments * sizeof(mxArray *)); + for (unsigned int i = 0; i < nb_input_arguments; i++) { mxArray *vv = mxCreateDoubleScalar(Stack.top()); input_arguments[i] = vv; @@ -1304,11 +1301,11 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si var = ((FSTPTEF_ *) it_code->second)->get_number(); #ifdef DEBUG mexPrintf("FSTPTEF\n"); - mexPrintf("var=%d Stack.size()=%d\n",var, Stack.size()); + mexPrintf("var=%d Stack.size()=%d\n", var, Stack.size()); #endif TEF[var-1] = Stack.top(); #ifdef DEBUG - mexPrintf("FSTP TEF[var-1]=%f done\n",TEF[var-1]); + mexPrintf("FSTP TEF[var-1]=%f done\n", TEF[var-1]); mexEvalString("drawnow;"); #endif Stack.pop(); @@ -1317,8 +1314,8 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si var = ((FLDTEF_ *) it_code->second)->get_number(); #ifdef DEBUG mexPrintf("FLDTEF\n"); - mexPrintf("var=%d Stack.size()=%d\n",var, Stack.size()); - mexPrintf("FLD TEF[var-1]=%f done\n",TEF[var-1]); + mexPrintf("var=%d Stack.size()=%d\n", var, Stack.size()); + mexPrintf("FLD TEF[var-1]=%f done\n", TEF[var-1]); mexEvalString("drawnow;"); #endif Stack.push(TEF[var-1]); @@ -1329,13 +1326,13 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si unsigned int row = ((FSTPTEFD_ *) it_code->second)->get_row(); #ifdef DEBUG mexPrintf("FSTPTEFD\n"); - mexPrintf("indx=%d Stack.size()=%d\n",indx, Stack.size()); + mexPrintf("indx=%d Stack.size()=%d\n", indx, Stack.size()); #endif if (function_type == ExternalFunctionNumericalFirstDerivative) { TEFD[make_pair(indx, row-1)] = Stack.top(); #ifdef DEBUG - mexPrintf("FSTP TEFD[make_pair(indx, row)]=%f done\n",TEFD[make_pair(indx, row-1)]); + mexPrintf("FSTP TEFD[make_pair(indx, row)]=%f done\n", TEFD[make_pair(indx, row-1)]); mexEvalString("drawnow;"); #endif Stack.pop(); @@ -1349,8 +1346,8 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si unsigned int row = ((FLDTEFD_ *) it_code->second)->get_row(); #ifdef DEBUG mexPrintf("FLDTEFD\n"); - mexPrintf("indx=%d row=%d Stack.size()=%d\n",indx, row, Stack.size()); - mexPrintf("FLD TEFD[make_pair(indx, row)]=%f done\n",TEFD[make_pair(indx, row-1)]); + mexPrintf("indx=%d row=%d Stack.size()=%d\n", indx, row, Stack.size()); + mexPrintf("FLD TEFD[make_pair(indx, row)]=%f done\n", TEFD[make_pair(indx, row-1)]); mexEvalString("drawnow;"); #endif Stack.push(TEFD[make_pair(indx, row-1)]); @@ -1363,13 +1360,13 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si unsigned int col = ((FSTPTEFDD_ *) it_code->second)->get_col(); #ifdef DEBUG mexPrintf("FSTPTEFD\n"); - mexPrintf("indx=%d Stack.size()=%d\n",indx, Stack.size()); + mexPrintf("indx=%d Stack.size()=%d\n", indx, Stack.size()); #endif if (function_type == ExternalFunctionNumericalSecondDerivative) { TEFDD[make_pair(indx, make_pair(row-1, col-1))] = Stack.top(); #ifdef DEBUG - mexPrintf("FSTP TEFDD[make_pair(indx, make_pair(row, col))]=%f done\n",TEFDD[make_pair(indx, make_pair(row, col))]); + mexPrintf("FSTP TEFDD[make_pair(indx, make_pair(row, col))]=%f done\n", TEFDD[make_pair(indx, make_pair(row, col))]); mexEvalString("drawnow;"); #endif Stack.pop(); @@ -1384,8 +1381,8 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si unsigned int col = ((FSTPTEFDD_ *) it_code->second)->get_col(); #ifdef DEBUG mexPrintf("FLDTEFD\n"); - mexPrintf("indx=%d Stack.size()=%d\n",indx, Stack.size()); - mexPrintf("FLD TEFD[make_pair(indx, make_pair(row, col))]=%f done\n",TEFDD[make_pair(indx, make_pair(row, col))]); + mexPrintf("indx=%d Stack.size()=%d\n", indx, Stack.size()); + mexPrintf("FLD TEFD[make_pair(indx, make_pair(row, col))]=%f done\n", TEFDD[make_pair(indx, make_pair(row, col))]); mexEvalString("drawnow;"); #endif Stack.push(TEFDD[make_pair(indx, make_pair(row-1, col-1))]); @@ -1411,15 +1408,15 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si if (evaluate) { #ifdef DEBUG - mexPrintf("FJMPIFEVAL length=%d\n",((FJMPIFEVAL_ *) it_code->second)->get_pos()); + mexPrintf("FJMPIFEVAL length=%d\n", ((FJMPIFEVAL_ *) it_code->second)->get_pos()); mexEvalString("drawnow;"); #endif - it_code += ((FJMPIFEVAL_ *) it_code->second)->get_pos()/* - 1*/; + it_code += ((FJMPIFEVAL_ *) it_code->second)->get_pos() /* - 1*/; } break; case FJMP: #ifdef DEBUG - mexPrintf("FJMP length=%d\n",((FJMP_ *) it_code->second)->get_pos()); + mexPrintf("FJMP length=%d\n", ((FJMP_ *) it_code->second)->get_pos()); mexEvalString("drawnow;"); #endif it_code += ((FJMP_ *) it_code->second)->get_pos() /*- 1 */; @@ -1441,7 +1438,7 @@ Interpreter::compute_block_time(int Per_u_, bool evaluate, int block_num, int si it_code++; } #ifdef DEBUG - mexPrintf("==> end of compute_block_time Block = %d\n",block_num); + mexPrintf("==> end of compute_block_time Block = %d\n", block_num); mexEvalString("drawnow;"); #endif } @@ -1452,7 +1449,7 @@ Interpreter::evaluate_a_block(const int size, const int type, string bin_basenam const int Block_List_Max_Lead, const int u_count_int, int block) { it_code_type begining; - + switch (type) { case EVALUATE_FORWARD: @@ -1468,7 +1465,7 @@ Interpreter::evaluate_a_block(const int size, const int type, string bin_basenam //mexPrintf("=>residual[Block_Contain[%d].Equation = %d]=%g (y = %g, ya = %g)\n", j, Block_Contain[j].Equation, y[Block_Contain[j].Variable] - ya[Block_Contain[j].Variable], y[Block_Contain[j].Variable], ya[Block_Contain[j].Variable]); residual[Block_Contain[j].Equation] = y[Block_Contain[j].Variable] - ya[Block_Contain[j].Variable]; } - } + } else { begining = it_code; @@ -1525,7 +1522,7 @@ Interpreter::evaluate_a_block(const int size, const int type, string bin_basenam else { for (int j = 0; j < size; j++) - residual[it_*size+j] = r[j]; + residual[it_*size+j] = r[j]; } } } @@ -1536,7 +1533,7 @@ Interpreter::evaluate_a_block(const int size, const int type, string bin_basenam fixe_u(&u, u_count_int, u_count_int); Read_SparseMatrix(bin_basename, size, 1, 0, 0, steady_state, false, stack_solve_algo, solve_algo); #ifdef DEBUG - mexPrintf("in SOLVE_FORWARD_COMPLETE r = mxMalloc(%d*sizeof(double))\n",size); + mexPrintf("in SOLVE_FORWARD_COMPLETE r = mxMalloc(%d*sizeof(double))\n", size); #endif r = (double *) mxMalloc(size*sizeof(double)); if (steady_state) @@ -1586,7 +1583,7 @@ Interpreter::evaluate_a_block(const int size, const int type, string bin_basenam //mexPrintf("residual[Block_Contain[%d].Equation = %d]=%g\n", j, Block_Contain[j].Equation, y[Block_Contain[j].Variable] - ya[Block_Contain[j].Variable]); residual[Block_Contain[j].Equation] = y[Block_Contain[j].Variable] - ya[Block_Contain[j].Variable]; } - } + } else { begining = it_code; @@ -1643,7 +1640,7 @@ Interpreter::evaluate_a_block(const int size, const int type, string bin_basenam else { for (int j = 0; j < size; j++) - residual[it_*size+j] = r[j]; + residual[it_*size+j] = r[j]; } } } @@ -1768,7 +1765,7 @@ Interpreter::simulate_a_block(const int size, const int type, string file_name, break; case SOLVE_FORWARD_SIMPLE: #ifdef DEBUG - mexPrintf("SOLVE_FORWARD_SIMPLE size=%d\n",size); + mexPrintf("SOLVE_FORWARD_SIMPLE size=%d\n", size); #endif g1 = (double *) mxMalloc(size*size*sizeof(double)); r = (double *) mxMalloc(size*sizeof(double)); @@ -1790,11 +1787,11 @@ Interpreter::simulate_a_block(const int size, const int type, string file_name, try { - y[Block_Contain[0].Variable] += - divide(r[0],g1[0]); + y[Block_Contain[0].Variable] += -divide(r[0], g1[0]); } - catch(FloatingPointExceptionHandling &fpeh) + catch (FloatingPointExceptionHandling &fpeh) { - mexPrintf("%s \n",fpeh.GetErrorMsg().c_str()); + mexPrintf("%s \n", fpeh.GetErrorMsg().c_str()); mexPrintf(" Singularity in block %d", block_num+1); } iter++; @@ -1828,11 +1825,11 @@ Interpreter::simulate_a_block(const int size, const int type, string file_name, continue; try { - y[Per_y_+Block_Contain[0].Variable] += - divide(r[0], g1[0]); + y[Per_y_+Block_Contain[0].Variable] += -divide(r[0], g1[0]); } - catch(FloatingPointExceptionHandling &fpeh) + catch (FloatingPointExceptionHandling &fpeh) { - mexPrintf("%s \n",fpeh.GetErrorMsg().c_str()); + mexPrintf("%s \n", fpeh.GetErrorMsg().c_str()); mexPrintf(" Singularity in block %d", block_num+1); } iter++; @@ -1871,11 +1868,11 @@ Interpreter::simulate_a_block(const int size, const int type, string file_name, continue; try { - y[Block_Contain[0].Variable] += - divide(r[0], g1[0]); + y[Block_Contain[0].Variable] += -divide(r[0], g1[0]); } - catch(FloatingPointExceptionHandling &fpeh) + catch (FloatingPointExceptionHandling &fpeh) { - mexPrintf("%s \n",fpeh.GetErrorMsg().c_str()); + mexPrintf("%s \n", fpeh.GetErrorMsg().c_str()); mexPrintf(" Singularity in block %d", block_num+1); } iter++; @@ -1909,11 +1906,11 @@ Interpreter::simulate_a_block(const int size, const int type, string file_name, continue; try { - y[Per_y_+Block_Contain[0].Variable] += - divide(r[0], g1[0]); + y[Per_y_+Block_Contain[0].Variable] += -divide(r[0], g1[0]); } - catch(FloatingPointExceptionHandling &fpeh) + catch (FloatingPointExceptionHandling &fpeh) { - mexPrintf("%s \n",fpeh.GetErrorMsg().c_str()); + mexPrintf("%s \n", fpeh.GetErrorMsg().c_str()); mexPrintf(" Singularity in block %d", block_num+1); } @@ -2082,7 +2079,7 @@ Interpreter::simulate_a_block(const int size, const int type, string file_name, g0 = res2; gp0 = -res2; try_at_iteration = 0; - } + } } if (!cvg) { @@ -2283,7 +2280,7 @@ Interpreter::simulate_a_block(const int size, const int type, string file_name, g0 = res2; gp0 = -res2; try_at_iteration = 0; - } + } } if (!cvg) { @@ -2458,11 +2455,11 @@ Interpreter::simulate_a_block(const int size, const int type, string file_name, void Interpreter::print_a_block(const int size, const int type, string bin_basename, bool steady_state, int block_num, - const bool is_linear, const int symbol_table_endo_nbr, const int Block_List_Max_Lag, - const int Block_List_Max_Lead, const int u_count_int, int block) + const bool is_linear, const int symbol_table_endo_nbr, const int Block_List_Max_Lag, + const int Block_List_Max_Lead, const int u_count_int, int block) { it_code_type begining; - mexPrintf("\nBlock %d\n",block_num+1); + mexPrintf("\nBlock %d\n", block_num+1); mexPrintf("----------\n"); if (steady_state) residual = vector<double>(size); @@ -2482,12 +2479,12 @@ Interpreter::print_a_block(const int size, const int type, string bin_basename, string s = print_expression(it_code, false, size, block_num, steady_state, Per_u_, it_, it_code, false); if (s == "if (evaluate)" || s == "else") space = false; - if (s.length()>0) + if (s.length() > 0) { if (space) - mexPrintf(" %s\n",s.c_str()); + mexPrintf(" %s\n", s.c_str()); else - mexPrintf("%s\n",s.c_str()); + mexPrintf("%s\n", s.c_str()); mexEvalString("drawnow;"); } if (s == "if (evaluate)" || s == "else") @@ -2496,7 +2493,6 @@ Interpreter::print_a_block(const int size, const int type, string bin_basename, } } - bool Interpreter::compute_blocks(string file_name, string bin_basename, bool steady_state, bool evaluate, int block, int &nb_blocks) { @@ -2517,7 +2513,7 @@ Interpreter::compute_blocks(string file_name, string bin_basename, bool steady_s tmp << " in compute_blocks, " << file_name.c_str() << " cannot be opened\n"; throw FatalExceptionHandling(tmp.str()); } - if (block >= (int)code.get_block_number()) + if (block >= (int) code.get_block_number()) { ostringstream tmp; tmp << " in compute_blocks, input argument block = " << block+1 << " is greater than the number of blocks in the model (" << code.get_block_number() << " see M_.blocksMFS)\n"; @@ -2536,7 +2532,7 @@ Interpreter::compute_blocks(string file_name, string bin_basename, bool steady_s else residual = vector<double>(y_size*(periods+y_kmin)); } - + while (go_on) { switch (it_code->first) @@ -2561,17 +2557,17 @@ Interpreter::compute_blocks(string file_name, string bin_basename, bool steady_s else if (evaluate) { #ifdef DEBUG - mexPrintf("jacobian_block=mxCreateDoubleMatrix(%d, %d, mxREAL)\n",fb->get_size(),fb->get_nb_col_jacob()); + mexPrintf("jacobian_block=mxCreateDoubleMatrix(%d, %d, mxREAL)\n", fb->get_size(), fb->get_nb_col_jacob()); #endif - jacobian_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_nb_col_jacob(),mxREAL)); + jacobian_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_nb_col_jacob(), mxREAL)); if (!steady_state) { #ifdef DEBUG - mexPrintf("allocates jacobian_exo_block( %d, %d, mxREAL)\n",fb->get_size(), fb->get_exo_size()); + mexPrintf("allocates jacobian_exo_block( %d, %d, mxREAL)\n", fb->get_size(), fb->get_exo_size()); #endif - jacobian_exo_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_exo_size(),mxREAL)); - jacobian_det_exo_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_det_exo_size(),mxREAL)); - jacobian_other_endo_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_nb_col_other_endo_jacob(),mxREAL)); + jacobian_exo_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_exo_size(), mxREAL)); + jacobian_det_exo_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_det_exo_size(), mxREAL)); + jacobian_other_endo_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_nb_col_other_endo_jacob(), mxREAL)); } if (block >= 0) { @@ -2627,7 +2623,7 @@ Interpreter::compute_blocks(string file_name, string bin_basename, bool steady_s break; case FDIMST: #ifdef DEBUG - mexPrintf("FDIMST size=%d\n",((FDIMST_ *) it_code->second)->get_size()); + mexPrintf("FDIMST size=%d\n", ((FDIMST_ *) it_code->second)->get_size()); #endif var = ((FDIMST_ *) it_code->second)->get_size(); if (T) @@ -2636,9 +2632,9 @@ Interpreter::compute_blocks(string file_name, string bin_basename, bool steady_s { if (GlobalTemporaryTerms == NULL) { - mexPrintf("GlobalTemporaryTerms is NULL\n");mexEvalString("drawnow;"); + mexPrintf("GlobalTemporaryTerms is NULL\n"); mexEvalString("drawnow;"); } - if (var != (int)mxGetNumberOfElements(GlobalTemporaryTerms)) + if (var != (int) mxGetNumberOfElements(GlobalTemporaryTerms)) GlobalTemporaryTerms = mxCreateDoubleMatrix(var, 1, mxREAL); T = mxGetPr(GlobalTemporaryTerms); } diff --git a/mex/sources/bytecode/Interpreter.hh b/mex/sources/bytecode/Interpreter.hh index 17fd8c16085e180ee1cc8ed9b44726f099e29b67..097f9b22616a7745db41e9f4fe2172175eea4a28 100644 --- a/mex/sources/bytecode/Interpreter.hh +++ b/mex/sources/bytecode/Interpreter.hh @@ -47,8 +47,8 @@ class Interpreter : public SparseMatrix private: unsigned int EQN_dvar1, EQN_dvar2, EQN_dvar3; int EQN_lag1, EQN_lag2, EQN_lag3; - mxArray* GlobalTemporaryTerms; - protected: + mxArray *GlobalTemporaryTerms; +protected: double pow1(double a, double b); double divide(double a, double b); double log1(double a); @@ -57,10 +57,10 @@ private: void evaluate_a_block(const int size, const int type, string bin_basename, bool steady_state, int block_num, const bool is_linear = false, const int symbol_table_endo_nbr = 0, const int Block_List_Max_Lag = 0, const int Block_List_Max_Lead = 0, const int u_count_int = 0, int block = -1); int simulate_a_block(const int size, const int type, string file_name, string bin_basename, bool Gaussian_Elimination, bool steady_state, int block_num, - const bool is_linear = false, const int symbol_table_endo_nbr = 0, const int Block_List_Max_Lag = 0, const int Block_List_Max_Lead = 0, const int u_count_int = 0); + const bool is_linear = false, const int symbol_table_endo_nbr = 0, const int Block_List_Max_Lag = 0, const int Block_List_Max_Lead = 0, const int u_count_int = 0); void print_a_block(const int size, const int type, string bin_basename, bool steady_state, int block_num, - const bool is_linear, const int symbol_table_endo_nbr, const int Block_List_Max_Lag, - const int Block_List_Max_Lead, const int u_count_int, int block); + const bool is_linear, const int symbol_table_endo_nbr, const int Block_List_Max_Lag, + const int Block_List_Max_Lead, const int u_count_int, int block); vector<Block_contain_type> Block_Contain; code_liste_type code_liste; it_code_type it_code; @@ -81,14 +81,38 @@ public: double *direction_arg, int y_size_arg, int nb_row_x_arg, int nb_row_xd_arg, int periods_arg, int y_kmin_arg, int y_kmax_arg, int maxit_arg_, double solve_tolf_arg, int size_o_direction_arg, double slowc_arg, int y_decal_arg, double markowitz_c_arg, string &filename_arg, int minimal_solving_periods_arg, int stack_solve_algo_arg, int solve_algo_arg, - bool global_temporary_terms_arg, bool print_arg, mxArray* GlobalTemporaryTerms_arg); + bool global_temporary_terms_arg, bool print_arg, mxArray *GlobalTemporaryTerms_arg); bool compute_blocks(string file_name, string bin_basename, bool steady_state, bool evaluate, int block, int &nb_blocks); - inline mxArray* get_jacob(int block_num) {return jacobian_block[block_num];}; - inline mxArray* get_jacob_exo(int block_num) {return jacobian_exo_block[block_num];}; - inline mxArray* get_jacob_exo_det(int block_num) {return jacobian_det_exo_block[block_num];}; - inline mxArray* get_jacob_other_endo(int block_num) {return jacobian_other_endo_block[block_num];}; - inline vector<double> get_residual() {return residual;}; - inline mxArray* get_Temporary_Terms() {return GlobalTemporaryTerms;}; + inline mxArray * + get_jacob(int block_num) + { + return jacobian_block[block_num]; + }; + inline mxArray * + get_jacob_exo(int block_num) + { + return jacobian_exo_block[block_num]; + }; + inline mxArray * + get_jacob_exo_det(int block_num) + { + return jacobian_det_exo_block[block_num]; + }; + inline mxArray * + get_jacob_other_endo(int block_num) + { + return jacobian_other_endo_block[block_num]; + }; + inline vector<double> + get_residual() + { + return residual; + }; + inline mxArray * + get_Temporary_Terms() + { + return GlobalTemporaryTerms; + }; }; #endif diff --git a/mex/sources/bytecode/Mem_Mngr.cc b/mex/sources/bytecode/Mem_Mngr.cc index 6729e3189e2cd572440e25ef2bf3c366f6ab4fef..6c5516bf05ebafc0a5db49ae4573d8c9e3d5d4a1 100644 --- a/mex/sources/bytecode/Mem_Mngr.cc +++ b/mex/sources/bytecode/Mem_Mngr.cc @@ -85,9 +85,9 @@ Mem_Mngr::mxMalloc_NZE() mexEvalString("drawnow;"); } if (NZE_Mem_add) - NZE_Mem_add = (NonZeroElem **) mxRealloc(NZE_Mem_add, CHUNK_SIZE*sizeof(NonZeroElem *)); /*We have to redefine the size of pointer on the memory*/ + NZE_Mem_add = (NonZeroElem **) mxRealloc(NZE_Mem_add, CHUNK_SIZE*sizeof(NonZeroElem *)); /*We have to redefine the size of pointer on the memory*/ else - NZE_Mem_add = (NonZeroElem **) mxMalloc(CHUNK_SIZE*sizeof(NonZeroElem *)); /*We have to define the size of pointer on the memory*/ + NZE_Mem_add = (NonZeroElem **) mxMalloc(CHUNK_SIZE*sizeof(NonZeroElem *)); /*We have to define the size of pointer on the memory*/ if (!NZE_Mem_add) { mexPrintf("Not enough memory available\n"); @@ -95,7 +95,7 @@ Mem_Mngr::mxMalloc_NZE() } for (i = CHUNK_heap_pos; i < CHUNK_SIZE; i++) { - NZE_Mem_add[i] = (NonZeroElem *)(NZE_Mem+(i-CHUNK_heap_pos)); + NZE_Mem_add[i] = (NonZeroElem *) (NZE_Mem+(i-CHUNK_heap_pos)); } i = CHUNK_heap_pos++; return (NZE_Mem_add[i]); @@ -109,7 +109,7 @@ Mem_Mngr::mxFree_NZE(void *pos) size_t gap; for (i = 0; i < Nb_CHUNK; i++) { - gap = ((size_t)(pos)-(size_t)(NZE_Mem_add[i*CHUNK_BLCK_SIZE]))/sizeof(NonZeroElem); + gap = ((size_t) (pos)-(size_t) (NZE_Mem_add[i*CHUNK_BLCK_SIZE]))/sizeof(NonZeroElem); if ((gap < CHUNK_BLCK_SIZE) && (gap >= 0)) break; } diff --git a/mex/sources/bytecode/SparseMatrix.cc b/mex/sources/bytecode/SparseMatrix.cc index 26712bbee0d690630d34d0f0fc451e907f767c4c..6201285f63c34dfa03d34297a5da49042866dddb 100644 --- a/mex/sources/bytecode/SparseMatrix.cc +++ b/mex/sources/bytecode/SparseMatrix.cc @@ -131,7 +131,8 @@ SparseMatrix::At_Col(int c, int lag, NonZeroElem **first) firsta = firsta->NZE_C_N; i++; } - if (firsta->lag_index == lag) i++; + if (firsta->lag_index == lag) + i++; } } return i; @@ -340,7 +341,7 @@ SparseMatrix::Read_SparseMatrix(string file_name, const int Size, int periods, i IM_i[make_pair(make_pair(eq, var), lag)] = j; } } - else if ( ((stack_solve_algo >= 0 || stack_solve_algo <= 4) && !steady_state) || ((solve_algo >= 6 || solve_algo <= 8) && steady_state) ) + else if (((stack_solve_algo >= 0 || stack_solve_algo <= 4) && !steady_state) || ((solve_algo >= 6 || solve_algo <= 8) && steady_state)) { for (i = 0; i < u_count_init; i++) { @@ -523,7 +524,7 @@ SparseMatrix::Init_Matlab_Sparse_Simple(int Size, map<pair<pair<int, int>, int>, eq = it4->first.second; int index = it4->second; #ifdef DEBUG - if (index<0 || index >= u_count_alloc || index > Size + Size*Size) + if (index < 0 || index >= u_count_alloc || index > Size + Size*Size) { ostringstream tmp; tmp << " in Init_Matlab_Sparse_Simple, index (" << index << ") out of range for u vector max = " << Size+Size*Size << " allocated = " << u_count_alloc << "\n"; @@ -545,7 +546,7 @@ SparseMatrix::Init_Matlab_Sparse_Simple(int Size, map<pair<pair<int, int>, int>, ostringstream tmp; tmp << " in Init_Matlab_Sparse_Simple, index (" << eq << ") out of range for b vector\n"; throw FatalExceptionHandling(tmp.str()); - } + } if (var < 0 || var >= Size) { ostringstream tmp; @@ -560,12 +561,10 @@ SparseMatrix::Init_Matlab_Sparse_Simple(int Size, map<pair<pair<int, int>, int>, } #endif it4++; - } + } Aj[Size] = NZE; } - - void SparseMatrix::Init_Matlab_Sparse(int periods, int y_kmin, int y_kmax, int Size, map<pair<pair<int, int>, int>, int> &IM, mxArray *A_m, mxArray *b_m, mxArray *x0_m) { @@ -637,24 +636,24 @@ SparseMatrix::Init_Matlab_Sparse(int periods, int y_kmin, int y_kmax, int Size, if (var < (periods+y_kmax)*Size) { ti_y_kmin = -min(t, y_kmin); - ti_y_kmax = min(periods-(t +1 ), y_kmax); + ti_y_kmax = min(periods-(t +1), y_kmax); int ti_new_y_kmax = min(t, y_kmax); int ti_new_y_kmin = -min(periods-(t+1), y_kmin); if (lag <= ti_new_y_kmax && lag >= ti_new_y_kmin) /*Build the index for sparse matrix containing the jacobian : u*/ { #ifdef DEBUG - if (index<0 || index >= u_count_alloc || index > Size + Size*Size) - { - ostringstream tmp; - tmp << " in Init_Matlab_Sparse, index (" << index << ") out of range for u vector max = " << Size+Size*Size << " allocated = " << u_count_alloc << "\n"; - throw FatalExceptionHandling(tmp.str()); - } - if (NZE >= max_nze) - { - ostringstream tmp; - tmp << " in Init_Matlab_Sparse, exceeds the capacity of A_m sparse matrix\n"; - throw FatalExceptionHandling(tmp.str()); - } + if (index < 0 || index >= u_count_alloc || index > Size + Size*Size) + { + ostringstream tmp; + tmp << " in Init_Matlab_Sparse, index (" << index << ") out of range for u vector max = " << Size+Size*Size << " allocated = " << u_count_alloc << "\n"; + throw FatalExceptionHandling(tmp.str()); + } + if (NZE >= max_nze) + { + ostringstream tmp; + tmp << " in Init_Matlab_Sparse, exceeds the capacity of A_m sparse matrix\n"; + throw FatalExceptionHandling(tmp.str()); + } #endif A[NZE] = u[index]; Ai[NZE] = eq - lag * Size; @@ -668,7 +667,7 @@ SparseMatrix::Init_Matlab_Sparse(int periods, int y_kmin, int y_kmax, int Size, ostringstream tmp; tmp << " in Init_Matlab_Sparse, index (" << eq << ") out of range for b vector\n"; throw FatalExceptionHandling(tmp.str()); - } + } if (var+Size*(y_kmin+t+lag) < 0 || var+Size*(y_kmin+t+lag) >= Size*(periods+y_kmin+y_kmax)) { ostringstream tmp; @@ -709,7 +708,6 @@ SparseMatrix::Init_Matlab_Sparse(int periods, int y_kmin, int y_kmax, int Size, Aj[Size*periods] = NZE; } - void SparseMatrix::Init_GE(int periods, int y_kmin, int y_kmax, int Size, map<pair<pair<int, int>, int>, int> &IM) { @@ -966,7 +964,7 @@ SparseMatrix::compare(int *save_op, int *save_opa, int *save_opaa, int beg_t, in i = j = 0; while (i < nop4) { - save_op_s = (t_save_op_s *)(&(save_op[i])); + save_op_s = (t_save_op_s *) (&(save_op[i])); up = &u[save_op_s->first+t*diff1[j]]; switch (save_op_s->operat) { @@ -997,7 +995,7 @@ SparseMatrix::compare(int *save_op, int *save_opa, int *save_opaa, int beg_t, in i = j = 0; while (i < nop4) { - save_op_s = (t_save_op_s *)(&(save_op[i])); + save_op_s = (t_save_op_s *) (&(save_op[i])); if (save_op_s->lag < (periods_beg_t-t)) { up = &u[save_op_s->first+t*diff1[j]]; @@ -1356,43 +1354,41 @@ SparseMatrix::Check_the_Solution(int periods, int y_kmin, int y_kmax, int Size, } } -mxArray* -SparseMatrix::substract_A_B(mxArray* A_m, mxArray* B_m) +mxArray * +SparseMatrix::substract_A_B(mxArray *A_m, mxArray *B_m) { unsigned int n_A = mxGetN(A_m); unsigned int m_A = mxGetM(A_m); - double* A_d = mxGetPr(A_m); + double *A_d = mxGetPr(A_m); unsigned int n_B = mxGetN(B_m); - double* B_d = mxGetPr(B_m); - mxArray* C_m = mxCreateDoubleMatrix(m_A, n_B, mxREAL); - double* C_d = mxGetPr(C_m); + double *B_d = mxGetPr(B_m); + mxArray *C_m = mxCreateDoubleMatrix(m_A, n_B, mxREAL); + double *C_d = mxGetPr(C_m); for (unsigned int j = 0; j < n_A; j++) for (unsigned int i = 0; i < m_A; i++) { unsigned int index = j*m_A+i; C_d[index] = A_d[index] - B_d[index]; - } + } return C_m; } - - -mxArray* -SparseMatrix::Sparse_substract_A_SB(mxArray* A_m, mxArray* B_m) +mxArray * +SparseMatrix::Sparse_substract_A_SB(mxArray *A_m, mxArray *B_m) { unsigned int n_B = mxGetN(B_m); unsigned int m_B = mxGetM(B_m); - mwIndex* B_i = mxGetIr(B_m); - mwIndex* B_j = mxGetJc(B_m); + mwIndex *B_i = mxGetIr(B_m); + mwIndex *B_j = mxGetJc(B_m); unsigned int total_nze_B = B_j[n_B]; - double* B_d = mxGetPr(B_m); - mxArray* C_m = mxDuplicateArray(A_m); - double* C_d = mxGetPr(C_m); + double *B_d = mxGetPr(B_m); + mxArray *C_m = mxDuplicateArray(A_m); + double *C_d = mxGetPr(C_m); unsigned int nze_B = 0; unsigned int B_col = 0; while (nze_B < total_nze_B) { - while (nze_B >= (unsigned int)B_j[B_col+1] && (nze_B < total_nze_B)) + while (nze_B >= (unsigned int) B_j[B_col+1] && (nze_B < total_nze_B)) B_col++; C_d[B_col*m_B+B_i[nze_B]] -= B_d[nze_B]; nze_B++; @@ -1400,35 +1396,33 @@ SparseMatrix::Sparse_substract_A_SB(mxArray* A_m, mxArray* B_m) return C_m; } - - -mxArray* -SparseMatrix::Sparse_substract_SA_SB(mxArray* A_m, mxArray* B_m) +mxArray * +SparseMatrix::Sparse_substract_SA_SB(mxArray *A_m, mxArray *B_m) { unsigned int n_A = mxGetN(A_m); unsigned int m_A = mxGetM(A_m); - mwIndex* A_i = mxGetIr(A_m); - mwIndex* A_j = mxGetJc(A_m); + mwIndex *A_i = mxGetIr(A_m); + mwIndex *A_j = mxGetJc(A_m); unsigned int total_nze_A = A_j[n_A]; - double* A_d = mxGetPr(A_m); + double *A_d = mxGetPr(A_m); unsigned int n_B = mxGetN(B_m); - mwIndex* B_i = mxGetIr(B_m); - mwIndex* B_j = mxGetJc(B_m); + mwIndex *B_i = mxGetIr(B_m); + mwIndex *B_j = mxGetJc(B_m); unsigned int total_nze_B = B_j[n_B]; - double* B_d = mxGetPr(B_m); - mxArray* C_m = mxCreateSparse(m_A, n_B, m_A*n_B, mxREAL); - mwIndex* C_i = mxGetIr(C_m); - mwIndex* C_j = mxGetJc(C_m); - double* C_d = mxGetPr(C_m); + double *B_d = mxGetPr(B_m); + mxArray *C_m = mxCreateSparse(m_A, n_B, m_A*n_B, mxREAL); + mwIndex *C_i = mxGetIr(C_m); + mwIndex *C_j = mxGetJc(C_m); + double *C_d = mxGetPr(C_m); unsigned int nze_B = 0, nze_C = 0, nze_A = 0; unsigned int A_col = 0, B_col = 0, C_col = 0; C_j[C_col] = 0; while (nze_A < total_nze_A || nze_B < total_nze_B) { - while (nze_A >= (unsigned int)A_j[A_col+1] && (nze_A < total_nze_A)) + while (nze_A >= (unsigned int) A_j[A_col+1] && (nze_A < total_nze_A)) A_col++; int A_row = A_i[nze_A]; - while (nze_B >= (unsigned int)B_j[B_col+1] && (nze_B < total_nze_B)) + while (nze_B >= (unsigned int) B_j[B_col+1] && (nze_B < total_nze_B)) B_col++; int B_row = B_i[nze_B]; if (A_col == B_col) @@ -1453,7 +1447,7 @@ SparseMatrix::Sparse_substract_SA_SB(mxArray* A_m, mxArray* B_m) } else { - C_d[nze_C] = - B_d[nze_B++]; + C_d[nze_C] = -B_d[nze_B++]; C_i[nze_C] = B_row; while (C_col < B_col) C_j[++C_col] = nze_C; @@ -1472,10 +1466,10 @@ SparseMatrix::Sparse_substract_SA_SB(mxArray* A_m, mxArray* B_m) } else { - C_d[nze_C] = - B_d[nze_B++]; + C_d[nze_C] = -B_d[nze_B++]; C_i[nze_C] = B_row; while (C_col < B_col) - C_j[++C_col] = nze_C; + C_j[++C_col] = nze_C; C_j[B_col+1] = nze_C++; C_col = B_col; } @@ -1486,27 +1480,26 @@ SparseMatrix::Sparse_substract_SA_SB(mxArray* A_m, mxArray* B_m) return C_m; } - -mxArray* -SparseMatrix::mult_SAT_B(mxArray* A_m, mxArray* B_m) +mxArray * +SparseMatrix::mult_SAT_B(mxArray *A_m, mxArray *B_m) { unsigned int n_A = mxGetN(A_m); unsigned int m_A = mxGetM(A_m); - mwIndex* A_i = mxGetIr(A_m); - mwIndex* A_j = mxGetJc(A_m); - double* A_d = mxGetPr(A_m); + mwIndex *A_i = mxGetIr(A_m); + mwIndex *A_j = mxGetJc(A_m); + double *A_d = mxGetPr(A_m); unsigned int n_B = mxGetN(B_m); - double* B_d = mxGetPr(B_m); - mxArray* C_m = mxCreateDoubleMatrix(m_A, n_B, mxREAL); - double* C_d = mxGetPr(C_m); + double *B_d = mxGetPr(B_m); + mxArray *C_m = mxCreateDoubleMatrix(m_A, n_B, mxREAL); + double *C_d = mxGetPr(C_m); unsigned int nze_A = 0; for (unsigned int j = 0; j < n_B; j++) { for (unsigned int i = 0; i < n_A; i++) - { + { double sum = 0; nze_A = A_j[i]; - while ( nze_A < (unsigned int)A_j[i+1] ) + while (nze_A < (unsigned int) A_j[i+1]) { unsigned int i_A = A_i[nze_A]; sum += A_d[nze_A++] * B_d[i_A]; @@ -1517,32 +1510,31 @@ SparseMatrix::mult_SAT_B(mxArray* A_m, mxArray* B_m) return C_m; } - -mxArray* -SparseMatrix::Sparse_mult_SAT_B(mxArray* A_m, mxArray* B_m) +mxArray * +SparseMatrix::Sparse_mult_SAT_B(mxArray *A_m, mxArray *B_m) { unsigned int n_A = mxGetN(A_m); unsigned int m_A = mxGetM(A_m); - mwIndex* A_i = mxGetIr(A_m); - mwIndex* A_j = mxGetJc(A_m); - double* A_d = mxGetPr(A_m); + mwIndex *A_i = mxGetIr(A_m); + mwIndex *A_j = mxGetJc(A_m); + double *A_d = mxGetPr(A_m); unsigned int n_B = mxGetN(B_m); unsigned int m_B = mxGetM(B_m); - double* B_d = mxGetPr(B_m); - mxArray* C_m = mxCreateSparse(m_A, n_B, m_A*n_B, mxREAL); - mwIndex* C_i = mxGetIr(C_m); - mwIndex* C_j = mxGetJc(C_m); - double* C_d = mxGetPr(C_m); + double *B_d = mxGetPr(B_m); + mxArray *C_m = mxCreateSparse(m_A, n_B, m_A*n_B, mxREAL); + mwIndex *C_i = mxGetIr(C_m); + mwIndex *C_j = mxGetJc(C_m); + double *C_d = mxGetPr(C_m); unsigned int nze_C = 0, nze_A = 0; unsigned int C_col = 0; C_j[C_col] = 0; for (unsigned int j = 0; j < n_B; j++) { for (unsigned int i = 0; i < n_A; i++) - { + { double sum = 0; nze_A = A_j[i]; - while ( nze_A < (unsigned int)A_j[i+1] ) + while (nze_A < (unsigned int) A_j[i+1]) { unsigned int i_A = A_i[nze_A]; sum += A_d[nze_A++] * B_d[i_A]; @@ -1563,38 +1555,37 @@ SparseMatrix::Sparse_mult_SAT_B(mxArray* A_m, mxArray* B_m) return C_m; } - -mxArray* -SparseMatrix::Sparse_mult_SAT_SB(mxArray* A_m, mxArray* B_m) +mxArray * +SparseMatrix::Sparse_mult_SAT_SB(mxArray *A_m, mxArray *B_m) { unsigned int n_A = mxGetN(A_m); unsigned int m_A = mxGetM(A_m); - mwIndex* A_i = mxGetIr(A_m); - mwIndex* A_j = mxGetJc(A_m); - double* A_d = mxGetPr(A_m); + mwIndex *A_i = mxGetIr(A_m); + mwIndex *A_j = mxGetJc(A_m); + double *A_d = mxGetPr(A_m); unsigned int n_B = mxGetN(B_m); - mwIndex* B_i = mxGetIr(B_m); - mwIndex* B_j = mxGetJc(B_m); - double* B_d = mxGetPr(B_m); - mxArray* C_m = mxCreateSparse(m_A, n_B, m_A*n_B, mxREAL); - mwIndex* C_i = mxGetIr(C_m); - mwIndex* C_j = mxGetJc(C_m); - double* C_d = mxGetPr(C_m); + mwIndex *B_i = mxGetIr(B_m); + mwIndex *B_j = mxGetJc(B_m); + double *B_d = mxGetPr(B_m); + mxArray *C_m = mxCreateSparse(m_A, n_B, m_A*n_B, mxREAL); + mwIndex *C_i = mxGetIr(C_m); + mwIndex *C_j = mxGetJc(C_m); + double *C_d = mxGetPr(C_m); unsigned int nze_B = 0, nze_C = 0, nze_A = 0; unsigned int C_col = 0; C_j[C_col] = 0; for (unsigned int j = 0; j < n_B; j++) { for (unsigned int i = 0; i < n_A; i++) - { + { double sum = 0; nze_B = B_j[j]; nze_A = A_j[i]; - while ( nze_A < (unsigned int)A_j[i+1] && nze_B < (unsigned int)B_j[j+1]) + while (nze_A < (unsigned int) A_j[i+1] && nze_B < (unsigned int) B_j[j+1]) { unsigned int i_A = A_i[nze_A]; unsigned int i_B = B_i[nze_B]; - if ( i_A == i_B) + if (i_A == i_B) sum += A_d[nze_A++] * B_d[nze_B++]; else if (i_A < i_B) nze_A++; @@ -1617,25 +1608,25 @@ SparseMatrix::Sparse_mult_SAT_SB(mxArray* A_m, mxArray* B_m) return C_m; } -mxArray* -SparseMatrix::Sparse_transpose(mxArray* A_m) +mxArray * +SparseMatrix::Sparse_transpose(mxArray *A_m) { unsigned int n_A = mxGetN(A_m); unsigned int m_A = mxGetM(A_m); - mwIndex* A_i = mxGetIr(A_m); - mwIndex* A_j = mxGetJc(A_m); + mwIndex *A_i = mxGetIr(A_m); + mwIndex *A_j = mxGetJc(A_m); unsigned int total_nze_A = A_j[n_A]; - double* A_d = mxGetPr(A_m); - mxArray* C_m = mxCreateSparse(n_A, m_A, total_nze_A, mxREAL); - mwIndex* C_i = mxGetIr(C_m); - mwIndex* C_j = mxGetJc(C_m); - double* C_d = mxGetPr(C_m); + double *A_d = mxGetPr(A_m); + mxArray *C_m = mxCreateSparse(n_A, m_A, total_nze_A, mxREAL); + mwIndex *C_i = mxGetIr(C_m); + mwIndex *C_j = mxGetJc(C_m); + double *C_d = mxGetPr(C_m); unsigned int nze_C = 0, nze_A = 0; memset(C_j, 0, m_A); map<pair<unsigned int, unsigned int>, double> B2; for (unsigned int i = 0; i < n_A; i++) { - while ( nze_A < (unsigned int)A_j[i+1]) + while (nze_A < (unsigned int) A_j[i+1]) { C_j[A_i[nze_A]+1]++; B2[make_pair(A_i[nze_A], i)] = A_d[nze_A]; @@ -1652,13 +1643,11 @@ SparseMatrix::Sparse_transpose(mxArray* A_m) return C_m; } - - void -SparseMatrix::Solve_Matlab_Relaxation(mxArray* A_m, mxArray* b_m, unsigned int Size, double slowc_l, bool is_two_boundaries, int it_) +SparseMatrix::Solve_Matlab_Relaxation(mxArray *A_m, mxArray *b_m, unsigned int Size, double slowc_l, bool is_two_boundaries, int it_) { mxArray *B1, *C1, *A2, *B2, *A3, *b1, *b2; - double* b_m_d = mxGetPr(b_m); + double *b_m_d = mxGetPr(b_m); if (!b_m_d) { ostringstream tmp; @@ -1690,56 +1679,56 @@ SparseMatrix::Solve_Matlab_Relaxation(mxArray* A_m, mxArray* b_m, unsigned int S unsigned int nze = 0; unsigned int var = A_m_j[nze]; B1 = mxCreateSparse(Size, Size, Size*Size, mxREAL); - mwIndex* B1_i = mxGetIr(B1); - mwIndex* B1_j = mxGetJc(B1); - double* B1_d = mxGetPr(B1); + mwIndex *B1_i = mxGetIr(B1); + mwIndex *B1_j = mxGetJc(B1); + double *B1_d = mxGetPr(B1); unsigned int B1_nze = 0; unsigned int B1_var = 0; B1_i[B1_nze] = 0; B1_j[B1_var] = 0; C1 = mxCreateSparse(Size, Size, Size*Size, mxREAL); - mwIndex* C1_i = mxGetIr(C1); - mwIndex* C1_j = mxGetJc(C1); - double* C1_d = mxGetPr(C1); + mwIndex *C1_i = mxGetIr(C1); + mwIndex *C1_j = mxGetJc(C1); + double *C1_d = mxGetPr(C1); unsigned int C1_nze = 0; unsigned int C1_var = 0; C1_i[C1_nze] = 0; C1_j[C1_var] = 0; A2 = mxCreateSparse(Size, Size, Size*Size, mxREAL); - mwIndex* A2_i = mxGetIr(A2); - mwIndex* A2_j = mxGetJc(A2); - double* A2_d = mxGetPr(A2); + mwIndex *A2_i = mxGetIr(A2); + mwIndex *A2_j = mxGetJc(A2); + double *A2_d = mxGetPr(A2); unsigned int A2_nze = 0; unsigned int A2_var = 0; A2_i[A2_nze] = 0; A2_j[A2_var] = 0; B2 = mxCreateSparse(Size, Size, Size*Size, mxREAL); - mwIndex* B2_i = mxGetIr(B2); - mwIndex* B2_j = mxGetJc(B2); - double* B2_d = mxGetPr(B2); + mwIndex *B2_i = mxGetIr(B2); + mwIndex *B2_j = mxGetJc(B2); + double *B2_d = mxGetPr(B2); unsigned int B2_nze = 0; unsigned int B2_var = 0; B2_i[B2_nze] = 0; B2_j[B2_var] = 0; A3 = mxCreateSparse(Size, Size, Size*Size, mxREAL); - mwIndex* A3_i = mxGetIr(A3); - mwIndex* A3_j = mxGetJc(A3); - double* A3_d = mxGetPr(A3); + mwIndex *A3_i = mxGetIr(A3); + mwIndex *A3_j = mxGetJc(A3); + double *A3_d = mxGetPr(A3); unsigned int A3_nze = 0; unsigned int A3_var = 0; A3_i[A3_nze] = 0; A3_j[A3_var] = 0; b1 = mxCreateDoubleMatrix(Size, 1, mxREAL); - double* b1_d = mxGetPr(b1); + double *b1_d = mxGetPr(b1); b2 = mxCreateDoubleMatrix(Size, 1, mxREAL); - double* b2_d = mxGetPr(b2); + double *b2_d = mxGetPr(b2); unsigned int eq = 0; /*B1 C1 A2 B2 - A3*/ + A3*/ while (var < 2*Size && nze < max_nze) { - if ((unsigned int)A_m_j[var+1] <= nze) + if ((unsigned int) A_m_j[var+1] <= nze) { if (var < Size) b1_d[var] = b_m_d[var]; @@ -1767,7 +1756,7 @@ SparseMatrix::Solve_Matlab_Relaxation(mxArray* A_m, mxArray* b_m, unsigned int S A2_nze++; } } - else if(var < 2*Size) + else if (var < 2*Size) { if (eq < Size) { @@ -1804,12 +1793,12 @@ SparseMatrix::Solve_Matlab_Relaxation(mxArray* A_m, mxArray* b_m, unsigned int S A2_j[++A2_var] = A2_nze; while (B2_var < Size) B2_j[++B2_var] = B2_nze; - while(A3_var < Size) + while (A3_var < Size) A3_j[++A3_var] = A3_nze; mxArray *d1 = NULL; - vector<pair<mxArray*, mxArray*> > triangular_form; + vector<pair<mxArray *, mxArray *> > triangular_form; int last_t = 0; - double sumc=0, C_sumc = 1000; + double sumc = 0, C_sumc = 1000; mxArray *B1_inv = NULL; mxArray *B1_inv_t = NULL; for (int t = 1; t <= periods; t++) @@ -1822,9 +1811,9 @@ SparseMatrix::Solve_Matlab_Relaxation(mxArray* A_m, mxArray* b_m, unsigned int S mexCallMATLAB(1, &B1_inv, 1, &B1, "inv"); mwIndex *B_inv_j = mxGetJc(B1_inv); unsigned int B_inv_nze = B_inv_j[Size]; - double* B_inv_d = mxGetPr(B1_inv); + double *B_inv_d = mxGetPr(B1_inv); sumc = 0; - for (unsigned int i = 0; i <B_inv_nze; i++ ) + for (unsigned int i = 0; i < B_inv_nze; i++) sumc += fabs(B_inv_d[i]); last_t = t; } @@ -1833,7 +1822,7 @@ SparseMatrix::Solve_Matlab_Relaxation(mxArray* A_m, mxArray* b_m, unsigned int S d1 = mult_SAT_B(B1_inv_t, b1); if (t < periods) - //Computation for the next lines + //Computation for the next lines { mxDestroyArray(B1_inv_t); mxArray *A2_t = Sparse_transpose(A2); @@ -1864,7 +1853,7 @@ SparseMatrix::Solve_Matlab_Relaxation(mxArray* A_m, mxArray* b_m, unsigned int S nze--; while (var < (t+2)*Size && nze < max_nze) { - if ((unsigned int)A_m_j[var+1] <= nze) + if ((unsigned int) A_m_j[var+1] <= nze) { b2_d[var - (t+1) * Size] = b_m_d[var]; var++; @@ -1889,30 +1878,30 @@ SparseMatrix::Solve_Matlab_Relaxation(mxArray* A_m, mxArray* b_m, unsigned int S } } double *d1_d = mxGetPr(d1); - for(unsigned i=0; i<Size; i++) + for (unsigned i = 0; i < Size; i++) { int eq = index_vara[i+Size*(y_kmin+periods-1)]; - double yy = - (d1_d[i] + y[eq]); + double yy = -(d1_d[i] + y[eq]); direction[eq] = yy; y[eq] += slowc_l * yy; } - pair<mxArray*, mxArray*> tf; + pair<mxArray *, mxArray *> tf; for (int t = periods-2; t >= 0; t--) { - mxArray* tmp; + mxArray *tmp; tf = triangular_form.back(); triangular_form.pop_back(); - mxArray* tf_first_t = Sparse_transpose(tf.first); + mxArray *tf_first_t = Sparse_transpose(tf.first); mxDestroyArray(tf.first); tmp = mult_SAT_B(tf_first_t, d1); d1 = substract_A_B(tf.second, tmp); d1_d = mxGetPr(d1); mxDestroyArray(tmp); - for(unsigned i=0; i<Size; i++) + for (unsigned i = 0; i < Size; i++) { int eq = index_vara[i+Size*(y_kmin+t)]; - double yy = - (d1_d[i] + y[eq]); + double yy = -(d1_d[i] + y[eq]); direction[eq] = yy; y[eq] += slowc_l * yy; } @@ -1931,7 +1920,7 @@ SparseMatrix::Solve_Matlab_Relaxation(mxArray* A_m, mxArray* b_m, unsigned int S } void -SparseMatrix::Solve_Matlab_LU_UMFPack(mxArray* A_m, mxArray* b_m, int Size, double slowc_l, bool is_two_boundaries, int it_) +SparseMatrix::Solve_Matlab_LU_UMFPack(mxArray *A_m, mxArray *b_m, int Size, double slowc_l, bool is_two_boundaries, int it_) { int n = mxGetM(A_m); mxArray *z; @@ -1944,15 +1933,15 @@ SparseMatrix::Solve_Matlab_LU_UMFPack(mxArray* A_m, mxArray* b_m, int Size, doub for (int i = 0; i < n; i++) { int eq = index_vara[i+Size*y_kmin]; - double yy = - (res[i] + y[eq]); - direction[eq] = yy; + double yy = -(res[i] + y[eq]); + direction[eq] = yy; y[eq] += slowc_l * yy; } else for (int i = 0; i < n; i++) { int eq = index_vara[i]; - double yy = - (res[i] + y[eq+it_*y_size]); + double yy = -(res[i] + y[eq+it_*y_size]); direction[eq] = yy; y[eq+it_*y_size] += slowc_l * yy; } @@ -1962,7 +1951,7 @@ SparseMatrix::Solve_Matlab_LU_UMFPack(mxArray* A_m, mxArray* b_m, int Size, doub } void -SparseMatrix::Solve_Matlab_GMRES(mxArray* A_m, mxArray* b_m, int Size, double slowc, int block, bool is_two_boundaries, int it_, bool steady_state, mxArray* x0_m) +SparseMatrix::Solve_Matlab_GMRES(mxArray *A_m, mxArray *b_m, int Size, double slowc, int block, bool is_two_boundaries, int it_, bool steady_state, mxArray *x0_m) { #ifdef OCTAVE_MEX_FILE ostringstream tmp; @@ -1991,7 +1980,7 @@ SparseMatrix::Solve_Matlab_GMRES(mxArray* A_m, mxArray* b_m, int Size, double sl rhs[6] = U1; rhs[7] = x0_m; mxArray *lhs[2]; - mexCallMATLAB(2,lhs, 8, rhs, "gmres"); + mexCallMATLAB(2, lhs, 8, rhs, "gmres"); mxArray *z = lhs[0]; mxArray *flag = lhs[1]; double *flag1 = mxGetPr(flag); @@ -2028,7 +2017,7 @@ SparseMatrix::Solve_Matlab_GMRES(mxArray* A_m, mxArray* b_m, int Size, double sl for (int i = 0; i < n; i++) { int eq = index_vara[i+Size*y_kmin]; - double yy = - (res[i] + y[eq]); + double yy = -(res[i] + y[eq]); direction[eq] = yy; y[eq] += slowc * yy; } @@ -2036,7 +2025,7 @@ SparseMatrix::Solve_Matlab_GMRES(mxArray* A_m, mxArray* b_m, int Size, double sl for (int i = 0; i < n; i++) { int eq = index_vara[i]; - double yy = - (res[i] + y[eq+it_*y_size]); + double yy = -(res[i] + y[eq+it_*y_size]); direction[eq] = yy; y[eq+it_*y_size] += slowc * yy; } @@ -2047,9 +2036,8 @@ SparseMatrix::Solve_Matlab_GMRES(mxArray* A_m, mxArray* b_m, int Size, double sl mxDestroyArray(flag); } - void -SparseMatrix::Solve_Matlab_BiCGStab(mxArray* A_m, mxArray* b_m, int Size, double slowc, int block, bool is_two_boundaries, int it_, mxArray* x0_m, bool steady_state) +SparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, double slowc, int block, bool is_two_boundaries, int it_, mxArray *x0_m, bool steady_state) { unsigned int n = mxGetM(A_m); /*[L1, U1]=luinc(g1a,luinc_tol);*/ @@ -2064,7 +2052,7 @@ SparseMatrix::Solve_Matlab_BiCGStab(mxArray* A_m, mxArray* b_m, int Size, double mxArray *z; if (steady_state) /*Octave BicStab algorihtm involves a 0 division in case of a preconditionner equal to the LU decomposition of A matrix*/ { - mxArray* res = mult_SAT_B(Sparse_transpose(A_m), x0_m); + mxArray *res = mult_SAT_B(Sparse_transpose(A_m), x0_m); double *resid = mxGetPr(res); double *b = mxGetPr(b_m); for (unsigned int i = 0; i < n; i++) @@ -2112,7 +2100,7 @@ SparseMatrix::Solve_Matlab_BiCGStab(mxArray* A_m, mxArray* b_m, int Size, double rhs[5] = U1; rhs[6] = x0_m; mxArray *lhs[2]; - mexCallMATLAB(2,lhs, 7, rhs, "bicgstab"); + mexCallMATLAB(2, lhs, 7, rhs, "bicgstab"); z = lhs[0]; mxArray *flag = lhs[1]; double *flag1 = mxGetPr(flag); @@ -2124,7 +2112,7 @@ SparseMatrix::Solve_Matlab_BiCGStab(mxArray* A_m, mxArray* b_m, int Size, double mxDestroyArray(rhs[5]); } /*mexPrintf("z"); - mexCallMATLAB(0, NULL, 1, &z, "disp");*/ + mexCallMATLAB(0, NULL, 1, &z, "disp");*/ mxDestroyArray(rhs0[1]); if (flags > 0) @@ -2154,16 +2142,16 @@ SparseMatrix::Solve_Matlab_BiCGStab(mxArray* A_m, mxArray* b_m, int Size, double for (unsigned int i = 0; i < n; i++) { int eq = index_vara[i+Size*y_kmin]; - double yy = - (res[i] + y[eq]); - direction[eq] = yy; + double yy = -(res[i] + y[eq]); + direction[eq] = yy; y[eq] += slowc * yy; } else for (unsigned int i = 0; i < n; i++) { int eq = index_vara[i]; - double yy = - (res[i] + y[eq+it_*y_size]); - direction[eq] = yy; + double yy = -(res[i] + y[eq+it_*y_size]); + direction[eq] = yy; y[eq+it_*y_size] += slowc * yy; } } @@ -2580,9 +2568,9 @@ SparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bool } } if (fabs(piv) < eps) - mexPrintf("==> Error NR_max=%d, N_max=%d and piv=%f, piv_abs=%f, markovitz_max=%f\n",NR_max, N_max, piv, piv_abs, markovitz_max); + mexPrintf("==> Error NR_max=%d, N_max=%d and piv=%f, piv_abs=%f, markovitz_max=%f\n", NR_max, N_max, piv, piv_abs, markovitz_max); if (NR_max == 0) - mexPrintf("==> Error NR_max=0 and piv=%f, markovitz_max=%f\n",piv, markovitz_max); + mexPrintf("==> Error NR_max=0 and piv=%f, markovitz_max=%f\n", piv, markovitz_max); pivot[i] = pivj; pivot_save[i] = pivj; pivotk[i] = pivk; @@ -2604,10 +2592,10 @@ SparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bool { if (nop+1 >= nopa) { - nopa = long (mem_increasing_factor*(double)nopa); + nopa = long (mem_increasing_factor*(double) nopa); save_op = (int *) mxRealloc(save_op, nopa*sizeof(int)); } - save_op_s = (t_save_op_s *)(&(save_op[nop])); + save_op_s = (t_save_op_s *) (&(save_op[nop])); save_op_s->operat = IFLD; save_op_s->first = pivk; save_op_s->lag = 0; @@ -2617,10 +2605,10 @@ SparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bool if (piv_abs < eps) { ostringstream tmp; - if (Block_number>1) + if (Block_number > 1) tmp << " in Solve_ByteCode_Symbolic_Sparse_GaussianElimination, singular system in block " << Block_number+1 << "\n"; else - tmp << " in Solve_ByteCode_Symbolic_Sparse_GaussianElimination, singular system\n"; + tmp << " in Solve_ByteCode_Symbolic_Sparse_GaussianElimination, singular system\n"; throw FatalExceptionHandling(tmp.str()); } /*divide all the non zeros elements of the line pivj by the max_pivot*/ @@ -2643,10 +2631,10 @@ SparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bool { if (nop+j*2+1 >= nopa) { - nopa = long (mem_increasing_factor*(double)nopa); + nopa = long (mem_increasing_factor*(double) nopa); save_op = (int *) mxRealloc(save_op, nopa*sizeof(int)); } - save_op_s = (t_save_op_s *)(&(save_op[nop+j*2])); + save_op_s = (t_save_op_s *) (&(save_op[nop+j*2])); save_op_s->operat = IFDIV; save_op_s->first = first->u_index; save_op_s->lag = first->lag_index; @@ -2662,10 +2650,10 @@ SparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bool { if (nop+1 >= nopa) { - nopa = long (mem_increasing_factor*(double)nopa); + nopa = long (mem_increasing_factor*(double) nopa); save_op = (int *) mxRealloc(save_op, nopa*sizeof(int)); } - save_op_s = (t_save_op_s *)(&(save_op[nop])); + save_op_s = (t_save_op_s *) (&(save_op[nop])); save_op_s->operat = IFDIV; save_op_s->first = b[pivj]; save_op_s->lag = 0; @@ -2699,10 +2687,10 @@ SparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bool { if (nop+1 >= nopa) { - nopa = long (mem_increasing_factor*(double)nopa); + nopa = long (mem_increasing_factor*(double) nopa); save_op = (int *) mxRealloc(save_op, nopa*sizeof(int)); } - save_op_s_l = (t_save_op_s *)(&(save_op[nop])); + save_op_s_l = (t_save_op_s *) (&(save_op[nop])); save_op_s_l->operat = IFLD; save_op_s_l->first = first->u_index; save_op_s_l->lag = abs(first->lag_index); @@ -2747,10 +2735,10 @@ SparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bool { if (nop+2 >= nopa) { - nopa = long (mem_increasing_factor*(double)nopa); + nopa = long (mem_increasing_factor*(double) nopa); save_op = (int *) mxRealloc(save_op, nopa*sizeof(int)); } - save_op_s_l = (t_save_op_s *)(&(save_op[nop])); + save_op_s_l = (t_save_op_s *) (&(save_op[nop])); save_op_s_l->operat = IFLESS; save_op_s_l->first = tmp_u_count; save_op_s_l->second = first_piv->u_index; @@ -2795,10 +2783,10 @@ SparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bool { if (nop+3 >= nopa) { - nopa = long (mem_increasing_factor*(double)nopa); + nopa = long (mem_increasing_factor*(double) nopa); save_op = (int *) mxRealloc(save_op, nopa*sizeof(int)); } - save_op_s_l = (t_save_op_s *)(&(save_op[nop])); + save_op_s_l = (t_save_op_s *) (&(save_op[nop])); save_op_s_l->operat = IFSUB; save_op_s_l->first = first_sub->u_index; save_op_s_l->second = first_piv->u_index; @@ -2829,10 +2817,10 @@ SparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bool { if (nop+3 >= nopa) { - nopa = long (mem_increasing_factor*(double)nopa); + nopa = long (mem_increasing_factor*(double) nopa); save_op = (int *) mxRealloc(save_op, nopa*sizeof(int)); } - save_op_s_l = (t_save_op_s *)(&(save_op[nop])); + save_op_s_l = (t_save_op_s *) (&(save_op[nop])); save_op_s_l->operat = IFSUB; save_op_s_l->first = b[row]; save_op_s_l->second = b[pivj]; @@ -2921,7 +2909,6 @@ SparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bool End_GE(Size); } - void SparseMatrix::Simulate_Newton_One_Boundary(int blck, int y_size, int it_, int y_kmin, int y_kmax, int Size, bool print_it, bool cvg, int &iter, bool steady_state, int stack_solve_algo, int solve_algo) { @@ -2930,7 +2917,7 @@ SparseMatrix::Simulate_Newton_One_Boundary(int blck, int y_size, int it_, int y_ Clear_u(); error_not_printed = true; u_count_alloc_save = u_count_alloc; - if (isnan(res1) || isinf(res1) || (res2 > 12*g0 && iter>0)) + if (isnan(res1) || isinf(res1) || (res2 > 12*g0 && iter > 0)) { if (iter == 0 || fabs(slowc_save) < 1e-8) { @@ -2967,12 +2954,12 @@ SparseMatrix::Simulate_Newton_One_Boundary(int blck, int y_size, int it_, int y_ throw FatalExceptionHandling(tmp.str()); } } - if(!(isnan(res1) || isinf(res1)) && !(isnan(g0) || isinf(g0))) + if (!(isnan(res1) || isinf(res1)) && !(isnan(g0) || isinf(g0))) { if (try_at_iteration == 0) { prev_slowc_save = slowc_save; - slowc_save = max( - gp0 / (2 * (res2 - g0 - gp0)) , 0.1); + slowc_save = max(-gp0 / (2 * (res2 - g0 - gp0)), 0.1); } else { @@ -2981,10 +2968,10 @@ SparseMatrix::Simulate_Newton_One_Boundary(int blck, int y_size, int it_, int y_ double a = (1/(slowc_save * slowc_save) * t1 - 1/(prev_slowc_save * prev_slowc_save) * t2) / (slowc_save - prev_slowc_save); double b = (-prev_slowc_save/(slowc_save * slowc_save) * t1 + slowc_save/(prev_slowc_save * prev_slowc_save) * t2) / (slowc_save - prev_slowc_save); prev_slowc_save = slowc_save; - slowc_save = max(min( -b + sqrt(b*b - 3 * a * gp0) / (3 * a), 0.5 * slowc_save), 0.1 * slowc_save); + slowc_save = max(min(-b + sqrt(b*b - 3 * a * gp0) / (3 * a), 0.5 * slowc_save), 0.1 * slowc_save); } glambda2 = res2; - try_at_iteration ++; + try_at_iteration++; } else { @@ -3002,40 +2989,40 @@ SparseMatrix::Simulate_Newton_One_Boundary(int blck, int y_size, int it_, int y_ { return; } - if (print_it ) + if (print_it) { //mexPrintf("solwc=%f g0=%f res2=%f glambda2=%f\n",slowc_save,g0, res2, glambda2); if (steady_state) { switch (solve_algo) { - case 0: - mexPrintf("MODEL STEADY STATE: MATLAB fsolve\n"); - break; - case 1: - mexPrintf("MODEL STEADY STATE: MATLAB solve1\n"); - break; - case 2: - case 4: - mexPrintf("MODEL STEADY STATE: block decomposition + MATLAB solve1\n"); - break; - case 3: - mexPrintf("MODEL STEADY STATE: MATLAB csolve\n"); - break; - case 5: - mexPrintf("MODEL STEADY STATE: (method=ByteCode own solver)\n"); - break; - case 6: - mexPrintf("MODEL STEADY STATE: Sparse LU\n"); - break; - case 7: - mexPrintf("MODEL STEADY STATE: (method=GMRES)\n"); - break; - case 8: - mexPrintf("MODEL STEADY STATE: (method=BiCGStab)\n"); - break; - default: - mexPrintf("MODEL STEADY STATE: (method=Unknown - %d - )\n", stack_solve_algo); + case 0: + mexPrintf("MODEL STEADY STATE: MATLAB fsolve\n"); + break; + case 1: + mexPrintf("MODEL STEADY STATE: MATLAB solve1\n"); + break; + case 2: + case 4: + mexPrintf("MODEL STEADY STATE: block decomposition + MATLAB solve1\n"); + break; + case 3: + mexPrintf("MODEL STEADY STATE: MATLAB csolve\n"); + break; + case 5: + mexPrintf("MODEL STEADY STATE: (method=ByteCode own solver)\n"); + break; + case 6: + mexPrintf("MODEL STEADY STATE: Sparse LU\n"); + break; + case 7: + mexPrintf("MODEL STEADY STATE: (method=GMRES)\n"); + break; + case 8: + mexPrintf("MODEL STEADY STATE: (method=BiCGStab)\n"); + break; + default: + mexPrintf("MODEL STEADY STATE: (method=Unknown - %d - )\n", stack_solve_algo); } } @@ -3051,21 +3038,21 @@ SparseMatrix::Simulate_Newton_One_Boundary(int blck, int y_size, int it_, int y_ Simple_Init(it_, y_kmin, y_kmax, Size, IM_i, zero_solution); else { - b_m = mxCreateDoubleMatrix(Size,1,mxREAL); + b_m = mxCreateDoubleMatrix(Size, 1, mxREAL); if (!b_m) { ostringstream tmp; tmp << " in Simulate_Newton_One_Boundary, can't allocate b_m vector\n"; throw FatalExceptionHandling(tmp.str()); } - A_m = mxCreateSparse(Size, Size, min(int(IM_i.size()*2), Size*Size), mxREAL); + A_m = mxCreateSparse(Size, Size, min(int (IM_i.size()*2), Size*Size), mxREAL); if (!A_m) { ostringstream tmp; tmp << " in Simulate_Newton_One_Boundary, can't allocate A_m matrix\n"; throw FatalExceptionHandling(tmp.str()); } - x0_m = mxCreateDoubleMatrix(Size,1,mxREAL); + x0_m = mxCreateDoubleMatrix(Size, 1, mxREAL); if (!x0_m) { ostringstream tmp; @@ -3079,7 +3066,7 @@ SparseMatrix::Simulate_Newton_One_Boundary(int blck, int y_size, int it_, int y_ for (int i = 0; i < Size; i++) { int eq = index_vara[i]; - double yy = - (y[eq+it_*y_size]); + double yy = -(y[eq+it_*y_size]); direction[eq] = yy; y[eq+it_*y_size] += slowc * yy; } @@ -3098,8 +3085,6 @@ SparseMatrix::Simulate_Newton_One_Boundary(int blck, int y_size, int it_, int y_ return; } - - void SparseMatrix::Simulate_Newton_Two_Boundaries(int blck, int y_size, int it_, int y_kmin, int y_kmax, int Size, int periods, bool print_it, bool cvg, int &iter, int minimal_solving_periods, int stack_solve_algo, unsigned int endo_name_length, char *P_endo_names) { @@ -3116,11 +3101,11 @@ SparseMatrix::Simulate_Newton_Two_Boundaries(int blck, int y_size, int it_, int mexEvalString("drawnow;"); time00 = clock(); } - if (isnan(res1) || isinf(res1) || (res2 > 12*g0 && iter>0)) + if (isnan(res1) || isinf(res1) || (res2 > 12*g0 && iter > 0)) { if (iter == 0 || fabs(slowc_save) < 1e-8) { - for (int j = 0; j < y_size; j++) + for (int j = 0; j < y_size; j++) { ostringstream res; for (unsigned int i = 0; i < endo_name_length; i++) @@ -3139,19 +3124,19 @@ SparseMatrix::Simulate_Newton_Two_Boundaries(int blck, int y_size, int it_, int mexPrintf(" variable %s (%d) at time %d = %f direction = %f\n", res.str().c_str(), j+1, it_, y[j+it_*y_size], direction[j+it_*y_size]); } ostringstream Error; - if (iter == 0 ) + if (iter == 0) Error << " in Simulate_Newton_Two_Boundaries, the initial values of endogenous variables are too far from the solution.\nChange them!\n"; else Error << " in Simulate_Newton_Two_Boundaries, dynare cannot improve the simulation in block " << blck+1 << " at time " << it_+1 << " (variable " << index_vara[max_res_idx]+1 << ")\n"; //Error << filename << " stopped"; throw FatalExceptionHandling(Error.str()); } - if(!(isnan(res1) || isinf(res1)) && !(isnan(g0) || isinf(g0)) && (stack_solve_algo == 4 || stack_solve_algo == 5)) + if (!(isnan(res1) || isinf(res1)) && !(isnan(g0) || isinf(g0)) && (stack_solve_algo == 4 || stack_solve_algo == 5)) { if (try_at_iteration == 0) { prev_slowc_save = slowc_save; - slowc_save = max( - gp0 / (2 * (res2 - g0 - gp0)) , 0.1); + slowc_save = max(-gp0 / (2 * (res2 - g0 - gp0)), 0.1); } else { @@ -3160,11 +3145,11 @@ SparseMatrix::Simulate_Newton_Two_Boundaries(int blck, int y_size, int it_, int double a = (1/(slowc_save * slowc_save) * t1 - 1/(prev_slowc_save * prev_slowc_save) * t2) / (slowc_save - prev_slowc_save); double b = (-prev_slowc_save/(slowc_save * slowc_save) * t1 + slowc_save/(prev_slowc_save * prev_slowc_save) * t2) / (slowc_save - prev_slowc_save); prev_slowc_save = slowc_save; - slowc_save = max(min( -b + sqrt(b*b - 3 * a * gp0) / (3 * a), 0.5 * slowc_save), 0.1 * slowc_save); + slowc_save = max(min(-b + sqrt(b*b - 3 * a * gp0) / (3 * a), 0.5 * slowc_save), 0.1 * slowc_save); } glambda2 = res2; - try_at_iteration ++; - if (slowc_save<=0.1) + try_at_iteration++; + if (slowc_save <= 0.1) { for (int i = 0; i < y_size*(periods+y_kmin); i++) y[i] = ya[i]+direction[i]; @@ -3234,28 +3219,28 @@ SparseMatrix::Simulate_Newton_Two_Boundaries(int blck, int y_size, int it_, int { if (iter == 0) { - switch(stack_solve_algo) - { - case 0: - mexPrintf("MODEL SIMULATION: (method=Sparse LU)\n"); - break; - case 1: - mexPrintf("MODEL SIMULATION: (method=Relaxation)\n"); - break; - case 2: - mexPrintf("MODEL SIMULATION: (method=GMRES)\n"); - break; - case 3: - mexPrintf("MODEL SIMULATION: (method=BiCGStab)\n"); - break; - case 4: - mexPrintf("MODEL SIMULATION: (method=Sparse LU & optimal path length)\n"); - break; - case 5: - mexPrintf("MODEL SIMULATION: (method=ByteCode own solver)\n"); - break; - default: - mexPrintf("MODEL SIMULATION: (method=Unknown - %d - )\n", stack_solve_algo); + switch (stack_solve_algo) + { + case 0: + mexPrintf("MODEL SIMULATION: (method=Sparse LU)\n"); + break; + case 1: + mexPrintf("MODEL SIMULATION: (method=Relaxation)\n"); + break; + case 2: + mexPrintf("MODEL SIMULATION: (method=GMRES)\n"); + break; + case 3: + mexPrintf("MODEL SIMULATION: (method=BiCGStab)\n"); + break; + case 4: + mexPrintf("MODEL SIMULATION: (method=Sparse LU & optimal path length)\n"); + break; + case 5: + mexPrintf("MODEL SIMULATION: (method=ByteCode own solver)\n"); + break; + default: + mexPrintf("MODEL SIMULATION: (method=Unknown - %d - )\n", stack_solve_algo); } } mexPrintf("-----------------------------------\n"); @@ -3276,14 +3261,14 @@ SparseMatrix::Simulate_Newton_Two_Boundaries(int blck, int y_size, int it_, int Init_GE(periods, y_kmin, y_kmax, Size, IM_i); else { - b_m = mxCreateDoubleMatrix(periods*Size,1,mxREAL); + b_m = mxCreateDoubleMatrix(periods*Size, 1, mxREAL); if (!b_m) { ostringstream tmp; tmp << " in Simulate_Newton_Two_Boundaries, can't allocate b_m vector\n"; throw FatalExceptionHandling(tmp.str()); } - x0_m = mxCreateDoubleMatrix(periods*Size,1,mxREAL); + x0_m = mxCreateDoubleMatrix(periods*Size, 1, mxREAL); if (!x0_m) { ostringstream tmp; @@ -3330,11 +3315,11 @@ SparseMatrix::fixe_u(double **u, int u_count_int, int max_lag_plus_max_lead_plus u_count = u_count_int * periods; u_count_alloc = 2*u_count; #ifdef DEBUG - mexPrintf("fixe_u : alloc(%d double)\n",u_count_alloc); + mexPrintf("fixe_u : alloc(%d double)\n", u_count_alloc); #endif (*u) = (double *) mxMalloc(u_count_alloc*sizeof(double)); #ifdef DEBUG - mexPrintf("*u=%d\n",*u); + mexPrintf("*u=%d\n", *u); #endif memset((*u), 0, u_count_alloc*sizeof(double)); u_count_init = max_lag_plus_max_lead_plus_1; diff --git a/mex/sources/bytecode/SparseMatrix.hh b/mex/sources/bytecode/SparseMatrix.hh index 1540b28f9dad41c181607618131dccbdf1d701ce..8f39129bd313d8844b82ccbc5e01893ba6b850f3 100644 --- a/mex/sources/bytecode/SparseMatrix.hh +++ b/mex/sources/bytecode/SparseMatrix.hh @@ -27,12 +27,11 @@ #include <ctime> #ifdef OCTAVE_MEX_FILE - #define CHAR_LENGTH 1 +# define CHAR_LENGTH 1 #else - #define CHAR_LENGTH 2 +# define CHAR_LENGTH 2 #endif - #include "Mem_Mngr.hh" #include "ErrorHandling.hh" #define NEW_ALLOC @@ -73,16 +72,16 @@ public: private: void Init_GE(int periods, int y_kmin, int y_kmax, int Size, map<pair<pair<int, int>, int>, int> &IM); - void Init_Matlab_Sparse(int periods, int y_kmin, int y_kmax, int Size, map<pair<pair<int, int>, int>, int> &IM, mxArray *A_m, mxArray *b_m, mxArray* x0_m); - void Init_Matlab_Sparse_Simple(int Size, map<pair<pair<int, int>, int>, int> &IM, mxArray *A_m, mxArray *b_m, bool &zero_solution, mxArray* x0_m); + void Init_Matlab_Sparse(int periods, int y_kmin, int y_kmax, int Size, map<pair<pair<int, int>, int>, int> &IM, mxArray *A_m, mxArray *b_m, mxArray *x0_m); + void Init_Matlab_Sparse_Simple(int Size, map<pair<pair<int, int>, int>, int> &IM, mxArray *A_m, mxArray *b_m, bool &zero_solution, mxArray *x0_m); void Simple_Init(int it_, int y_kmin, int y_kmax, int Size, std::map<std::pair<std::pair<int, int>, int>, int> &IM, bool &zero_solution); void End_GE(int Size); void Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bool symbolic, int Block_number); void Solve_ByteCode_Sparse_GaussianElimination(int Size, int blck, bool steady_state, int it_); - void Solve_Matlab_Relaxation(mxArray* A_m, mxArray* b_m, unsigned int Size, double slowc_l, bool is_two_boundaries, int it_); - void Solve_Matlab_LU_UMFPack(mxArray* A_m, mxArray* b_m, int Size, double slowc_l, bool is_two_boundaries, int it_); - void Solve_Matlab_GMRES(mxArray* A_m, mxArray* b_m, int Size, double slowc, int block, bool is_two_boundaries, int it_, bool steady_state, mxArray* x0_m); - void Solve_Matlab_BiCGStab(mxArray* A_m, mxArray* b_m, int Size, double slowc, int block, bool is_two_boundaries, int it_, mxArray* x0_m, bool steady_state); + void Solve_Matlab_Relaxation(mxArray *A_m, mxArray *b_m, unsigned int Size, double slowc_l, bool is_two_boundaries, int it_); + void Solve_Matlab_LU_UMFPack(mxArray *A_m, mxArray *b_m, int Size, double slowc_l, bool is_two_boundaries, int it_); + void Solve_Matlab_GMRES(mxArray *A_m, mxArray *b_m, int Size, double slowc, int block, bool is_two_boundaries, int it_, bool steady_state, mxArray *x0_m); + void Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, double slowc, int block, bool is_two_boundaries, int it_, mxArray *x0_m, bool steady_state); bool compare(int *save_op, int *save_opa, int *save_opaa, int beg_t, int periods, long int nop4, int Size #ifdef PROFILER , long int *ndiv, long int *nsub @@ -111,14 +110,13 @@ private: #endif ); double simple_bksub(int it_, int Size, double slowc_l); - mxArray* Sparse_transpose(mxArray* A_m); - mxArray* Sparse_mult_SAT_SB(mxArray* A_m, mxArray* B_m); - mxArray* Sparse_mult_SAT_B(mxArray* A_m, mxArray* B_m); - mxArray* mult_SAT_B(mxArray* A_m, mxArray* B_m); - mxArray* Sparse_substract_SA_SB(mxArray* A_m, mxArray* B_m); - mxArray* Sparse_substract_A_SB(mxArray* A_m, mxArray* B_m); - mxArray* substract_A_B(mxArray* A_m, mxArray* B_m); - + mxArray *Sparse_transpose(mxArray *A_m); + mxArray *Sparse_mult_SAT_SB(mxArray *A_m, mxArray *B_m); + mxArray *Sparse_mult_SAT_B(mxArray *A_m, mxArray *B_m); + mxArray *mult_SAT_B(mxArray *A_m, mxArray *B_m); + mxArray *Sparse_substract_SA_SB(mxArray *A_m, mxArray *B_m); + mxArray *Sparse_substract_A_SB(mxArray *A_m, mxArray *B_m); + mxArray *substract_A_B(mxArray *A_m, mxArray *B_m); stack<double> Stack; int nb_prologue_table_u, nb_first_table_u, nb_middle_table_u, nb_last_table_u; @@ -153,7 +151,7 @@ private: protected: vector<double> residual; int u_count_alloc, u_count_alloc_save; - vector<double*> jac; + vector<double *> jac; double *jcb; double res1, res2, max_res; int max_res_idx; diff --git a/mex/sources/bytecode/bytecode.cc b/mex/sources/bytecode/bytecode.cc index 77dbf12a857511effc010f231c65ac5760970fde..4156af584d18ba5d3a3bbadae5eaec005a18f3e9 100644 --- a/mex/sources/bytecode/bytecode.cc +++ b/mex/sources/bytecode/bytecode.cc @@ -19,7 +19,6 @@ #include <cstring> #include "Interpreter.hh" - #ifdef DEBUG_EX using namespace std; @@ -32,7 +31,6 @@ Get_Argument(const char *argv) return f; } - #else string @@ -68,80 +66,80 @@ Get_Arguments_and_global_variables(int nrhs, bool &steady_state, bool &evaluate, int &block, mxArray *M_[], mxArray *oo_[], mxArray *options_[], bool &global_temporary_terms, bool &print, - mxArray* GlobalTemporaryTerms[]) + mxArray *GlobalTemporaryTerms[]) { #ifdef DEBUG_EX for (int i = 2; i < nrhs; i++) #else - for (int i = 0; i < nrhs; i++) + for (int i = 0; i < nrhs; i++) #endif - { + { #ifndef DEBUG_EX - if (!mxIsChar(prhs[i])) - { - switch (count_array_argument) - { - case 0: - *yd = mxGetPr(prhs[i]); - row_y = mxGetM(prhs[i]); - col_y = mxGetN(prhs[i]); - break; - case 1: - *xd = mxGetPr(prhs[i]); - row_x = mxGetM(prhs[i]); - col_x = mxGetN(prhs[i]); - break; - case 2: - *params = mxGetPr(prhs[i]); - break; - case 3: - periods = mxGetScalar(prhs[i]); - break; - case 4: - *block_structur = mxDuplicateArray(prhs[i]); - break; - case 5: - global_temporary_terms = true; - *GlobalTemporaryTerms = mxDuplicateArray(prhs[i]); - break; - default: - //mexPrintf("Unknown argument count_array_argument=%d\n",count_array_argument); - break; - } - count_array_argument++; - } - else + if (!mxIsChar(prhs[i])) + { + switch (count_array_argument) + { + case 0: + *yd = mxGetPr(prhs[i]); + row_y = mxGetM(prhs[i]); + col_y = mxGetN(prhs[i]); + break; + case 1: + *xd = mxGetPr(prhs[i]); + row_x = mxGetM(prhs[i]); + col_x = mxGetN(prhs[i]); + break; + case 2: + *params = mxGetPr(prhs[i]); + break; + case 3: + periods = mxGetScalar(prhs[i]); + break; + case 4: + *block_structur = mxDuplicateArray(prhs[i]); + break; + case 5: + global_temporary_terms = true; + *GlobalTemporaryTerms = mxDuplicateArray(prhs[i]); + break; + default: + //mexPrintf("Unknown argument count_array_argument=%d\n",count_array_argument); + break; + } + count_array_argument++; + } + else #endif - if (Get_Argument(prhs[i]) == "static") - steady_state = true; - else if (Get_Argument(prhs[i]) == "dynamic") - steady_state = false; - else if (Get_Argument(prhs[i]) == "evaluate") - evaluate = true; - else if (Get_Argument(prhs[i]) == "global_temporary_terms") - global_temporary_terms = true; - else if (Get_Argument(prhs[i]) == "print") - print = true; - else - { - int pos = Get_Argument(prhs[i]).find("block"); - if (pos != (int)string::npos) - { - int pos1 = Get_Argument(prhs[i]).find("=", pos+5); - if (pos1 != (int)string::npos) - pos = pos1 + 1; - else - pos += 5; - block = atoi(Get_Argument(prhs[i]).substr(pos, string::npos).c_str())-1; - } + if (Get_Argument(prhs[i]) == "static") + steady_state = true; + else if (Get_Argument(prhs[i]) == "dynamic") + steady_state = false; + else if (Get_Argument(prhs[i]) == "evaluate") + evaluate = true; + else if (Get_Argument(prhs[i]) == "global_temporary_terms") + global_temporary_terms = true; + else if (Get_Argument(prhs[i]) == "print") + print = true; else { - ostringstream tmp; - tmp << " in main, unknown argument : " << Get_Argument(prhs[i]) << "\n"; - throw FatalExceptionHandling(tmp.str()); + int pos = Get_Argument(prhs[i]).find("block"); + if (pos != (int) string::npos) + { + int pos1 = Get_Argument(prhs[i]).find("=", pos+5); + if (pos1 != (int) string::npos) + pos = pos1 + 1; + else + pos += 5; + block = atoi(Get_Argument(prhs[i]).substr(pos, string::npos).c_str())-1; + } + else + { + ostringstream tmp; + tmp << " in main, unknown argument : " << Get_Argument(prhs[i]) << "\n"; + throw FatalExceptionHandling(tmp.str()); + } } - } - } + } if (count_array_argument > 0 && count_array_argument < 4) { if (count_array_argument == 3 && steady_state) @@ -182,18 +180,18 @@ int main(int nrhs, const char *prhs[]) #else /* The gateway routine */ -void -mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) + void + mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) #endif { mxArray *M_, *oo_, *options_; - mxArray* GlobalTemporaryTerms; + mxArray *GlobalTemporaryTerms; #ifndef DEBUG_EX mxArray *block_structur = NULL; #else int nlhs = 0; char *plhs[1]; - load_global((char*)prhs[1]); + load_global((char *) prhs[1]); #endif //ErrorHandlingException error_handling; unsigned int i, row_y = 0, col_y = 0, row_x = 0, col_x = 0, nb_row_xd = 0; @@ -213,22 +211,21 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) try { Get_Arguments_and_global_variables(nrhs, prhs, count_array_argument, - &yd, row_y, col_y, - &xd, row_x, col_x, - ¶ms, periods, + &yd, row_y, col_y, + &xd, row_x, col_x, + ¶ms, periods, #ifndef DEBUG_EX - &block_structur, + &block_structur, #endif - steady_state, evaluate, block, - &M_, &oo_, &options_, global_temporary_terms, - print, &GlobalTemporaryTerms); + steady_state, evaluate, block, + &M_, &oo_, &options_, global_temporary_terms, + print, &GlobalTemporaryTerms); } catch (GeneralExceptionHandling &feh) { DYN_MEX_FUNC_ERR_MSG_TXT(feh.GetErrorMsg().c_str()); } - if (!count_array_argument) params = mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "params"))); @@ -282,10 +279,10 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) int solve_algo; double solve_tolf; if (steady_state) - { - solve_algo = int (*(mxGetPr(mxGetFieldByNumber(options_, 0, mxGetFieldNumber(options_, "solve_algo"))))); - solve_tolf = *(mxGetPr(mxGetFieldByNumber(options_, 0, mxGetFieldNumber(options_, "solve_tolf")))); - } + { + solve_algo = int (*(mxGetPr(mxGetFieldByNumber(options_, 0, mxGetFieldNumber(options_, "solve_algo"))))); + solve_tolf = *(mxGetPr(mxGetFieldByNumber(options_, 0, mxGetFieldNumber(options_, "solve_tolf")))); + } else { @@ -383,7 +380,7 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) } else for (i = 0; i < row_y*col_y; i++) - pind[i] = y[i]; + pind[i] = y[i]; } if (nlhs > 2) { @@ -392,11 +389,11 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) int jacob_field_number = 0, jacob_exo_field_number = 0, jacob_exo_det_field_number = 0, jacob_other_endo_field_number = 0; if (!block_structur) { - const char *field_names[] = {"g1","g1_x","g1_xd","g1_o"}; - jacob_field_number=0; - jacob_exo_field_number=1; - jacob_exo_det_field_number=2; - jacob_other_endo_field_number=2; + const char *field_names[] = {"g1", "g1_x", "g1_xd", "g1_o"}; + jacob_field_number = 0; + jacob_exo_field_number = 1; + jacob_exo_det_field_number = 2; + jacob_other_endo_field_number = 2; mwSize dims[1] = {nb_blocks }; plhs[2] = mxCreateStructArray(1, dims, 4, field_names); } @@ -425,15 +422,15 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) if (!dont_store_a_structure) { for (int i = 0; i < nb_blocks; i++) - { - mxSetFieldByNumber(plhs[2],i,jacob_field_number,interprete.get_jacob(i)); - mxSetFieldByNumber(plhs[2],i,jacob_exo_field_number,interprete.get_jacob_exo(i)); - mxSetFieldByNumber(plhs[2],i,jacob_exo_det_field_number,interprete.get_jacob_exo_det(i)); - mxSetFieldByNumber(plhs[2],i,jacob_other_endo_field_number,interprete.get_jacob_other_endo(i)); + { + mxSetFieldByNumber(plhs[2], i, jacob_field_number, interprete.get_jacob(i)); + mxSetFieldByNumber(plhs[2], i, jacob_exo_field_number, interprete.get_jacob_exo(i)); + mxSetFieldByNumber(plhs[2], i, jacob_exo_det_field_number, interprete.get_jacob_exo_det(i)); + mxSetFieldByNumber(plhs[2], i, jacob_other_endo_field_number, interprete.get_jacob_other_endo(i)); } } } - else + else { plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL); pind = mxGetPr(plhs[0]); @@ -447,7 +444,7 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) pind[i] = y[i]; if (nlhs > 4) { - mxArray* GlobalTemporaryTerms = interprete.get_Temporary_Terms(); + mxArray *GlobalTemporaryTerms = interprete.get_Temporary_Terms(); unsigned int nb_temp_terms = mxGetM(GlobalTemporaryTerms); plhs[4] = mxCreateDoubleMatrix(nb_temp_terms, 1, mxREAL); pind = mxGetPr(plhs[4]); diff --git a/mex/sources/bytecode/testing/mex_interface.cc b/mex/sources/bytecode/testing/mex_interface.cc index 47a2e9ca8cf7084c9eacda718dd769f112e2b94a..58828536aebe269225f4951d44da867f41cfcf87 100644 --- a/mex/sources/bytecode/testing/mex_interface.cc +++ b/mex/sources/bytecode/testing/mex_interface.cc @@ -23,7 +23,7 @@ using namespace std; -map<string, mxArray*> mxglobal; +map<string, mxArray *> mxglobal; mxArray_tag::mxArray_tag() { @@ -82,7 +82,7 @@ mxRealloc(void *to_extend, unsigned int amount) return realloc(to_extend, amount); } -void* +void * mxCalloc(unsigned int nb_elements, unsigned int amount_per_element) { return calloc(nb_elements, amount_per_element); @@ -93,35 +93,35 @@ mexEvalString(const string str) { } -double* +double * mxGetPr(const mxArray *b_m) { return b_m->data; } -mxArray* -mxCreateDoubleMatrix(unsigned int rows,unsigned int cols, mxData_type mx_type) +mxArray * +mxCreateDoubleMatrix(unsigned int rows, unsigned int cols, mxData_type mx_type) { mxArray *Array = new mxArray; Array->type = mxDOUBLE_CLASS; Array->size_1 = rows; Array->size_2 = cols; - Array->data = (double*)mxMalloc(rows*cols*sizeof(double)); - return(Array); + Array->data = (double *) mxMalloc(rows*cols*sizeof(double)); + return (Array); } -mxArray* -mxCreateCharArray(unsigned int rows,unsigned int cols, mxData_type mx_type) +mxArray * +mxCreateCharArray(unsigned int rows, unsigned int cols, mxData_type mx_type) { mxArray *Array = new mxArray; Array->type = mxCHAR_CLASS; Array->size_1 = rows; Array->size_2 = cols; - Array->data = (double*)mxMalloc(2*rows*cols*sizeof(char)); - return(Array); + Array->data = (double *) mxMalloc(2*rows*cols*sizeof(char)); + return (Array); } -mxArray* +mxArray * mxCreateSparse(unsigned int rows, unsigned int cols, unsigned int nz_max, mxData_type mx_type) { mxArray *Array = new mxArray; @@ -129,31 +129,31 @@ mxCreateSparse(unsigned int rows, unsigned int cols, unsigned int nz_max, mxData Array->size_1 = rows; Array->size_2 = cols; Array->Nzmax = nz_max; - Array->data = (double*)mxMalloc(nz_max*sizeof(double)); - Array->Ir = (mwIndex*)mxMalloc(nz_max*sizeof(mwIndex)); - Array->Jc = (mwIndex*)mxMalloc((cols+1)*sizeof(mwIndex)); - return(Array); + Array->data = (double *) mxMalloc(nz_max*sizeof(double)); + Array->Ir = (mwIndex *) mxMalloc(nz_max*sizeof(mwIndex)); + Array->Jc = (mwIndex *) mxMalloc((cols+1)*sizeof(mwIndex)); + return (Array); } -mxArray* +mxArray * mxCreateDoubleScalar(double value) { mxArray *Array = new mxArray; Array->type = mxSINGLE_CLASS; Array->size_1 = 1; Array->size_2 = 1; - Array->data = (double*)mxMalloc(sizeof(double)); + Array->data = (double *) mxMalloc(sizeof(double)); Array->data[0] = value; - return(Array); + return (Array); } -mxArray* +mxArray * mxCreatNULLMatrix() { return NULL; } -mxArray* +mxArray * mxCreateStructMatrix(unsigned int rows, unsigned int cols, unsigned int nfields, const vector<string> &fieldnames) { mxArray *Array = new mxArray; @@ -166,7 +166,7 @@ mxCreateStructMatrix(unsigned int rows, unsigned int cols, unsigned int nfields, } void -mxDestroyArray(mxArray* A_m) +mxDestroyArray(mxArray *A_m) { mxFree(A_m->data); if (A_m->Ir) @@ -176,17 +176,17 @@ mxDestroyArray(mxArray* A_m) mxFree(A_m); } -mxArray* -mxSetNzmax(mxArray* A_m, mwSize nz_max) +mxArray * +mxSetNzmax(mxArray *A_m, mwSize nz_max) { A_m->Nzmax = nz_max; - A_m->data = (double*)mxRealloc(A_m->data, nz_max*sizeof(double)); - A_m->Ir = (mwIndex*)mxRealloc(A_m->Ir, nz_max*sizeof(mwIndex)); - return(A_m); + A_m->data = (double *) mxRealloc(A_m->data, nz_max*sizeof(double)); + A_m->Ir = (mwIndex *) mxRealloc(A_m->Ir, nz_max*sizeof(mwIndex)); + return (A_m); } void -mexCallMATLAB(unsigned int n_lhs, mxArray* matrix_lhs[], unsigned int n_rhs, mxArray* matrix_rhs[], const char* function) +mexCallMATLAB(unsigned int n_lhs, mxArray *matrix_lhs[], unsigned int n_rhs, mxArray *matrix_rhs[], const char *function) { if (strncmp(function, "disp", 4) == 0) { @@ -194,7 +194,7 @@ mexCallMATLAB(unsigned int n_lhs, mxArray* matrix_lhs[], unsigned int n_rhs, mxA int rows = mxGetM(matrix_rhs[0]); if (matrix_rhs[0]->type == mxCHAR_CLASS) { - char* p = (char*)matrix_rhs[0]->data; + char *p = (char *) matrix_rhs[0]->data; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) @@ -203,7 +203,7 @@ mexCallMATLAB(unsigned int n_lhs, mxArray* matrix_lhs[], unsigned int n_rhs, mxA } } else - for (int i = 0 ; i < rows; i++) + for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) mexPrintf("%8.4f ", matrix_rhs[0]->data[i+j*rows]); @@ -212,8 +212,8 @@ mexCallMATLAB(unsigned int n_lhs, mxArray* matrix_lhs[], unsigned int n_rhs, mxA } } -mxArray* -mexGetVariable(const char* space_name, const char* matrix_name) +mxArray * +mexGetVariable(const char *space_name, const char *matrix_name) { if (strncmp(space_name, "global", 6) != 0) mexErrMsgTxt("space_name not handle in mexGetVariable\n"); @@ -221,7 +221,7 @@ mexGetVariable(const char* space_name, const char* matrix_name) } int -mxGetFieldNumber(const mxArray* Struct, const char* field_name) +mxGetFieldNumber(const mxArray *Struct, const char *field_name) { vector<string>::const_iterator it = find(Struct->field_name.begin(), Struct->field_name.end(), field_name); if (it == Struct->field_name.end()) @@ -233,8 +233,8 @@ mxGetFieldNumber(const mxArray* Struct, const char* field_name) return it - Struct->field_name.begin(); } -mxArray* -mxGetFieldByNumber(mxArray* Struct, unsigned int pos, unsigned int field_number) +mxArray * +mxGetFieldByNumber(mxArray *Struct, unsigned int pos, unsigned int field_number) { if (pos > Struct->size_1 * Struct->size_2) mexErrMsgTxt("index out of range in mxGetFieldByNumber\n"); @@ -244,7 +244,7 @@ mxGetFieldByNumber(mxArray* Struct, unsigned int pos, unsigned int field_number) } int -mxAddField(mxArray* Struct, const char* fieldname) +mxAddField(mxArray *Struct, const char *fieldname) { if (!mxIsStruct(Struct)) return -1; @@ -264,7 +264,7 @@ mxSetFieldByNumber(mxArray *Struct, mwIndex index, unsigned int field_number, mx if (field_number >= nfields) mexErrMsgTxt("field_number out of range in mxSetFieldByNumber\n"); while (Struct->field_array.size() <= index) - Struct->field_array.push_back(vector<mxArray*>(nfields, NULL)); + Struct->field_array.push_back(vector<mxArray *>(nfields, NULL)); Struct->field_array[index][field_number] = pvalue; } @@ -278,7 +278,7 @@ mxGetString(const mxArray *array, char *buf, unsigned int buflen) return -1; else { - char *pchar = (char*)array->data; + char *pchar = (char *) array->data; for (unsigned int i = 0; i < size; i++) buf[i] = pchar[2*i]; buf[size+1] = ' '; @@ -286,23 +286,23 @@ mxGetString(const mxArray *array, char *buf, unsigned int buflen) return 0; } -mxArray* +mxArray * mxDuplicateArray(const mxArray *array) { unsigned int Size; unsigned int i; - vector<mxArray*>::const_iterator it_v_array; + vector<mxArray *>::const_iterator it_v_array; vector<string>::const_iterator it_v_string; - mxArray *Array = (mxArray*)mxMalloc(sizeof(mxArray)); + mxArray *Array = (mxArray *) mxMalloc(sizeof(mxArray)); Array->type = array->type; Array->size_1 = array->size_1; Array->size_2 = Array->size_2; - switch(array->type) + switch (array->type) { case mxDOUBLE_CLASS: case mxSINGLE_CLASS: Size = array->size_1*array->size_2*sizeof(double); - Array->data = (double*)mxMalloc(Size); + Array->data = (double *) mxMalloc(Size); memcpy(Array->data, array->data, Size); break; case mxSTRUCT_CLASS: @@ -315,29 +315,29 @@ mxDuplicateArray(const mxArray *array) case mxSPARSE_CLASS: Array->Nzmax = array->Nzmax; Size = array->Nzmax * sizeof(double); - Array->data = (double*)mxMalloc(Size); + Array->data = (double *) mxMalloc(Size); memcpy(Array->data, array->data, Size); Size = array->Nzmax * sizeof(mwIndex); - Array->Ir = (mwIndex*)mxMalloc(Size); + Array->Ir = (mwIndex *) mxMalloc(Size); memcpy(Array->Ir, array->Ir, Size); Size = array->size_2*sizeof(mwIndex); - Array->Jc = (mwIndex*)mxMalloc(Size); + Array->Jc = (mwIndex *) mxMalloc(Size); memcpy(Array->Jc, array->Jc, Size); break; case mxCHAR_CLASS: Size = 2*array->size_1*array->size_2*sizeof(char); - Array->data = (double*)mxMalloc(Size); - memcpy(Array->data , array->data, Size); + Array->data = (double *) mxMalloc(Size); + memcpy(Array->data, array->data, Size); break; default: ostringstream tmp; tmp << "Array type not handle: " << array->type << "\n"; mexErrMsgTxt(tmp.str()); } - return(Array); + return (Array); } -mxArray* +mxArray * read_struct(FILE *fid) { unsigned int nfields = 0; @@ -346,8 +346,8 @@ read_struct(FILE *fid) fscanf(fid, "%d", &size_1); fscanf(fid, "%d", &size_2); vector<string> fieldnames; - vector<mxArray*> v_Array; - vector<vector<mxArray* > > vv_Array; + vector<mxArray *> v_Array; + vector<vector<mxArray * > > vv_Array; for (unsigned int j = 0; j < size_1 * size_2; j++) { for (unsigned int i = 0; i < nfields; i++) @@ -361,7 +361,7 @@ read_struct(FILE *fid) vv_Array.push_back(v_Array); v_Array.clear(); } - mxArray* Struct; + mxArray *Struct; Struct = mxCreateStructMatrix(size_1, size_2, nfields, fieldnames); for (unsigned int j = 0; j < size_1 * size_2; j++) { @@ -374,14 +374,14 @@ read_struct(FILE *fid) return Struct; } -mxArray* +mxArray * read_double_array(FILE *fid) { int size_1, size_2; fscanf(fid, "%d", &size_1); fscanf(fid, "%d", &size_2); mxArray *A = mxCreateDoubleMatrix(size_1, size_2, mxREAL); - double* data = mxGetPr(A); + double *data = mxGetPr(A); float f; for (int i = 0; i < size_1*size_2; i++) { @@ -391,27 +391,27 @@ read_double_array(FILE *fid) return A; } -mxArray* +mxArray * read_char_array(FILE *fid) { unsigned int size_1, size_2; fscanf(fid, "%d", &size_1); fscanf(fid, "%d", &size_2); mxArray *A = mxCreateCharArray(size_1, size_2, mxREAL); - char* data = (char*)mxGetPr(A); + char *data = (char *) mxGetPr(A); char pchar[size_2+1]; for (unsigned int i = 0; i < size_1; i++) { fscanf(fid, "%s", pchar); - for(unsigned int j = 0; j < strlen(pchar); j++) + for (unsigned int j = 0; j < strlen(pchar); j++) data[2*(i+j*size_1)] = pchar[j]; - for(unsigned int j = strlen(pchar); j < size_2; j++) + for (unsigned int j = strlen(pchar); j < size_2; j++) data[2*(i+j*size_1)] = ' '; } return A; } -mxArray* +mxArray * read_Array(FILE *fid) { mxArray *Array; @@ -419,7 +419,7 @@ read_Array(FILE *fid) unsigned int j; fscanf(fid, "%d", &j); array_type = static_cast<mxArray_type>(j); - switch(array_type) + switch (array_type) { case mxDOUBLE_CLASS: case mxSINGLE_CLASS: @@ -436,11 +436,11 @@ read_Array(FILE *fid) tmp << "Array type not handle in read_Array: " << array_type << "\n"; mexErrMsgTxt(tmp.str()); } - return(Array); + return (Array); } void -load_global(char* file_name) +load_global(char *file_name) { FILE *fid; ostringstream tmp_out(""); @@ -481,14 +481,14 @@ load_global(char* file_name) } void -Free_simple_array(mxArray* array) +Free_simple_array(mxArray *array) { mxFree(array->data); delete array; } void -Free_struct_array(mxArray* array) +Free_struct_array(mxArray *array) { for (unsigned int i = 0; i < array->size_1 * array->size_2; i++) for (unsigned int j = 0; j < array->field_name.size(); j++) @@ -497,9 +497,9 @@ Free_struct_array(mxArray* array) } void -Free_Array(mxArray* array) +Free_Array(mxArray *array) { - switch(array->type) + switch (array->type) { case mxDOUBLE_CLASS: case mxSINGLE_CLASS: @@ -517,6 +517,6 @@ Free_Array(mxArray* array) void Free_global() { - for (map<string, mxArray*>::iterator it = mxglobal.begin(); it != mxglobal.end(); it++) + for (map<string, mxArray *>::iterator it = mxglobal.begin(); it != mxglobal.end(); it++) Free_Array(it->second); } diff --git a/mex/sources/bytecode/testing/mex_interface.hh b/mex/sources/bytecode/testing/mex_interface.hh index c053cceafd5f53a55b0ed0ae3a3ecbf2b27023dc..04d753366e9930f113310ccb82726bf7f35bcfe5 100644 --- a/mex/sources/bytecode/testing/mex_interface.hh +++ b/mex/sources/bytecode/testing/mex_interface.hh @@ -30,10 +30,10 @@ using namespace std; #if !defined(DYN_MEX_FUNC_ERR_MSG_TXT) -#define DYN_MEX_FUNC_ERR_MSG_TXT(str) \ +# define DYN_MEX_FUNC_ERR_MSG_TXT(str) \ do { \ mexPrintf("%s\n", str); \ - } while(0) + } while (0) #endif typedef unsigned int mwIndex; @@ -64,66 +64,111 @@ enum mxArray_type mxUINT64_CLASS = 14 }; -class mxArray_tag { - public: +class mxArray_tag +{ +public: unsigned int size_1, size_2; mwIndex *Ir, *Jc; int Nzmax; double *data; mxArray_type type; vector<string> field_name; - vector<vector<mxArray_tag*> > field_array; + vector<vector<mxArray_tag *> > field_array; mxArray_tag(); }; - - typedef mxArray_tag mxArray; -void load_global(char* file_name); +void load_global(char *file_name); /*Matlab clone function*/ int mexPrintf(const char *str, ...); void mexErrMsgTxt(const string str); void mexWarnMsgTxt(const string str); -void* mxMalloc(unsigned int amount); -void* mxRealloc(void *to_extend, unsigned int amount); -void* mxCalloc(unsigned int nb_elements, unsigned int amount_per_element); +void *mxMalloc(unsigned int amount); +void *mxRealloc(void *to_extend, unsigned int amount); +void *mxCalloc(unsigned int nb_elements, unsigned int amount_per_element); void mxFree(void *to_release); void mexEvalString(const string str); -double* mxGetPr(const mxArray *b_m); -inline mwIndex* mxGetIr(const mxArray *A_m) {return (mwIndex*)A_m->Ir;}; -inline mwIndex* mxGetJc(const mxArray *A_m) {return (mwIndex*)A_m->Jc;}; -mxArray* mxSetNzmax(mxArray* A_m, mwSize nz_max); -inline int mxGetNzmax(const mxArray *A_m) {return A_m->Nzmax;}; -inline int mxGetM(const mxArray *A_m) {return A_m->size_1;}; -inline int mxGetN(const mxArray *A_m) {return A_m->size_2;}; -inline bool mxIsChar(const mxArray *A) {return A->type == mxCHAR_CLASS;}; -inline bool mxIsFloat(const mxArray *A) {return A->type == mxDOUBLE_CLASS || A->type == mxSINGLE_CLASS;}; -inline bool mxIsStruct(const mxArray *A) {return A->type == mxSTRUCT_CLASS;}; -mxArray* mxCreateDoubleMatrix(unsigned int rows,unsigned int cols, mxData_type mx_type); -mxArray* mxCreateSparse(unsigned int rows, unsigned int cols, unsigned int nz_max, mxData_type mx_type); -mxArray* mxCreateCharArray(unsigned int rows, unsigned int cols, mxData_type mx_type); -mxArray* mxCreateDoubleScalar(double value); -mxArray* mxCreateStructMatrix(unsigned int rows, unsigned int cols, unsigned int nfields, const string &fieldnames); -inline mxArray* mxCreateStructArray(unsigned int rows, mwSize* cols, int nfields, const string &fieldnames) {return mxCreateStructMatrix(rows, *cols, nfields, fieldnames);}; -mxArray* mxCreatNULLMatrix(); -void mexCallMATLAB(unsigned int n_lhs, mxArray* lhs[], unsigned int n_rhs, mxArray* rhs[], const char* function); -void mxDestroyArray(mxArray* A_m); -mxArray* read_struct(FILE *fid); -mxArray* read_Array(FILE *fid); -mxArray* read_double_array(FILE *fid); -mxArray* mexGetVariable(const char* space_name, const char* matrix_name); -int mxGetFieldNumber(const mxArray* Struct, const char* field_name); -mxArray* mxGetFieldByNumber(mxArray* Struct, unsigned int pos, unsigned int field_number); +double *mxGetPr(const mxArray *b_m); +inline mwIndex * +mxGetIr(const mxArray *A_m) +{ + return (mwIndex *) A_m->Ir; +}; +inline mwIndex * +mxGetJc(const mxArray *A_m) +{ + return (mwIndex *) A_m->Jc; +}; +mxArray *mxSetNzmax(mxArray *A_m, mwSize nz_max); +inline int +mxGetNzmax(const mxArray *A_m) +{ + return A_m->Nzmax; +}; +inline int +mxGetM(const mxArray *A_m) +{ + return A_m->size_1; +}; +inline int +mxGetN(const mxArray *A_m) +{ + return A_m->size_2; +}; +inline bool +mxIsChar(const mxArray *A) +{ + return A->type == mxCHAR_CLASS; +}; +inline bool +mxIsFloat(const mxArray *A) +{ + return A->type == mxDOUBLE_CLASS || A->type == mxSINGLE_CLASS; +}; +inline bool +mxIsStruct(const mxArray *A) +{ + return A->type == mxSTRUCT_CLASS; +}; +mxArray *mxCreateDoubleMatrix(unsigned int rows, unsigned int cols, mxData_type mx_type); +mxArray *mxCreateSparse(unsigned int rows, unsigned int cols, unsigned int nz_max, mxData_type mx_type); +mxArray *mxCreateCharArray(unsigned int rows, unsigned int cols, mxData_type mx_type); +mxArray *mxCreateDoubleScalar(double value); +mxArray *mxCreateStructMatrix(unsigned int rows, unsigned int cols, unsigned int nfields, const string &fieldnames); +inline mxArray * +mxCreateStructArray(unsigned int rows, mwSize *cols, int nfields, const string &fieldnames) +{ + return mxCreateStructMatrix(rows, *cols, nfields, fieldnames); +}; +mxArray *mxCreatNULLMatrix(); +void mexCallMATLAB(unsigned int n_lhs, mxArray* lhs[], unsigned int n_rhs, mxArray* rhs[], const char *function); +void mxDestroyArray(mxArray *A_m); +mxArray *read_struct(FILE *fid); +mxArray *read_Array(FILE *fid); +mxArray *read_double_array(FILE *fid); +mxArray *mexGetVariable(const char *space_name, const char *matrix_name); +int mxGetFieldNumber(const mxArray *Struct, const char *field_name); +mxArray *mxGetFieldByNumber(mxArray *Struct, unsigned int pos, unsigned int field_number); void mxSetFieldByNumber(mxArray *Struct, mwIndex index, unsigned int field_number, mxArray *pvalue); -int mxAddField(mxArray* Struct, const char* field_name); +int mxAddField(mxArray *Struct, const char *field_name); void mxSetFieldByNumber(mxArray *Struct, mwIndex index, unsigned int fieldnumber, mxArray *pvalue); -inline unsigned int mxGetNumberOfElements(const mxArray* A) {return A->size_1 * A->size_2;}; +inline unsigned int +mxGetNumberOfElements(const mxArray *A) +{ + return A->size_1 * A->size_2; +}; int mxGetString(const mxArray *array, char *buf, unsigned int buflen); -inline double mxGetScalar(const mxArray *array) {if (!mxIsFloat(array)) mexErrMsgTxt("not a float array\n");return array->data[0];}; -mxArray* mxDuplicateArray(const mxArray *array); -void Free_simple_array(mxArray* array); -void Free_struct_array(mxArray* array); -void Free_Array(mxArray* array); +inline double +mxGetScalar(const mxArray *array) +{ + if (!mxIsFloat(array)) + mexErrMsgTxt("not a float array\n"); + return array->data[0]; +}; +mxArray *mxDuplicateArray(const mxArray *array); +void Free_simple_array(mxArray *array); +void Free_struct_array(mxArray *array); +void Free_Array(mxArray *array); void Free_global(); #endif diff --git a/mex/sources/dynblas.h b/mex/sources/dynblas.h index 0977a5a8e570b5ec1fc7e048ddae481041a9e384..d9c8e9f4f25e1733bfe99615d1101d01da680218 100644 --- a/mex/sources/dynblas.h +++ b/mex/sources/dynblas.h @@ -82,7 +82,7 @@ extern "C" { CONST_BLDOU beta, BLDOU y, CONST_BLINT incy); #define dsymv FORTRAN_WRAPPER(dsymv) - void dsymv(BLCHAR uplo, CONST_BLINT m, CONST_BLDOU alpha, CONST_BLDOU a, + void dsymv(BLCHAR uplo, CONST_BLINT m, CONST_BLDOU alpha, CONST_BLDOU a, CONST_BLINT lda, CONST_BLDOU b, CONST_BLINT ldb, CONST_BLDOU beta, BLDOU c, CONST_BLINT ldc); diff --git a/mex/sources/dynlapack.h b/mex/sources/dynlapack.h index a185a46fe07125315fbea49d59e5d0d53c05356f..bceeeaa12c0bca4d66869e5740418ac65247b27d 100644 --- a/mex/sources/dynlapack.h +++ b/mex/sources/dynlapack.h @@ -106,7 +106,7 @@ extern "C" { #define dppsv FORTRAN_WRAPPER(dppsv) void dppsv(LACHAR uplo, CONST_LAINT n, CONST_LAINT m, LADOU a, LADOU b, CONST_LAINT ldb, - LAINT info); + LAINT info); #define dpotri FORTRAN_WRAPPER(dpotri) void dpotri(LACHAR uplo, CONST_LAINT n, LADOU a, CONST_LAINT lda, diff --git a/mex/sources/dynmex.h b/mex/sources/dynmex.h index ed7e9377d17de75da987e413ac5e5760b4cd01d7..b4471abf7723b0407e17ccb960af8446c54753ff 100644 --- a/mex/sources/dynmex.h +++ b/mex/sources/dynmex.h @@ -36,14 +36,14 @@ typedef int mwSize; * Fix for trac ticket Ticket #137 */ #if !defined(DYN_MEX_FUNC_ERR_MSG_TXT) -#define DYN_MEX_FUNC_ERR_MSG_TXT(str) \ +# define DYN_MEX_FUNC_ERR_MSG_TXT(str) \ do { \ mexPrintf("%s\n", str); \ int i; \ for (i = 0; i < nlhs; i++) \ plhs[i] = mxCreateDoubleScalar(1); \ return; \ - } while(0) + } while (0) #endif #endif diff --git a/mex/sources/estimation/DecisionRules.cc b/mex/sources/estimation/DecisionRules.cc index 75fea6762f7cb5fbed7a309d7a5bcc4a55606b70..5aaedcace06fcf0f8b1cb46fe561a6d84fa7b0fe 100644 --- a/mex/sources/estimation/DecisionRules.cc +++ b/mex/sources/estimation/DecisionRules.cc @@ -70,7 +70,7 @@ DecisionRules::DecisionRules(size_t n_arg, size_t p_arg, back_inserter(zeta_dynamic)); // Compute beta_back and pi_back - for(size_t i = 0; i < n_back_mixed; i++) + for (size_t i = 0; i < n_back_mixed; i++) if (find(zeta_mixed.begin(), zeta_mixed.end(), zeta_back_mixed[i]) == zeta_mixed.end()) pi_back.push_back(i); @@ -78,7 +78,7 @@ DecisionRules::DecisionRules(size_t n_arg, size_t p_arg, beta_back.push_back(i); // Compute beta_fwrd and pi_fwrd - for(size_t i = 0; i < n_fwrd_mixed; i++) + for (size_t i = 0; i < n_fwrd_mixed; i++) if (find(zeta_mixed.begin(), zeta_mixed.end(), zeta_fwrd_mixed[i]) == zeta_mixed.end()) pi_fwrd.push_back(i); @@ -95,7 +95,7 @@ DecisionRules::compute(const Matrix &jacobian, Matrix &g_y, Matrix &g_u) throw ( assert(g_u.getRows() == n && g_u.getCols() == p); // Construct S, perform QR decomposition and get A = Q*jacobian - for(size_t i = 0; i < n_static; i++) + for (size_t i = 0; i < n_static; i++) mat::col_copy(jacobian, n_back_mixed+zeta_static[i], S, i); A = MatrixConstView(jacobian, 0, 0, n, n_back_mixed + n + n_fwrd_mixed); diff --git a/mex/sources/estimation/EstimatedParameter.cc b/mex/sources/estimation/EstimatedParameter.cc index a61db1cb35622193893f07e90ab6d4c9ce978661..cad7466702d2f46e0daefa0e2283e2e0d74ad9ea 100644 --- a/mex/sources/estimation/EstimatedParameter.cc +++ b/mex/sources/estimation/EstimatedParameter.cc @@ -27,7 +27,7 @@ EstimatedParameter::EstimatedParameter(const EstimatedParameter::pType type_arg, size_t ID1_arg, size_t ID2_arg, const std::vector<size_t> &subSampleIDs_arg, - double lower_bound_arg, double upper_bound_arg, Prior* prior_arg) : + double lower_bound_arg, double upper_bound_arg, Prior *prior_arg) : ptype(type_arg), ID1(ID1_arg), ID2(ID2_arg), lower_bound(lower_bound_arg), upper_bound(upper_bound_arg), prior(prior_arg), subSampleIDs(subSampleIDs_arg) diff --git a/mex/sources/estimation/EstimatedParameter.hh b/mex/sources/estimation/EstimatedParameter.hh index 40226fd02251a3d98894894259e1a27a180059d4..f80be7e141adfa364ac39b2c4f1999aee365aee4 100644 --- a/mex/sources/estimation/EstimatedParameter.hh +++ b/mex/sources/estimation/EstimatedParameter.hh @@ -43,7 +43,7 @@ public: EstimatedParameter(const EstimatedParameter::pType type, size_t ID1, size_t ID2, const std::vector<size_t> &subSampleIDs, - double lower_bound, double upper_bound, Prior* prior + double lower_bound, double upper_bound, Prior *prior ); virtual ~EstimatedParameter(); @@ -52,7 +52,7 @@ public: size_t ID2; double lower_bound; double upper_bound; - Prior* prior; + Prior *prior; std::vector<size_t> subSampleIDs; }; diff --git a/mex/sources/estimation/EstimationSubsample.hh b/mex/sources/estimation/EstimationSubsample.hh index ab3ed3c7a1e4bd3ca66c9e7d104dd199abded0c2..c33b21df232b4211317f736eab288ff19b88568d 100644 --- a/mex/sources/estimation/EstimationSubsample.hh +++ b/mex/sources/estimation/EstimationSubsample.hh @@ -55,7 +55,8 @@ * * Time indices follow C convention: first period has index 0. */ -class EstimationSubsample { +class EstimationSubsample +{ public: EstimationSubsample(size_t startPeriod, size_t endPeriod); virtual ~EstimationSubsample(); diff --git a/mex/sources/estimation/InitializeKalmanFilter.cc b/mex/sources/estimation/InitializeKalmanFilter.cc index 9c9176964954e1bdd3319d6df4c2a946bffcc95c..e25d73614297a3f07951ab1270ab3d1b9abed1b6 100644 --- a/mex/sources/estimation/InitializeKalmanFilter.cc +++ b/mex/sources/estimation/InitializeKalmanFilter.cc @@ -44,7 +44,7 @@ InitializeKalmanFilter::InitializeKalmanFilter(const std::string &dynamicDllFile g_x(n_endo_arg, zeta_back_arg.size() + zeta_mixed_arg.size()), g_u(n_endo_arg, n_exo_arg), Rt(n_exo_arg, zeta_varobs_back_mixed.size()), - RQ(zeta_varobs_back_mixed.size(), n_exo_arg) + RQ(zeta_varobs_back_mixed.size(), n_exo_arg) { std::vector<size_t> zeta_back_mixed; set_union(zeta_back_arg.begin(), zeta_back_arg.end(), @@ -53,12 +53,12 @@ InitializeKalmanFilter::InitializeKalmanFilter(const std::string &dynamicDllFile for (size_t i = 0; i < zeta_back_mixed.size(); i++) pi_bm_vbm.push_back(find(zeta_varobs_back_mixed.begin(), zeta_varobs_back_mixed.end(), zeta_back_mixed[i]) - zeta_varobs_back_mixed.begin()); - + } // initialise parameter dependent KF matrices only but not Ps void InitializeKalmanFilter::initialize(VectorView &steadyState, const Vector &deepParams, Matrix &R, - const Matrix &Q, Matrix &RQRt, Matrix &T, + const Matrix &Q, Matrix &RQRt, Matrix &T, double &penalty, const MatrixConstView &dataView, MatrixView &detrendedDataView, int &info) { @@ -80,7 +80,6 @@ InitializeKalmanFilter::initialize(VectorView &steadyState, const Vector &deepPa setPstar(Pstar, Pinf, T, RQRt, info); } - void InitializeKalmanFilter::setT(Matrix &T, int &info) { @@ -104,27 +103,27 @@ InitializeKalmanFilter::setPstar(Matrix &Pstar, Matrix &Pinf, const Matrix &T, c { try - { - // disclyap_fast(T, RQR, Pstar, lyapunov_tol, 0 or 1 to check chol) - discLyapFast.solve_lyap(T, RQRt, Pstar, lyapunov_tol, 0); + { + // disclyap_fast(T, RQR, Pstar, lyapunov_tol, 0 or 1 to check chol) + discLyapFast.solve_lyap(T, RQRt, Pstar, lyapunov_tol, 0); - Pinf.setAll(0.0); - } - catch(const DiscLyapFast::DLPException &e) - { - if (e.info > 0) // The matrix is not positive definite in NormCholesky calculator - { - printf(e.message.c_str()); - info = -1; //likelihood = penalty; - return; - } - else if (e.info < 0) - { - printf("Caugth unhandled TS exception with Pstar matrix: "); - printf(e.message.c_str()); - info = -1; //likelihood = penalty; - throw; - } - } + Pinf.setAll(0.0); + } + catch (const DiscLyapFast::DLPException &e) + { + if (e.info > 0) // The matrix is not positive definite in NormCholesky calculator + { + printf(e.message.c_str()); + info = -1; //likelihood = penalty; + return; + } + else if (e.info < 0) + { + printf("Caugth unhandled TS exception with Pstar matrix: "); + printf(e.message.c_str()); + info = -1; //likelihood = penalty; + throw; + } + } } diff --git a/mex/sources/estimation/InitializeKalmanFilter.hh b/mex/sources/estimation/InitializeKalmanFilter.hh index 196b3e47804a76ad378119e3967e6df9c73e148e..49b018abe57e6f7ef986152e736d2c927b2bcdab 100644 --- a/mex/sources/estimation/InitializeKalmanFilter.hh +++ b/mex/sources/estimation/InitializeKalmanFilter.hh @@ -43,7 +43,7 @@ public: /*! \param[in] zeta_varobs_back_mixed_arg The union of indices of observed, backward and mixed variables */ - InitializeKalmanFilter(const std::string& dynamicDllFile, size_t n_endo, size_t n_exo, const std::vector<size_t> &zeta_fwrd_arg, + InitializeKalmanFilter(const std::string &dynamicDllFile, size_t n_endo, size_t n_exo, const std::vector<size_t> &zeta_fwrd_arg, const std::vector<size_t> &zeta_back_arg, const std::vector<size_t> &zeta_mixed_arg, const std::vector<size_t> &zeta_static_arg, const std::vector<size_t> &zeta_varobs_back_mixed_arg, double qz_criterium_arg, double lyapunov_tol_arg, int &info); diff --git a/mex/sources/estimation/KalmanFilter.cc b/mex/sources/estimation/KalmanFilter.cc index 52c5c477ca838deaf9edc810a51a2804dade9b98..e8040cfe7519833687dedc588b154e2f35754809 100644 --- a/mex/sources/estimation/KalmanFilter.cc +++ b/mex/sources/estimation/KalmanFilter.cc @@ -37,8 +37,8 @@ KalmanFilter::KalmanFilter(const std::string &dynamicDllFile, size_t n_endo, siz double qz_criterium_arg, const std::vector<size_t> &varobs_arg, double riccati_tol_arg, double lyapunov_tol_arg, int &info) : zeta_varobs_back_mixed(compute_zeta_varobs_back_mixed(zeta_back_arg, zeta_mixed_arg, varobs_arg)), - Z(varobs_arg.size(), zeta_varobs_back_mixed.size()), Zt(Z.getCols(),Z.getRows()), T(zeta_varobs_back_mixed.size()), R(zeta_varobs_back_mixed.size(), n_exo), - Pstar(zeta_varobs_back_mixed.size(), zeta_varobs_back_mixed.size()), Pinf(zeta_varobs_back_mixed.size(), zeta_varobs_back_mixed.size()), + Z(varobs_arg.size(), zeta_varobs_back_mixed.size()), Zt(Z.getCols(), Z.getRows()), T(zeta_varobs_back_mixed.size()), R(zeta_varobs_back_mixed.size(), n_exo), + Pstar(zeta_varobs_back_mixed.size(), zeta_varobs_back_mixed.size()), Pinf(zeta_varobs_back_mixed.size(), zeta_varobs_back_mixed.size()), RQRt(zeta_varobs_back_mixed.size(), zeta_varobs_back_mixed.size()), Ptmp(zeta_varobs_back_mixed.size(), zeta_varobs_back_mixed.size()), F(varobs_arg.size(), varobs_arg.size()), Finv(varobs_arg.size(), varobs_arg.size()), K(zeta_varobs_back_mixed.size(), varobs_arg.size()), KFinv(zeta_varobs_back_mixed.size(), varobs_arg.size()), oldKFinv(zeta_varobs_back_mixed.size(), varobs_arg.size()), a_init(zeta_varobs_back_mixed.size()), @@ -54,7 +54,7 @@ KalmanFilter::KalmanFilter(const std::string &dynamicDllFile, size_t n_endo, siz size_t j = find(zeta_varobs_back_mixed.begin(), zeta_varobs_back_mixed.end(), varobs_arg[i]) - zeta_varobs_back_mixed.begin(); Z(i, j) = 1.0; - Zt(j, i) = 1.0; + Zt(j, i) = 1.0; } } @@ -79,27 +79,27 @@ KalmanFilter::compute(const MatrixConstView &dataView, VectorView &steadyState, VectorView &vll, MatrixView &detrendedDataView, size_t start, size_t period, double &penalty, int &info) { - double lik=INFINITY; + double lik = INFINITY; try { - if(period==0) // initialise all KF matrices + if (period == 0) // initialise all KF matrices initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T, Pstar, Pinf, - penalty, dataView, detrendedDataView, info); - else // initialise parameter dependent KF matrices only but not Ps - initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T, - penalty, dataView, detrendedDataView, info); + penalty, dataView, detrendedDataView, info); + else // initialise parameter dependent KF matrices only but not Ps + initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T, + penalty, dataView, detrendedDataView, info); - lik= filter(detrendedDataView, H, vll, start, info); + lik = filter(detrendedDataView, H, vll, start, info); } catch (const DecisionRules::BlanchardKahnException &bke) { - info =22; + info = 22; return penalty; } - + if (info != 0) return penalty; - else + else return lik; }; @@ -110,7 +110,7 @@ KalmanFilter::compute(const MatrixConstView &dataView, VectorView &steadyState, double KalmanFilter::filter(const MatrixView &detrendedDataView, const Matrix &H, VectorView &vll, size_t start, int &info) { - double loglik=0.0, ll, logFdet, Fdet, dvtFinvVt; + double loglik = 0.0, ll, logFdet, Fdet, dvtFinvVt; size_t p = Finv.getRows(); bool nonstationary = true; a_init.setAll(0.0); @@ -130,25 +130,25 @@ KalmanFilter::filter(const MatrixView &detrendedDataView, const Matrix &H, Vect // Finv=inv(F) mat::set_identity(Finv); // Pack F upper trinagle as vector - for (size_t i=1;i<=p;++i) - for(size_t j=i;j<=p;++j) - FUTP(i + (j-1)*j/2 -1) = F(i-1,j-1); + for (size_t i = 1; i <= p; ++i) + for (size_t j = i; j <= p; ++j) + FUTP(i + (j-1)*j/2 -1) = F(i-1, j-1); - info=lapack::choleskySolver(FUTP, Finv, "U"); // F now contains its Chol decomposition! - if (info<0) + info = lapack::choleskySolver(FUTP, Finv, "U"); // F now contains its Chol decomposition! + if (info < 0) { std::cout << "Info:" << info << std::endl; std::cout << "t:" << t << std::endl; return 0; } - if (info>0) + if (info > 0) { //enforce Pstar symmetry with P=(P+P')/2=0.5P+0.5P' mat::transpose(Ptmp, Pstar); - mat::add(Pstar,Ptmp); - for (size_t i=0;i<Pstar.getCols();++i) - for(size_t j=0;j<Pstar.getCols();++j) - Pstar(i,j)*=0.5; + mat::add(Pstar, Ptmp); + for (size_t i = 0; i < Pstar.getCols(); ++i) + for (size_t j = 0; j < Pstar.getCols(); ++j) + Pstar(i, j) *= 0.5; // K=PZ' //blas::gemm("N", "T", 1.0, Pstar, Z, 0.0, K); @@ -161,12 +161,12 @@ KalmanFilter::filter(const MatrixView &detrendedDataView, const Matrix &H, Vect // Finv=inv(F) mat::set_identity(Finv); // Pack F upper trinagle as vector - for (size_t i=1;i<=p;++i) - for(size_t j=i;j<=p;++j) - FUTP(i + (j-1)*j/2 -1) = F(i-1,j-1); + for (size_t i = 1; i <= p; ++i) + for (size_t j = i; j <= p; ++j) + FUTP(i + (j-1)*j/2 -1) = F(i-1, j-1); - info=lapack::choleskySolver(FUTP, Finv, "U"); // F now contains its Chol decomposition! - if (info!=0) + info = lapack::choleskySolver(FUTP, Finv, "U"); // F now contains its Chol decomposition! + if (info != 0) { return 0; } @@ -177,9 +177,9 @@ KalmanFilter::filter(const MatrixView &detrendedDataView, const Matrix &H, Vect Fdet = 1; for (size_t d = 1; d <= p; ++d) Fdet *= FUTP(d + (d-1)*d/2 -1); - Fdet *=Fdet; + Fdet *= Fdet; - logFdet=log(fabs(Fdet)); + logFdet = log(fabs(Fdet)); Ptmp = Pstar; // Pt+1= T(Pt - KFinvK')T' +RQR' @@ -193,13 +193,13 @@ KalmanFilter::filter(const MatrixView &detrendedDataView, const Matrix &H, Vect Pstar = RQRt; blas::gemm("N", "T", 1.0, Ptmp, T, 1.0, Pstar); - if (t>0) + if (t > 0) nonstationary = mat::isDiff(KFinv, oldKFinv, riccati_tol); - oldKFinv=KFinv; + oldKFinv = KFinv; } // err= Yt - Za - VectorConstView yt=mat::get_col(detrendedDataView, t); + VectorConstView yt = mat::get_col(detrendedDataView, t); vt = yt; blas::gemv("N", -1.0, Z, a_init, 1.0, vt); @@ -212,12 +212,13 @@ KalmanFilter::filter(const MatrixView &detrendedDataView, const Matrix &H, Vect Here we calc likelihood and store results. *****************/ blas::symv("U", 1.0, Finv, vt, 0.0, vtFinv); - dvtFinvVt=blas::dot(vtFinv, vt ); + dvtFinvVt = blas::dot(vtFinv, vt); ll = -0.5*(p*log(2*M_PI)+logFdet+dvtFinvVt); vll(t) = ll; - if (t >= start) loglik += ll; + if (t >= start) + loglik += ll; } diff --git a/mex/sources/estimation/KalmanFilter.hh b/mex/sources/estimation/KalmanFilter.hh index 70f9f5d0353daf04db33bd10aa8c400327ccfd5f..395d990ab107ff7672827448f428e07d1244a946 100644 --- a/mex/sources/estimation/KalmanFilter.hh +++ b/mex/sources/estimation/KalmanFilter.hh @@ -44,7 +44,8 @@ * Analysis, vol. 24(1), pp. 85-98). */ -class KalmanFilter { +class KalmanFilter +{ public: virtual ~KalmanFilter(); @@ -72,7 +73,7 @@ private: Matrix K, KFinv, oldKFinv; // mm*nobs K=PZt and K*Finv gain matrices Vector a_init, a_new; // state vector Vector vt; // current observation error vectors - Vector vtFinv;// intermediate observation error *Finv vector + Vector vtFinv; // intermediate observation error *Finv vector double riccati_tol; InitializeKalmanFilter initKalmanFilter; //Initialise KF matrices Vector FUTP; // F upper triangle packed as vector FUTP(i + (j-1)*j/2) = F(i,j) for 1<=i<=j; diff --git a/mex/sources/estimation/LogLikelihoodMain.cc b/mex/sources/estimation/LogLikelihoodMain.cc index cf480a761c9baf480d7fe43f4f12c5f5875afb0f..26ccaa424b15d4963187d600c65ef25e82d84775 100644 --- a/mex/sources/estimation/LogLikelihoodMain.cc +++ b/mex/sources/estimation/LogLikelihoodMain.cc @@ -25,15 +25,14 @@ #include "LogLikelihoodMain.hh" -LogLikelihoodMain::LogLikelihoodMain( //const Matrix &data_arg, Vector &deepParams_arg, - const std::string &dynamicDllFile, EstimatedParametersDescription &estiParDesc, size_t n_endo, size_t n_exo, - const std::vector<size_t> &zeta_fwrd_arg, const std::vector<size_t> &zeta_back_arg, - const std::vector<size_t> &zeta_mixed_arg, const std::vector<size_t> &zeta_static_arg, const double qz_criterium, - const std::vector<size_t> &varobs, double riccati_tol, double lyapunov_tol, int &info_arg) +LogLikelihoodMain::LogLikelihoodMain(const std::string &dynamicDllFile, EstimatedParametersDescription &estiParDesc, size_t n_endo, size_t n_exo, + const std::vector<size_t> &zeta_fwrd_arg, const std::vector<size_t> &zeta_back_arg, + const std::vector<size_t> &zeta_mixed_arg, const std::vector<size_t> &zeta_static_arg, const double qz_criterium, + const std::vector<size_t> &varobs, double riccati_tol, double lyapunov_tol, int &info_arg) : estSubsamples(estiParDesc.estSubsamples), - logLikelihoodSubSample(dynamicDllFile, estiParDesc, n_endo, n_exo, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium, - varobs, riccati_tol, lyapunov_tol, info_arg), + logLikelihoodSubSample(dynamicDllFile, estiParDesc, n_endo, n_exo, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium, + varobs, riccati_tol, lyapunov_tol, info_arg), vll(estiParDesc.getNumberOfPeriods()), // time dimension size of data detrendedData(varobs.size(), estiParDesc.getNumberOfPeriods()) { diff --git a/mex/sources/estimation/LogLikelihoodMain.hh b/mex/sources/estimation/LogLikelihoodMain.hh index 0b7af4556fee8750d412dab0992a8a66175b6c21..4d74f43a7ebbee19068408e3aac7d30d601800b1 100644 --- a/mex/sources/estimation/LogLikelihoodMain.hh +++ b/mex/sources/estimation/LogLikelihoodMain.hh @@ -27,7 +27,8 @@ #include "LogLikelihoodSubSample.hh" -class LogLikelihoodMain { +class LogLikelihoodMain +{ private: std::vector<EstimationSubsample> &estSubsamples; // reference to member of EstimatedParametersDescription LogLikelihoodSubSample logLikelihoodSubSample; @@ -36,11 +37,10 @@ private: public: virtual ~LogLikelihoodMain(); - LogLikelihoodMain( //const Matrix &data, Vector &deepParams_arg, //GeneralParams& estimOptions, - const std::string &dynamicDllFile, EstimatedParametersDescription &estiParDesc, size_t n_endo, size_t n_exo, - const std::vector<size_t> &zeta_fwrd_arg, const std::vector<size_t> &zeta_back_arg, const std::vector<size_t> &zeta_mixed_arg, - const std::vector<size_t> &zeta_static_arg, const double qz_criterium_arg, const std::vector<size_t> &varobs_arg, - double riccati_tol_arg, double lyapunov_tol_arg, int &info); + LogLikelihoodMain(const std::string &dynamicDllFile, EstimatedParametersDescription &estiParDesc, size_t n_endo, size_t n_exo, + const std::vector<size_t> &zeta_fwrd_arg, const std::vector<size_t> &zeta_back_arg, const std::vector<size_t> &zeta_mixed_arg, + const std::vector<size_t> &zeta_static_arg, const double qz_criterium_arg, const std::vector<size_t> &varobs_arg, + double riccati_tol_arg, double lyapunov_tol_arg, int &info); /** * Compute method Inputs: @@ -50,8 +50,8 @@ public: * Q and H KF matrices of shock and measurement error varinaces and covariances * KF logLikelihood calculation start period. */ - double compute(Matrix &steadyState, const Vector &estParams, Vector &deepParams, const MatrixConstView &data, - Matrix &Q, Matrix &H, size_t presampleStart, int &info); // for calls from estimation and to set Steady State + double compute(Matrix &steadyState, const Vector &estParams, Vector &deepParams, const MatrixConstView &data, + Matrix &Q, Matrix &H, size_t presampleStart, int &info); // for calls from estimation and to set Steady State Vector & getVll() diff --git a/mex/sources/estimation/LogLikelihoodSubSample.cc b/mex/sources/estimation/LogLikelihoodSubSample.cc index a2e230b67d1295fb9ef7f199b2f83a0f2a192c6f..53543b1bda723a2a38bf7ddd4f9c3db4f9bbb77c 100644 --- a/mex/sources/estimation/LogLikelihoodSubSample.cc +++ b/mex/sources/estimation/LogLikelihoodSubSample.cc @@ -36,7 +36,7 @@ LogLikelihoodSubSample::LogLikelihoodSubSample(const std::string &dynamicDllFile const std::vector<size_t> &zeta_fwrd_arg, const std::vector<size_t> &zeta_back_arg, const std::vector<size_t> &zeta_mixed_arg, const std::vector<size_t> &zeta_static_arg, const double qz_criterium, const std::vector<size_t> &varobs, double riccati_tol, double lyapunov_tol, int &INinfo) : - startPenalty(-1e8),estiParDesc(INestiParDesc), + startPenalty(-1e8), estiParDesc(INestiParDesc), kalmanFilter(dynamicDllFile, n_endo, n_exo, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium, varobs, riccati_tol, lyapunov_tol, INinfo), eigQ(n_exo), eigH(varobs.size()), info(INinfo) { @@ -46,8 +46,8 @@ double LogLikelihoodSubSample::compute(VectorView &steadyState, const MatrixConstView &dataView, const Vector &estParams, Vector &deepParams, Matrix &Q, Matrix &H, VectorView &vll, MatrixView &detrendedDataView, int &info, size_t start, size_t period) { - penalty=startPenalty; - logLikelihood=startPenalty; + penalty = startPenalty; + logLikelihood = startPenalty; updateParams(estParams, deepParams, Q, H, period); if (info == 0) @@ -159,7 +159,7 @@ LogLikelihoodSubSample::updateParams(const Vector &estParams, Vector &deepParams } // end if break; - //if estim_params_.np > 0 // i.e. num of deep parameters >0 + //if estim_params_.np > 0 // i.e. num of deep parameters >0 case EstimatedParameter::deepPar: k = estiParDesc.estParams[i].ID1; deepParams(k) = estParams(i); diff --git a/mex/sources/estimation/LogLikelihoodSubSample.hh b/mex/sources/estimation/LogLikelihoodSubSample.hh index eeeca471667767491b5ee63b69664ac841d91206..318baf2cf4f743d59c4f37007fb474d7c157b6c6 100644 --- a/mex/sources/estimation/LogLikelihoodSubSample.hh +++ b/mex/sources/estimation/LogLikelihoodSubSample.hh @@ -30,7 +30,8 @@ #include "KalmanFilter.hh" #include "VDVEigDecomposition.hh" -class LogLikelihoodSubSample { +class LogLikelihoodSubSample +{ public: LogLikelihoodSubSample(const std::string &dynamicDllFile, EstimatedParametersDescription &estiParDesc, size_t n_endo, size_t n_exo, diff --git a/mex/sources/estimation/LogPosteriorDensity.cc b/mex/sources/estimation/LogPosteriorDensity.cc index b663ea7fd335809ef316992161a192fa1da1f555..286fa848f6a583f4eb7041bc35557480f3f7d90f 100644 --- a/mex/sources/estimation/LogPosteriorDensity.cc +++ b/mex/sources/estimation/LogPosteriorDensity.cc @@ -44,7 +44,7 @@ double LogPosteriorDensity::compute(Matrix &steadyState, const Vector &estParams, Vector &deepParams, const MatrixConstView &data, Matrix &Q, Matrix &H, size_t presampleStart, int &info) { return -logLikelihoodMain.compute(steadyState, estParams, deepParams, data, Q, H, presampleStart, info) - -logPriorDensity.compute(estParams); + -logPriorDensity.compute(estParams); } /** @@ -56,4 +56,3 @@ LogPosteriorDensity::getLikVector() return logLikelihoodMain.getVll(); } - diff --git a/mex/sources/estimation/LogPosteriorDensity.hh b/mex/sources/estimation/LogPosteriorDensity.hh index 92fbc8550120a66e90ec00f65bd91296140f4ee7..f375310afef8257ee27130c9966f3af5bb4cfc37 100644 --- a/mex/sources/estimation/LogPosteriorDensity.hh +++ b/mex/sources/estimation/LogPosteriorDensity.hh @@ -34,7 +34,8 @@ * Class that calculates Log Posterior Density using kalman, based on Dynare * DsgeLikelihood.m */ -class LogPosteriorDensity { +class LogPosteriorDensity +{ private: LogPriorDensity logPriorDensity; diff --git a/mex/sources/estimation/LogPriorDensity.cc b/mex/sources/estimation/LogPriorDensity.cc index 882b553438ac7923b23c35ad64adfc6c07205dc1..265af69f2da85d581b0f306d09b103d5b609f7ff 100644 --- a/mex/sources/estimation/LogPriorDensity.cc +++ b/mex/sources/estimation/LogPriorDensity.cc @@ -37,7 +37,7 @@ double LogPriorDensity::compute(const Vector &ep) { assert(estParsDesc.estParams.size() == ep.getSize()); - double logPriorDensity=0; + double logPriorDensity = 0; for (size_t i = 0; i < ep.getSize(); ++i) { logPriorDensity += log(((*(estParsDesc.estParams[i]).prior)).pdf(ep(i))); diff --git a/mex/sources/estimation/LogPriorDensity.hh b/mex/sources/estimation/LogPriorDensity.hh index f3f5d483ebd0df3ef3146a4d18838fbb8b1c33e0..b76d529daba11de949a45b4c2068c5c278f1ed47 100644 --- a/mex/sources/estimation/LogPriorDensity.hh +++ b/mex/sources/estimation/LogPriorDensity.hh @@ -11,10 +11,11 @@ #include "Vector.hh" #include "EstimatedParametersDescription.hh" -class LogPriorDensity { +class LogPriorDensity +{ public: - LogPriorDensity(EstimatedParametersDescription& estParsDesc); + LogPriorDensity(EstimatedParametersDescription &estParsDesc); virtual ~LogPriorDensity(); double compute(const Vector &estParams); diff --git a/mex/sources/estimation/ModelSolution.cc b/mex/sources/estimation/ModelSolution.cc index bd7fa822a735e21b6139acecf3f45790a066b410..2c3888816b8c8a14771ddade9a791d023c8faffb 100644 --- a/mex/sources/estimation/ModelSolution.cc +++ b/mex/sources/estimation/ModelSolution.cc @@ -28,17 +28,17 @@ #include "ModelSolution.hh" /** -* compute the steady state (2nd stage), and computes first order approximation -*/ -ModelSolution::ModelSolution(const std::string& dynamicDllFile, size_t n_endo_arg, size_t n_exo_arg, const std::vector<size_t>& zeta_fwrd_arg, - const std::vector<size_t>& zeta_back_arg, const std::vector<size_t>& zeta_mixed_arg, - const std::vector<size_t>& zeta_static_arg, double INqz_criterium) - : n_endo(n_endo_arg), n_exo(n_exo_arg), // n_jcols = Num of Jacobian columns = nStat+2*nPred+3*nBoth+2*nForw+nExog - n_jcols (n_exo+n_endo+ zeta_back_arg.size() /*nsPred*/ + zeta_fwrd_arg.size() /*nsForw*/ +2*zeta_mixed_arg.size()), - jacobian (n_endo,n_jcols), residual(n_endo), Mx(1,n_exo), - decisionRules ( n_endo_arg, n_exo_arg, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, INqz_criterium), - dynamicDLLp(dynamicDllFile, n_exo), - llXsteadyState(n_jcols-n_exo) + * compute the steady state (2nd stage), and computes first order approximation + */ +ModelSolution::ModelSolution(const std::string &dynamicDllFile, size_t n_endo_arg, size_t n_exo_arg, const std::vector<size_t> &zeta_fwrd_arg, + const std::vector<size_t> &zeta_back_arg, const std::vector<size_t> &zeta_mixed_arg, + const std::vector<size_t> &zeta_static_arg, double INqz_criterium) : + n_endo(n_endo_arg), n_exo(n_exo_arg), // n_jcols = Num of Jacobian columns = nStat+2*nPred+3*nBoth+2*nForw+nExog + n_jcols(n_exo+n_endo+ zeta_back_arg.size() /*nsPred*/ + zeta_fwrd_arg.size() /*nsForw*/ +2*zeta_mixed_arg.size()), + jacobian(n_endo, n_jcols), residual(n_endo), Mx(1, n_exo), + decisionRules(n_endo_arg, n_exo_arg, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, INqz_criterium), + dynamicDLLp(dynamicDllFile, n_exo), + llXsteadyState(n_jcols-n_exo) { Mx.setAll(0.0); jacobian.setAll(0.0); @@ -51,20 +51,20 @@ ModelSolution::ModelSolution(const std::string& dynamicDllFile, size_t n_endo_a back_inserter(zeta_back_mixed)); } -void -ModelSolution::compute(VectorView& steadyState, const Vector& deepParams, Matrix& ghx, Matrix& ghu) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException) +void +ModelSolution::compute(VectorView &steadyState, const Vector &deepParams, Matrix &ghx, Matrix &ghu) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException) { // compute Steady State ComputeSteadyState(steadyState, deepParams); - // then get jacobian and + // then get jacobian and - ComputeModelSolution( steadyState, deepParams, ghx, ghu); + ComputeModelSolution(steadyState, deepParams, ghx, ghu); } -void -ModelSolution::ComputeModelSolution(VectorView &steadyState, const Vector& deepParams, Matrix& ghx, Matrix& ghu) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException) +void +ModelSolution::ComputeModelSolution(VectorView &steadyState, const Vector &deepParams, Matrix &ghx, Matrix &ghu) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException) { // set extended Steady State @@ -77,14 +77,14 @@ ModelSolution::ComputeModelSolution(VectorView &steadyState, const Vector& deepP for (size_t i = 0; i < zeta_fwrd_mixed.size(); i++) llXsteadyState(zeta_back_mixed.size() + n_endo + i) = steadyState(zeta_fwrd_mixed[i]); - //get jacobian + //get jacobian dynamicDLLp.eval(llXsteadyState, Mx, deepParams, steadyState, residual, &jacobian, NULL, NULL); - //compute rules - decisionRules.compute(jacobian,ghx, ghu); + //compute rules + decisionRules.compute(jacobian, ghx, ghu); } -void -ModelSolution::ComputeSteadyState(VectorView& steadyState, const Vector& deepParams) +void +ModelSolution::ComputeSteadyState(VectorView &steadyState, const Vector &deepParams) { // does nothig for time being. } diff --git a/mex/sources/estimation/ModelSolution.hh b/mex/sources/estimation/ModelSolution.hh index c176dcefae753d0cdb43df15ca379aa15692208e..724f9566891e075b447f3acc018e0c95c50bf81e 100644 --- a/mex/sources/estimation/ModelSolution.hh +++ b/mex/sources/estimation/ModelSolution.hh @@ -29,20 +29,20 @@ #include "DecisionRules.hh" #include "dynamic_dll.hh" - /** -* compute the steady state (2nd stage), and -* computes first order approximation -* -*/ -class ModelSolution{ + * compute the steady state (2nd stage), and + * computes first order approximation + * + */ +class ModelSolution +{ public: - ModelSolution(const std::string& dynamicDllFile, size_t n_endo, size_t n_exo, const std::vector<size_t>& zeta_fwrd_arg, - const std::vector<size_t>& zeta_back_arg, const std::vector<size_t>& zeta_mixed_arg, - const std::vector<size_t>& zeta_static_arg, double qz_criterium); - virtual ~ModelSolution(){}; - void compute( VectorView& steadyState, const Vector& deepParams, Matrix& ghx, Matrix& ghu ) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException); + ModelSolution(const std::string &dynamicDllFile, size_t n_endo, size_t n_exo, const std::vector<size_t> &zeta_fwrd_arg, + const std::vector<size_t> &zeta_back_arg, const std::vector<size_t> &zeta_mixed_arg, + const std::vector<size_t> &zeta_static_arg, double qz_criterium); + virtual ~ModelSolution() {}; + void compute(VectorView &steadyState, const Vector &deepParams, Matrix &ghx, Matrix &ghu) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException); private: const size_t n_endo; @@ -56,12 +56,9 @@ private: DynamicModelDLL dynamicDLLp; Vector llXsteadyState; //Matrix jacobian; - void ComputeModelSolution( VectorView& steadyState, const Vector& deepParams, Matrix& ghx, Matrix& ghu ) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException); - void ComputeSteadyState( VectorView& steadyState, const Vector& deepParams); + void ComputeModelSolution(VectorView &steadyState, const Vector &deepParams, Matrix &ghx, Matrix &ghu) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException); + void ComputeSteadyState(VectorView &steadyState, const Vector &deepParams); }; - - - #endif // !defined(5ADFF920_9C74_46f5_9FE9_88AD4D4BBF19__INCLUDED_) diff --git a/mex/sources/estimation/Prior.hh b/mex/sources/estimation/Prior.hh index 4719d85af43e936e6572904400714f7bb82c15ce..2eb86825d3a40fd5ef7b5a301b56dff88e70ed45 100644 --- a/mex/sources/estimation/Prior.hh +++ b/mex/sources/estimation/Prior.hh @@ -187,7 +187,7 @@ public: }; // If x~InvGamma(a,b) , then 1/x ~Gamma(a,1/b) distribution -// i.e. Dynare lpdfig2(x*x,n,s) = lpdfgam(1/(x*x),s/2,2/n) - 2*log(x*x) +// i.e. Dynare lpdfig2(x*x,n,s) = lpdfgam(1/(x*x),s/2,2/n) - 2*log(x*x) struct InvGamma2_Prior : public Prior { public: diff --git a/mex/sources/estimation/Proposal.hh b/mex/sources/estimation/Proposal.hh index 7fef8de90b3f2c2c0dc42eb437f4857de1c3ce86..21aedddce021076d69d58e20c697c2cc1afe5762 100644 --- a/mex/sources/estimation/Proposal.hh +++ b/mex/sources/estimation/Proposal.hh @@ -63,7 +63,7 @@ public: public: Proposal(const VectorConstView &vJscale, const MatrixConstView &covariance); - virtual ~Proposal(){}; + virtual ~Proposal() {}; virtual void draw(Vector &mean, Vector &draw); virtual Matrix&getVar(); virtual int seed(); diff --git a/mex/sources/estimation/RandomWalkMetropolisHastings.cc b/mex/sources/estimation/RandomWalkMetropolisHastings.cc index 27191c5d3d821e6c0953b7a898d9c6eaf393cfe7..3eada5b0c413a4b5fb17c1a4d1e1107f3aaa154d 100644 --- a/mex/sources/estimation/RandomWalkMetropolisHastings.cc +++ b/mex/sources/estimation/RandomWalkMetropolisHastings.cc @@ -25,29 +25,29 @@ double RandomWalkMetropolisHastings::compute(VectorView &mhLogPostDens, MatrixView &mhParams, Matrix &steadyState, Vector &estParams, Vector &deepParams, const MatrixConstView &data, Matrix &Q, Matrix &H, - const size_t presampleStart, int &info, const size_t startDraw, size_t nMHruns, + const size_t presampleStart, int &info, const size_t startDraw, size_t nMHruns, LogPosteriorDensity &lpd, Proposal &pDD, EstimatedParametersDescription &epd) { //streambuf *likbuf, *drawbuf *backup; std::ofstream urandfilestr, drawfilestr; - urandfilestr.open ("urand.csv"); - drawfilestr.open ("paramdraws.csv"); + urandfilestr.open("urand.csv"); + drawfilestr.open("paramdraws.csv"); bool overbound; double newLogpost, logpost, urand; size_t count, accepted = 0; parDraw = estParams; - logpost = - lpd.compute(steadyState, estParams, deepParams, data, Q, H, presampleStart, info); + logpost = -lpd.compute(steadyState, estParams, deepParams, data, Q, H, presampleStart, info); for (size_t run = startDraw - 1; run < nMHruns; ++run) { - overbound=false; + overbound = false; pDD.draw(parDraw, newParDraw); - for (count=0;count<parDraw.getSize();++count) + for (count = 0; count < parDraw.getSize(); ++count) { - overbound=(newParDraw(count) < epd.estParams[count].lower_bound || newParDraw(count) > epd.estParams[count].upper_bound ); - if (overbound) + overbound = (newParDraw(count) < epd.estParams[count].lower_bound || newParDraw(count) > epd.estParams[count].upper_bound); + if (overbound) { newLogpost = -INFINITY; break; @@ -57,9 +57,9 @@ RandomWalkMetropolisHastings::compute(VectorView &mhLogPostDens, MatrixView &mhP { try { - newLogpost = - lpd.compute(steadyState, newParDraw, deepParams, data, Q, H, presampleStart, info); + newLogpost = -lpd.compute(steadyState, newParDraw, deepParams, data, Q, H, presampleStart, info); } - catch(const std::exception &e) + catch (const std::exception &e) { throw; // for now handle the system and other errors higher-up } @@ -68,7 +68,7 @@ RandomWalkMetropolisHastings::compute(VectorView &mhLogPostDens, MatrixView &mhP newLogpost = -INFINITY; } } - urand=pDD.selectionTestDraw(); + urand = pDD.selectionTestDraw(); if ((newLogpost > -INFINITY) && log(urand) < newLogpost-logpost) { parDraw = newParDraw; @@ -78,11 +78,9 @@ RandomWalkMetropolisHastings::compute(VectorView &mhLogPostDens, MatrixView &mhP mat::get_row(mhParams, run) = parDraw; mhLogPostDens(run) = logpost; - //urandfilestr.write(urand); urandfilestr << urand << "\n"; //"," - for (size_t c=0;c<newParDraw.getSize()-1;++c) + for (size_t c = 0; c < newParDraw.getSize()-1; ++c) drawfilestr << newParDraw(c) << ","; -// drawfilestr.write(newParDraw(i)); drawfilestr << newParDraw(newParDraw.getSize()-1) << "\n"; } diff --git a/mex/sources/estimation/RandomWalkMetropolisHastings.hh b/mex/sources/estimation/RandomWalkMetropolisHastings.hh index 02643eb30d0636e1ba0c968736a6088fcba53ec7..57cd6d9b93ae9d86c8668a033c4ccd23b2947239 100644 --- a/mex/sources/estimation/RandomWalkMetropolisHastings.hh +++ b/mex/sources/estimation/RandomWalkMetropolisHastings.hh @@ -40,10 +40,10 @@ public: parDraw(size), newParDraw(size) { }; - virtual ~RandomWalkMetropolisHastings(){}; + virtual ~RandomWalkMetropolisHastings() {}; virtual double compute(VectorView &mhLogPostDens, MatrixView &mhParams, Matrix &steadyState, Vector &estParams, Vector &deepParams, const MatrixConstView &data, Matrix &Q, Matrix &H, - const size_t presampleStart, int &info, const size_t startDraw, size_t nMHruns, + const size_t presampleStart, int &info, const size_t startDraw, size_t nMHruns, LogPosteriorDensity &logPosteriorDensity, Proposal &proposalDrawDistribution, EstimatedParametersDescription &epd); }; diff --git a/mex/sources/estimation/libmat/BlasBindings.hh b/mex/sources/estimation/libmat/BlasBindings.hh index 6010d2df09ea2d1814a4fd05434c0fee76780528..063fc1bd2404e390c348492f7f81676984f3b4f3 100644 --- a/mex/sources/estimation/libmat/BlasBindings.hh +++ b/mex/sources/estimation/libmat/BlasBindings.hh @@ -41,7 +41,7 @@ namespace blas } /* Level 2 */ - + //! Symmetric rank 1 operation: A = alpha*X*X' + A template<class Mat, class Vec> inline void @@ -163,7 +163,7 @@ namespace blas dsymm(side, uplo, &m, &n, &alpha, A.getData(), &lda, B.getData(), &ldb, &beta, C.getData(), &ldc); } - + } // End of namespace #endif diff --git a/mex/sources/estimation/libmat/DiscLyapFast.hh b/mex/sources/estimation/libmat/DiscLyapFast.hh index c02acc795b4d05d45125bf12e5f58f6e9ec93e50..eebb851d7c753a1c29c2e0646f5b416599606379 100644 --- a/mex/sources/estimation/libmat/DiscLyapFast.hh +++ b/mex/sources/estimation/libmat/DiscLyapFast.hh @@ -50,7 +50,8 @@ public: const int info; std::string message; DLPException(int info_arg, std::string message_arg) : - info(info_arg), message(message_arg) { + info(info_arg), message(message_arg) + { }; }; @@ -59,15 +60,15 @@ public: { mat::set_identity(I); }; - virtual ~DiscLyapFast(){}; + virtual ~DiscLyapFast() {}; template <class MatG, class MatV, class MatX > - void solve_lyap(const MatG &G, const MatV &V, MatX &X, double tol, size_t flag_ch) throw(DLPException); + void solve_lyap(const MatG &G, const MatV &V, MatX &X, double tol, size_t flag_ch) throw (DLPException); }; template <class MatG, class MatV, class MatX > void -DiscLyapFast::solve_lyap(const MatG &G, const MatV &V, MatX &X, double tol = 1e-16, size_t flag_ch = 0) throw(DLPException) +DiscLyapFast::solve_lyap(const MatG &G, const MatV &V, MatX &X, double tol = 1e-16, size_t flag_ch = 0) throw (DLPException) { P0 = V; P1 = V; diff --git a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc index 3d0d5d140f6a2c836368217b2b83039ed62891a7..f88b63116bf9433514d206f0fb6ecdcd77c98b56 100644 --- a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc +++ b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc @@ -24,8 +24,8 @@ double GeneralizedSchurDecomposition::criterium_static; -GeneralizedSchurDecomposition::GeneralizedSchurDecomposition(size_t n_arg, double criterium_arg) - : n(n_arg), criterium(criterium_arg) +GeneralizedSchurDecomposition::GeneralizedSchurDecomposition(size_t n_arg, double criterium_arg) : + n(n_arg), criterium(criterium_arg) { alphar = new double[n]; alphai = new double[n]; @@ -51,7 +51,7 @@ GeneralizedSchurDecomposition::~GeneralizedSchurDecomposition() lapack_int GeneralizedSchurDecomposition::selctg(const double *alphar, const double *alphai, const double *beta) { - return((*alphar * *alphar + *alphai * *alphai) < criterium_static * *beta * *beta); + return ((*alphar * *alphar + *alphai * *alphai) < criterium_static * *beta * *beta); } std::ostream & diff --git a/mex/sources/estimation/libmat/LapackBindings.hh b/mex/sources/estimation/libmat/LapackBindings.hh index 1ba29708231b8aa9b3bc9aae6a3ba4106b359cfd..6b166f4d3d084fc678b8d60fc9e921f7f8aadf34 100644 --- a/mex/sources/estimation/libmat/LapackBindings.hh +++ b/mex/sources/estimation/libmat/LapackBindings.hh @@ -41,7 +41,6 @@ namespace lapack return info; } - // calc Cholesky Decomposition based solution X to A*X=B // for A pos. def. and symmetric supplied as uppper/lower triangle // packed in a vector if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j; @@ -61,7 +60,6 @@ namespace lapack return info; } - } // End of namespace #endif diff --git a/mex/sources/estimation/libmat/Matrix.cc b/mex/sources/estimation/libmat/Matrix.cc index 20eecdd86e773c53a153e3bd4064af93397260eb..a38a32a9df1b8389d7e2b769cde994fcd661905a 100644 --- a/mex/sources/estimation/libmat/Matrix.cc +++ b/mex/sources/estimation/libmat/Matrix.cc @@ -44,7 +44,7 @@ Matrix::~Matrix() } Matrix & -Matrix::operator= (const Matrix &arg) +Matrix::operator=(const Matrix &arg) { assert(rows == arg.rows && cols == arg.cols); memcpy(data, arg.data, rows*cols*sizeof(double)); @@ -58,8 +58,8 @@ operator<<(std::ostream &out, const Matrix &M) return out; } -MatrixView::MatrixView(double *data_arg, size_t rows_arg, size_t cols_arg, size_t ld_arg) - : data(data_arg), rows(rows_arg), cols(cols_arg), ld(ld_arg) +MatrixView::MatrixView(double *data_arg, size_t rows_arg, size_t cols_arg, size_t ld_arg) : + data(data_arg), rows(rows_arg), cols(cols_arg), ld(ld_arg) { } @@ -71,7 +71,7 @@ operator<<(std::ostream &out, const MatrixView &M) } MatrixView & -MatrixView::operator= (const MatrixView &arg) +MatrixView::operator=(const MatrixView &arg) { assert(rows == arg.getRows() && cols == arg.getCols()); for (size_t j = 0; j < cols; j++) @@ -79,8 +79,8 @@ MatrixView::operator= (const MatrixView &arg) return *this; } -MatrixConstView::MatrixConstView(const double *data_arg, size_t rows_arg, size_t cols_arg, size_t ld_arg) - : data(data_arg), rows(rows_arg), cols(cols_arg), ld(ld_arg) +MatrixConstView::MatrixConstView(const double *data_arg, size_t rows_arg, size_t cols_arg, size_t ld_arg) : + data(data_arg), rows(rows_arg), cols(cols_arg), ld(ld_arg) { } diff --git a/mex/sources/estimation/libmat/Matrix.hh b/mex/sources/estimation/libmat/Matrix.hh index 858a0dcd951968e6f42df931dc8e9688d597a62e..09a4ef3d6593f9e15d9ea43ed3626c3c90b7591d 100644 --- a/mex/sources/estimation/libmat/Matrix.hh +++ b/mex/sources/estimation/libmat/Matrix.hh @@ -61,11 +61,11 @@ /*! Owns the data space for the elements */ class Matrix { - private: +private: //! Stored in column-major order, as in Fortran and MATLAB double *data; const size_t rows, cols; - public: +public: Matrix(size_t rows_arg, size_t cols_arg); Matrix(size_t size_arg); Matrix(const Matrix &arg); @@ -90,17 +90,17 @@ class Matrix } //! The copy assignment operator, which is not generated by the template assignment operator /*! See C++ standard, §12.8.9, in the footnote */ - Matrix &operator= (const Matrix &arg); + Matrix &operator=(const Matrix &arg); }; //! A contiguous submatrix of another matrix, implements the "mutable matrix concept" /*! Does not own the data space for the elements, so depends on another matrix */ class MatrixView { - private: +private: double *const data; const size_t rows, cols, ld; - public: +public: MatrixView(double *data_arg, size_t rows_arg, size_t cols_arg, size_t ld_arg); template<class Mat> MatrixView(Mat &arg, size_t row_offset, size_t col_offset, @@ -137,16 +137,16 @@ class MatrixView } //! The copy assignment operator, which is not generated by the template assignment operator /*! See C++ standard, §12.8.9, in the footnote */ - MatrixView &operator= (const MatrixView &arg); + MatrixView &operator=(const MatrixView &arg); }; //! Like MatrixView, but cannot be modified (implements the "matrix concept") class MatrixConstView { - private: +private: const double *const data; const size_t rows, cols, ld; - public: +public: MatrixConstView(const double *data_arg, size_t rows_arg, size_t cols_arg, size_t ld_arg); template<class Mat> MatrixConstView(const Mat &arg, size_t row_offset, size_t col_offset, @@ -181,9 +181,9 @@ namespace mat void print(std::ostream &out, const Mat &M) { - for(size_t i = 0; i < M.getRows(); i++) + for (size_t i = 0; i < M.getRows(); i++) { - for(size_t j = 0; j < M.getCols(); j++) + for (size_t j = 0; j < M.getCols(); j++) out << std::setw(13) << std::right << M(i, j) << " "; out << std::endl; } @@ -307,7 +307,7 @@ namespace mat assert(M.getRows() == M.getCols()); for (size_t i = 0; i < M.getRows(); i++) for (size_t j = 0; j < i; j++) - std::swap(M(i,j), M(j,i)); + std::swap(M(i, j), M(j, i)); } //! Computes M1 = M2' (even for rectangular matrices) @@ -439,9 +439,9 @@ namespace mat if (vToRows.size() == 0 && vToCols.size() == 0 && vrows.size() == 0 && vcols.size() == 0) a = b; - else if (vToRows.size() == 0 && vrows.size() == 0) // just reorder columns + else if (vToRows.size() == 0 && vrows.size() == 0) // just reorder columns reorderColumnsByVectors(a, vToCols, b, vcols); - else if (vToCols.size() == 0 && vcols.size() == 0) // just reorder rows + else if (vToCols.size() == 0 && vcols.size() == 0) // just reorder rows reorderRowsByVectors(a, vToRows, b, vrows); else { diff --git a/mex/sources/estimation/libmat/QRDecomposition.hh b/mex/sources/estimation/libmat/QRDecomposition.hh index f1236c285676aa8e2598c566e2f0040a400410dd..0ca6e85e406d9b7e550fc2926f14c2ac6f2658a1 100644 --- a/mex/sources/estimation/libmat/QRDecomposition.hh +++ b/mex/sources/estimation/libmat/QRDecomposition.hh @@ -39,7 +39,7 @@ public: \param[in] rows_arg Number of rows of the matrix to decompose \param[in] cols_arg Number of columns of the matrix to decompose \param[in] cols2_arg Number of columns of the matrix to be multiplied by Q - */ + */ QRDecomposition(size_t rows_arg, size_t cols_arg, size_t cols2_arg); virtual ~QRDecomposition(); //! Performs the QR decomposition of a matrix, and left-multiplies another matrix by Q diff --git a/mex/sources/estimation/libmat/VDVEigDecomposition.cc b/mex/sources/estimation/libmat/VDVEigDecomposition.cc index 706e7a7a89a6ad997d300b61c5bb86ad8e5bd7b9..fc294d0191554f7bba11c9ab1a41277482186a2a 100644 --- a/mex/sources/estimation/libmat/VDVEigDecomposition.cc +++ b/mex/sources/estimation/libmat/VDVEigDecomposition.cc @@ -19,22 +19,22 @@ #include "VDVEigDecomposition.hh" -VDVEigDecomposition::VDVEigDecomposition(const Matrix &m) throw(VDVEigException) : +VDVEigDecomposition::VDVEigDecomposition(const Matrix &m) throw (VDVEigException) : lda(m.getLd()), n(m.getCols()), lwork(-1), info(0), converged(false), V(m), D(n) { if (m.getRows() != m.getCols()) - throw(VDVEigException(info, "Matrix is not square in VDVEigDecomposition constructor")); + throw (VDVEigException(info, "Matrix is not square in VDVEigDecomposition constructor")); double tmpwork; dsyev("V", "U", &n, V.getData(), &lda, D.getData(), &tmpwork, &lwork, &info); lwork = (lapack_int) tmpwork; work = new double[lwork]; if (info < 0) - throw(VDVEigException(info, "Internal error in VDVEigDecomposition constructor")); + throw (VDVEigException(info, "Internal error in VDVEigDecomposition constructor")); } -VDVEigDecomposition::VDVEigDecomposition(size_t inn) throw(VDVEigException) : +VDVEigDecomposition::VDVEigDecomposition(size_t inn) throw (VDVEigException) : lda(inn), n(inn), lwork(3*inn-1), info(0), converged(false), V(inn), D(inn) { diff --git a/mex/sources/estimation/libmat/VDVEigDecomposition.hh b/mex/sources/estimation/libmat/VDVEigDecomposition.hh index 2449978aee7b92d554e4a21d8aa63921d321175c..e5096e405bb87002808fc5ef1ece4adce6c21795 100644 --- a/mex/sources/estimation/libmat/VDVEigDecomposition.hh +++ b/mex/sources/estimation/libmat/VDVEigDecomposition.hh @@ -47,28 +47,29 @@ public: const lapack_int info; std::string message; VDVEigException(lapack_int info_arg, std::string message_arg) : - info(info_arg), message(message_arg) { + info(info_arg), message(message_arg) + { }; }; -/** - * This constructor only creates optimal workspace using - * input matrix m - */ - VDVEigDecomposition(const Matrix &m) throw(VDVEigException); + /** + * This constructor only creates optimal workspace using + * input matrix m + */ + VDVEigDecomposition(const Matrix &m) throw (VDVEigException); -/** - * This constructoro only crates workspace using the size of - * the input matrix m - */ - VDVEigDecomposition(size_t n) throw(VDVEigException); + /** + * This constructoro only crates workspace using the size of + * the input matrix m + */ + VDVEigDecomposition(size_t n) throw (VDVEigException); virtual ~VDVEigDecomposition() { delete[] work; }; template <class Mat> - void calculate(const Mat &H) throw(VDVEigException); + void calculate(const Mat &H) throw (VDVEigException); // get eigenvalues Vector & getD() @@ -91,14 +92,14 @@ public: template <class Mat> void -VDVEigDecomposition::calculate(const Mat &m) throw(VDVEigException) +VDVEigDecomposition::calculate(const Mat &m) throw (VDVEigException) { info = 0; if (m.getRows() != m.getCols()) - throw(VDVEigException(info, "Matrix is not square in VDVEigDecomposition calculate")); + throw (VDVEigException(info, "Matrix is not square in VDVEigDecomposition calculate")); if (m.getCols() != (size_t) n || m.getLd() != (size_t) lda) - throw(VDVEigException(info, "Matrix not matching VDVEigDecomposition class")); + throw (VDVEigException(info, "Matrix not matching VDVEigDecomposition class")); double tmpwork; lapack_int tmplwork = -1; @@ -113,7 +114,7 @@ VDVEigDecomposition::calculate(const Mat &m) throw(VDVEigException) dsyev("V", "U", &n, V.getData(), &lda, D.getData(), work, &lwork, &info); if (info < 0) - throw(VDVEigException(info, "Internal error in VDVEigDecomposition calculation")); + throw (VDVEigException(info, "Internal error in VDVEigDecomposition calculation")); converged = true; if (info) converged = false; diff --git a/mex/sources/estimation/libmat/Vector.cc b/mex/sources/estimation/libmat/Vector.cc index 34d873a761736af2100cbdffde294434bcdae81e..dac5d43426dae66672f1f83e3ce2482eaec85be9 100644 --- a/mex/sources/estimation/libmat/Vector.cc +++ b/mex/sources/estimation/libmat/Vector.cc @@ -39,7 +39,7 @@ Vector::~Vector() } Vector & -Vector::operator= (const Vector &arg) +Vector::operator=(const Vector &arg) { assert(size == arg.size); memcpy(data, arg.data, size*sizeof(double)); @@ -53,25 +53,25 @@ operator<<(std::ostream &out, const Vector &V) return out; } -VectorView::VectorView(double *data_arg, size_t size_arg, size_t stride_arg) - : data(data_arg), size(size_arg), stride(stride_arg) +VectorView::VectorView(double *data_arg, size_t size_arg, size_t stride_arg) : + data(data_arg), size(size_arg), stride(stride_arg) { } -VectorView::VectorView(Vector &arg, size_t offset, size_t size_arg) - : data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) +VectorView::VectorView(Vector &arg, size_t offset, size_t size_arg) : + data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) { assert(offset < arg.getSize() && offset + size <= arg.getSize()); } -VectorView::VectorView(VectorView &arg, size_t offset, size_t size_arg) - : data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) +VectorView::VectorView(VectorView &arg, size_t offset, size_t size_arg) : + data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) { assert(offset < arg.getSize() && offset + size <= arg.getSize()); } VectorView & -VectorView::operator= (const VectorView &arg) +VectorView::operator=(const VectorView &arg) { assert(size == arg.getSize()); double *p1; @@ -81,25 +81,25 @@ VectorView::operator= (const VectorView &arg) return *this; } -VectorConstView::VectorConstView(const double *data_arg, size_t size_arg, size_t stride_arg) - : data(data_arg), size(size_arg), stride(stride_arg) +VectorConstView::VectorConstView(const double *data_arg, size_t size_arg, size_t stride_arg) : + data(data_arg), size(size_arg), stride(stride_arg) { } -VectorConstView::VectorConstView(const Vector &arg, size_t offset, size_t size_arg) - : data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) +VectorConstView::VectorConstView(const Vector &arg, size_t offset, size_t size_arg) : + data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) { assert(offset < arg.getSize() && offset + size <= arg.getSize()); } -VectorConstView::VectorConstView(const VectorView &arg, size_t offset, size_t size_arg) - : data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) +VectorConstView::VectorConstView(const VectorView &arg, size_t offset, size_t size_arg) : + data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) { assert(offset < arg.getSize() && offset + size <= arg.getSize()); } -VectorConstView::VectorConstView(const VectorConstView &arg, size_t offset, size_t size_arg) - : data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) +VectorConstView::VectorConstView(const VectorConstView &arg, size_t offset, size_t size_arg) : + data(arg.getData() + offset*arg.getStride()), size(size_arg), stride(arg.getStride()) { assert(offset < arg.getSize() && offset + size <= arg.getSize()); } diff --git a/mex/sources/estimation/libmat/Vector.hh b/mex/sources/estimation/libmat/Vector.hh index cfedb52e79efaf8a035e8ad53eb4fe23ab253904..f8d8cfaffdf78c61835e88debe958d1c3d678846 100644 --- a/mex/sources/estimation/libmat/Vector.hh +++ b/mex/sources/estimation/libmat/Vector.hh @@ -57,10 +57,10 @@ /*! Owns the data space for the elements */ class Vector { - private: +private: double *data; const size_t size; - public: +public: Vector(size_t size_arg); Vector(const Vector &arg); virtual ~Vector(); @@ -73,11 +73,11 @@ class Vector inline const double &operator() (size_t i) const { return data[i]; } //! Assignment operator, only works for vectors of same size template<class Vec> - Vector &operator= (const Vec &arg) + Vector &operator=(const Vec &arg) { assert(size == arg.getSize()); const double *p2 = arg.getData(); - for(double *p1 = data; p1 < data + size; p1++) + for (double *p1 = data; p1 < data + size; p1++) { *p1 = *p2; p2 += arg.getStride(); @@ -86,7 +86,7 @@ class Vector } //! The copy assignment operator, which is not generated by the template assignment operator /*! See C++ standard, §12.8.9, in the footnote */ - Vector &operator= (const Vector &arg); + Vector &operator=(const Vector &arg); }; //! A vector view (i.e. a subvector of another vector, or a row or column of a matrix), implements the "mutable vector concept" @@ -128,7 +128,7 @@ public: } //! The copy assignment operator, which is not generated by the template assignment operator /*! See C++ standard, §12.8.9, in the footnote */ - VectorView &operator= (const VectorView &arg); + VectorView &operator=(const VectorView &arg); }; //! Like a VectorView, but the data cannot be modified (implements the "vector concept") @@ -140,12 +140,12 @@ private: public: VectorConstView(const double *data_arg, size_t size_arg, size_t stride_arg); /* Can't use a template for the 3 constructors below: this would override the - constructor which uses a pointer, because the argument list is the same */ + constructor which uses a pointer, because the argument list is the same */ VectorConstView(const Vector &arg, size_t offset, size_t size_arg); VectorConstView(const VectorView &arg, size_t offset, size_t size_arg); VectorConstView(const VectorConstView &arg, size_t offset, size_t size_arg); - virtual ~VectorConstView(){}; + virtual ~VectorConstView() {}; inline size_t getSize() const { return size; } inline size_t getStride() const { return stride; } inline const double *getData() const { return data; } @@ -235,7 +235,7 @@ namespace vec meanSumMinMax(double &sum, double &min, double &max, const Vec &v) { sum = 0; - min=max=v(0); + min = max = v(0); const double *p = v.getData(); while (p < v.getData() + v.getSize() * v.getStride()) { @@ -243,7 +243,7 @@ namespace vec max = (*p); if ((*p) < min) min = (*p); - sum+=*p; + sum += *p; p += v.getStride(); } return sum/v.getSize(); diff --git a/mex/sources/estimation/logMHMCMCposterior.cc b/mex/sources/estimation/logMHMCMCposterior.cc index c3e9f3fa4390a316c3d11636f963c7126fda0412..e3168e2bf5cc9fbf4edf0f17e5a69e1e2d371f93 100644 --- a/mex/sources/estimation/logMHMCMCposterior.cc +++ b/mex/sources/estimation/logMHMCMCposterior.cc @@ -31,7 +31,7 @@ #if defined MATLAB_MEX_FILE # include "mat.h" #else // OCTAVE_MEX_FILE e.t.c. -#include "matio.h" +# include "matio.h" #endif #if defined(_WIN32) || defined(__CYGWIN32__) || defined(WINDOWS) @@ -105,12 +105,12 @@ fillEstParamsInfo(const mxArray *estim_params_info, EstimatedParameter::pType ty int sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, Matrix &steadyState, Vector &estParams, Vector &deepParams, const MatrixConstView &data, - Matrix &Q, Matrix &H, size_t presampleStart, int &info, const VectorConstView &nruns, + Matrix &Q, Matrix &H, size_t presampleStart, int &info, const VectorConstView &nruns, size_t fblock, size_t nBlocks, Proposal pdd, EstimatedParametersDescription &epd, const std::string &resultsFileStem, size_t console_mode, size_t load_mh_file) { enum {iMin, iMax}; - int iret=0; // return value + int iret = 0; // return value std::vector<size_t> OpenOldFile(nBlocks, 0); size_t jloop = 0, irun, j; // counters double dsum, dmax, dmin, sux = 0, jsux = 0; @@ -130,28 +130,28 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, Matrix MinMax(npar, 2); const mxArray *InitSizeArrayPtr = mexGetVariablePtr("caller", "InitSizeArray"); - if (InitSizeArrayPtr==NULL) + if (InitSizeArrayPtr == NULL) { mexPrintf("Metropolis-Hastings myinputs field InitSizeArrayPtr Initialisation failed!\n"); - return(-1); + return (-1); } const VectorConstView InitSizeArrayVw(mxGetPr(InitSizeArrayPtr), nBlocks, 1); Vector InitSizeArray(InitSizeArrayVw.getSize()); InitSizeArray = InitSizeArrayVw; //const mxArray *flinePtr = mxGetField(myinputs, 0, "fline"); const mxArray *flinePtr = mexGetVariable("caller", "fline"); - if (flinePtr==NULL) + if (flinePtr == NULL) { mexPrintf("Metropolis-Hastings myinputs field fline Initialisation failed!\n"); - return(-1); + return (-1); } VectorView fline(mxGetPr(flinePtr), nBlocks, 1); mxArray *NewFileArrayPtr = mexGetVariable("caller", "NewFile"); - if (NewFileArrayPtr==NULL) + if (NewFileArrayPtr == NULL) { mexPrintf("Metropolis-Hastings myinputs fields NewFileArrayPtr Initialisation failed!\n"); - return(-1); + return (-1); } VectorView NewFileVw(mxGetPr(NewFileArrayPtr), nBlocks, 1); //Vector NewFile(NewFileVw.getSize()); @@ -169,16 +169,16 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, const mxArray *record = mexGetVariable("caller", "record"); //const mxArray *record = mxGetField(myinputs, 0, "record"); - if (record==NULL) + if (record == NULL) { mexPrintf("Metropolis-Hastings record Initialisation failed!\n"); - return(-1); + return (-1); } mxArray *AcceptationRatesPtr = mxGetField(record, 0, "AcceptationRates"); - if (AcceptationRatesPtr==NULL) + if (AcceptationRatesPtr == NULL) { mexPrintf("Metropolis-Hastings record AcceptationRatesPtr Initialisation failed!\n"); - return(-1); + return (-1); } VectorView AcceptationRates(mxGetPr(AcceptationRatesPtr), nBlocks, 1); @@ -199,7 +199,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, waitBarRhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); std::string barTitle; std::stringstream ssbarTitle; - if (console_mode==0) + if (console_mode == 0) { ssbarTitle.clear(); ssbarTitle.str(""); @@ -243,7 +243,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, OpenOldFile[b] = 1; } } // end if - if (console_mode==0) + if (console_mode == 0) { ssbarTitle.clear(); ssbarTitle.str(""); @@ -264,20 +264,20 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, // new or different size result arrays/matrices currInitSizeArray = (size_t) InitSizeArray(b-1); if (mxMhLogPostDensPtr) - mxDestroyArray(mxMhLogPostDensPtr); // log post density array + mxDestroyArray(mxMhLogPostDensPtr); // log post density array mxMhLogPostDensPtr = mxCreateDoubleMatrix(currInitSizeArray, 1, mxREAL); - if( mxMhLogPostDensPtr == NULL) + if (mxMhLogPostDensPtr == NULL) { mexPrintf("Metropolis-Hastings mxMhLogPostDensPtr Initialisation failed!\n"); - return(-1); + return (-1); } if (mxMhParamDrawsPtr) - mxDestroyArray(mxMhParamDrawsPtr); // accepted MCMC MH draws + mxDestroyArray(mxMhParamDrawsPtr); // accepted MCMC MH draws mxMhParamDrawsPtr = mxCreateDoubleMatrix(currInitSizeArray, npar, mxREAL); - if( mxMhParamDrawsPtr == NULL) + if (mxMhParamDrawsPtr == NULL) { mexPrintf("Metropolis-Hastings mxMhParamDrawsPtr Initialisation failed!\n"); - return(-1); + return (-1); } } @@ -294,10 +294,10 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, } else { - int start[2]={0,0},edge[2]={2,2},stride[2]={1,1}, err=0; + int start[2] = {0, 0}, edge[2] = {2, 2}, stride[2] = {1, 1}, err = 0; mexPrintf("MHMCMC: Using interim partial draws file %s \n", mhFName.c_str()); -// matvar = Mat_VarReadInfo(drawmat, "x2"); - matvar = Mat_VarReadInfo(drawmat, (char *)"x2"); + // matvar = Mat_VarReadInfo(drawmat, "x2"); + matvar = Mat_VarReadInfo(drawmat, (char *) "x2"); if (matvar == NULL) { fline(b) = 1; @@ -309,7 +309,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, // GetVariable(drawmat, "x2"); dims[0] = matvar->dims[0]-1; dims[1] = matvar->dims[1]-1; - err=Mat_VarReadData(drawmat,matvar,mxGetPr(mxMhParamDrawsPtr),start,stride,matvar->dims); + err = Mat_VarReadData(drawmat, matvar, mxGetPr(mxMhParamDrawsPtr), start, stride, matvar->dims); if (err) { fline(b) = 1; @@ -319,7 +319,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, Mat_VarFree(matvar); } //mxMhLogPostDensPtr = Mat_GetVariable(drawmat, "logpo2"); - matvar = Mat_VarReadInfo(drawmat, (char*)"logpo2"); + matvar = Mat_VarReadInfo(drawmat, (char *) "logpo2"); if (matvar == NULL) { fline(b) = 1; @@ -331,7 +331,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, // GetVariable(drawmat, "x2"); dims[0] = matvar->dims[0]-1; dims[1] = matvar->dims[1]-1; - err=Mat_VarReadData(drawmat,matvar,mxGetPr(mxMhLogPostDensPtr),start,stride,matvar->dims); + err = Mat_VarReadData(drawmat, matvar, mxGetPr(mxMhLogPostDensPtr), start, stride, matvar->dims); if (err) { fline(b) = 1; @@ -360,20 +360,20 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, // new or different size result arrays/matrices currInitSizeArray = (size_t) InitSizeArray(b-1); if (mxMhLogPostDensPtr) - mxDestroyArray(mxMhLogPostDensPtr); // log post density array + mxDestroyArray(mxMhLogPostDensPtr); // log post density array mxMhLogPostDensPtr = mxCreateDoubleMatrix(currInitSizeArray, 1, mxREAL); - if( mxMhLogPostDensPtr == NULL) + if (mxMhLogPostDensPtr == NULL) { mexPrintf("Metropolis-Hastings mxMhLogPostDensPtr Initialisation failed!\n"); - return(-1); + return (-1); } if (mxMhParamDrawsPtr) - mxDestroyArray(mxMhParamDrawsPtr); // accepted MCMC MH draws + mxDestroyArray(mxMhParamDrawsPtr); // accepted MCMC MH draws mxMhParamDrawsPtr = mxCreateDoubleMatrix(currInitSizeArray, npar, mxREAL); - if( mxMhParamDrawsPtr == NULL) + if (mxMhParamDrawsPtr == NULL) { mexPrintf("Metropolis-Hastings mxMhParamDrawsPtr Initialisation failed!\n"); - return(-1); + return (-1); } } startParams = LastParametersRow; @@ -382,62 +382,62 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, try { jsux = rwmh.compute(mhLogPostDens, mhParamDraws, steadyState, startParams, deepParams, data, Q, H, - presampleStart, info, irun, currInitSizeArray, lpd, pdd, epd); + presampleStart, info, irun, currInitSizeArray, lpd, pdd, epd); irun = currInitSizeArray; sux += jsux*currInitSizeArray; j += currInitSizeArray; //j=j+1; } catch (const TSException &tse) { - iret=-100; + iret = -100; mexPrintf(" TSException Exception in RandomWalkMH dynamic_dll: %s \n", (tse.getMessage()).c_str()); goto cleanup; } catch (const DecisionRules::BlanchardKahnException &bke) { - iret=-90; + iret = -90; mexPrintf(" Too many Blanchard-Kahn Exceptions in RandomWalkMH : n_fwrd_vars %d n_explosive_eigenvals %d \n", bke.n_fwrd_vars, bke.n_explosive_eigenvals); goto cleanup; - } + } catch (const GeneralizedSchurDecomposition::GSDException &gsde) { - iret=-80; + iret = -80; mexPrintf(" GeneralizedSchurDecomposition Exception in RandomWalkMH: info %d, n %d \n", gsde.info, gsde.n); goto cleanup; } catch (const LUSolver::LUException &lue) { - iret=-70; + iret = -70; mexPrintf(" LU Exception in RandomWalkMH : info %d \n", lue.info); goto cleanup; } catch (const VDVEigDecomposition::VDVEigException &vdve) { - iret=-60; + iret = -60; mexPrintf(" VDV Eig Exception in RandomWalkMH : %s , info: %d\n", vdve.message.c_str(), vdve.info); goto cleanup; } catch (const DiscLyapFast::DLPException &dlpe) { - iret=-50; + iret = -50; mexPrintf(" Lyapunov solver Exception in RandomWalkMH : %s , info: %d\n", dlpe.message.c_str(), dlpe.info); goto cleanup; } catch (const std::runtime_error &re) { - iret=-3; + iret = -3; mexPrintf(" Runtime Error Exception in RandomWalkMH: %s \n", re.what()); goto cleanup; } catch (const std::exception &e) { - iret=-2; + iret = -2; mexPrintf(" Standard System Exception in RandomWalkMH: %s \n", e.what()); goto cleanup; } catch (...) { - iret=-1000; + iret = -1000; mexPrintf(" Unknown unhandled Exception in RandomWalkMH! %s \n"); goto cleanup; } @@ -500,21 +500,21 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, mexPrintf("Error in MH: Can not open draws Mat file for writing: %s \n", mhFName.c_str()); exit(1); } - dims[0]= currInitSizeArray; - dims[1]= npar; - matvar = Mat_VarCreate("x2",MAT_C_DOUBLE,MAT_T_DOUBLE,2,dims,mxGetPr(mxMhParamDrawsPtr),0); - matfStatus=Mat_VarWrite( drawmat, matvar, 0); - Mat_VarFree(matvar); + dims[0] = currInitSizeArray; + dims[1] = npar; + matvar = Mat_VarCreate("x2", MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, mxGetPr(mxMhParamDrawsPtr), 0); + matfStatus = Mat_VarWrite(drawmat, matvar, 0); + Mat_VarFree(matvar); if (matfStatus) { mexPrintf("Error in MH: Can not use draws Mat file for writing: %s \n", mhFName.c_str()); exit(1); } //matfStatus = matPutVariable(drawmat, "logpo2", mxMhLogPostDensPtr); - dims[1]= 1; - matvar = Mat_VarCreate("logpo2",MAT_C_DOUBLE,MAT_T_DOUBLE,2,dims,mxGetPr(mxMhLogPostDensPtr),0); - matfStatus=Mat_VarWrite( drawmat, matvar, 0); - Mat_VarFree(matvar); + dims[1] = 1; + matvar = Mat_VarCreate("logpo2", MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, mxGetPr(mxMhLogPostDensPtr), 0); + matfStatus = Mat_VarWrite(drawmat, matvar, 0); + Mat_VarFree(matvar); if (matfStatus) { mexPrintf("Error in MH: Can not usee draws Mat file for writing: %s \n", mhFName.c_str()); @@ -556,11 +556,11 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, jsux = 0; LastParametersRow = mat::get_row(mhParamDraws, currInitSizeArray-1); //x2(end,:); LastLogLiK(b-1) = mhLogPostDens(currInitSizeArray-1); //logpo2(end); - InitSizeArray(b-1) = std::min( (size_t) nruns(b-1)-j, MAX_nruns); + InitSizeArray(b-1) = std::min((size_t) nruns(b-1)-j, MAX_nruns); // initialization of next file if necessary if (InitSizeArray(b-1)) { - NewFileVw(b-1)++;// = NewFile(b-1) + 1; + NewFileVw(b-1)++; // = NewFile(b-1) + 1; irun = 1; } // end //irun++; @@ -584,21 +584,21 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, mexPrintf("MH Warning: due to error NewFile is NOT set !! \n"); // Cleanup -mexPrintf("MH Cleanup !! \n"); + mexPrintf("MH Cleanup !! \n"); -cleanup: + cleanup: if (mxMhLogPostDensPtr) - mxDestroyArray(mxMhLogPostDensPtr); // delete log post density array + mxDestroyArray(mxMhLogPostDensPtr); // delete log post density array if (mxMhParamDrawsPtr) - mxDestroyArray(mxMhParamDrawsPtr); // delete accepted MCMC MH draws + mxDestroyArray(mxMhParamDrawsPtr); // delete accepted MCMC MH draws #ifdef MATLAB_MEX_FILE - // Waitbar - if (console_mode==0) + // Waitbar + if (console_mode == 0) { - // Bellow call to close waitbar seems to cause crashes and it is for + // Bellow call to close waitbar seems to cause crashes and it is for // now left commented out and the waitbar neeeds to be closed manually - // alternativelly, call with options_.console_mode=1; + // alternativelly, call with options_.console_mode=1; //mexCallMATLAB(0, NULL, 1, waitBarLhs, "close"); //mxDestroyArray(waitBarLhs[0]); mxDestroyArray(waitBarRhs[1]); @@ -607,8 +607,8 @@ cleanup: #endif // return error code or last line run in the last MH block sub-array - if (iret==0) - iret=(int)irun; + if (iret == 0) + iret = (int) irun; return iret; } @@ -717,11 +717,11 @@ logMCMCposterior(const VectorConstView &estParams, const MatrixConstView &data, const mxArray *bayestopt_ = mexGetVariablePtr("global", "bayestopt_"); const Matrix Jscale(n_estParams); const VectorConstView vJscale(mxGetPr(mxGetField(bayestopt_, 0, "jscale")), n_estParams, 1); - Proposal pdd(vJscale,D); + Proposal pdd(vJscale, D); //sample MHMCMC draws and get get last line run in the last MH block sub-array int lastMHblockArrayLine = sampleMHMC(lpd, rwmh, steadyState, estParams2, deepParams, data, Q, H, presample, info, - nMHruns, fblock, nBlocks, pdd, epd, resultsFileStem, console_mode, load_mh_file); + nMHruns, fblock, nBlocks, pdd, epd, resultsFileStem, console_mode, load_mh_file); // Cleanups for (std::vector<EstimatedParameter>::iterator it = estParamsInfo.begin(); @@ -741,7 +741,7 @@ mexFunction(int nlhs, mxArray *plhs[], mexErrMsgTxt("logposterior: exactly one return argument is required."); plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); -// Check and retrieve the arguments + // Check and retrieve the arguments if (!mxIsDouble(prhs[0]) || mxGetN(prhs[0]) != 1) mexErrMsgTxt("logposterior: First argument must be a column vector of double-precision numbers"); diff --git a/mex/sources/estimation/logposterior.cc b/mex/sources/estimation/logposterior.cc index e3590b6b935778f3d52838f00240ba46f72c2908..42a2ec7339b9248123d4addcea60b462b72dfd41 100644 --- a/mex/sources/estimation/logposterior.cc +++ b/mex/sources/estimation/logposterior.cc @@ -177,7 +177,7 @@ logposterior(const VectorConstView &estParams, const MatrixConstView &data, // Allocate LogPosteriorDensity object int info; LogPosteriorDensity lpd(dynamicDllFile, epd, n_endo, n_exo, zeta_fwrd, zeta_back, zeta_mixed, zeta_static, - qz_criterium, varobs, riccati_tol, lyapunov_tol, info); + qz_criterium, varobs, riccati_tol, lyapunov_tol, info); // Construct arguments of compute() method Matrix steadyState(n_endo, 1); @@ -189,7 +189,7 @@ logposterior(const VectorConstView &estParams, const MatrixConstView &data, deepParams = VectorConstView(mxGetPr(mxGetField(M_, 0, "params")), n_param, 1); Matrix Q(n_exo); Q = MatrixConstView(mxGetPr(mxGetField(M_, 0, "Sigma_e")), n_exo, n_exo, n_exo); - + Matrix H(n_varobs); const mxArray *H_mx = mxGetField(M_, 0, "H"); if (mxGetM(H_mx) == 1 && mxGetN(H_mx) == 1 && *mxGetPr(H_mx) == 0) @@ -198,7 +198,7 @@ logposterior(const VectorConstView &estParams, const MatrixConstView &data, H = MatrixConstView(mxGetPr(mxGetField(M_, 0, "H")), n_varobs, n_varobs, n_varobs); // Compute the posterior - double logPD =lpd.compute(steadyState, estParams2, deepParams, data, Q, H, presample, info); + double logPD = lpd.compute(steadyState, estParams2, deepParams, data, Q, H, presample, info); // Cleanups for (std::vector<EstimatedParameter>::iterator it = estParamsInfo.begin(); @@ -212,7 +212,7 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { - if (nrhs != 3 || nlhs !=2) + if (nrhs != 3 || nlhs != 2) DYN_MEX_FUNC_ERR_MSG_TXT("logposterior: exactly three input arguments and two output arguments are required."); // Check and retrieve the arguments @@ -232,7 +232,7 @@ mexFunction(int nlhs, mxArray *plhs[], char *mexext_mx = mxArrayToString(prhs[2]); std::string - mexext(mexext_mx); + mexext(mexext_mx); mxFree(mexext_mx); // Compute and return the value diff --git a/mex/sources/estimation/tests/test-dr.cc b/mex/sources/estimation/tests/test-dr.cc index 8a524e90078a3b004a704a1dc909dac2f2b846a1..c6d49c18d5d88f4b0ec3bcec5c9512aa48721a45 100644 --- a/mex/sources/estimation/tests/test-dr.cc +++ b/mex/sources/estimation/tests/test-dr.cc @@ -141,11 +141,11 @@ main(int argc, char **argv) { dr.compute(jacobian, g_y, g_u); } - catch(GeneralizedSchurDecomposition::GSDException &e) + catch (GeneralizedSchurDecomposition::GSDException &e) { std::cerr << e << std::endl; } - catch(DecisionRules::BlanchardKahnException &e) + catch (DecisionRules::BlanchardKahnException &e) { std::cerr << e << std::endl; } diff --git a/mex/sources/estimation/tests/testInitKalman.cc b/mex/sources/estimation/tests/testInitKalman.cc index 220011da86ee3204d055e266640d64b957658379..4998ffec085dd1d3f70517b5fea77cabfffad271 100644 --- a/mex/sources/estimation/tests/testInitKalman.cc +++ b/mex/sources/estimation/tests/testInitKalman.cc @@ -40,8 +40,7 @@ main(int argc, char **argv) std::vector<size_t> zeta_static_arg; //std::vector<size_t> double qz_criterium = 1.000001; //1.0+1.0e-9; - Vector - steadyState(n_endo), deepParams(npar); + Vector steadyState(n_endo), deepParams(npar); double dYSparams [] = { 1.000199998312523, @@ -62,8 +61,8 @@ main(int argc, char **argv) }; double vcov[] = { - 0.001256631601, 0.0, - 0.0, 0.000078535044 + 0.001256631601, 0.0, + 0.0, 0.000078535044 }; double dparams[] = { @@ -76,11 +75,9 @@ main(int argc, char **argv) 0.0100 }; - VectorView - modParamsVW(dparams, npar, 1); + VectorView modParamsVW(dparams, npar, 1); deepParams = modParamsVW; - VectorView - steadyStateVW(dYSparams, n_endo, 1); + VectorView steadyStateVW(dYSparams, n_endo, 1); steadyState = steadyStateVW; std::cout << "Vector deepParams: " << std::endl << deepParams << std::endl; std::cout << "Vector steadyState: " << std::endl << steadyState << std::endl; @@ -117,35 +114,29 @@ main(int argc, char **argv) size_t n_vbm = zeta_varobs_back_mixed.size(); - Matrix - T(n_vbm, n_vbm), R(n_vbm, n_exo), - RQRt(n_vbm, n_vbm), Pstar(n_vbm, n_vbm), - Pinf(n_vbm, n_vbm), Q(n_exo); + Matrix T(n_vbm, n_vbm), R(n_vbm, n_exo), + RQRt(n_vbm, n_vbm), Pstar(n_vbm, n_vbm), + Pinf(n_vbm, n_vbm), Q(n_exo); - MatrixView - vCovVW(vcov, n_exo, n_exo, n_exo); + MatrixView vCovVW(vcov, n_exo, n_exo, n_exo); Q = vCovVW; double lyapunov_tol = 1e-16; int info = 0; size_t nobs = 2; - Matrix yView(nobs,192); // dummy + Matrix yView(nobs, 192); // dummy yView.setAll(0.2); - const MatrixConstView dataView(yView, 0, 0, nobs, yView.getCols() ); // dummy - Matrix yDetrendView(nobs,yView.getCols()); // dummy - MatrixView dataDetrendView(yDetrendView, 0, 0, nobs, yDetrendView.getCols() ); // dummy + const MatrixConstView dataView(yView, 0, 0, nobs, yView.getCols()); // dummy + Matrix yDetrendView(nobs, yView.getCols()); // dummy + MatrixView dataDetrendView(yDetrendView, 0, 0, nobs, yDetrendView.getCols()); // dummy - - - const Vector - xparams1(0); // dummy + const Vector xparams1(0); // dummy double penalty = 1e8; - InitializeKalmanFilter - initializeKalmanFilter(modName, n_endo, n_exo, - zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, - zeta_varobs_back_mixed, qz_criterium, - lyapunov_tol, info); + InitializeKalmanFilter initializeKalmanFilter(modName, n_endo, n_exo, + zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, + zeta_varobs_back_mixed, qz_criterium, + lyapunov_tol, info); std::cout << "Initialize KF with Q: " << std::endl << Q << std::endl; diff --git a/mex/sources/estimation/tests/testKalman.cc b/mex/sources/estimation/tests/testKalman.cc index 1a59b2fb90cdeb390d2d156257d867c5c8bd60f8..2befecfb3d80a5e2451ec196d82011c45a92c1eb 100644 --- a/mex/sources/estimation/tests/testKalman.cc +++ b/mex/sources/estimation/tests/testKalman.cc @@ -40,8 +40,7 @@ main(int argc, char **argv) std::vector<size_t> zeta_static_arg; //std::vector<size_t> double qz_criterium = 1.000001; //1.0+1.0e-9; - Vector - steadyState(n_endo), deepParams(npar); + Vector steadyState(n_endo), deepParams(npar); double dYSparams [] = { 1.000199998312523, @@ -62,8 +61,8 @@ main(int argc, char **argv) }; double vcov[] = { - 0.001256631601, 0.0, - 0.0, 0.000078535044 + 0.001256631601, 0.0, + 0.0, 0.000078535044 }; double dparams[] = { @@ -76,11 +75,9 @@ main(int argc, char **argv) 0.0100 }; - VectorView - modParamsVW(dparams, npar, 1); + VectorView modParamsVW(dparams, npar, 1); deepParams = modParamsVW; - VectorView - steadyStateVW(dYSparams, n_endo, 1); + VectorView steadyStateVW(dYSparams, n_endo, 1); steadyState = steadyStateVW; std::cout << "Vector deepParams: " << std::endl << deepParams << std::endl; std::cout << "Vector steadyState: " << std::endl << steadyState << std::endl; @@ -109,31 +106,30 @@ main(int argc, char **argv) Matrix Q(n_exo), H(nobs); H.setAll(0.0); - MatrixView - vCovVW(vcov, n_exo, n_exo, n_exo); + MatrixView vCovVW(vcov, n_exo, n_exo, n_exo); Q = vCovVW; std::cout << "Matrix Q: " << std::endl << Q << std::endl; double lyapunov_tol = 1e-16; double riccati_tol = 1e-16; int info = 0; - Matrix yView(nobs,192); // dummy + Matrix yView(nobs, 192); // dummy yView.setAll(0.2); - const MatrixConstView dataView(yView, 0, 0, nobs, yView.getCols() ); // dummy - Matrix yDetrendView(nobs,yView.getCols()); // dummy - MatrixView dataDetrendView(yDetrendView, 0, 0, nobs, yDetrendView.getCols() ); // dummy + const MatrixConstView dataView(yView, 0, 0, nobs, yView.getCols()); // dummy + Matrix yDetrendView(nobs, yView.getCols()); // dummy + MatrixView dataDetrendView(yDetrendView, 0, 0, nobs, yDetrendView.getCols()); // dummy Vector vll(yView.getCols()); - VectorView vwll(vll,0,vll.getSize()); - + VectorView vwll(vll, 0, vll.getSize()); + double penalty = 1e8; KalmanFilter kalman(modName, n_endo, n_exo, - zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium, - varobs_arg, riccati_tol, lyapunov_tol, info); + zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium, + varobs_arg, riccati_tol, lyapunov_tol, info); - size_t start=0, period=0; - double ll=kalman.compute(dataView, steadyStateVW, Q, H, deepParams, - vwll, dataDetrendView, start, period, penalty, info); + size_t start = 0, period = 0; + double ll = kalman.compute(dataView, steadyStateVW, Q, H, deepParams, + vwll, dataDetrendView, start, period, penalty, info); std::cout << "ll: " << std::endl << ll << std::endl; } diff --git a/mex/sources/estimation/tests/testModelSolution.cc b/mex/sources/estimation/tests/testModelSolution.cc index 20709a049f1aa93a08dab76993426de1aa7430ce..5117a19fca6f7ced4aaad5fc2feabc2a2f2ae98d 100644 --- a/mex/sources/estimation/tests/testModelSolution.cc +++ b/mex/sources/estimation/tests/testModelSolution.cc @@ -18,12 +18,12 @@ */ // Test for ModelSolution -// Uses fs2000k2.mod and its ..._dynamic.mexw32 +// Uses fs2000k2.mod and its ..._dynamic.mexw32 #include "ModelSolution.hh" int -main (int argc, char** argv) +main(int argc, char **argv) { if (argc < 2) { @@ -33,12 +33,12 @@ main (int argc, char** argv) std::string modName = argv[1]; const int npar = 7; - const size_t n_endo=15, n_exo=2; - std::vector<size_t> zeta_fwrd_arg; - std::vector<size_t> zeta_back_arg; + const size_t n_endo = 15, n_exo = 2; + std::vector<size_t> zeta_fwrd_arg; + std::vector<size_t> zeta_back_arg; std::vector<size_t> zeta_mixed_arg; std::vector<size_t> zeta_static_arg; - double qz_criterium=1.0+1.0e-9; + double qz_criterium = 1.0+1.0e-9; Vector deepParams(npar); double dYSparams [] = { @@ -52,45 +52,45 @@ main (int argc, char** argv) 0.0, 0.0250e-3 }; int nVCVpar = 2; - MatrixView vCovVW(vcov,nVCVpar,nVCVpar,nVCVpar); - Matrix vCov (nVCVpar, nVCVpar); + MatrixView vCovVW(vcov, nVCVpar, nVCVpar, nVCVpar); + Matrix vCov(nVCVpar, nVCVpar); vCov = vCovVW; double dparams[] = { 0.3300, - 0.9900, - 0.0030, - 1.0110, - 0.7000, - 0.7870, - 0.0200}; + 0.9900, + 0.0030, + 1.0110, + 0.7000, + 0.7870, + 0.0200}; - VectorView modParamsVW (dparams, npar,1); - deepParams=modParamsVW; - VectorView steadyState(dYSparams,n_endo,1); + VectorView modParamsVW(dparams, npar, 1); + deepParams = modParamsVW; + VectorView steadyState(dYSparams, n_endo, 1); std::cout << "Vector deepParams: " << std::endl << deepParams << std::endl; std::cout << "Matrix vCov: " << std::endl << vCov << std::endl; std::cout << "Vector steadyState: " << std::endl << steadyState << std::endl; // Set zeta vectors [0:(n-1)] from Matlab indices [1:n] //order_var = [ stat_var(:); pred_var(:); both_var(:); fwrd_var(:)]; - size_t statc[]={ 4, 5, 6, 8, 9, 10, 11, 12, 14}; - size_t back[]={1,7,13}; - size_t both[]={2}; - size_t fwd[]={ 3,15}; - for (int i=0;i<9;++i) + size_t statc[] = { 4, 5, 6, 8, 9, 10, 11, 12, 14}; + size_t back[] = {1, 7, 13}; + size_t both[] = {2}; + size_t fwd[] = { 3, 15}; + for (int i = 0; i < 9; ++i) zeta_static_arg.push_back(statc[i]-1); - for (int i=0;i<3;++i) + for (int i = 0; i < 3; ++i) zeta_back_arg.push_back(back[i]-1); - for (int i=0;i<1;++i) + for (int i = 0; i < 1; ++i) zeta_mixed_arg.push_back(both[i]-1); - for (int i=0;i<2;++i) + for (int i = 0; i < 2; ++i) zeta_fwrd_arg.push_back(fwd[i]-1); Matrix ghx(n_endo, zeta_back_arg.size() + zeta_mixed_arg.size()); - Matrix ghu(n_endo,n_exo); + Matrix ghu(n_endo, n_exo); - ModelSolution modelSolution( modName, n_endo, n_exo - , zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium); + ModelSolution modelSolution(modName, n_endo, n_exo, + zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium); modelSolution.compute(steadyState, deepParams, ghx, ghu); diff --git a/mex/sources/estimation/tests/testPDF.cc b/mex/sources/estimation/tests/testPDF.cc index 2bac4b909eef7ace055f19e753a811ab2163dbe4..4b07d0adb5bf39187b4af61748c91c64a57f9bda 100644 --- a/mex/sources/estimation/tests/testPDF.cc +++ b/mex/sources/estimation/tests/testPDF.cc @@ -24,18 +24,15 @@ int main(int argc, char **argv) { -//BetaPrior bp( Prior::Beta, 0.1, 0.1, 0.1, 0.0, 1.0, 5.0, 1.0); BetaPrior bp(0.1, 0.1, 0.0, 1.0, 5.0, 1.0); double pdf = bp.pdf(0.5); std::cout << "beta pdf of 5,1, 0.5: " << std::setw(13) << pdf << std::endl; - BetaPrior *bpp = new BetaPrior( //Prior::Beta, - 0.1, 0.1, 0.0, 1.0, 1.0, 5.0); + BetaPrior *bpp = new BetaPrior(0.1, 0.1, 0.0, 1.0, 1.0, 5.0); Prior *pp = bpp; pdf = (*pp).pdf(0.1); std::cout << "Parent (Beta) pdf of 1,5, 0.1: " << std::setw(13) << pdf << std::endl; - GammaPrior *gpp = new GammaPrior( //Prior::Beta, - 0.1, 0.1, 0.0, 1.0, 1.0, 5.0); + GammaPrior *gpp = new GammaPrior(0.1, 0.1, 0.0, 1.0, 1.0, 5.0); pp = gpp; pdf = (*pp).pdf(0.1); std::cout << "Parent (Gamma) pdf of 1,5, 0.1: " << std::setw(13) << pdf << std::endl; diff --git a/mex/sources/estimation/utils/dynamic_dll.cc b/mex/sources/estimation/utils/dynamic_dll.cc index 8a1f7f6e8c8852f57a5fd785dd27a5f7f4734265..fc6961a935746b87c73b6362cc42a37a174bbf90 100644 --- a/mex/sources/estimation/utils/dynamic_dll.cc +++ b/mex/sources/estimation/utils/dynamic_dll.cc @@ -34,49 +34,49 @@ DynamicModelDLL::DynamicModelDLL(const std::string &dynamicDllFile, size_t n_exo fName += dynamicDllFile; try - { -#if defined(__CYGWIN32__) || defined(_WIN32) - dynamicHinstance = LoadLibrary(fName.c_str()); - if (dynamicHinstance == NULL) - throw 1; - Dynamic = (DynamicFn) GetProcAddress(dynamicHinstance, "Dynamic"); - if (Dynamic == NULL) { - FreeLibrary(dynamicHinstance); // Free the library - throw 2; - } +#if defined(__CYGWIN32__) || defined(_WIN32) + dynamicHinstance = LoadLibrary(fName.c_str()); + if (dynamicHinstance == NULL) + throw 1; + Dynamic = (DynamicFn) GetProcAddress(dynamicHinstance, "Dynamic"); + if (Dynamic == NULL) + { + FreeLibrary(dynamicHinstance); // Free the library + throw 2; + } #else // Linux or Mac - dynamicHinstance = dlopen(fName.c_str(), RTLD_NOW); - if ((dynamicHinstance == NULL) || dlerror()) - { - cerr << dlerror() << endl; - throw 1; - } - Dynamic = (DynamicFn) dlsym(dynamicHinstance, "Dynamic"); - if ((Dynamic == NULL) || dlerror()) - { - dlclose(dynamicHinstance); // Free the library - cerr << dlerror() << endl; - throw 2; - } + dynamicHinstance = dlopen(fName.c_str(), RTLD_NOW); + if ((dynamicHinstance == NULL) || dlerror()) + { + cerr << dlerror() << endl; + throw 1; + } + Dynamic = (DynamicFn) dlsym(dynamicHinstance, "Dynamic"); + if ((Dynamic == NULL) || dlerror()) + { + dlclose(dynamicHinstance); // Free the library + cerr << dlerror() << endl; + throw 2; + } #endif - } + } catch (int i) - { - std::ostringstream msg; - msg << "Error when loading " << fName << " ("; - if (i == 1) - msg << "can't dynamically load the file"; - if (i == 2) - msg << "can't locate the 'Dynamic' symbol"; - msg << ")"; - throw TSException(__FILE__, __LINE__, msg.str()); - } + { + std::ostringstream msg; + msg << "Error when loading " << fName << " ("; + if (i == 1) + msg << "can't dynamically load the file"; + if (i == 2) + msg << "can't locate the 'Dynamic' symbol"; + msg << ")"; + throw TSException(__FILE__, __LINE__, msg.str()); + } catch (...) - { - throw TSException(__FILE__, __LINE__, std::string("Can't find Dynamic function in ") + fName); - } + { + throw TSException(__FILE__, __LINE__, std::string("Can't find Dynamic function in ") + fName); + } } DynamicModelDLL::~DynamicModelDLL() diff --git a/mex/sources/estimation/utils/dynamic_dll.hh b/mex/sources/estimation/utils/dynamic_dll.hh index a7d9a78e52cf53f0eb9077a9be4d4d97424dbaaf..5e65497430753e87656abca964c200eb6eb1e922 100644 --- a/mex/sources/estimation/utils/dynamic_dll.hh +++ b/mex/sources/estimation/utils/dynamic_dll.hh @@ -35,9 +35,9 @@ typedef void (*DynamicFn) int it_, double *residual, double *g1, double *g2, double *g3); /** -* creates pointer to Dynamic function inside <model>_dynamic.dll -* and handles calls to it. -**/ + * creates pointer to Dynamic function inside <model>_dynamic.dll + * and handles calls to it. + **/ class DynamicModelDLL { private: diff --git a/mex/sources/estimation/utils/ts_exception.h b/mex/sources/estimation/utils/ts_exception.h index 381a4c55e2b6d08aad79bbf8060bfd2baf837181..a67cc7cda80b071a7f3cb7c21404515db5b227ba 100644 --- a/mex/sources/estimation/utils/ts_exception.h +++ b/mex/sources/estimation/utils/ts_exception.h @@ -15,53 +15,59 @@ * * You should have received a copy of the GNU General Public License * along with Dynare. If not, see <http://www.gnu.org/licenses/>. - */ - -/* derived from c++kalman_filter library by O. Kamenik */ - -#ifndef TS_EXCEPTION_H -#define TS_EXCEPTION_H - -#include <stdio.h> -#include <string> - -#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) -#include "mex.h" -#endif - -#define TS_RAISE(mes) \ - throw TSException(__FILE__, __LINE__, mes); - -#define TS_RAISE_IF(expr, mes) \ - if (expr) throw TSException(__FILE__, __LINE__, mes); - - -class TSException -{ - std::string fname; //char fname[50]; - int lnum; - std::string message;// char message[500]; -public: - TSException(const char*f,int l,const std::string &mes) - { - fname =std::string(f); // strncpy(fname,f,50);fname[49]= '\0'; - message=mes;//strncpy(message,mes,500);message[499]= '\0'; - lnum= l; - } - virtual ~TSException(){}; - - virtual void print()const - { - printf("At %s:%d:%s\n",fname.c_str(),lnum,message.c_str()); -#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) - mexPrintf("At %s:%d:%s\n",fname.c_str(),lnum,message.c_str()); -#endif - } - - virtual const std::string getMessage()const - {return message;} -}; - -; -#endif - + */ + +/* derived from c++kalman_filter library by O. Kamenik */ + +#ifndef TS_EXCEPTION_H +#define TS_EXCEPTION_H + +#include <stdio.h> +#include <string> + +#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) +# include "mex.h" +#endif + +#define TS_RAISE(mes) \ + throw TSException(__FILE__, __LINE__, mes); + +#define TS_RAISE_IF(expr, mes) \ + if (expr) throw TSException(__FILE__, __LINE__, mes); + +class TSException +{ + std::string fname; //char fname[50]; + int lnum; + std::string message; // char message[500]; +public: + TSException(const char *f, int l, const std::string &mes) + { + fname = std::string(f); // strncpy(fname,f,50);fname[49]= '\0'; + message = mes; //strncpy(message,mes,500);message[499]= '\0'; + lnum = l; + } + virtual + ~TSException() + { + }; + + virtual void + print() const + { + printf("At %s:%d:%s\n", fname.c_str(), lnum, message.c_str()); +#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) + mexPrintf("At %s:%d:%s\n", fname.c_str(), lnum, message.c_str()); +#endif + } + + virtual const std::string + getMessage() const + { + return message; + } +}; + +; +#endif + diff --git a/mex/sources/k_order_perturbation/dynamic_abstract_class.cc b/mex/sources/k_order_perturbation/dynamic_abstract_class.cc index 9825c1344c071f6a61fb78253979ca831d17ebb7..4c3d047fed6445630e0836dda821841c8f01918d 100644 --- a/mex/sources/k_order_perturbation/dynamic_abstract_class.cc +++ b/mex/sources/k_order_perturbation/dynamic_abstract_class.cc @@ -23,9 +23,9 @@ void DynamicModelAC::copyDoubleIntoTwoDMatData(double *dm, TwoDMatrix *tdm, int rows, int cols) { int dmIdx = 0; - for (int j=0; j<cols; j++) - for (int i=0; i<rows; i++) - tdm->get(i,j) = dm[dmIdx++]; + for (int j = 0; j < cols; j++) + for (int i = 0; i < rows; i++) + tdm->get(i, j) = dm[dmIdx++]; } double * @@ -37,15 +37,15 @@ DynamicModelAC::unpackSparseMatrix(mxArray *sparseMat) mwIndex *colIdxVector = mxGetJc(sparseMat); double *ptr = mxGetPr(sparseMat); - double *newMat = (double *)malloc(sizeRowIdxVector*3*sizeof(double)); + double *newMat = (double *) malloc(sizeRowIdxVector*3*sizeof(double)); int rind = 0; int retvalind0 = 0; int retvalind1 = sizeRowIdxVector; int retvalind2 = sizeRowIdxVector*2; - for (int i=0; i<totalCols; i++) - for (int j=0;j<(int)(colIdxVector[i+1]-colIdxVector[i]); j++, rind++) + for (int i = 0; i < totalCols; i++) + for (int j = 0; j < (int) (colIdxVector[i+1]-colIdxVector[i]); j++, rind++) { newMat[retvalind0++] = rowIdxVector[rind] + 1; newMat[retvalind1++] = i + 1; diff --git a/mex/sources/k_order_perturbation/dynamic_m.cc b/mex/sources/k_order_perturbation/dynamic_m.cc index 4096c4c363c35b0148a2d0c252c0c2a5619943d6..ac2ce35b59a07bdfda58499cf7805388d1eb7532 100644 --- a/mex/sources/k_order_perturbation/dynamic_m.cc +++ b/mex/sources/k_order_perturbation/dynamic_m.cc @@ -30,7 +30,7 @@ DynamicModelMFile::~DynamicModelMFile() void DynamicModelMFile::eval(const Vector &y, const Vector &x, const Vector &modParams, const Vector &ySteady, - Vector &residual, TwoDMatrix *g1, TwoDMatrix *g2, TwoDMatrix *g3) throw (DynareException) + Vector &residual, TwoDMatrix *g1, TwoDMatrix *g2, TwoDMatrix *g3) throw (DynareException) { mxArray *prhs[nrhs_dynamic], *plhs[nlhs_dynamic]; @@ -39,23 +39,23 @@ DynamicModelMFile::eval(const Vector &y, const Vector &x, const Vector &modParam prhs[2] = mxCreateDoubleMatrix(modParams.length(), 1, mxREAL); prhs[3] = mxCreateDoubleScalar(1.0); - memcpy((void *)(mxGetPr(prhs[0])), (void *)y.base(), y.length()*sizeof(double)); - memcpy((void *)(mxGetPr(prhs[1])), (void *)x.base(), x.length()*sizeof(double)); - memcpy((void *)(mxGetPr(prhs[2])), (void *)modParams.base(), modParams.length()*sizeof(double)); + memcpy((void *) (mxGetPr(prhs[0])), (void *) y.base(), y.length()*sizeof(double)); + memcpy((void *) (mxGetPr(prhs[1])), (void *) x.base(), x.length()*sizeof(double)); + memcpy((void *) (mxGetPr(prhs[2])), (void *) modParams.base(), modParams.length()*sizeof(double)); int retVal = mexCallMATLAB(nlhs_dynamic, plhs, nrhs_dynamic, prhs, DynamicMFilename.c_str()); if (retVal != 0) throw DynareException(__FILE__, __LINE__, "Trouble calling " + DynamicMFilename); - residual = Vector(mxGetPr(plhs[0]), residual.skip(), (int)mxGetM(plhs[0])); - copyDoubleIntoTwoDMatData(mxGetPr(plhs[1]), g1, (int)mxGetM(plhs[1]), (int)mxGetN(plhs[1])); + residual = Vector(mxGetPr(plhs[0]), residual.skip(), (int) mxGetM(plhs[0])); + copyDoubleIntoTwoDMatData(mxGetPr(plhs[1]), g1, (int) mxGetM(plhs[1]), (int) mxGetN(plhs[1])); if (g2 != NULL) - copyDoubleIntoTwoDMatData(unpackSparseMatrix(plhs[2]), g2, (int)mxGetNzmax(plhs[2]), 3); + copyDoubleIntoTwoDMatData(unpackSparseMatrix(plhs[2]), g2, (int) mxGetNzmax(plhs[2]), 3); if (g3 != NULL) - copyDoubleIntoTwoDMatData(unpackSparseMatrix(plhs[3]), g3, (int)mxGetNzmax(plhs[3]), 3); + copyDoubleIntoTwoDMatData(unpackSparseMatrix(plhs[3]), g3, (int) mxGetNzmax(plhs[3]), 3); - for (int i=0; i<nrhs_dynamic; i++) - mxDestroyArray(prhs[i]); - for (int i=0; i<nlhs_dynamic; i++) - mxDestroyArray(plhs[i]); + for (int i = 0; i < nrhs_dynamic; i++) + mxDestroyArray(prhs[i]); + for (int i = 0; i < nlhs_dynamic; i++) + mxDestroyArray(plhs[i]); } diff --git a/mex/sources/k_order_perturbation/k_ord_dynare.cc b/mex/sources/k_order_perturbation/k_ord_dynare.cc index e24de39fe429df08f9cfb47d1fe694ab5dbff3ce..302a3517d708d847f577a5db8be66535d546cf18 100644 --- a/mex/sources/k_order_perturbation/k_ord_dynare.cc +++ b/mex/sources/k_order_perturbation/k_ord_dynare.cc @@ -28,7 +28,6 @@ #include "memory_file.h" - #include <iostream> #include <fstream> diff --git a/mex/sources/k_order_perturbation/k_order_perturbation.cc b/mex/sources/k_order_perturbation/k_order_perturbation.cc index 699ee0db5316c1bd135b7bac91811b8fde1f8c63..3f6ccf3392ff3d2a73d348b61b87dbb4b0ee8930 100644 --- a/mex/sources/k_order_perturbation/k_order_perturbation.cc +++ b/mex/sources/k_order_perturbation/k_order_perturbation.cc @@ -26,10 +26,10 @@ 3) options 4) string containing the MEX extension (with a dot at the beginning) - Outputs: - - if order == 1: only g_1 - - if order == 2: g_0, g_1, g_2 - - if order == 3: g_0, g_1, g_2, g_3 + Outputs: + - if order == 1: only g_1 + - if order == 2: g_0, g_1, g_2 + - if order == 3: g_0, g_1, g_2, g_3 */ #include "dynamic_m.hh" @@ -42,7 +42,7 @@ #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) // exclude mexFunction for other applications -#include "dynmex.h" +# include "dynmex.h" ////////////////////////////////////////////////////// // Convert MATLAB Dynare endo and exo names array to a vector<string> array of string pointers @@ -75,7 +75,7 @@ extern "C" { const mxArray *dr = prhs[0]; const mxArray *M_ = prhs[1]; const mxArray *options_ = prhs[2]; - int use_dll = (int)mxGetScalar(mxGetField(options_, 0, "use_dll")); + int use_dll = (int) mxGetScalar(mxGetField(options_, 0, "use_dll")); mxArray *mFname = mxGetField(M_, 0, "fname"); if (!mxIsChar(mFname)) @@ -147,7 +147,7 @@ extern "C" { vector<int> var_order_vp(nEndo); for (int v = 0; v < nEndo; v++) - var_order_vp[v] = (int)(*(dparams++)); + var_order_vp[v] = (int) (*(dparams++)); // the lag, current and lead blocks of the jacobian respectively mxFldp = mxGetField(M_, 0, "lead_lag_incidence"); diff --git a/mex/sources/k_order_perturbation/tests/k_order_test_main.cc b/mex/sources/k_order_perturbation/tests/k_order_test_main.cc index 12291837d452c558b3d27eb1e4e0b576fc36cd24..68cfcac0e28740dc24e4a88af119ad3f4c5070fd 100644 --- a/mex/sources/k_order_perturbation/tests/k_order_test_main.cc +++ b/mex/sources/k_order_perturbation/tests/k_order_test_main.cc @@ -271,7 +271,7 @@ main(int argc, char *argv[]) // get latest ysteady double *dYsteady = (dynare.getSteady().base()); - ySteady = (Vector *)(&dynare.getSteady()); + ySteady = (Vector *) (&dynare.getSteady()); } catch (const KordException &e) { diff --git a/mex/sources/kalman_steady_state/kalman_steady_state.cc b/mex/sources/kalman_steady_state/kalman_steady_state.cc index 6e053351eb94f979b679dad2e8b70639d34457a6..1ce87c0f5f679f88d85631a32ae773d23eccd8d9 100644 --- a/mex/sources/kalman_steady_state/kalman_steady_state.cc +++ b/mex/sources/kalman_steady_state/kalman_steady_state.cc @@ -21,33 +21,33 @@ */ /* -++ INPUTS -++ ====== -++ -++ -++ [0] T (double) n-by-n transition matrix. -++ -++ [1] QQ (double) n-by-n matrix (=R*Q*R', where Q is the covariance matrix of the structural innovations). -++ -++ [2] Z (double) n-by-p selection matrix. -++ -++ [3] H (double) p-by-p covariance matrix of the measurement errors. -++ -++ -++ -++ -++ OUTPUTS -++ ======= -++ -++ -++ [0] P (double) n-by-n covariance matrix of the state vector. -++ -++ -++ NOTES -++ ===== -++ -++ [1] T = transpose(dynare transition matrix) and Z = transpose(dynare selection matrix). -*/ + ++ INPUTS + ++ ====== + ++ + ++ + ++ [0] T (double) n-by-n transition matrix. + ++ + ++ [1] QQ (double) n-by-n matrix (=R*Q*R', where Q is the covariance matrix of the structural innovations). + ++ + ++ [2] Z (double) n-by-p selection matrix. + ++ + ++ [3] H (double) p-by-p covariance matrix of the measurement errors. + ++ + ++ + ++ + ++ + ++ OUTPUTS + ++ ======= + ++ + ++ + ++ [0] P (double) n-by-n covariance matrix of the state vector. + ++ + ++ + ++ NOTES + ++ ===== + ++ + ++ [1] T = transpose(dynare transition matrix) and Z = transpose(dynare selection matrix). +*/ #include <string.h> #include <stdlib.h> @@ -55,131 +55,136 @@ #include <dynlapack.h> #if !defined(MATLAB_MEX_FILE) || !defined(_WIN32) -#define sb02od sb02od_ +# define sb02od sb02od_ #endif extern "C" { - int sb02od(char*, char*, char*, char*, char*, char*, mwSize*, mwSize*, mwSize*, double*, mwSize*, double*, mwSize*, double*, mwSize*, double*, mwSize*, double*, mwSize*, double*, double*, mwSize*, double*, double*, double*, double*, mwSize*, double*, mwSize*, double*, mwSize*, double*, lapack_int*, double*, mwSize*, lapack_int*, lapack_int*); + int sb02od(char *, char *, char *, char *, char *, char *, mwSize *, mwSize *, mwSize *, double *, mwSize *, double *, mwSize *, double *, mwSize *, double *, mwSize *, double *, mwSize *, double *, double *, mwSize *, double *, double *, double *, double *, mwSize *, double *, mwSize *, double *, mwSize *, double *, lapack_int *, double *, mwSize *, lapack_int *, lapack_int *); } -template <typename T> T max(T x, T y) +template <typename T> +T +max(T x, T y) { - return x < y ? y : x; + return x < y ? y : x; } -template <typename T> T max(T x, T y, T z) +template <typename T> +T +max(T x, T y, T z) { return max(x, max(y, z)); } -void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) +void +mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Check the number of arguments and set some flags. int measurement_error_flag = 1; - if ( nrhs>4 ) + if (nrhs > 4) { mexErrMsgTxt("This function requires at most 4 input arguments!"); } - if ( nrhs<3 ) + if (nrhs < 3) { mexErrMsgTxt("This function requires at least 3 input arguments!"); } - if ( nrhs<4) + if (nrhs < 4) { measurement_error_flag = 0; } - if ( nlhs>1 ) + if (nlhs > 1) { mexErrMsgTxt("This function gives at most 1 output argument!"); } // Check the type of the input arguments and get the size of the matrices. mwSize n = mxGetM(prhs[0]); - if ( n!=mxGetN(prhs[0]) ) + if (n != mxGetN(prhs[0])) { mexErrMsgTxt("The first input argument (T) must be a square matrix!"); } - if ( (mxIsNumeric(prhs[0])==0) || (mxIsComplex(prhs[0])==1) ) + if ((mxIsNumeric(prhs[0]) == 0) || (mxIsComplex(prhs[0]) == 1)) { mexErrMsgTxt("The first input argument (T) must be a real matrix!"); } mwSize q = mxGetM(prhs[1]); - if ( q!=mxGetN(prhs[1]) ) + if (q != mxGetN(prhs[1])) { mexErrMsgTxt("The second input argument (QQ) must be a square matrix!"); } - if ( (mxIsNumeric(prhs[1])==0) || (mxIsComplex(prhs[1])==1) ) + if ((mxIsNumeric(prhs[1]) == 0) || (mxIsComplex(prhs[1]) == 1)) { mexErrMsgTxt("The second input argument (QQ) must be a real matrix!"); } - if ( q!=n ) + if (q != n) { mexErrMsgTxt("The size of the second input argument (QQ) must match the size of the first argument (T)!"); } mwSize p = mxGetN(prhs[2]); - if ( mxGetM(prhs[2])!=n ) + if (mxGetM(prhs[2]) != n) { mexErrMsgTxt("The number of rows of the third argument (Z) must match the number of rows of the first argument (T)!"); } - if ( (mxIsNumeric(prhs[2])==0) || (mxIsComplex(prhs[2])==1) ) + if ((mxIsNumeric(prhs[2]) == 0) || (mxIsComplex(prhs[2]) == 1)) { mexErrMsgTxt("The third input argument (Z) must be a real matrix!"); } - if ( measurement_error_flag) + if (measurement_error_flag) { - if ( mxGetM(prhs[3])!=mxGetN(prhs[3]) ) + if (mxGetM(prhs[3]) != mxGetN(prhs[3])) { mexErrMsgTxt("The fourth input argument (H) must be a square matrix!"); } - if ( mxGetM(prhs[3])!=p ) + if (mxGetM(prhs[3]) != p) { mexErrMsgTxt("The number of rows of the fourth input argument (H) must match the number of rows of the third input argument!"); } - if ( (mxIsNumeric(prhs[3])==0) || (mxIsComplex(prhs[3])==1) ) + if ((mxIsNumeric(prhs[3]) == 0) || (mxIsComplex(prhs[3]) == 1)) { mexErrMsgTxt("The fifth input argument (H) must be a real matrix!"); } } // Get input matrices. - double *T, *QQ, *Z, *H, *L;// Remark. L will not be used. - T = (double *) mxCalloc(n*n,sizeof(double)); - memcpy(T,mxGetPr(prhs[0]),n*n*sizeof(double)); - QQ = (double *) mxCalloc(n*n,sizeof(double)); - memcpy(QQ,mxGetPr(prhs[1]),n*n*sizeof(double)); - Z = (double *) mxCalloc(n*p,sizeof(double)); - memcpy(Z,mxGetPr(prhs[2]),n*p*sizeof(double)); - H = (double *) mxCalloc(p*p,sizeof(double)); + double *T, *QQ, *Z, *H, *L; // Remark. L will not be used. + T = (double *) mxCalloc(n*n, sizeof(double)); + memcpy(T, mxGetPr(prhs[0]), n*n*sizeof(double)); + QQ = (double *) mxCalloc(n*n, sizeof(double)); + memcpy(QQ, mxGetPr(prhs[1]), n*n*sizeof(double)); + Z = (double *) mxCalloc(n*p, sizeof(double)); + memcpy(Z, mxGetPr(prhs[2]), n*p*sizeof(double)); + H = (double *) mxCalloc(p*p, sizeof(double)); if (measurement_error_flag) { - memcpy(H,mxGetPr(prhs[3]),p*p*sizeof(double)); + memcpy(H, mxGetPr(prhs[3]), p*p*sizeof(double)); } L = (double *) mxCalloc(n*p, sizeof(double)); - char *DICO, *JOBB, * FACT, *UPLO, *JOBL, *SORT; - DICO = (char *) mxCalloc(2,sizeof(char)); - memcpy(DICO,"D",2*sizeof(char));// We want to solve a discrete Riccati equation. - JOBB = (char *) mxCalloc(2,sizeof(char)); - memcpy(JOBB,"B",2*sizeof(char));// Matrices Z and H are given. - FACT = (char *) mxCalloc(2,sizeof(char)); - memcpy(FACT,"N",2*sizeof(char));// Given matrices H and QQ are not factored. - UPLO = (char *) mxCalloc(2,sizeof(char)); - memcpy(UPLO,"U",2*sizeof(char));// Upper triangle of matrix H is stored. - JOBL = (char *) mxCalloc(2,sizeof(char)); - memcpy(JOBL,"Z",2*sizeof(char));// L matrix is zero. - SORT = (char *) mxCalloc(2,sizeof(char)); - memcpy(SORT,"S",2*sizeof(char));// Stable eigenvalues come first. + char *DICO, *JOBB, *FACT, *UPLO, *JOBL, *SORT; + DICO = (char *) mxCalloc(2, sizeof(char)); + memcpy(DICO, "D", 2*sizeof(char)); // We want to solve a discrete Riccati equation. + JOBB = (char *) mxCalloc(2, sizeof(char)); + memcpy(JOBB, "B", 2*sizeof(char)); // Matrices Z and H are given. + FACT = (char *) mxCalloc(2, sizeof(char)); + memcpy(FACT, "N", 2*sizeof(char)); // Given matrices H and QQ are not factored. + UPLO = (char *) mxCalloc(2, sizeof(char)); + memcpy(UPLO, "U", 2*sizeof(char)); // Upper triangle of matrix H is stored. + JOBL = (char *) mxCalloc(2, sizeof(char)); + memcpy(JOBL, "Z", 2*sizeof(char)); // L matrix is zero. + SORT = (char *) mxCalloc(2, sizeof(char)); + memcpy(SORT, "S", 2*sizeof(char)); // Stable eigenvalues come first. mwSize nn = 2*n; - mwSize LDA = max((mwSize)1, n); + mwSize LDA = max((mwSize) 1, n); mwSize LDQ = LDA; - mwSize LDU = max((mwSize)1, nn); - mwSize LDS = max((mwSize)1, nn+p ); - mwSize LIWORK = max((mwSize)1, p, nn ); - mwSize LDR = max((mwSize)1, p ); + mwSize LDU = max((mwSize) 1, nn); + mwSize LDS = max((mwSize) 1, nn+p); + mwSize LIWORK = max((mwSize) 1, p, nn); + mwSize LDR = max((mwSize) 1, p); mwSize LDB = LDA; mwSize LDL = LDA; mwSize LDT = LDS; mwSize LDX = LDA; - mwSize LDWORK = max( (mwSize)7*((mwSize)2*n + (mwSize)1) + (mwSize)16, (mwSize)16*n ); - LDWORK = max( LDWORK, (mwSize)2*n + p, (mwSize)3*p); + mwSize LDWORK = max((mwSize) 7*((mwSize) 2*n + (mwSize) 1) + (mwSize) 16, (mwSize) 16*n); + LDWORK = max(LDWORK, (mwSize) 2*n + p, (mwSize) 3*p); double tolerance = -1.0; lapack_int INFO; // Outputs of subroutine sb02OD @@ -200,7 +205,7 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) BWORK = (lapack_int *) mxCalloc(nn, sizeof(lapack_int)); // Initialize the output of the mex file double *P; - plhs[0] = mxCreateDoubleMatrix(n,n,mxREAL); + plhs[0] = mxCreateDoubleMatrix(n, n, mxREAL); P = mxGetPr(plhs[0]); // Call the slicot routine sb02od(DICO, JOBB, FACT, UPLO, JOBL, SORT, &n, &p, &p, &T[0], &LDA, &Z[0], &LDB, &QQ[0], &LDQ, &H[0], &LDR, &L[0], &LDL, &rcond, &P[0], &LDX, &WR[0], &WI[0], &BETA[0], &S[0], &LDS, &TT[0], &LDT, &UU[0], &LDU, &tolerance, &IWORK[0], &DWORK[0], &LDWORK, &BWORK[0], &INFO); @@ -209,7 +214,7 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) mxFree(Z); mxFree(H); mxFree(L); - mxFree(DICO); + mxFree(DICO); mxFree(JOBB); mxFree(FACT); mxFree(UPLO); @@ -224,9 +229,9 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) mxFree(IWORK); mxFree(DWORK); mxFree(BWORK); - if (INFO!=0) + if (INFO != 0) { - switch(INFO) + switch (INFO) { case 1: { @@ -238,7 +243,7 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) mexPrintf("The QZ (or QR) algorithm failed"); break; } - case 3: + case 3: { mexPrintf("The reordering of the (generalized) eigenvalues failed"); break; @@ -259,7 +264,7 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { mexPrintf("a singular matrix was encountered during the computation of the solution matrix P"); break; - } + } default: { mexPrintf("Unknown problem!"); diff --git a/mex/sources/kronecker/A_times_B_kronecker_C.cc b/mex/sources/kronecker/A_times_B_kronecker_C.cc index 99098fd9281912c884b248c59f2399213903bc03..e30d9d1bf36906ab1c2beb63d0f0f327552ac9b1 100644 --- a/mex/sources/kronecker/A_times_B_kronecker_C.cc +++ b/mex/sources/kronecker/A_times_B_kronecker_C.cc @@ -140,12 +140,12 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) mC = mxGetM(prhs[2]); nC = mxGetN(prhs[2]); if (mB*mC != nA) - DYN_MEX_FUNC_ERR_MSG_TXT( "Input dimension error!"); + DYN_MEX_FUNC_ERR_MSG_TXT("Input dimension error!"); } else // A*kron(B,B) is to be computed. { if (mB*mB != nA) - DYN_MEX_FUNC_ERR_MSG_TXT( "Input dimension error!"); + DYN_MEX_FUNC_ERR_MSG_TXT("Input dimension error!"); } // Get input matrices: double *B, *C, *A; diff --git a/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc b/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc index bdec5d859591c3d6d42ed86b4f2c19df116d85fa..1ba6b8c7f0612da11e9cbd69fc5ef06e25f590e6 100644 --- a/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc +++ b/mex/sources/kronecker/sparse_hessian_times_B_kronecker_C.cc @@ -143,7 +143,7 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Check input and output: - if ((nrhs > 4) || (nrhs < 3) || nlhs!=2) + if ((nrhs > 4) || (nrhs < 3) || nlhs != 2) DYN_MEX_FUNC_ERR_MSG_TXT("sparse_hessian_times_B_kronecker_C takes 3 or 4 input arguments and provides exactly 2 output argument."); if (!mxIsSparse(prhs[0])) @@ -195,7 +195,7 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) // Computational part: if (nrhs == 3) { - sparse_hessian_times_B_kronecker_B(isparseA, jsparseA, vsparseA, B, D, mA, nA, mB, nB,numthreads); + sparse_hessian_times_B_kronecker_B(isparseA, jsparseA, vsparseA, B, D, mA, nA, mB, nB, numthreads); } else { diff --git a/mex/sources/mjdgges/mjdgges.c b/mex/sources/mjdgges/mjdgges.c index 4c5438701fe94ac57c2a0614fff0b78aec2652c8..5fccd66698fb15f5592fad4e45d162646b08663a 100644 --- a/mex/sources/mjdgges/mjdgges.c +++ b/mex/sources/mjdgges/mjdgges.c @@ -62,9 +62,9 @@ mjdgges(double *a, double *b, double *z, double *n, double *sdim, double *eval_r { *per = *par / *pb; if (*pai == 0.0 && *pb == 0.0) - *pei = 0.0; + *pei = 0.0; else - *pei = *pai / *pb; + *pei = *pai / *pb; ++par; ++pai; ++pb; diff --git a/mex/sources/ordschur/ordschur.cc b/mex/sources/ordschur/ordschur.cc index 2830b8f55f9e3f842d704c1f68080c722c531d0c..0f7667dd9b17c8a4d9e4771bb13c695bbed2d155 100644 --- a/mex/sources/ordschur/ordschur.cc +++ b/mex/sources/ordschur/ordschur.cc @@ -40,7 +40,7 @@ extern "C" const octave_idx_type &, octave_idx_type &); } -DEFUN_DLD (ordschur, args, nargout, "-*- texinfo -*-\n\ +DEFUN_DLD(ordschur, args, nargout, "-*- texinfo -*-\n\ @deftypefn {Loadable Function} [ @var{us}, @var{ts} ] = ordschur (@var{u}, @var{t}, @var{select})\n\ \n\ Reorders the real Schur factorization @math{X = U*T*U'} so that selected\n\ @@ -89,11 +89,11 @@ eigenvalues as they appear along @math{T}'s diagonal.\n\ OCTAVE_LOCAL_BUFFER(octave_idx_type, S2, n); for (int i = 0; i < n; i++) S2[i] = S(i); - - F77_XFCN (dtrsen, dtrsen, (F77_CONST_CHAR_ARG("N"), F77_CONST_CHAR_ARG("V"), - S2, n, T.fortran_vec(), n, U.fortran_vec(), n, - wr, wi, m, cond1, cond2, work, lwork, - iwork, liwork, info)); + + F77_XFCN(dtrsen, dtrsen, (F77_CONST_CHAR_ARG("N"), F77_CONST_CHAR_ARG("V"), + S2, n, T.fortran_vec(), n, U.fortran_vec(), n, + wr, wi, m, cond1, cond2, work, lwork, + iwork, liwork, info)); if (info != 0) { @@ -108,10 +108,10 @@ eigenvalues as they appear along @math{T}'s diagonal.\n\ /* -%!test -%! A = [1 2 3 -2; 4 5 6 -5 ; 7 8 9 -5; 10 11 12 4 ]; -%! [U, T] = schur(A); -%! [US, TS] = ordschur(U, T, [ 0 0 1 1 ]); -%! assert(US*TS*US', A, sqrt(eps)) + %!test + %! A = [1 2 3 -2; 4 5 6 -5 ; 7 8 9 -5; 10 11 12 4 ]; + %! [U, T] = schur(A); + %! [US, TS] = ordschur(U, T, [ 0 0 1 1 ]); + %! assert(US*TS*US', A, sqrt(eps)) */ diff --git a/mex/sources/qzcomplex/qzcomplex.cc b/mex/sources/qzcomplex/qzcomplex.cc index a0f47d5c9fbcf3b59f90d7201c95700cb66230b7..5390cde21f69571db1d247e454ced5be2fb8bfea 100644 --- a/mex/sources/qzcomplex/qzcomplex.cc +++ b/mex/sources/qzcomplex/qzcomplex.cc @@ -31,14 +31,14 @@ extern "C" { F77_RET_T F77_FUNC(zgges, ZGGES) (F77_CONST_CHAR_ARG_DECL, F77_CONST_CHAR_ARG_DECL, F77_CONST_CHAR_ARG_DECL, - octave_idx_type (*) (Complex *, Complex *), const octave_idx_type &, + octave_idx_type (*)(Complex *, Complex *), const octave_idx_type &, Complex *, const octave_idx_type &, Complex *, const octave_idx_type &, octave_idx_type &, Complex *, Complex *, Complex *, const octave_idx_type &, Complex *, const octave_idx_type &, Complex *, const octave_idx_type &, double *, octave_idx_type *, octave_idx_type &); } -DEFUN_DLD (qzcomplex, args, nargout, "-*- texinfo -*-\n\ +DEFUN_DLD(qzcomplex, args, nargout, "-*- texinfo -*-\n\ @deftypefn {Loadable Function} [ @var{aa}, @var{bb}, @var{q}, @var{z} ] = qzcomplex (@var{a}, @var{b})\n\ \n\ Computes the complex QZ decomposition of @math{(A, B)}, satisfying:\n\ @@ -76,14 +76,14 @@ Computes the complex QZ decomposition of @math{(A, B)}, satisfying:\n\ OCTAVE_LOCAL_BUFFER(Complex, beta, n); OCTAVE_LOCAL_BUFFER(Complex, work, lwork); OCTAVE_LOCAL_BUFFER(double, rwork, 8*n); - ComplexMatrix vsl(n, n), vsr(n,n); + ComplexMatrix vsl(n, n), vsr(n, n); octave_idx_type sdim, info; - - F77_XFCN (zgges, ZGGES, (F77_CONST_CHAR_ARG("V"), F77_CONST_CHAR_ARG("V"), - F77_CONST_CHAR_ARG("N"), NULL, - n, A.fortran_vec(), n, B.fortran_vec(), n, sdim, - alpha, beta, vsl.fortran_vec(), n, vsr.fortran_vec(), n, - work, lwork, rwork, NULL, info)); + + F77_XFCN(zgges, ZGGES, (F77_CONST_CHAR_ARG("V"), F77_CONST_CHAR_ARG("V"), + F77_CONST_CHAR_ARG("N"), NULL, + n, A.fortran_vec(), n, B.fortran_vec(), n, sdim, + alpha, beta, vsl.fortran_vec(), n, vsr.fortran_vec(), n, + work, lwork, rwork, NULL, info)); if (info != 0) { @@ -100,11 +100,11 @@ Computes the complex QZ decomposition of @math{(A, B)}, satisfying:\n\ /* -%!test -%! A = [ 1 2 3+1i; 4 5-1i 0; -1 -5 3]; -%! B = [ -2 -8i 4; 1 5+3i 5; 7 -10 -2]; -%! [AA,BB,Q,Z] = qzcomplex(A,B); -%! assert(Q'*A*Z, AA, sqrt(eps)) -%! assert(Q'*B*Z, BB, sqrt(eps)) + %!test + %! A = [ 1 2 3+1i; 4 5-1i 0; -1 -5 3]; + %! B = [ -2 -8i 4; 1 5+3i 5; 7 -10 -2]; + %! [AA,BB,Q,Z] = qzcomplex(A,B); + %! assert(Q'*A*Z, AA, sqrt(eps)) + %! assert(Q'*B*Z, BB, sqrt(eps)) */