diff --git a/dynare++/parser/cc/atom_assignings.h b/dynare++/parser/cc/atom_assignings.h index 2151f9bccbf545a7dcccdf627cfd702dd26a36bc..14f11b2cbf247d1df5e7d3193ab0e3bbd5b0f0f3 100644 --- a/dynare++/parser/cc/atom_assignings.h +++ b/dynare++/parser/cc/atom_assignings.h @@ -12,114 +12,126 @@ #include <vector> #include <map> -namespace ogp { +namespace ogp +{ - class AtomAsgnEvaluator; + class AtomAsgnEvaluator; - /** This class represents atom assignments used in parameters - * settings and initval initialization. It maintains atoms of the - * all expressions on the right hand side, the parsed formulas of - * the right hand sides, and the information about the left hand - * sides. See documentation to the order member below. */ - class AtomAssignings { - friend class AtomAsgnEvaluator; - protected: - typedef std::map<const char*, int, ltstr> Tvarintmap; - /** All atoms which should be sufficient for formulas at the - * right hand sides. The atoms should be filled with names - * (preregistered). This is a responsibility of the caller. */ - StaticAtoms& atoms; - /** The formulas of right hand sides. */ - FormulaParser expr; - /** Name storage of the names from left hand sides. */ - NameStorage left_names; - /** Information on left hand sides. This maps a name to the - * index of its assigned expression in expr. More than one - * name may reference to the same expression. */ - Tvarintmap lname2expr; - /** Information on left hand sides. If order[i] >= 0, then it - * says that i-th expression in expr is assigned to atom with - * order[i] tree index. */ - std::vector<int> order; - public: - /** Construct the object using the provided static atoms. */ - AtomAssignings(StaticAtoms& a) : atoms(a), expr(atoms) - {} - /** Make a copy with provided reference to (posibly different) - * static atoms. */ - AtomAssignings(const AtomAssignings& aa, StaticAtoms& a); - virtual ~AtomAssignings() - {} - /** Parse the assignments from the given string. */ - void parse(int length, const char* stream); - /** Process a syntax error from bison. */ - void error(const char* mes); - /** Add an assignment of the given name to the given - * double. Can be called by a user, anytime. */ - void add_assignment_to_double(const char* name, double val); - /** Add an assignment. Called from assign.y. */ - void add_assignment(int asgn_off, const char* str, int name_len, - int right_off, int right_len); - /** This applies old2new map (possibly from atom - * substitutions) to this object. It registers new variables - * in the atoms, and adds the expressions to expr, and left - * names to lname2expr. The information about dynamical part - * of substitutions is ignored, since we are now in the static - * world. */ - void apply_subst(const AtomSubstitutions::Toldnamemap& mm); - /** Debug print. */ - void print() const; - }; + /** This class represents atom assignments used in parameters + * settings and initval initialization. It maintains atoms of the + * all expressions on the right hand side, the parsed formulas of + * the right hand sides, and the information about the left hand + * sides. See documentation to the order member below. */ + class AtomAssignings + { + friend class AtomAsgnEvaluator; + protected: + typedef std::map<const char *, int, ltstr> Tvarintmap; + /** All atoms which should be sufficient for formulas at the + * right hand sides. The atoms should be filled with names + * (preregistered). This is a responsibility of the caller. */ + StaticAtoms &atoms; + /** The formulas of right hand sides. */ + FormulaParser expr; + /** Name storage of the names from left hand sides. */ + NameStorage left_names; + /** Information on left hand sides. This maps a name to the + * index of its assigned expression in expr. More than one + * name may reference to the same expression. */ + Tvarintmap lname2expr; + /** Information on left hand sides. If order[i] >= 0, then it + * says that i-th expression in expr is assigned to atom with + * order[i] tree index. */ + std::vector<int> order; + public: + /** Construct the object using the provided static atoms. */ + AtomAssignings(StaticAtoms &a) : atoms(a), expr(atoms) + { + } + /** Make a copy with provided reference to (posibly different) + * static atoms. */ + AtomAssignings(const AtomAssignings &aa, StaticAtoms &a); + virtual ~AtomAssignings() + { + } + /** Parse the assignments from the given string. */ + void parse(int length, const char *stream); + /** Process a syntax error from bison. */ + void error(const char *mes); + /** Add an assignment of the given name to the given + * double. Can be called by a user, anytime. */ + void add_assignment_to_double(const char *name, double val); + /** Add an assignment. Called from assign.y. */ + void add_assignment(int asgn_off, const char *str, int name_len, + int right_off, int right_len); + /** This applies old2new map (possibly from atom + * substitutions) to this object. It registers new variables + * in the atoms, and adds the expressions to expr, and left + * names to lname2expr. The information about dynamical part + * of substitutions is ignored, since we are now in the static + * world. */ + void apply_subst(const AtomSubstitutions::Toldnamemap &mm); + /** Debug print. */ + void print() const; + }; - /** This class basically evaluates the atom assignments - * AtomAssignings, so it inherits from ogp::FormulaEvaluator. It - * is also a storage for the results of the evaluation stored as a - * vector, so the class inherits from std::vector<double> and - * ogp::FormulaEvalLoader. As the expressions for atoms are - * evaluated, the results are values for atoms which will be - * used in subsequent evaluations. For this reason, the class - * inherits also from AtomValues. */ - class AtomAsgnEvaluator : public FormulaEvalLoader, - public AtomValues, - protected FormulaEvaluator, - public std::vector<double> { - protected: - typedef std::map<int, double> Tusrvalmap; - Tusrvalmap user_values; - const AtomAssignings& aa; - public: - AtomAsgnEvaluator(const AtomAssignings& a) - : FormulaEvaluator(a.expr), - std::vector<double>(a.expr.nformulas()), aa(a) {} - virtual ~AtomAsgnEvaluator() {} - /** This sets all initial values to NaNs, all constants and - * all values set by user by call set_value. This is called by - * FormulaEvaluator::eval() method, which is called by eval() - * method passing this argument as AtomValues. So the - * ogp::EvalTree will be always this->etree. */ - void setValues(EvalTree& et) const; - /** User setting of the values. For example in initval, - * parameters are known and should be set to their values. In - * constrast endogenous variables are set initially to NaNs by - * AtomValues::setValues. */ - void set_user_value(const char* name, double val); - /** This sets the result of i-th expression in aa to res, and - * also checks whether the i-th expression is an atom. If so, - * it sets the value of the atom in ogp::EvalTree - * this->etree. */ - void load(int i, double res); - /** After the user values have been set, the assignments can - * be evaluated. For this purpose we have eval() method. The - * result is that this object as std::vector<double> will - * contain the values. It is ordered given by formulas in - * expr. */ - void eval() - {FormulaEvaluator::eval(*this, *this);} - /** This returns a value for a given name. If the name is not - * found among atoms, or there is no assignment for the atom, - * NaN is returned. */ - double get_value(const char* name) const; - }; + /** This class basically evaluates the atom assignments + * AtomAssignings, so it inherits from ogp::FormulaEvaluator. It + * is also a storage for the results of the evaluation stored as a + * vector, so the class inherits from std::vector<double> and + * ogp::FormulaEvalLoader. As the expressions for atoms are + * evaluated, the results are values for atoms which will be + * used in subsequent evaluations. For this reason, the class + * inherits also from AtomValues. */ + class AtomAsgnEvaluator : public FormulaEvalLoader, + public AtomValues, + protected FormulaEvaluator, + public std::vector<double> + { + protected: + typedef std::map<int, double> Tusrvalmap; + Tusrvalmap user_values; + const AtomAssignings &aa; + public: + AtomAsgnEvaluator(const AtomAssignings &a) + : FormulaEvaluator(a.expr), + std::vector<double>(a.expr.nformulas()), aa(a) + { + } + virtual ~AtomAsgnEvaluator() + { + } + /** This sets all initial values to NaNs, all constants and + * all values set by user by call set_value. This is called by + * FormulaEvaluator::eval() method, which is called by eval() + * method passing this argument as AtomValues. So the + * ogp::EvalTree will be always this->etree. */ + void setValues(EvalTree &et) const; + /** User setting of the values. For example in initval, + * parameters are known and should be set to their values. In + * constrast endogenous variables are set initially to NaNs by + * AtomValues::setValues. */ + void set_user_value(const char *name, double val); + /** This sets the result of i-th expression in aa to res, and + * also checks whether the i-th expression is an atom. If so, + * it sets the value of the atom in ogp::EvalTree + * this->etree. */ + void load(int i, double res); + /** After the user values have been set, the assignments can + * be evaluated. For this purpose we have eval() method. The + * result is that this object as std::vector<double> will + * contain the values. It is ordered given by formulas in + * expr. */ + void + eval() + { + FormulaEvaluator::eval(*this, *this); + } + /** This returns a value for a given name. If the name is not + * found among atoms, or there is no assignment for the atom, + * NaN is returned. */ + double get_value(const char *name) const; + }; }; diff --git a/dynare++/parser/cc/atom_substitutions.h b/dynare++/parser/cc/atom_substitutions.h index 82c99946b08e47840b4f98995ab062fd85e472fd..a0e060960d7e3abbdfd73c82bc67ed391d4d99a3 100644 --- a/dynare++/parser/cc/atom_substitutions.h +++ b/dynare++/parser/cc/atom_substitutions.h @@ -9,148 +9,185 @@ #include <string> -namespace ogp { +namespace ogp +{ - using std::string; - using std::map; - using std::pair; + using std::string; + using std::map; + using std::pair; - /** This class tracts an information about the performed - * substitutions. In fact, there is only one number to keep track - * about, this is a number of substitutions. */ - struct SubstInfo { - int num_substs; - SubstInfo() : num_substs(0) {} - }; + /** This class tracts an information about the performed + * substitutions. In fact, there is only one number to keep track + * about, this is a number of substitutions. */ + struct SubstInfo + { + int num_substs; + SubstInfo() : num_substs(0) + { + } + }; - /** This class tracks all atom substitutions during the job and - * then builds structures when all substitutions are finished. */ - class AtomSubstitutions { - public: - typedef pair<const char*, int> Tshiftname; - typedef map<const char*, Tshiftname, ltstr> Tshiftmap; - typedef set<Tshiftname> Tshiftnameset; - typedef map<const char*, Tshiftnameset, ltstr> Toldnamemap; - protected: - /** This maps a new name to a shifted old name. This is, one - * entry looks as "a_m3 ==> a(-3)", saying that a variable - * "a_m3" corresponds to a variable "a" lagged by 3. */ - Tshiftmap new2old; - /** This is inverse to new2old, which is not unique. For old - * name, say "a", it says what new names are derived with what - * shifts from the "a". For example, it can map "a" to a two - * element set {["a_m3", +3], ["a_p2", -2]}. This says that - * leading "a_m3" by 3 one gets old "a" and lagging "a_p2" by - * 2 one gets also old "a". */ - Toldnamemap old2new; - /** This is a reference to old atoms with multiple leads and - * lags. They are supposed to be used with parsing finished - * being had called, so that the external ordering is - * available. */ - const FineAtoms& old_atoms; - /** This is a reference to new atoms. All name pointers point - * to storage of these atoms. */ - FineAtoms& new_atoms; - /** Substitutions information. */ - SubstInfo info; - public: - /** Create the object with reference to the old and new - * atoms. In the beginning, old atoms are supposed to be with - * parsing_finished() called, and new atoms a simple copy of - * old atoms. The new atoms will be an instance of SAtoms. All - * substitution job is done by a substitution method of the - * new atoms. */ - AtomSubstitutions(const FineAtoms& oa, FineAtoms& na) - : old_atoms(oa), new_atoms(na) {} - /** Construct a copy of the object using a different instances - * of old atoms and new atoms, which are supposed to be - * semantically same as the atoms from as. */ - AtomSubstitutions(const AtomSubstitutions& as, const FineAtoms& oa, FineAtoms& na); - virtual ~AtomSubstitutions() {} - /** This is called during the substitution job from the - * substitution method of the new atoms. This says that the - * new name, say "a_m3" is a substitution of old name "a" - * shifted by -3. */ - void add_substitution(const char* newname, const char* oldname, int tshift); - /** This is called when all substitutions are finished. This - * forms the new external ordering of the new atoms and calls - * parsing_finished() for the new atoms with the given ordering type. */ - void substitutions_finished(VarOrdering::ord_type ot); - /** Returns a new name for old name and given tshift. For "a" - * and tshift=-3, it returns "a_m3". If there is no such - * substitution, it returns NULL. */ - const char* get_new4old(const char* oldname, int tshift) const; - /** Return new2old. */ - const Tshiftmap& get_new2old() const - {return new2old;} - /** Return old2new. */ - const Toldnamemap& get_old2new() const - {return old2new;} - /** Return substitution info. */ - const SubstInfo& get_info() const - {return info;} - /** Return old atoms. */ - const FineAtoms& get_old_atoms() const - {return old_atoms;} - /** Return new atoms. */ - const FineAtoms& get_new_atoms() const - {return new_atoms;} - /** Debug print. */ - void print() const; - }; + /** This class tracks all atom substitutions during the job and + * then builds structures when all substitutions are finished. */ + class AtomSubstitutions + { + public: + typedef pair<const char *, int> Tshiftname; + typedef map<const char *, Tshiftname, ltstr> Tshiftmap; + typedef set<Tshiftname> Tshiftnameset; + typedef map<const char *, Tshiftnameset, ltstr> Toldnamemap; + protected: + /** This maps a new name to a shifted old name. This is, one + * entry looks as "a_m3 ==> a(-3)", saying that a variable + * "a_m3" corresponds to a variable "a" lagged by 3. */ + Tshiftmap new2old; + /** This is inverse to new2old, which is not unique. For old + * name, say "a", it says what new names are derived with what + * shifts from the "a". For example, it can map "a" to a two + * element set {["a_m3", +3], ["a_p2", -2]}. This says that + * leading "a_m3" by 3 one gets old "a" and lagging "a_p2" by + * 2 one gets also old "a". */ + Toldnamemap old2new; + /** This is a reference to old atoms with multiple leads and + * lags. They are supposed to be used with parsing finished + * being had called, so that the external ordering is + * available. */ + const FineAtoms &old_atoms; + /** This is a reference to new atoms. All name pointers point + * to storage of these atoms. */ + FineAtoms &new_atoms; + /** Substitutions information. */ + SubstInfo info; + public: + /** Create the object with reference to the old and new + * atoms. In the beginning, old atoms are supposed to be with + * parsing_finished() called, and new atoms a simple copy of + * old atoms. The new atoms will be an instance of SAtoms. All + * substitution job is done by a substitution method of the + * new atoms. */ + AtomSubstitutions(const FineAtoms &oa, FineAtoms &na) + : old_atoms(oa), new_atoms(na) + { + } + /** Construct a copy of the object using a different instances + * of old atoms and new atoms, which are supposed to be + * semantically same as the atoms from as. */ + AtomSubstitutions(const AtomSubstitutions &as, const FineAtoms &oa, FineAtoms &na); + virtual ~AtomSubstitutions() + { + } + /** This is called during the substitution job from the + * substitution method of the new atoms. This says that the + * new name, say "a_m3" is a substitution of old name "a" + * shifted by -3. */ + void add_substitution(const char *newname, const char *oldname, int tshift); + /** This is called when all substitutions are finished. This + * forms the new external ordering of the new atoms and calls + * parsing_finished() for the new atoms with the given ordering type. */ + void substitutions_finished(VarOrdering::ord_type ot); + /** Returns a new name for old name and given tshift. For "a" + * and tshift=-3, it returns "a_m3". If there is no such + * substitution, it returns NULL. */ + const char *get_new4old(const char *oldname, int tshift) const; + /** Return new2old. */ + const Tshiftmap & + get_new2old() const + { + return new2old; + } + /** Return old2new. */ + const Toldnamemap & + get_old2new() const + { + return old2new; + } + /** Return substitution info. */ + const SubstInfo & + get_info() const + { + return info; + } + /** Return old atoms. */ + const FineAtoms & + get_old_atoms() const + { + return old_atoms; + } + /** Return new atoms. */ + const FineAtoms & + get_new_atoms() const + { + return new_atoms; + } + /** Debug print. */ + void print() const; + }; - class SAtoms : public FineAtoms { - public: - SAtoms() - : FineAtoms() {} - SAtoms(const SAtoms& sa) - : FineAtoms(sa) {} - virtual ~SAtoms() {} - /** This substitutes all lags and leads for all exogenous and - * all lags and leads greater than 1 for all endogenous - * variables. This is useful for perfect foresight problems - * where we can do that. */ - void substituteAllLagsAndLeads(FormulaParser& fp, AtomSubstitutions& as); - /** This substitutes all lags of all endo and exo and one step - * leads of all exo variables. This is useful for stochastic - * models where we cannot solve leads more than 1. */ - void substituteAllLagsAndExo1Leads(FormulaParser& fp, AtomSubstitutions& as); - protected: - /** This finds an endogenous variable name which occurs between - * ll1 and ll2 included. */ - const char* findEndoWithLeadInInterval(int ll1, int ll2) const - {return findNameWithLeadInInterval(get_endovars(), ll1, ll2);} - /** This finds an exogenous variable name which occurs between - * ll1 and ll2 included. */ - const char* findExoWithLeadInInterval(int ll1, int ll2) const - {return findNameWithLeadInInterval(get_exovars(), ll1, ll2);} + class SAtoms : public FineAtoms + { + public: + SAtoms() + : FineAtoms() + { + } + SAtoms(const SAtoms &sa) + : FineAtoms(sa) + { + } + virtual ~SAtoms() + { + } + /** This substitutes all lags and leads for all exogenous and + * all lags and leads greater than 1 for all endogenous + * variables. This is useful for perfect foresight problems + * where we can do that. */ + void substituteAllLagsAndLeads(FormulaParser &fp, AtomSubstitutions &as); + /** This substitutes all lags of all endo and exo and one step + * leads of all exo variables. This is useful for stochastic + * models where we cannot solve leads more than 1. */ + void substituteAllLagsAndExo1Leads(FormulaParser &fp, AtomSubstitutions &as); + protected: + /** This finds an endogenous variable name which occurs between + * ll1 and ll2 included. */ + const char * + findEndoWithLeadInInterval(int ll1, int ll2) const + { + return findNameWithLeadInInterval(get_endovars(), ll1, ll2); + } + /** This finds an exogenous variable name which occurs between + * ll1 and ll2 included. */ + const char * + findExoWithLeadInInterval(int ll1, int ll2) const + { + return findNameWithLeadInInterval(get_exovars(), ll1, ll2); + } - /** This attempts to find a non registered name of the form - * <str>_m<abs(ll)> or <str>_p<abs(ll)>. A letter 'p' is - * chosen if ll is positive, 'm' if negative. If a name of - * such form is already registered, one more character (either - * 'p' or 'm') is added and the test is performed again. The - * resulting name is returned in a string out. */ - void attemptAuxName(const char* str, int ll, string& out) const; + /** This attempts to find a non registered name of the form + * <str>_m<abs(ll)> or <str>_p<abs(ll)>. A letter 'p' is + * chosen if ll is positive, 'm' if negative. If a name of + * such form is already registered, one more character (either + * 'p' or 'm') is added and the test is performed again. The + * resulting name is returned in a string out. */ + void attemptAuxName(const char *str, int ll, string &out) const; - /** This makes auxiliary variables to eliminate all leads/lags - * greater/less than or equal to start up to the limit_lead - * for a variable with the given name. If the limit_lead is - * greater/less than the maxlead/minlag of the variable, than - * maxlead/minlag is used. This process is recorded in - * AtomSubstitutions. The new auxiliary variables and their - * atoms are created in this object. The auxiliary equations - * are created in the given FormulaParser. The value of step - * is allowed to be either -1 (lags) or +1 (leads). */ - void makeAuxVariables(const char* name, int step, int start, int limit_lead, - FormulaParser& fp, AtomSubstitutions& as); - private: - /** This is a worker routine for findEndoWithLeadInInterval - * and findExoWithLeadInInterval. */ - const char* findNameWithLeadInInterval(const vector<const char*>& names, - int ll1, int ll2) const; + /** This makes auxiliary variables to eliminate all leads/lags + * greater/less than or equal to start up to the limit_lead + * for a variable with the given name. If the limit_lead is + * greater/less than the maxlead/minlag of the variable, than + * maxlead/minlag is used. This process is recorded in + * AtomSubstitutions. The new auxiliary variables and their + * atoms are created in this object. The auxiliary equations + * are created in the given FormulaParser. The value of step + * is allowed to be either -1 (lags) or +1 (leads). */ + void makeAuxVariables(const char *name, int step, int start, int limit_lead, + FormulaParser &fp, AtomSubstitutions &as); + private: + /** This is a worker routine for findEndoWithLeadInInterval + * and findExoWithLeadInInterval. */ + const char *findNameWithLeadInInterval(const vector<const char *> &names, + int ll1, int ll2) const; - }; + }; }; diff --git a/dynare++/parser/cc/csv_parser.h b/dynare++/parser/cc/csv_parser.h index 3edc52a4e92f6d6d0f0ce830943ae330da09d942..95b12354e995b8976fc7b14221c082b3bf400e29 100644 --- a/dynare++/parser/cc/csv_parser.h +++ b/dynare++/parser/cc/csv_parser.h @@ -5,38 +5,58 @@ #ifndef OGP_CSV_PARSER #define OGP_CSV_PARSER -namespace ogp { - - class CSVParserPeer { - public: - virtual ~CSVParserPeer() {} - virtual void item(int irow, int icol, const char* str, int length) = 0; - }; - - class CSVParser { - private: - CSVParserPeer& peer; - int row; - int col; - const char* parsed_string; - public: - CSVParser(CSVParserPeer& p) - : peer(p), row(0), col(0), parsed_string(0) {} - CSVParser(const CSVParser& csvp) - : peer(csvp.peer), row(csvp.row), - col(csvp.col), parsed_string(csvp.parsed_string) {} - virtual ~CSVParser() {} - - void csv_error(const char* mes); - void csv_parse(int length, const char* str); - - void nextrow() - {row++; col = 0;} - void nextcol() - {col++;} - void item(int off, int length) - {peer.item(row, col, parsed_string+off, length);} - }; +namespace ogp +{ + + class CSVParserPeer + { + public: + virtual ~CSVParserPeer() + { + } + virtual void item(int irow, int icol, const char *str, int length) = 0; + }; + + class CSVParser + { + private: + CSVParserPeer &peer; + int row; + int col; + const char *parsed_string; + public: + CSVParser(CSVParserPeer &p) + : peer(p), row(0), col(0), parsed_string(0) + { + } + CSVParser(const CSVParser &csvp) + : peer(csvp.peer), row(csvp.row), + col(csvp.col), parsed_string(csvp.parsed_string) + { + } + virtual ~CSVParser() + { + } + + void csv_error(const char *mes); + void csv_parse(int length, const char *str); + + void + nextrow() + { + row++; col = 0; + } + void + nextcol() + { + col++; + } + void + item(int off, int length) + { + peer.item(row, col, parsed_string+off, length); + } + }; }; #endif diff --git a/dynare++/parser/cc/dynamic_atoms.h b/dynare++/parser/cc/dynamic_atoms.h index 7d44d6dcc2e71faa4066145281b9229dbd6c7bc5..cf28da2ef67b5e74b9125919c6bc251881d09a21 100644 --- a/dynare++/parser/cc/dynamic_atoms.h +++ b/dynare++/parser/cc/dynamic_atoms.h @@ -13,389 +13,462 @@ #include <string> #include <cstring> -namespace ogp { - using std::vector; - using std::map; - using std::set; - using std::string; +namespace ogp +{ + using std::vector; + using std::map; + using std::set; + using std::string; - struct ltstr { - bool operator()(const char* a1, const char* a2) const - { return strcmp(a1, a2) < 0; } - }; + struct ltstr + { + bool + operator()(const char *a1, const char *a2) const + { + return strcmp(a1, a2) < 0; + } + }; - /** Class storing names. We will keep names of variables in - * various places, and all these pointers will point to one - * storage, which will be responsible for allocation and - * deallocation. The main function of the class is to allocate - * space for names, and return a pointer of the stored name if - * required. */ - class NameStorage { - protected: - /** Vector of names allocated, this is the storage. */ - vector<char*> name_store; - /** Map useful to quickly decide if the name is already - * allocated or not. */ - set<const char*, ltstr> name_set; - public: - NameStorage() {} - NameStorage(const NameStorage& stor); - virtual ~NameStorage(); - /** Query for the name. If the name has been stored, it - * returns its address, otherwise 0. */ - const char* query(const char* name) const; - /** Insert the name if it has not been inserted yet, and - * return its new or old allocation. */ - const char* insert(const char* name); - int num() const - {return (int)name_store.size();} - const char* get_name(int i) const - {return name_store[i];} - /** Debug print. */ - void print() const; - }; + /** Class storing names. We will keep names of variables in + * various places, and all these pointers will point to one + * storage, which will be responsible for allocation and + * deallocation. The main function of the class is to allocate + * space for names, and return a pointer of the stored name if + * required. */ + class NameStorage + { + protected: + /** Vector of names allocated, this is the storage. */ + vector<char *> name_store; + /** Map useful to quickly decide if the name is already + * allocated or not. */ + set<const char *, ltstr> name_set; + public: + NameStorage() + { + } + NameStorage(const NameStorage &stor); + virtual + ~NameStorage(); + /** Query for the name. If the name has been stored, it + * returns its address, otherwise 0. */ + const char *query(const char *name) const; + /** Insert the name if it has not been inserted yet, and + * return its new or old allocation. */ + const char *insert(const char *name); + int + num() const + { + return (int) name_store.size(); + } + const char * + get_name(int i) const + { + return name_store[i]; + } + /** Debug print. */ + void print() const; + }; - class Constants : public AtomValues { - public: - /** Type for a map mapping tree indices to double values. */ - typedef map<int,double> Tconstantmap; - typedef map<int,int> Tintintmap; - protected: - /** Map mapping a tree index of a constant to its double value. */ - Tconstantmap cmap; - public: - Constants() {} - /** Copy constructor. */ - Constants(const Constants& c) - : cmap(c.cmap), cinvmap(c.cinvmap) {} - /** Copy constructor registering the constants in the given - * tree. The mapping from old tree indices to new ones is - * traced in tmap. */ - Constants(const Constants& c, OperationTree& otree, Tintintmap& tmap) - {import_constants(c, otree, tmap);} - /** Import constants registering their tree indices in the - * given tree. The mapping form old tree indices to new ones - * is traced in tmap. */ - void import_constants(const Constants& c, OperationTree& otree, Tintintmap& tmap); - /** Implements AtomValues interface. This sets the values to - * the evaluation tree EvalTree. */ - void setValues(EvalTree& et) const; - /** This adds a constant with the given tree index. The - * constant must be checked previously and asserted that it - * does not exist. */ - void add_constant(int t, double val); - /** Returns true if the tree index is either an hardwired - * constant (initial number OperationTree:num_constants in - * OperationTree) or the tree index is a registered constant - * by add_constant method. */ - bool is_constant(int t) const; - double get_constant_value(int t) const; - /** Return -1 if the given string representation of a constant - * is not among the constants (double represenations). If it - * is, its tree index is returned. */ - int check(const char* str) const; - /** Debug print. */ - void print() const; - const Tconstantmap& get_constantmap() const - {return cmap;} - private: - /** Inverse map to Tconstantmap. */ - typedef map<double,int> Tconstantinvmap; - /** This is an inverse map to cmap. This is only used for fast - * queries for the existing double constants in check - * method and add_constant. */ - Tconstantinvmap cinvmap; - }; + class Constants : public AtomValues + { + public: + /** Type for a map mapping tree indices to double values. */ + typedef map<int, double> Tconstantmap; + typedef map<int, int> Tintintmap; + protected: + /** Map mapping a tree index of a constant to its double value. */ + Tconstantmap cmap; + public: + Constants() + { + } + /** Copy constructor. */ + Constants(const Constants &c) + : cmap(c.cmap), cinvmap(c.cinvmap) + { + } + /** Copy constructor registering the constants in the given + * tree. The mapping from old tree indices to new ones is + * traced in tmap. */ + Constants(const Constants &c, OperationTree &otree, Tintintmap &tmap) + { + import_constants(c, otree, tmap); + } + /** Import constants registering their tree indices in the + * given tree. The mapping form old tree indices to new ones + * is traced in tmap. */ + void import_constants(const Constants &c, OperationTree &otree, Tintintmap &tmap); + /** Implements AtomValues interface. This sets the values to + * the evaluation tree EvalTree. */ + void setValues(EvalTree &et) const; + /** This adds a constant with the given tree index. The + * constant must be checked previously and asserted that it + * does not exist. */ + void add_constant(int t, double val); + /** Returns true if the tree index is either an hardwired + * constant (initial number OperationTree:num_constants in + * OperationTree) or the tree index is a registered constant + * by add_constant method. */ + bool is_constant(int t) const; + double get_constant_value(int t) const; + /** Return -1 if the given string representation of a constant + * is not among the constants (double represenations). If it + * is, its tree index is returned. */ + int check(const char *str) const; + /** Debug print. */ + void print() const; + const Tconstantmap & + get_constantmap() const + { + return cmap; + } + private: + /** Inverse map to Tconstantmap. */ + typedef map<double, int> Tconstantinvmap; + /** This is an inverse map to cmap. This is only used for fast + * queries for the existing double constants in check + * method and add_constant. */ + Tconstantinvmap cinvmap; + }; - /** This class is a parent to Atoms classes which distinguish between - * constants (numerical literals), and variables with lags and - * leads. This abstraction does not distinguish between a parameter - * and a variable without lag or lead. In this sense, everything is a - * variable.*/ - class DynamicAtoms : public Atoms, public Constants { - public: - /** Definition of a type mapping lags to the indices of the variables. */ - typedef map<int,int> Tlagmap; - protected: - /** Definition of a type mapping names of the atoms to Tlagmap. */ - typedef map<const char*, Tlagmap, ltstr> Tvarmap; - /** Definition of a type mapping indices of variables to the variable names. */ - typedef map<int, const char*> Tindexmap; - /** This is just a storage for variable names, since all other - * instances of a variable name just point to the memory - * allocated by this object. */ - NameStorage varnames; - /** This is the map for variables. Each variable name is - * mapped to the Tlagmap, which maps lags/leads to the nulary - * term indices in the tree. */ - Tvarmap vars; - /** This is almost inverse map to the vars. It maps variable - * indices to the names. A returned name can be in turn used - * as a key in vars. */ - Tindexmap indices; + /** This class is a parent to Atoms classes which distinguish between + * constants (numerical literals), and variables with lags and + * leads. This abstraction does not distinguish between a parameter + * and a variable without lag or lead. In this sense, everything is a + * variable.*/ + class DynamicAtoms : public Atoms, public Constants + { + public: + /** Definition of a type mapping lags to the indices of the variables. */ + typedef map<int, int> Tlagmap; + protected: + /** Definition of a type mapping names of the atoms to Tlagmap. */ + typedef map<const char *, Tlagmap, ltstr> Tvarmap; + /** Definition of a type mapping indices of variables to the variable names. */ + typedef map<int, const char *> Tindexmap; + /** This is just a storage for variable names, since all other + * instances of a variable name just point to the memory + * allocated by this object. */ + NameStorage varnames; + /** This is the map for variables. Each variable name is + * mapped to the Tlagmap, which maps lags/leads to the nulary + * term indices in the tree. */ + Tvarmap vars; + /** This is almost inverse map to the vars. It maps variable + * indices to the names. A returned name can be in turn used + * as a key in vars. */ + Tindexmap indices; - /** Number of variables. */ - int nv; - /** Minimum lag, if there is at least one lag, than this is a negative number. */ - int minlag; - /** Maximum lead, if there is at least one lead, than this is a positive number. */ - int maxlead; - public: - /** Construct empty DynamicAtoms. */ - DynamicAtoms(); - DynamicAtoms(const DynamicAtoms& da); - virtual ~DynamicAtoms() {} - /** Check the nulary term identified by its string - * representation. The nulary term can be either a constant or - * a variable. If constant, -1 is returned so that it could be - * assigned regardless if the same constant has already - * appeared or not. If variable, then -1 is returned only if - * the variable has not been assigned an index, otherwise the - * assigned index is returned. */ - int check(const char* name) const; - /** Assign the nulary term identified by its string - * representation. This method should be called when check() - * returns -1. */ - void assign(const char* name, int t); - /** Return a number of all variables. */ - int nvar() const - { return nv; } - /** Return the vector of variable indices. */ - vector<int> variables() const; - /** Return max lead and min lag for a variable given by the - * index. If a variable cannot be found, the method retursn - * the smallest integer as maxlead and the largest integer as - * minlag. */ - void varspan(int t, int& mlead, int& mlag) const; - /** Return max lead and min lag for a variable given by the - * name (without lead, lag). The same is valid if the variable - * name cannot be found. */ - void varspan(const char* name, int& mlead, int& mlag) const; - /** Return max lead and min lag for a vector of variables given by the names. */ - void varspan(const vector<const char*>& names, int& mlead, int& mlag) const; - /** Return true for all tree indices corresponding to a - * variable in the sense of this class. (This is parameters, - * exo and endo). Since the semantics of 'variable' will be - * changed in subclasses, we use name 'named atom'. These are - * all atoms but constants. */ - bool is_named_atom(int t) const; - /** Return index of the variable described by the variable - * name and lag/lead. If it doesn't exist, return -1. */ - int index(const char* name, int ll) const; - /** Return true if a variable is referenced, i.e. it has lag - * map. */ - bool is_referenced(const char* name) const; - /** Return the lag map for the variable name. */ - const Tlagmap& lagmap(const char* name) const; - /** Return the variable name for the tree index. It throws an - * exception if the tree index t is not a named atom. */ - const char* name(int t) const; - /** Return the lead/lag for the tree index. It throws an - * exception if the tree index t is not a named atom. */ - int lead(int t) const; - /** Return maximum lead. */ - int get_maxlead() const - {return maxlead;} - /** Return minimum lag. */ - int get_minlag() const - {return minlag;} - /** Return the name storage to allow querying to other - * classes. */ - const NameStorage& get_name_storage() const - {return varnames;} - /** Assign the variable with a given lead. The varname must be - * from the varnames storage. The method checks if the - * variable iwht the given lead/lag is not assigned. If so, an - * exception is thrown. */ - void assign_variable(const char* varname, int ll, int t); - /** Unassign the variable with a given lead and given tree - * index. The tree index is only provided as a check. An - * exception is thrown if the name, ll, and the tree index t - * are not consistent. The method also updates nv, indices, - * maxlead and minlag. The varname must be from the varnames - * storage. */ - void unassign_variable(const char* varname, int ll, int t); - /** Debug print. */ - void print() const; - protected: - /** Do the check for the variable. A subclass may need to - * reimplement this so that it could raise an error if the - * variable is not among a given list. */ - virtual int check_variable(const char* name) const; - /** Assign the constant. */ - void assign_constant(const char* name, int t); - /** Assign the variable. */ - void assign_variable(const char* name, int t); - /** The method just updates minlag or/and maxlead. Note that - * when assigning variables, the update is done when inserting - * to the maps, however, if removing a variable, we need to - * call this method. */ - void update_minmaxll(); - /** The method parses the string to recover a variable name - * and lag/lead ll. The variable name doesn't contain a lead/lag. */ - virtual void parse_variable(const char* in, string& out, int& ll) const = 0; - public: - /** Return true if the str represents a double.*/ - static bool is_string_constant(const char* str); - }; + /** Number of variables. */ + int nv; + /** Minimum lag, if there is at least one lag, than this is a negative number. */ + int minlag; + /** Maximum lead, if there is at least one lead, than this is a positive number. */ + int maxlead; + public: + /** Construct empty DynamicAtoms. */ + DynamicAtoms(); + DynamicAtoms(const DynamicAtoms &da); + virtual ~DynamicAtoms() + { + } + /** Check the nulary term identified by its string + * representation. The nulary term can be either a constant or + * a variable. If constant, -1 is returned so that it could be + * assigned regardless if the same constant has already + * appeared or not. If variable, then -1 is returned only if + * the variable has not been assigned an index, otherwise the + * assigned index is returned. */ + int check(const char *name) const; + /** Assign the nulary term identified by its string + * representation. This method should be called when check() + * returns -1. */ + void assign(const char *name, int t); + /** Return a number of all variables. */ + int + nvar() const + { + return nv; + } + /** Return the vector of variable indices. */ + vector<int> variables() const; + /** Return max lead and min lag for a variable given by the + * index. If a variable cannot be found, the method retursn + * the smallest integer as maxlead and the largest integer as + * minlag. */ + void varspan(int t, int &mlead, int &mlag) const; + /** Return max lead and min lag for a variable given by the + * name (without lead, lag). The same is valid if the variable + * name cannot be found. */ + void varspan(const char *name, int &mlead, int &mlag) const; + /** Return max lead and min lag for a vector of variables given by the names. */ + void varspan(const vector<const char *> &names, int &mlead, int &mlag) const; + /** Return true for all tree indices corresponding to a + * variable in the sense of this class. (This is parameters, + * exo and endo). Since the semantics of 'variable' will be + * changed in subclasses, we use name 'named atom'. These are + * all atoms but constants. */ + bool is_named_atom(int t) const; + /** Return index of the variable described by the variable + * name and lag/lead. If it doesn't exist, return -1. */ + int index(const char *name, int ll) const; + /** Return true if a variable is referenced, i.e. it has lag + * map. */ + bool is_referenced(const char *name) const; + /** Return the lag map for the variable name. */ + const Tlagmap&lagmap(const char *name) const; + /** Return the variable name for the tree index. It throws an + * exception if the tree index t is not a named atom. */ + const char *name(int t) const; + /** Return the lead/lag for the tree index. It throws an + * exception if the tree index t is not a named atom. */ + int lead(int t) const; + /** Return maximum lead. */ + int + get_maxlead() const + { + return maxlead; + } + /** Return minimum lag. */ + int + get_minlag() const + { + return minlag; + } + /** Return the name storage to allow querying to other + * classes. */ + const NameStorage & + get_name_storage() const + { + return varnames; + } + /** Assign the variable with a given lead. The varname must be + * from the varnames storage. The method checks if the + * variable iwht the given lead/lag is not assigned. If so, an + * exception is thrown. */ + void assign_variable(const char *varname, int ll, int t); + /** Unassign the variable with a given lead and given tree + * index. The tree index is only provided as a check. An + * exception is thrown if the name, ll, and the tree index t + * are not consistent. The method also updates nv, indices, + * maxlead and minlag. The varname must be from the varnames + * storage. */ + void unassign_variable(const char *varname, int ll, int t); + /** Debug print. */ + void print() const; + protected: + /** Do the check for the variable. A subclass may need to + * reimplement this so that it could raise an error if the + * variable is not among a given list. */ + virtual int check_variable(const char *name) const; + /** Assign the constant. */ + void assign_constant(const char *name, int t); + /** Assign the variable. */ + void assign_variable(const char *name, int t); + /** The method just updates minlag or/and maxlead. Note that + * when assigning variables, the update is done when inserting + * to the maps, however, if removing a variable, we need to + * call this method. */ + void update_minmaxll(); + /** The method parses the string to recover a variable name + * and lag/lead ll. The variable name doesn't contain a lead/lag. */ + virtual void parse_variable(const char *in, string &out, int &ll) const = 0; + public: + /** Return true if the str represents a double.*/ + static bool is_string_constant(const char *str); + }; - - /** This class is a parent of all orderings of the dynamic atoms - * of variables which can appear before t, at t, or after t. It - * encapsulates the ordering, and the information about the number - * of static (appearing only at time t) predetermined (appearing - * before t and possibly at t), both (appearing before t and after - * t and possibly at t) and forward looking (appearing after t and - * possibly at t). - * - * The constructor takes a list of variable names. The class also - * provides mapping from the ordering of the variables in the list - * (outer) to the new ordering (at time t) and back. - * - * The user of the subclass must call do_ordering() after - * initialization. - * - * The class contains a few preimplemented methods for - * ordering. The class is used in this way: Make a subclass, and - * implement pure virtual do_ordering() by just plugging a - * preimplemented method, or plugging your own implementation. The - * method do_ordering() is called by the user after the constructor. - */ - class VarOrdering { - protected: - /** Number of static variables. */ - int n_stat; - /** Number of predetermined variables. */ - int n_pred; - /** Number of both variables. */ - int n_both; - /** Number of forward looking variables. */ - int n_forw; - /** This is a set of tree indices corresponding to the - * variables at all times as they occur in the formulas. In - * fact, since this is used only for derivatives, the ordering - * of this vector is only important for ordering of the - * derivatives, in other contexts the ordering is not - * important, so it is rather a set of indices.*/ - vector<int> der_atoms; - /** This maps tree index of the variable to the position in - * the row of the ordering. One should be careful with making - * space in the positions for variables not appearing at time - * t. For instance in the pred(t-1), both(t-1), stat(t), - * pred(t), both(t), forw(t), both(t+1), forw(t+1) ordering, - * the variables x(t-1), y(t-1), x(t+1), z(t-1), z(t), and - * z(t+1) having tree indices 6,5,4,3,2,1 will be ordered as - * follows: y(t-1), x(t-1), z(t-1), [y(t)], [x(t)], z(t), - * x(t+1), where a bracketed expresion means non-existent by - * occupying a space. The map thus will look as follows: - * {5->0, 6->1, 3->2, 2->5, 3->6}. Note that nothing is mapped - * to positions 3 and 4. */ - map<int,int> positions; - /** This maps an ordering of the list of variables in - * constructor to the new ordering (at time t). The length is - * the number of variables. */ - vector<int> outer2y; - /** This maps a new ordering to the ordering of the list of - * variables in constructor (at time t). The length is the - * number of variables. */ - vector<int> y2outer; - /** This is just a reference for variable names to keep it - * from constructor to do_ordering() implementations. */ - const vector<const char*>& varnames; - /** This is just a reference to atoms to keep it from - * constructor to do_ordering() implementations. */ - const DynamicAtoms& atoms; - public: - /** This is an enum type for an ordering type implemented by - * do_general. */ - enum ord_type {pbspbfbf, bfspbfpb}; - /** Construct the ordering of the variables given by the names - * with their dynamic occurrences defined by the atoms. It - * calls the virtual method do_ordering which can be - * reimplemented. */ - VarOrdering(const vector<const char*>& vnames, const DynamicAtoms& a) - : n_stat(0), n_pred(0), n_both(0), n_forw(0), varnames(vnames), atoms(a) - {} - VarOrdering(const VarOrdering& vo, const vector<const char*>& vnames, - const DynamicAtoms& a); - virtual VarOrdering* clone(const vector<const char*>& vnames, - const DynamicAtoms& a) const = 0; - /** Destructor does nothing here. */ - virtual ~VarOrdering() {} - /** This is the method setting the ordering and the map. A - * subclass must reimplement it, possibly using a - * preimplemented ordering. This method must be called by the - * user after the class has been created. */ - virtual void do_ordering() = 0; - /** Return number of static. */ - int nstat() const - {return n_stat;} - /** Return number of predetermined. */ - int npred() const - {return n_pred;} - /** Return number of both. */ - int nboth() const - {return n_both;} - /** Return number of forward looking. */ - int nforw() const - {return n_forw;} - /** Return the set of tree indices for derivatives. */ - const vector<int>& get_der_atoms() const - {return der_atoms;} - /** Return the y2outer. */ - const vector<int>& get_y2outer() const - {return y2outer;} - /** Return the outer2y. */ - const vector<int>& get_outer2y() const - {return outer2y;} - /** Query the atom given by the tree index. True is returned - * if the atom is one of the variables in the object. */ - bool check(int t) const; - /** Return the position of the atom (nulary term) given by a - * tree index. It is a lookup to the map. If the atom cannot - * be found, the exception is raised. */ - int get_pos_of(int t) const; - /** This returns a length of ordered row of atoms. In all - * cases so far, it does not depend on the ordering and it is - * as follows. */ - int length() const - {return n_stat+2*n_pred+3*n_both+2*n_forw;} - /** Debug print. */ - void print() const; - protected: - /** This is a general ordering method which orders the - * variables by the given ordering ord_type. See documentation - * for respective do_ methods. */ - void do_general(ord_type ordering); - /** This is a preimplemented ordering for do_ordering() - * method. It assumes that the variables appear only at time - * t-1, t, t+1. It orders the atoms as pred(t-1), both(t-1), - * stat(t), pred(t), both(t), forw(t), both(t+1), - * forw(t+1). It builds the der_atoms, the map of positions, - * as well as y2outer and outer2y. */ - void do_pbspbfbf() - {do_general(pbspbfbf);} - /** This is a preimplemented ordering for do_ordering() - * method. It assumes that the variables appear only at time - * t-1, t, t+1. It orders the atoms as both(t+1), forw(t+1), - * stat(t), pred(t), both(t), forw(t), pred(t-1), - * both(t-1). It builds the der_atoms, the map of positions, - * as well as y2outer and outer2y. */ - void do_bfspbfpb() - {do_general(bfspbfpb);} - /** This is a preimplemented ordering for do_ordering() - * method. It makes no assumptions about occurences of - * variables at different times. It orders the atoms with - * increasing time keeping the given ordering within one - * time. This implies that y2outer and outer2y will be - * identities. The der_atoms will be just a sequence of atoms - * from the least to the most time preserving the order of atoms - * within one time. */ - void do_increasing_time(); - private: - /** Declare this copy constructor as private to hide it. */ - VarOrdering(const VarOrdering& vo); - }; + /** This class is a parent of all orderings of the dynamic atoms + * of variables which can appear before t, at t, or after t. It + * encapsulates the ordering, and the information about the number + * of static (appearing only at time t) predetermined (appearing + * before t and possibly at t), both (appearing before t and after + * t and possibly at t) and forward looking (appearing after t and + * possibly at t). + * + * The constructor takes a list of variable names. The class also + * provides mapping from the ordering of the variables in the list + * (outer) to the new ordering (at time t) and back. + * + * The user of the subclass must call do_ordering() after + * initialization. + * + * The class contains a few preimplemented methods for + * ordering. The class is used in this way: Make a subclass, and + * implement pure virtual do_ordering() by just plugging a + * preimplemented method, or plugging your own implementation. The + * method do_ordering() is called by the user after the constructor. + */ + class VarOrdering + { + protected: + /** Number of static variables. */ + int n_stat; + /** Number of predetermined variables. */ + int n_pred; + /** Number of both variables. */ + int n_both; + /** Number of forward looking variables. */ + int n_forw; + /** This is a set of tree indices corresponding to the + * variables at all times as they occur in the formulas. In + * fact, since this is used only for derivatives, the ordering + * of this vector is only important for ordering of the + * derivatives, in other contexts the ordering is not + * important, so it is rather a set of indices.*/ + vector<int> der_atoms; + /** This maps tree index of the variable to the position in + * the row of the ordering. One should be careful with making + * space in the positions for variables not appearing at time + * t. For instance in the pred(t-1), both(t-1), stat(t), + * pred(t), both(t), forw(t), both(t+1), forw(t+1) ordering, + * the variables x(t-1), y(t-1), x(t+1), z(t-1), z(t), and + * z(t+1) having tree indices 6,5,4,3,2,1 will be ordered as + * follows: y(t-1), x(t-1), z(t-1), [y(t)], [x(t)], z(t), + * x(t+1), where a bracketed expresion means non-existent by + * occupying a space. The map thus will look as follows: + * {5->0, 6->1, 3->2, 2->5, 3->6}. Note that nothing is mapped + * to positions 3 and 4. */ + map<int, int> positions; + /** This maps an ordering of the list of variables in + * constructor to the new ordering (at time t). The length is + * the number of variables. */ + vector<int> outer2y; + /** This maps a new ordering to the ordering of the list of + * variables in constructor (at time t). The length is the + * number of variables. */ + vector<int> y2outer; + /** This is just a reference for variable names to keep it + * from constructor to do_ordering() implementations. */ + const vector<const char *> &varnames; + /** This is just a reference to atoms to keep it from + * constructor to do_ordering() implementations. */ + const DynamicAtoms &atoms; + public: + /** This is an enum type for an ordering type implemented by + * do_general. */ + enum ord_type {pbspbfbf, bfspbfpb}; + /** Construct the ordering of the variables given by the names + * with their dynamic occurrences defined by the atoms. It + * calls the virtual method do_ordering which can be + * reimplemented. */ + VarOrdering(const vector<const char *> &vnames, const DynamicAtoms &a) + : n_stat(0), n_pred(0), n_both(0), n_forw(0), varnames(vnames), atoms(a) + { + } + VarOrdering(const VarOrdering &vo, const vector<const char *> &vnames, + const DynamicAtoms &a); + virtual VarOrdering *clone(const vector<const char *> &vnames, + const DynamicAtoms &a) const = 0; + /** Destructor does nothing here. */ + virtual ~VarOrdering() + { + } + /** This is the method setting the ordering and the map. A + * subclass must reimplement it, possibly using a + * preimplemented ordering. This method must be called by the + * user after the class has been created. */ + virtual void do_ordering() = 0; + /** Return number of static. */ + int + nstat() const + { + return n_stat; + } + /** Return number of predetermined. */ + int + npred() const + { + return n_pred; + } + /** Return number of both. */ + int + nboth() const + { + return n_both; + } + /** Return number of forward looking. */ + int + nforw() const + { + return n_forw; + } + /** Return the set of tree indices for derivatives. */ + const vector<int> & + get_der_atoms() const + { + return der_atoms; + } + /** Return the y2outer. */ + const vector<int> & + get_y2outer() const + { + return y2outer; + } + /** Return the outer2y. */ + const vector<int> & + get_outer2y() const + { + return outer2y; + } + /** Query the atom given by the tree index. True is returned + * if the atom is one of the variables in the object. */ + bool check(int t) const; + /** Return the position of the atom (nulary term) given by a + * tree index. It is a lookup to the map. If the atom cannot + * be found, the exception is raised. */ + int get_pos_of(int t) const; + /** This returns a length of ordered row of atoms. In all + * cases so far, it does not depend on the ordering and it is + * as follows. */ + int + length() const + { + return n_stat+2*n_pred+3*n_both+2*n_forw; + } + /** Debug print. */ + void print() const; + protected: + /** This is a general ordering method which orders the + * variables by the given ordering ord_type. See documentation + * for respective do_ methods. */ + void do_general(ord_type ordering); + /** This is a preimplemented ordering for do_ordering() + * method. It assumes that the variables appear only at time + * t-1, t, t+1. It orders the atoms as pred(t-1), both(t-1), + * stat(t), pred(t), both(t), forw(t), both(t+1), + * forw(t+1). It builds the der_atoms, the map of positions, + * as well as y2outer and outer2y. */ + void + do_pbspbfbf() + { + do_general(pbspbfbf); + } + /** This is a preimplemented ordering for do_ordering() + * method. It assumes that the variables appear only at time + * t-1, t, t+1. It orders the atoms as both(t+1), forw(t+1), + * stat(t), pred(t), both(t), forw(t), pred(t-1), + * both(t-1). It builds the der_atoms, the map of positions, + * as well as y2outer and outer2y. */ + void + do_bfspbfpb() + { + do_general(bfspbfpb); + } + /** This is a preimplemented ordering for do_ordering() + * method. It makes no assumptions about occurences of + * variables at different times. It orders the atoms with + * increasing time keeping the given ordering within one + * time. This implies that y2outer and outer2y will be + * identities. The der_atoms will be just a sequence of atoms + * from the least to the most time preserving the order of atoms + * within one time. */ + void do_increasing_time(); + private: + /** Declare this copy constructor as private to hide it. */ + VarOrdering(const VarOrdering &vo); + }; }; diff --git a/dynare++/parser/cc/fine_atoms.h b/dynare++/parser/cc/fine_atoms.h index 7cc82560864d4771823370e38895363ab9a3a5b3..27e5a384165e3c6e3b34a005d8d38eb435aae6aa 100644 --- a/dynare++/parser/cc/fine_atoms.h +++ b/dynare++/parser/cc/fine_atoms.h @@ -10,337 +10,417 @@ #include <vector> #include <string> -namespace ogp { +namespace ogp +{ - using std::vector; - using std::string; + using std::vector; + using std::string; - /** This is just ordering used for endogenous variables. It - * assumes that we have only time t-1, t, and t+1, orders them as - * pred(t-1), both(t-1), stat(t), pred(t), both(t), forw(t), - * both(t+1), forw(t+1). */ - class EndoVarOrdering1 : public VarOrdering { - public: - EndoVarOrdering1(const vector<const char*>& vnames, const DynamicAtoms& a) - : VarOrdering(vnames, a) {} - EndoVarOrdering1(const EndoVarOrdering1& vo, const vector<const char*>& vnames, - const DynamicAtoms& a) - : VarOrdering(vo, vnames, a) {} - VarOrdering* clone(const vector<const char*>& vnames, const DynamicAtoms& a) const - {return new EndoVarOrdering1(*this, vnames, a);} - void do_ordering() - {do_pbspbfbf();} - }; + /** This is just ordering used for endogenous variables. It + * assumes that we have only time t-1, t, and t+1, orders them as + * pred(t-1), both(t-1), stat(t), pred(t), both(t), forw(t), + * both(t+1), forw(t+1). */ + class EndoVarOrdering1 : public VarOrdering + { + public: + EndoVarOrdering1(const vector<const char *> &vnames, const DynamicAtoms &a) + : VarOrdering(vnames, a) + { + } + EndoVarOrdering1(const EndoVarOrdering1 &vo, const vector<const char *> &vnames, + const DynamicAtoms &a) + : VarOrdering(vo, vnames, a) + { + } + VarOrdering * + clone(const vector<const char *> &vnames, const DynamicAtoms &a) const + { + return new EndoVarOrdering1(*this, vnames, a); + } + void + do_ordering() + { + do_pbspbfbf(); + } + }; - /** This is just another ordering used for endogenous - * variables. It assumes that we have only time t-1, t, and t+1, - * orders them as both(t+1), forw(t+1), pred(t-1), both(t-1), - * stat(t), pred(t), both(t), forw(t). */ - class EndoVarOrdering2 : public VarOrdering { - public: - EndoVarOrdering2(const vector<const char*>& vnames, const DynamicAtoms& a) - : VarOrdering(vnames, a) {} - EndoVarOrdering2(const EndoVarOrdering2& vo, const vector<const char*>& vnames, - const DynamicAtoms& a) - : VarOrdering(vo, vnames, a) {} - VarOrdering* clone(const vector<const char*>& vnames, const DynamicAtoms& a) const - {return new EndoVarOrdering2(*this, vnames, a);} - void do_ordering() - {do_bfspbfpb();} - }; + /** This is just another ordering used for endogenous + * variables. It assumes that we have only time t-1, t, and t+1, + * orders them as both(t+1), forw(t+1), pred(t-1), both(t-1), + * stat(t), pred(t), both(t), forw(t). */ + class EndoVarOrdering2 : public VarOrdering + { + public: + EndoVarOrdering2(const vector<const char *> &vnames, const DynamicAtoms &a) + : VarOrdering(vnames, a) + { + } + EndoVarOrdering2(const EndoVarOrdering2 &vo, const vector<const char *> &vnames, + const DynamicAtoms &a) + : VarOrdering(vo, vnames, a) + { + } + VarOrdering * + clone(const vector<const char *> &vnames, const DynamicAtoms &a) const + { + return new EndoVarOrdering2(*this, vnames, a); + } + void + do_ordering() + { + do_bfspbfpb(); + } + }; - /** This is just ordering used for exogenous variables. It makes - * no assumptions about their timing. It orders them from the - * least time to the latest time. */ - class ExoVarOrdering : public VarOrdering { - public: - ExoVarOrdering(const vector<const char*>& vnames, const DynamicAtoms& a) - : VarOrdering(vnames, a) {} - ExoVarOrdering(const ExoVarOrdering& vo, const vector<const char*>& vnames, - const DynamicAtoms& a) - : VarOrdering(vo, vnames, a) {} - VarOrdering* clone(const vector<const char*>& vnames, const DynamicAtoms& a) const - {return new ExoVarOrdering(*this, vnames, a);} - void do_ordering() - {do_increasing_time();} - }; + /** This is just ordering used for exogenous variables. It makes + * no assumptions about their timing. It orders them from the + * least time to the latest time. */ + class ExoVarOrdering : public VarOrdering + { + public: + ExoVarOrdering(const vector<const char *> &vnames, const DynamicAtoms &a) + : VarOrdering(vnames, a) + { + } + ExoVarOrdering(const ExoVarOrdering &vo, const vector<const char *> &vnames, + const DynamicAtoms &a) + : VarOrdering(vo, vnames, a) + { + } + VarOrdering * + clone(const vector<const char *> &vnames, const DynamicAtoms &a) const + { + return new ExoVarOrdering(*this, vnames, a); + } + void + do_ordering() + { + do_increasing_time(); + } + }; - class FineAtoms; + class FineAtoms; - /** This class provides an outer ordering of all variables (endo - * and exo). It maps the ordering to the particular outer - * orderings of endo and exo. It works tightly with the FineAtoms - * class. */ - class AllvarOuterOrdering { - protected: - /** Type for a map mapping a variable name to an integer. */ - typedef map<const char*, int, ltstr> Tvarintmap; - /** Reference to atoms. */ - const FineAtoms& atoms; - /** The vector of all endo and exo variables in outer - * ordering. The pointers point to storage in atoms. */ - vector<const char*> allvar; - /** The mapping from outer endogenous to outer all. For - * example endo2all[0] is the order of the first outer - * endogenous variable in the allvar ordering. */ - vector<int> endo2all; - /** The mapping from outer exogenous to outer all. For example - * exo2all[0] is the order of the first outer exogenous - * variables in the allvar ordering. */ - vector<int> exo2all; - public: - /** Construct the allvar outer ordering from the provided - * sequence of endo and exo names. The names can have an - * arbitrary storage, the storage is transformed to the atoms - * storage. An exception is thrown if either the list is not - * exhaustive, or some string is not a variable. */ - AllvarOuterOrdering(const vector<const char*>& allvar_outer, const FineAtoms& a); - /** Copy constructor using the storage of provided atoms. */ - AllvarOuterOrdering(const AllvarOuterOrdering& allvar_outer, const FineAtoms& a); - /** Return endo2all mapping. */ - const vector<int>& get_endo2all() const - {return endo2all;} - /** Return exo2all mapping. */ - const vector<int>& get_exo2all() const - {return exo2all;} - /** Return the allvar ordering. */ - const vector<const char*>& get_allvar() const - {return allvar;} - }; + /** This class provides an outer ordering of all variables (endo + * and exo). It maps the ordering to the particular outer + * orderings of endo and exo. It works tightly with the FineAtoms + * class. */ + class AllvarOuterOrdering + { + protected: + /** Type for a map mapping a variable name to an integer. */ + typedef map<const char *, int, ltstr> Tvarintmap; + /** Reference to atoms. */ + const FineAtoms &atoms; + /** The vector of all endo and exo variables in outer + * ordering. The pointers point to storage in atoms. */ + vector<const char *> allvar; + /** The mapping from outer endogenous to outer all. For + * example endo2all[0] is the order of the first outer + * endogenous variable in the allvar ordering. */ + vector<int> endo2all; + /** The mapping from outer exogenous to outer all. For example + * exo2all[0] is the order of the first outer exogenous + * variables in the allvar ordering. */ + vector<int> exo2all; + public: + /** Construct the allvar outer ordering from the provided + * sequence of endo and exo names. The names can have an + * arbitrary storage, the storage is transformed to the atoms + * storage. An exception is thrown if either the list is not + * exhaustive, or some string is not a variable. */ + AllvarOuterOrdering(const vector<const char *> &allvar_outer, const FineAtoms &a); + /** Copy constructor using the storage of provided atoms. */ + AllvarOuterOrdering(const AllvarOuterOrdering &allvar_outer, const FineAtoms &a); + /** Return endo2all mapping. */ + const vector<int> & + get_endo2all() const + { + return endo2all; + } + /** Return exo2all mapping. */ + const vector<int> & + get_exo2all() const + { + return exo2all; + } + /** Return the allvar ordering. */ + const vector<const char *> & + get_allvar() const + { + return allvar; + } + }; - /** This class refines the DynamicAtoms by distinguishing among - * parameters (no lag and leads) and endogenous and exogenous - * variables (with lags and leads). For parameters, endogenous and - * exogenous, it defines outer orderings and internal - * orderings. The internal orderings are created by - * parsing_finished() method when it is sure that no new variables - * would be registered. The outer orderings are given by the order - * of calls of registering methods. - * - * In addition, the class also defines outer ordering of - * endogenous and exogenous variables. This is input as a - * parameter to parsing_finished(). By default, this whole outer - * ordering is just a concatenation of outer ordering of - * endogenous and exogenous variables. - * - * The internal ordering of all endo and exo variables is just a - * concatenation of endo and exo variables in their internal - * orderings. This is the ordering with respect to which all - * derivatives are taken. */ - class FineAtoms : public DynamicAtoms { - friend class AllvarOuterOrdering; - protected: - typedef map<const char*, int, ltstr> Tvarintmap; - private: - /** The vector of parameters names. The order gives the order - * the data is communicated with outside world. */ - vector<const char*> params; - /** A map mapping a name of a parameter to an index in the outer - * ordering. */ - Tvarintmap param_outer_map; - /** The vector of endogenous variables. This defines the order - * like parameters. */ - vector<const char*> endovars; - /** A map mapping a name of an endogenous variable to an index - * in the outer ordering. */ - Tvarintmap endo_outer_map; - /** The vector of exogenous variables. Also defines the order - * like parameters and endovars. */ - vector<const char*> exovars; - /** A map mapping a name of an exogenous variable to an index - * in the outer ordering. */ - Tvarintmap exo_outer_map; + /** This class refines the DynamicAtoms by distinguishing among + * parameters (no lag and leads) and endogenous and exogenous + * variables (with lags and leads). For parameters, endogenous and + * exogenous, it defines outer orderings and internal + * orderings. The internal orderings are created by + * parsing_finished() method when it is sure that no new variables + * would be registered. The outer orderings are given by the order + * of calls of registering methods. + * + * In addition, the class also defines outer ordering of + * endogenous and exogenous variables. This is input as a + * parameter to parsing_finished(). By default, this whole outer + * ordering is just a concatenation of outer ordering of + * endogenous and exogenous variables. + * + * The internal ordering of all endo and exo variables is just a + * concatenation of endo and exo variables in their internal + * orderings. This is the ordering with respect to which all + * derivatives are taken. */ + class FineAtoms : public DynamicAtoms + { + friend class AllvarOuterOrdering; + protected: + typedef map<const char *, int, ltstr> Tvarintmap; + private: + /** The vector of parameters names. The order gives the order + * the data is communicated with outside world. */ + vector<const char *> params; + /** A map mapping a name of a parameter to an index in the outer + * ordering. */ + Tvarintmap param_outer_map; + /** The vector of endogenous variables. This defines the order + * like parameters. */ + vector<const char *> endovars; + /** A map mapping a name of an endogenous variable to an index + * in the outer ordering. */ + Tvarintmap endo_outer_map; + /** The vector of exogenous variables. Also defines the order + * like parameters and endovars. */ + vector<const char *> exovars; + /** A map mapping a name of an exogenous variable to an index + * in the outer ordering. */ + Tvarintmap exo_outer_map; - protected: - /** This is the internal ordering of all atoms corresponding - * to endogenous variables. It is constructed by - * parsing_finished() method, which should be called after all - * parsing jobs have been finished. */ - VarOrdering* endo_order; - /** This is the internal ordering of all atoms corresponding - * to exogenous variables. It has the same handling as - * endo_order. */ - VarOrdering* exo_order; - /** This is the all variables outer ordering. It is - * constructed by parsing finished. */ - AllvarOuterOrdering* allvar_order; - /** This vector defines a set of atoms as tree indices used - * for differentiation. The order of the atoms in this vector - * defines ordering of the derivative tensors. The ordering is - * a concatenation of atoms from endo_order and then - * exo_order. This vector is setup by parsing_finished() and - * is returned by variables(). */ - vector<int> der_atoms; - /** This is a mapping from endogenous atoms to all atoms in - * der_atoms member. The mapping maps index in endogenous atom - * ordering to index (not value) in der_atoms. It is useful if - * one wants to evaluate derivatives wrt only endogenous - * variables. It is set by parsing_finished(). By definition, - * it is monotone. */ - vector<int> endo_atoms_map; - /** This is a mapping from exogenous atoms to all atoms in - * der_atoms member. It is the same as endo_atoms_map for - * atoms of exogenous variables. */ - vector<int> exo_atoms_map; - public: - FineAtoms() - : endo_order(NULL), exo_order(NULL), allvar_order(NULL) {} - FineAtoms(const FineAtoms& fa); - /** Deletes endo_order and exo_order. */ - virtual ~FineAtoms() - { - if (endo_order) delete endo_order; - if (exo_order) delete exo_order; - if (allvar_order) delete allvar_order; - } - /** Overrides DynamicAtoms::check_variable so that the error - * would be raised if the variable name is not declared. A - * variable is declared by inserting it to - * DynamicAtoms::varnames. This is a responsibility of a - * subclass. */ - int check_variable(const char* name) const; - /** This calculates min lag and max lead of endogenous variables. */ - void endovarspan(int& mlead, int& mlag) const - {varspan(endovars, mlead, mlag);} - /** This calculates mim lag and max lead of exogenous variables. */ - void exovarspan(int& mlead, int& mlag) const - {varspan(exovars, mlead, mlag);} - /** This calculates the number of periods in which at least - * one exogenous variable occurs. */ - int num_exo_periods() const; - /** Return an (external) ordering of parameters. */ - const vector<const char*>& get_params() const - {return params;} - /** Return an external ordering of endogenous variables. */ - const vector<const char*>& get_endovars() const - {return endovars;} - /** Return an external ordering of exogenous variables. */ - const vector<const char*>& get_exovars() const - {return exovars;} - /** This constructs internal orderings and makes the indices - * returned by variables method available. Further it - * constructs outer ordering of all variables by a simple - * concatenation of outer endogenous and outer exogenous. In - * addition, it makes nstat, npred, nboth, nforw available. */ - void parsing_finished(VarOrdering::ord_type ot); - /** This does the same thing as - * parsing_finished(VarOrdering::ord_type) plus it allows for - * inputing a different outer ordering of all variables. The - * ordering is input as a list of strings, their storage can - * be arbitrary. */ - void parsing_finished(VarOrdering::ord_type ot, const vector<const char*> avo); - /** Return the external ordering of all variables (endo and - * exo). This is either the second argument to - * parsing_finished or the default external ordering. This - * must be called only after parsing_finished. */ - const vector<const char*>& get_allvar() const; - /** Return the map from outer ordering of endo variables to - * the allvar ordering. This must be called only after - * parsing_finished. */ - const vector<int>& outer_endo2all() const; - /** Return the map from outer ordering of exo variables to - * the allvar ordering. This must be called only after - * parsing_finished. */ - const vector<int>& outer_exo2all() const; - /** Return the atoms with respect to which we are going to - * differentiate. This must be called after - * parsing_finished. */ - vector<int> variables() const; - /** Return the number of static. */ - int nstat() const; - /** Return the number of predetermined. */ - int npred() const; - /** Return the number of both. */ - int nboth() const; - /** Return the number of forward looking. */ - int nforw() const; - /** Return the index of an endogenous atom given by tree index in - * the endo ordering. This must be also called only after - * parsing_finished(). */ - int get_pos_of_endo(int t) const; - /** Return the index of an exogenous atom given by tree index in - * the exo ordering. This must be also called only after - * parsing_finished(). */ - int get_pos_of_exo(int t) const; - /** Return the index of either endogenous or exogenous atom - * given by tree index in the concatenated ordering of - * endogenous and exogenous atoms. This must be also called - * only after parsing_finished(). */ - int get_pos_of_all(int t) const; - /** Return the mapping from endogenous at time t to outer - * ordering of endogenous. */ - const vector<int>& y2outer_endo() const; - /** Return the mapping from the outer ordering of endogenous to endogenous - * at time t. */ - const vector<int>& outer2y_endo() const; - /** Return the mapping from exogenous at time t to outer - * ordering of exogenous. */ - const vector<int>& y2outer_exo() const; - /** Return the mapping from the outer ordering of exogenous to exogenous - * at time t. */ - const vector<int>& outer2y_exo() const; - /** Return the endo_atoms_map. */ - const vector<int>& get_endo_atoms_map() const; - /** Return the exo_atoms_map. */ - const vector<int>& get_exo_atoms_map() const; - /** Return an index in the outer ordering of a given - * parameter. An exception is thrown if the name is not a - * parameter. */ - int name2outer_param(const char* name) const; - /** Return an index in the outer ordering of a given - * endogenous variable. An exception is thrown if the name is not a - * and endogenous variable. */ - int name2outer_endo(const char* name) const; - /** Return an index in the outer ordering of a given - * exogenous variable. An exception is thrown if the name is not a - * and exogenous variable. */ - int name2outer_exo(const char* name) const; - /** Return an index in the outer ordering of all variables - * (endo and exo) for a given name. An exception is thrown if - * the name is not a variable. This must be called only after - * parsing_finished(). */ - int name2outer_allvar(const char* name) const; - /** Return the number of endogenous variables at time t-1, these are state - * variables. */ - int nys() const - {return npred()+nboth();} - /** Return the number of endogenous variables at time t+1. */ - int nyss() const - {return nboth()+nforw();} - /** Return the number of endogenous variables. */ - int ny() const - {return endovars.size();} - /** Return the number of exogenous variables. */ - int nexo() const - {return (int)exovars.size();} - /** Return the number of parameters. */ - int np() const - {return (int)(params.size());} - /** Register unique endogenous variable name. The order of - * calls defines the endo outer ordering. The method is - * virtual, since a superclass may want to do some additional - * action. */ - virtual void register_uniq_endo(const char* name); - /** Register unique exogenous variable name. The order of - * calls defines the exo outer ordering. The method is - * virtual, since a superclass may want to do somem additional - * action. */ - virtual void register_uniq_exo(const char* name); - /** Register unique parameter name. The order of calls defines - * the param outer ordering. The method is - * virtual, since a superclass may want to do somem additional - * action. */ - virtual void register_uniq_param(const char* name); - /** Debug print. */ - void print() const; - private: - /** This performs the common part of parsing_finished(), which - * is a construction of internal orderings. */ - void make_internal_orderings(VarOrdering::ord_type ot); - protected: - /** This remembers the ordering type of the last call make_internal_ordering. */ - VarOrdering::ord_type order_type; - }; + protected: + /** This is the internal ordering of all atoms corresponding + * to endogenous variables. It is constructed by + * parsing_finished() method, which should be called after all + * parsing jobs have been finished. */ + VarOrdering *endo_order; + /** This is the internal ordering of all atoms corresponding + * to exogenous variables. It has the same handling as + * endo_order. */ + VarOrdering *exo_order; + /** This is the all variables outer ordering. It is + * constructed by parsing finished. */ + AllvarOuterOrdering *allvar_order; + /** This vector defines a set of atoms as tree indices used + * for differentiation. The order of the atoms in this vector + * defines ordering of the derivative tensors. The ordering is + * a concatenation of atoms from endo_order and then + * exo_order. This vector is setup by parsing_finished() and + * is returned by variables(). */ + vector<int> der_atoms; + /** This is a mapping from endogenous atoms to all atoms in + * der_atoms member. The mapping maps index in endogenous atom + * ordering to index (not value) in der_atoms. It is useful if + * one wants to evaluate derivatives wrt only endogenous + * variables. It is set by parsing_finished(). By definition, + * it is monotone. */ + vector<int> endo_atoms_map; + /** This is a mapping from exogenous atoms to all atoms in + * der_atoms member. It is the same as endo_atoms_map for + * atoms of exogenous variables. */ + vector<int> exo_atoms_map; + public: + FineAtoms() + : endo_order(NULL), exo_order(NULL), allvar_order(NULL) + { + } + FineAtoms(const FineAtoms &fa); + /** Deletes endo_order and exo_order. */ + virtual ~FineAtoms() + { + if (endo_order) + delete endo_order; + if (exo_order) + delete exo_order; + if (allvar_order) + delete allvar_order; + } + /** Overrides DynamicAtoms::check_variable so that the error + * would be raised if the variable name is not declared. A + * variable is declared by inserting it to + * DynamicAtoms::varnames. This is a responsibility of a + * subclass. */ + int check_variable(const char *name) const; + /** This calculates min lag and max lead of endogenous variables. */ + void + endovarspan(int &mlead, int &mlag) const + { + varspan(endovars, mlead, mlag); + } + /** This calculates mim lag and max lead of exogenous variables. */ + void + exovarspan(int &mlead, int &mlag) const + { + varspan(exovars, mlead, mlag); + } + /** This calculates the number of periods in which at least + * one exogenous variable occurs. */ + int num_exo_periods() const; + /** Return an (external) ordering of parameters. */ + const vector<const char *> & + get_params() const + { + return params; + } + /** Return an external ordering of endogenous variables. */ + const vector<const char *> & + get_endovars() const + { + return endovars; + } + /** Return an external ordering of exogenous variables. */ + const vector<const char *> & + get_exovars() const + { + return exovars; + } + /** This constructs internal orderings and makes the indices + * returned by variables method available. Further it + * constructs outer ordering of all variables by a simple + * concatenation of outer endogenous and outer exogenous. In + * addition, it makes nstat, npred, nboth, nforw available. */ + void parsing_finished(VarOrdering::ord_type ot); + /** This does the same thing as + * parsing_finished(VarOrdering::ord_type) plus it allows for + * inputing a different outer ordering of all variables. The + * ordering is input as a list of strings, their storage can + * be arbitrary. */ + void parsing_finished(VarOrdering::ord_type ot, const vector<const char *> avo); + /** Return the external ordering of all variables (endo and + * exo). This is either the second argument to + * parsing_finished or the default external ordering. This + * must be called only after parsing_finished. */ + const vector<const char *>&get_allvar() const; + /** Return the map from outer ordering of endo variables to + * the allvar ordering. This must be called only after + * parsing_finished. */ + const vector<int>&outer_endo2all() const; + /** Return the map from outer ordering of exo variables to + * the allvar ordering. This must be called only after + * parsing_finished. */ + const vector<int>&outer_exo2all() const; + /** Return the atoms with respect to which we are going to + * differentiate. This must be called after + * parsing_finished. */ + vector<int> variables() const; + /** Return the number of static. */ + int nstat() const; + /** Return the number of predetermined. */ + int npred() const; + /** Return the number of both. */ + int nboth() const; + /** Return the number of forward looking. */ + int nforw() const; + /** Return the index of an endogenous atom given by tree index in + * the endo ordering. This must be also called only after + * parsing_finished(). */ + int get_pos_of_endo(int t) const; + /** Return the index of an exogenous atom given by tree index in + * the exo ordering. This must be also called only after + * parsing_finished(). */ + int get_pos_of_exo(int t) const; + /** Return the index of either endogenous or exogenous atom + * given by tree index in the concatenated ordering of + * endogenous and exogenous atoms. This must be also called + * only after parsing_finished(). */ + int get_pos_of_all(int t) const; + /** Return the mapping from endogenous at time t to outer + * ordering of endogenous. */ + const vector<int>&y2outer_endo() const; + /** Return the mapping from the outer ordering of endogenous to endogenous + * at time t. */ + const vector<int>&outer2y_endo() const; + /** Return the mapping from exogenous at time t to outer + * ordering of exogenous. */ + const vector<int>&y2outer_exo() const; + /** Return the mapping from the outer ordering of exogenous to exogenous + * at time t. */ + const vector<int>&outer2y_exo() const; + /** Return the endo_atoms_map. */ + const vector<int>&get_endo_atoms_map() const; + /** Return the exo_atoms_map. */ + const vector<int>&get_exo_atoms_map() const; + /** Return an index in the outer ordering of a given + * parameter. An exception is thrown if the name is not a + * parameter. */ + int name2outer_param(const char *name) const; + /** Return an index in the outer ordering of a given + * endogenous variable. An exception is thrown if the name is not a + * and endogenous variable. */ + int name2outer_endo(const char *name) const; + /** Return an index in the outer ordering of a given + * exogenous variable. An exception is thrown if the name is not a + * and exogenous variable. */ + int name2outer_exo(const char *name) const; + /** Return an index in the outer ordering of all variables + * (endo and exo) for a given name. An exception is thrown if + * the name is not a variable. This must be called only after + * parsing_finished(). */ + int name2outer_allvar(const char *name) const; + /** Return the number of endogenous variables at time t-1, these are state + * variables. */ + int + nys() const + { + return npred()+nboth(); + } + /** Return the number of endogenous variables at time t+1. */ + int + nyss() const + { + return nboth()+nforw(); + } + /** Return the number of endogenous variables. */ + int + ny() const + { + return endovars.size(); + } + /** Return the number of exogenous variables. */ + int + nexo() const + { + return (int) exovars.size(); + } + /** Return the number of parameters. */ + int + np() const + { + return (int) (params.size()); + } + /** Register unique endogenous variable name. The order of + * calls defines the endo outer ordering. The method is + * virtual, since a superclass may want to do some additional + * action. */ + virtual void register_uniq_endo(const char *name); + /** Register unique exogenous variable name. The order of + * calls defines the exo outer ordering. The method is + * virtual, since a superclass may want to do somem additional + * action. */ + virtual void register_uniq_exo(const char *name); + /** Register unique parameter name. The order of calls defines + * the param outer ordering. The method is + * virtual, since a superclass may want to do somem additional + * action. */ + virtual void register_uniq_param(const char *name); + /** Debug print. */ + void print() const; + private: + /** This performs the common part of parsing_finished(), which + * is a construction of internal orderings. */ + void make_internal_orderings(VarOrdering::ord_type ot); + protected: + /** This remembers the ordering type of the last call make_internal_ordering. */ + VarOrdering::ord_type order_type; + }; }; #endif diff --git a/dynare++/parser/cc/formula_parser.h b/dynare++/parser/cc/formula_parser.h index 0f5c965c6aeb4c5a55c6d95f20856947d91dd799..5cd4476e5103ac2d4d14eb278b2205670deb9118 100644 --- a/dynare++/parser/cc/formula_parser.h +++ b/dynare++/parser/cc/formula_parser.h @@ -5,408 +5,492 @@ #include "tree.h" -namespace ogp { - using std::vector; +namespace ogp +{ + using std::vector; - /** Pure virtual class defining a minimal interface for - * representation of nulary terms within FormulaParser. */ - class Atoms { - public: - Atoms() {} - virtual ~Atoms() {} - /** This returns previously assigned internal index to the - * given atom, or returns -1 if the atom has not been assigned - * yet. The method can raise an exception, if the Atoms - * implementation is strict and the name is not among - * prescribed possible values. */ - virtual int check(const char* name) const = 0; - /** This method assigns an internal index to the nulary term - * described by the name. The internal index is allocated by - * OperationTree class. */ - virtual void assign(const char* name, int t) = 0; - /** Returns a number of variables which will be used for - * differentiations. */ - virtual int nvar() const = 0; - /** Returns a vector of variable's internal indices which will - * be used for differentiations. */ - virtual vector<int> variables() const = 0; - /** Debug print. */ - virtual void print() const = 0; - }; + /** Pure virtual class defining a minimal interface for + * representation of nulary terms within FormulaParser. */ + class Atoms + { + public: + Atoms() + { + } + virtual ~Atoms() + { + } + /** This returns previously assigned internal index to the + * given atom, or returns -1 if the atom has not been assigned + * yet. The method can raise an exception, if the Atoms + * implementation is strict and the name is not among + * prescribed possible values. */ + virtual int check(const char *name) const = 0; + /** This method assigns an internal index to the nulary term + * described by the name. The internal index is allocated by + * OperationTree class. */ + virtual void assign(const char *name, int t) = 0; + /** Returns a number of variables which will be used for + * differentiations. */ + virtual int nvar() const = 0; + /** Returns a vector of variable's internal indices which will + * be used for differentiations. */ + virtual vector<int> variables() const = 0; + /** Debug print. */ + virtual void print() const = 0; + }; - /** Pure virtual class defining interface for all classes able to - * set nulary terms to evaluation tree EvalTree. The - * implementations of this class will have to be connected with - * Atoms to have knowledge about the atoms and their indices in - * the tree, and will call EvalTree::set_nulary. */ - class AtomValues { - public: - virtual ~AtomValues() {} - virtual void setValues(EvalTree& et) const = 0; - }; + /** Pure virtual class defining interface for all classes able to + * set nulary terms to evaluation tree EvalTree. The + * implementations of this class will have to be connected with + * Atoms to have knowledge about the atoms and their indices in + * the tree, and will call EvalTree::set_nulary. */ + class AtomValues + { + public: + virtual ~AtomValues() + { + } + virtual void setValues(EvalTree &et) const = 0; + }; - class FormulaDerEvaluator; - class FoldMultiIndex; - /** For ordering FoldMultiIndex in the std::map. */ - struct ltfmi { - bool operator()(const FoldMultiIndex& i1, const FoldMultiIndex& i2) const; - }; + class FormulaDerEvaluator; + class FoldMultiIndex; + /** For ordering FoldMultiIndex in the std::map. */ + struct ltfmi + { + bool operator()(const FoldMultiIndex &i1, const FoldMultiIndex &i2) const; + }; - /** This class stores derivatives (tree indices) of one formula - * for all orders upto a given one. It stores the derivatives as a - * sequence (vector) of these tree indices and sequence of the - * multidimensional indices of variables wrt which the derivatives - * were taken. In order to speed up querying for a derivative - * given the variables, we have a map mapping the multidimensional - * index to the order of the derivative in the sequence. - * - * The only reason we do not have only this map is that the - * iterators of the map do not survive the insertions to the map, - * and implementation of the constructor has to be very difficult. - */ - class FormulaDerivatives { - friend class FormulaDerEvaluator; - protected: - /** Vector of derivatives. This is a list of derivatives (tree - * indices), the ordering is given by the algorithm used to - * create it. Currently, it starts with zero-th derivative, - * the formula itself and carries with first order, second, - * etc. */ - vector<int> tder; - /** Vector of multiindices corresponding to the vector of - * derivatives. */ - vector<FoldMultiIndex> indices; - /** For retrieving derivatives via a multiindex, we have a map - * mapping a multiindex to a derivative in the tder - * ordering. This means that indices[ind2der[index]] == index. */ - typedef map<FoldMultiIndex, int, ltfmi> Tfmiintmap; - Tfmiintmap ind2der; - /** The number of variables. */ - int nvar; - /** The maximum order of derivatives. */ - int order; - public: - /** The constructor allocates and fills the sequence of the - * indices of derivatives for a formula. - * @param otree the OperationTree for which all work is done - * and to which the derivatives are added. - * @param vars the vector of nulary terms in the tree; the - * derivatives are taken with respect to these variables in - * the ordering given by the vector. - * @param f the index of the formula being differentiated. The - * zero derivative is set to f. - * @param max_order the maximum order of differentiation. - */ - FormulaDerivatives(OperationTree& otree, const vector<int>& vars, int f, int max_order); - /** Copy constructor. */ - FormulaDerivatives(const FormulaDerivatives& fd); - virtual ~FormulaDerivatives(){} - /** Random access to the derivatives via multiindex. */ - int derivative(const FoldMultiIndex& mi) const; - /** Return the order. */ - int get_order() const - {return order;} - /** Debug print. */ - void print(const OperationTree& otree) const; - }; + /** This class stores derivatives (tree indices) of one formula + * for all orders upto a given one. It stores the derivatives as a + * sequence (vector) of these tree indices and sequence of the + * multidimensional indices of variables wrt which the derivatives + * were taken. In order to speed up querying for a derivative + * given the variables, we have a map mapping the multidimensional + * index to the order of the derivative in the sequence. + * + * The only reason we do not have only this map is that the + * iterators of the map do not survive the insertions to the map, + * and implementation of the constructor has to be very difficult. + */ + class FormulaDerivatives + { + friend class FormulaDerEvaluator; + protected: + /** Vector of derivatives. This is a list of derivatives (tree + * indices), the ordering is given by the algorithm used to + * create it. Currently, it starts with zero-th derivative, + * the formula itself and carries with first order, second, + * etc. */ + vector<int> tder; + /** Vector of multiindices corresponding to the vector of + * derivatives. */ + vector<FoldMultiIndex> indices; + /** For retrieving derivatives via a multiindex, we have a map + * mapping a multiindex to a derivative in the tder + * ordering. This means that indices[ind2der[index]] == index. */ + typedef map<FoldMultiIndex, int, ltfmi> Tfmiintmap; + Tfmiintmap ind2der; + /** The number of variables. */ + int nvar; + /** The maximum order of derivatives. */ + int order; + public: + /** The constructor allocates and fills the sequence of the + * indices of derivatives for a formula. + * @param otree the OperationTree for which all work is done + * and to which the derivatives are added. + * @param vars the vector of nulary terms in the tree; the + * derivatives are taken with respect to these variables in + * the ordering given by the vector. + * @param f the index of the formula being differentiated. The + * zero derivative is set to f. + * @param max_order the maximum order of differentiation. + */ + FormulaDerivatives(OperationTree &otree, const vector<int> &vars, int f, int max_order); + /** Copy constructor. */ + FormulaDerivatives(const FormulaDerivatives &fd); + virtual ~FormulaDerivatives() + { + } + /** Random access to the derivatives via multiindex. */ + int derivative(const FoldMultiIndex &mi) const; + /** Return the order. */ + int + get_order() const + { + return order; + } + /** Debug print. */ + void print(const OperationTree &otree) const; + }; - class FormulaEvaluator; + class FormulaEvaluator; - /** This class is able to parse a number of formulas and - * differentiate them. The life cycle of the object is as follows: - * After it is created, a few calls to parse will add formulas - * (zero derivatives) to the object. Then a method differentiate() - * can be called and a vector of pointers to derivatives for each - * formula is created. After this, no one should call other - * parse() or differentiate(). A const reference of the object can - * be used in constructors of FormulaEvaluator and - * FormulaDerEvaluator in order to evaluate formulas (zero - * derivatives) and higher derivatives resp. */ - class FormulaParser { - friend class FormulaCustomEvaluator; - friend class FormulaDerEvaluator; - protected: - /** The OperationTree of all formulas, including derivatives. */ - OperationTree otree; - /** Reference to Atoms. The Atoms are filled with nulary terms - * during execution of parse(). */ - Atoms& atoms; - /** Vector of formulas (zero derivatives) in the order as they - * have been parsed. */ - vector<int> formulas; - /** The vector to derivatives, each vector corresponds to a - * formula in the vector formulas. */ - vector<FormulaDerivatives*> ders; - public: - /** Construct an empty formula parser. */ - FormulaParser(Atoms& a) - : atoms(a) {} - /** Copy constructor using a different instance of Atoms. */ - FormulaParser(const FormulaParser& fp, Atoms& a); - virtual ~FormulaParser(); + /** This class is able to parse a number of formulas and + * differentiate them. The life cycle of the object is as follows: + * After it is created, a few calls to parse will add formulas + * (zero derivatives) to the object. Then a method differentiate() + * can be called and a vector of pointers to derivatives for each + * formula is created. After this, no one should call other + * parse() or differentiate(). A const reference of the object can + * be used in constructors of FormulaEvaluator and + * FormulaDerEvaluator in order to evaluate formulas (zero + * derivatives) and higher derivatives resp. */ + class FormulaParser + { + friend class FormulaCustomEvaluator; + friend class FormulaDerEvaluator; + protected: + /** The OperationTree of all formulas, including derivatives. */ + OperationTree otree; + /** Reference to Atoms. The Atoms are filled with nulary terms + * during execution of parse(). */ + Atoms &atoms; + /** Vector of formulas (zero derivatives) in the order as they + * have been parsed. */ + vector<int> formulas; + /** The vector to derivatives, each vector corresponds to a + * formula in the vector formulas. */ + vector<FormulaDerivatives *> ders; + public: + /** Construct an empty formula parser. */ + FormulaParser(Atoms &a) + : atoms(a) + { + } + /** Copy constructor using a different instance of Atoms. */ + FormulaParser(const FormulaParser &fp, Atoms &a); + virtual + ~FormulaParser(); - /** Requires an addition of the formula; called from the - * parser. */ - void add_formula(int t); - /** Requires an addition of the binary operation; called from - * the parser. */ - int add_binary(code_t code, int t1, int t2); - /** Requires an addition of the unary operation; called from - * the parser. */ - int add_unary(code_t code, int t); - /** Requires an addition of the nulary operation given by the - * string. The Atoms are consulted for uniquness and are given - * an internal index generated by the OperationTree. This is - * the channel through which the Atoms are filled. */ - int add_nulary(const char* str); + /** Requires an addition of the formula; called from the + * parser. */ + void add_formula(int t); + /** Requires an addition of the binary operation; called from + * the parser. */ + int add_binary(code_t code, int t1, int t2); + /** Requires an addition of the unary operation; called from + * the parser. */ + int add_unary(code_t code, int t); + /** Requires an addition of the nulary operation given by the + * string. The Atoms are consulted for uniquness and are given + * an internal index generated by the OperationTree. This is + * the channel through which the Atoms are filled. */ + int add_nulary(const char *str); - /** Adds a derivative to the tree. This just calls - * OperationTree::add_derivative. */ - int add_derivative(int t, int v) - {return otree.add_derivative(t, v);} - /** Adds a substitution. This just calls - * OperationTree::add_substitution. */ - int add_substitution(int t, const map<int,int>& subst) - {return otree.add_substitution(t, subst);} - /** Add the substitution given by the map where left sides of - * substitutions come from another parser. The right sides are - * from this object. The given t is from the given parser fp. */ - int add_substitution(int t, const map<int,int>& subst, - const FormulaParser& fp) - {return otree.add_substitution(t, subst, fp.otree);} - /** This adds formulas from the given parser with (possibly) - * different atoms applying substitutions from the given map - * mapping atoms from fp to atoms of the object. */ - void add_subst_formulas(const map<int,int>& subst, const FormulaParser& fp); - /** Substitute formulas. For each i from 1 through all - * formulas, it adds a substitution of the i-th formula and - * make it to be i-th formula.*/ - void substitute_formulas(const std::map<int,int>& subst); - /** This method turns the given term to nulary operation. It - * should be used with caution, since this method does not - * anything do with atoms, but usually some action is also - * needed (at leat to assign the tree index t to some - * atom). */ - void nularify(int t) - {otree.nularify(t);} - /** Returns a set of nulary terms of the given term. Just - * calls OperationTree::nulary_of_term. */ - const unordered_set<int>& nulary_of_term(int t) const - {return otree.nulary_of_term(t);} + /** Adds a derivative to the tree. This just calls + * OperationTree::add_derivative. */ + int + add_derivative(int t, int v) + { + return otree.add_derivative(t, v); + } + /** Adds a substitution. This just calls + * OperationTree::add_substitution. */ + int + add_substitution(int t, const map<int, int> &subst) + { + return otree.add_substitution(t, subst); + } + /** Add the substitution given by the map where left sides of + * substitutions come from another parser. The right sides are + * from this object. The given t is from the given parser fp. */ + int + add_substitution(int t, const map<int, int> &subst, + const FormulaParser &fp) + { + return otree.add_substitution(t, subst, fp.otree); + } + /** This adds formulas from the given parser with (possibly) + * different atoms applying substitutions from the given map + * mapping atoms from fp to atoms of the object. */ + void add_subst_formulas(const map<int, int> &subst, const FormulaParser &fp); + /** Substitute formulas. For each i from 1 through all + * formulas, it adds a substitution of the i-th formula and + * make it to be i-th formula.*/ + void substitute_formulas(const std::map<int, int> &subst); + /** This method turns the given term to nulary operation. It + * should be used with caution, since this method does not + * anything do with atoms, but usually some action is also + * needed (at leat to assign the tree index t to some + * atom). */ + void + nularify(int t) + { + otree.nularify(t); + } + /** Returns a set of nulary terms of the given term. Just + * calls OperationTree::nulary_of_term. */ + const unordered_set<int> & + nulary_of_term(int t) const + { + return otree.nulary_of_term(t); + } - /** Parse a given string containing one or more formulas. The - * formulas are parsed and added to the OperationTree and to - * the formulas vector. */ - void parse(int length, const char* stream); - /** Processes a syntax error from bison. */ - void error(const char* mes) const; - /** Differentiate all the formulas up to the given order. The - * variables with respect to which the derivatives are taken - * are obtained by Atoms::variables(). If the derivates exist, - * they are destroyed and created again (with possibly - * different order). */ - void differentiate(int max_order); - /** Return i-th formula derivatives. */ - const FormulaDerivatives& derivatives(int i) const; + /** Parse a given string containing one or more formulas. The + * formulas are parsed and added to the OperationTree and to + * the formulas vector. */ + void parse(int length, const char *stream); + /** Processes a syntax error from bison. */ + void error(const char *mes) const; + /** Differentiate all the formulas up to the given order. The + * variables with respect to which the derivatives are taken + * are obtained by Atoms::variables(). If the derivates exist, + * they are destroyed and created again (with possibly + * different order). */ + void differentiate(int max_order); + /** Return i-th formula derivatives. */ + const FormulaDerivatives&derivatives(int i) const; - /** This returns a maximum index of zero derivative formulas - * including all nulary terms. This is a mimumum length of the - * tree for which it is safe to evaluate zero derivatives of - * the formulas. */ - int last_formula() const; - /** This returns a tree index of the i-th formula in the - * vector. */ - int formula(int i) const - {return formulas[i];} + /** This returns a maximum index of zero derivative formulas + * including all nulary terms. This is a mimumum length of the + * tree for which it is safe to evaluate zero derivatives of + * the formulas. */ + int last_formula() const; + /** This returns a tree index of the i-th formula in the + * vector. */ + int + formula(int i) const + { + return formulas[i]; + } + /** This returns a tree index of the last formula and pops its + * item from the formulas vector. The number of formulas is + * then less by one. Returns -1 if there is no formula. If + * there are derivatives of the last formula, they are + * destroyed and the vector ders is popped from the back. */ + int pop_last_formula(); - /** This returns a tree index of the last formula and pops its - * item from the formulas vector. The number of formulas is - * then less by one. Returns -1 if there is no formula. If - * there are derivatives of the last formula, they are - * destroyed and the vector ders is popped from the back. */ - int pop_last_formula(); + /** This returns a number of formulas. */ + int + nformulas() const + { + return (int) (formulas.size()); + } - /** This returns a number of formulas. */ - int nformulas() const - {return (int)(formulas.size());} + /** This returns a reference to atoms. */ + const Atoms & + getAtoms() const + { + return atoms; + } + Atoms & + getAtoms() + { + return atoms; + } + /** This returns the tree. */ + const OperationTree & + getTree() const + { + return otree; + } + OperationTree & + getTree() + { + return otree; + } - /** This returns a reference to atoms. */ - const Atoms& getAtoms() const - {return atoms;} - Atoms& getAtoms() - {return atoms;} - /** This returns the tree. */ - const OperationTree& getTree() const - {return otree;} - OperationTree& getTree() - {return otree;} + /** Debug print. */ + void print() const; + private: + /** Hide this copy constructor declaration by declaring it as + * private. */ + FormulaParser(const FormulaParser &fp); + /** Destroy all derivatives. */ + void destroy_derivatives(); + }; - /** Debug print. */ - void print() const; - private: - /** Hide this copy constructor declaration by declaring it as - * private. */ - FormulaParser(const FormulaParser& fp); - /** Destroy all derivatives. */ - void destroy_derivatives(); - }; + /** This is a pure virtual class defining an interface for all + * classes which will load the results of formula (zero + * derivative) evaluations. A primitive implementation of this + * class can be a vector of doubles. */ + class FormulaEvalLoader + { + public: + virtual ~FormulaEvalLoader() + { + } + /** Set the value res for the given formula. The formula is + * identified by an index corresponding to the ordering in + * which the formulas have been parsed (starting from + * zero). */ + virtual void load(int i, double res) = 0; + }; - /** This is a pure virtual class defining an interface for all - * classes which will load the results of formula (zero - * derivative) evaluations. A primitive implementation of this - * class can be a vector of doubles. */ - class FormulaEvalLoader { - public: - virtual ~FormulaEvalLoader() {} - /** Set the value res for the given formula. The formula is - * identified by an index corresponding to the ordering in - * which the formulas have been parsed (starting from - * zero). */ - virtual void load(int i, double res) = 0; - }; + /** This class evaluates a selected subset of terms of the + * tree. In the protected constructor, one can constraint the + * initialization of the evaluation tree to a given number of + * terms in the beginning. Using this constructor, one has to make + * sure, that the terms in the beginning do not refer to terms + * behind the initial part. */ + class FormulaCustomEvaluator + { + protected: + /** The evaluation tree. */ + EvalTree etree; + /** The custom tree indices to be evaluated. */ + vector<int> terms; + public: + /** Construct from FormulaParser and given list of terms. */ + FormulaCustomEvaluator(const FormulaParser &fp, const vector<int> &ts) + : etree(fp.otree), terms(ts) + { + } + /** Construct from OperationTree and given list of terms. */ + FormulaCustomEvaluator(const OperationTree &ot, const vector<int> &ts) + : etree(ot), terms(ts) + { + } + /** Evaluate the terms using the given AtomValues and load the + * results using the given loader. The loader is called for + * each term in the order of the terms. */ + void eval(const AtomValues &av, FormulaEvalLoader &loader); + protected: + FormulaCustomEvaluator(const FormulaParser &fp) + : etree(fp.otree, fp.last_formula()), terms(fp.formulas) + { + } + }; - /** This class evaluates a selected subset of terms of the - * tree. In the protected constructor, one can constraint the - * initialization of the evaluation tree to a given number of - * terms in the beginning. Using this constructor, one has to make - * sure, that the terms in the beginning do not refer to terms - * behind the initial part. */ - class FormulaCustomEvaluator { - protected: - /** The evaluation tree. */ - EvalTree etree; - /** The custom tree indices to be evaluated. */ - vector<int> terms; - public: - /** Construct from FormulaParser and given list of terms. */ - FormulaCustomEvaluator(const FormulaParser& fp, const vector<int>& ts) - : etree(fp.otree), terms(ts) - {} - /** Construct from OperationTree and given list of terms. */ - FormulaCustomEvaluator(const OperationTree& ot, const vector<int>& ts) - : etree(ot), terms(ts) - {} - /** Evaluate the terms using the given AtomValues and load the - * results using the given loader. The loader is called for - * each term in the order of the terms. */ - void eval(const AtomValues& av, FormulaEvalLoader& loader); - protected: - FormulaCustomEvaluator(const FormulaParser& fp) - : etree(fp.otree, fp.last_formula()), terms(fp.formulas) - {} - }; + /** This class evaluates zero derivatives of the FormulaParser. */ + class FormulaEvaluator : public FormulaCustomEvaluator + { + public: + /** Construct from FormulaParser. */ + FormulaEvaluator(const FormulaParser &fp) + : FormulaCustomEvaluator(fp) + { + } + }; - /** This class evaluates zero derivatives of the FormulaParser. */ - class FormulaEvaluator : public FormulaCustomEvaluator { - public: - /** Construct from FormulaParser. */ - FormulaEvaluator(const FormulaParser& fp) - : FormulaCustomEvaluator(fp) {} - }; + /** This is a pure virtual class defining an interface for all + * classes which will load the results of formula derivative + * evaluations. */ + class FormulaDerEvalLoader + { + public: + virtual ~FormulaDerEvalLoader() + { + } + /** This loads the result of the derivative of the given + * order. The semantics of i is the same as in + * FormulaEvalLoader::load. The indices of variables with + * respect to which the derivative was taken are stored in + * memory pointed by vars. These are the tree indices of the + * variables. */ + virtual void load(int i, int order, const int *vars, double res) = 0; + }; - /** This is a pure virtual class defining an interface for all - * classes which will load the results of formula derivative - * evaluations. */ - class FormulaDerEvalLoader { - public: - virtual ~FormulaDerEvalLoader() {} - /** This loads the result of the derivative of the given - * order. The semantics of i is the same as in - * FormulaEvalLoader::load. The indices of variables with - * respect to which the derivative was taken are stored in - * memory pointed by vars. These are the tree indices of the - * variables. */ - virtual void load(int i, int order, const int* vars, double res) = 0; - }; + /** This class is a utility class representing the tensor + * multindex. It can basically increment itself, and calculate + * its offset in the folded tensor. */ + class FoldMultiIndex + { + /** Number of variables. */ + int nvar; + /** Dimension. */ + int ord; + /** The multiindex. */ + int *data; + public: + /** Initializes to the zero derivative. Order is 0, data is + * empty. */ + FoldMultiIndex(int nv); + /** Initializes the multiindex to zeros or given i. */ + FoldMultiIndex(int nv, int order, int i = 0); + /** Makes a new multiindex of the same order applying a given + * mapping to the indices. The mapping is supposed to be monotone. */ + FoldMultiIndex(int nv, const FoldMultiIndex &mi, const vector<int> &mp); + /** Shifting constructor. This adds a given number of orders + * to the end, copying the last item to the newly added items, + * keeping the index ordered. If the index was empty (zero-th + * dimension), then zeros are added. */ + FoldMultiIndex(const FoldMultiIndex &fmi, int new_orders); + /** Copy constructor. */ + FoldMultiIndex(const FoldMultiIndex &fmi); + /** Desctructor. */ + virtual ~FoldMultiIndex() + { + delete [] data; + } + /** Assignment operator. */ + const FoldMultiIndex &operator=(const FoldMultiIndex &fmi); + /** Operator < implementing lexicographic ordering within one + * order, increasing order across orders. */ + bool operator<(const FoldMultiIndex &fmi) const; + bool operator==(const FoldMultiIndex &fmi) const; + /** Increment the multiindex. */ + void increment(); + /** Return offset of the multiindex in the folded tensor. */ + int offset() const; + const int & + operator[](int i) const + { + return data[i]; + } + /** Return order of the multiindex, i.e. dimension of the + * tensor. */ + int + order() const + { + return ord; + } + /** Return the number of variables. */ + int + nv() const + { + return nvar; + } + /** Return the data. */ + const int * + ind() const + { + return data; + } + /** Return true if the end of the tensor is reached. The + * result of a subsequent increment should be considered + * unpredictable. */ + bool + past_the_end() const + { + return (ord == 0) || (data[0] == nvar); + } + /** Prints the multiindex in the brackets. */ + void print() const; + private: + static int offset_recurse(int *data, int len, int nv); + }; - /** This class is a utility class representing the tensor - * multindex. It can basically increment itself, and calculate - * its offset in the folded tensor. */ - class FoldMultiIndex { - /** Number of variables. */ - int nvar; - /** Dimension. */ - int ord; - /** The multiindex. */ - int* data; - public: - /** Initializes to the zero derivative. Order is 0, data is - * empty. */ - FoldMultiIndex(int nv); - /** Initializes the multiindex to zeros or given i. */ - FoldMultiIndex(int nv, int order, int i = 0); - /** Makes a new multiindex of the same order applying a given - * mapping to the indices. The mapping is supposed to be monotone. */ - FoldMultiIndex(int nv, const FoldMultiIndex& mi, const vector<int>& mp); - /** Shifting constructor. This adds a given number of orders - * to the end, copying the last item to the newly added items, - * keeping the index ordered. If the index was empty (zero-th - * dimension), then zeros are added. */ - FoldMultiIndex(const FoldMultiIndex& fmi, int new_orders); - /** Copy constructor. */ - FoldMultiIndex(const FoldMultiIndex& fmi); - /** Desctructor. */ - virtual ~FoldMultiIndex() - {delete [] data;} - /** Assignment operator. */ - const FoldMultiIndex& operator=(const FoldMultiIndex& fmi); - /** Operator < implementing lexicographic ordering within one - * order, increasing order across orders. */ - bool operator<(const FoldMultiIndex& fmi) const; - bool operator==(const FoldMultiIndex& fmi) const; - /** Increment the multiindex. */ - void increment(); - /** Return offset of the multiindex in the folded tensor. */ - int offset() const; - const int& operator[](int i) const - {return data[i];} - /** Return order of the multiindex, i.e. dimension of the - * tensor. */ - int order() const - {return ord;} - /** Return the number of variables. */ - int nv() const - {return nvar;} - /** Return the data. */ - const int* ind() const - {return data;} - /** Return true if the end of the tensor is reached. The - * result of a subsequent increment should be considered - * unpredictable. */ - bool past_the_end() const - {return (ord == 0) || (data[0] == nvar);} - /** Prints the multiindex in the brackets. */ - void print() const; - private: - static int offset_recurse(int* data, int len, int nv); - }; - - /** This class evaluates derivatives of the FormulaParser. */ - class FormulaDerEvaluator { - /** Its own instance of EvalTree. */ - EvalTree etree; - /** The indices of derivatives for each formula. This is a - * const copy FormulaParser::ders. We do not allocate nor - * deallocate anything here. */ - vector<const FormulaDerivatives*> ders; - /** A copy of tree indices corresponding to atoms to with - * respect the derivatives were taken. */ - vector<int> der_atoms; - public: - /** Construct the object from FormulaParser. */ - FormulaDerEvaluator(const FormulaParser& fp); - /** Evaluate the derivatives from the FormulaParser wrt to all - * atoms in variables vector at the given AtomValues. The - * given loader is used for output. */ - void eval(const AtomValues& av, FormulaDerEvalLoader& loader, int order); - /** Evaluate the derivatives from the FormulaParser wrt to a - * selection of atoms of the atoms in der_atoms vector at the - * given AtomValues. The selection is given by a monotone - * mapping to the indices (not values) of the der_atoms. */ - void eval(const vector<int>& mp, const AtomValues& av, FormulaDerEvalLoader& loader, - int order); - }; + /** This class evaluates derivatives of the FormulaParser. */ + class FormulaDerEvaluator + { + /** Its own instance of EvalTree. */ + EvalTree etree; + /** The indices of derivatives for each formula. This is a + * const copy FormulaParser::ders. We do not allocate nor + * deallocate anything here. */ + vector<const FormulaDerivatives *> ders; + /** A copy of tree indices corresponding to atoms to with + * respect the derivatives were taken. */ + vector<int> der_atoms; + public: + /** Construct the object from FormulaParser. */ + FormulaDerEvaluator(const FormulaParser &fp); + /** Evaluate the derivatives from the FormulaParser wrt to all + * atoms in variables vector at the given AtomValues. The + * given loader is used for output. */ + void eval(const AtomValues &av, FormulaDerEvalLoader &loader, int order); + /** Evaluate the derivatives from the FormulaParser wrt to a + * selection of atoms of the atoms in der_atoms vector at the + * given AtomValues. The selection is given by a monotone + * mapping to the indices (not values) of the der_atoms. */ + void eval(const vector<int> &mp, const AtomValues &av, FormulaDerEvalLoader &loader, + int order); + }; }; #endif diff --git a/dynare++/parser/cc/location.h b/dynare++/parser/cc/location.h index 55182942bc337483f273ce1e2840656ce87f06cd..93b51cf1705b6891e486075dcfe46b005970e3cb 100644 --- a/dynare++/parser/cc/location.h +++ b/dynare++/parser/cc/location.h @@ -15,29 +15,32 @@ // in EVERY action consuming material (this can be done with #define // YY_USER_ACTION) and in bison you must use option %locations. - #ifndef OG_LOCATION_H #define OG_LOCATION_H -namespace ogp { +namespace ogp +{ - struct location_type { - int off; // offset of the token - int ll; // length ot the token - location_type() : off(0), ll(0) {} - }; + struct location_type + { + int off; // offset of the token + int ll; // length ot the token + location_type() : off(0), ll(0) + { + } + }; }; #define YYLTYPE ogp::location_type // set current off to the first off and add all lengths -#define YYLLOC_DEFAULT(Current, Rhs, N) \ - {(Current).off = (Rhs)[1].off; \ - (Current).ll = 0; \ - for (int i = 1; i <= N; i++) (Current).ll += (Rhs)[i].ll;} +#define YYLLOC_DEFAULT(Current, Rhs, N) \ + {(Current).off = (Rhs)[1].off; \ + (Current).ll = 0; \ + for (int i = 1; i <= N; i++) (Current).ll += (Rhs)[i].ll; } -#define SET_LLOC(prefix) (prefix##lloc.off += prefix##lloc.ll, prefix##lloc.ll = prefix##leng) +#define SET_LLOC(prefix) (prefix ## lloc.off += prefix ## lloc.ll, prefix ## lloc.ll = prefix ## leng) #endif diff --git a/dynare++/parser/cc/matrix_parser.h b/dynare++/parser/cc/matrix_parser.h index f2c85d2eb5d9562de53fa5db44d1cc9d2f84a49f..e86f57f0e5af737c63782d6118039fa02c8fbf2a 100644 --- a/dynare++/parser/cc/matrix_parser.h +++ b/dynare++/parser/cc/matrix_parser.h @@ -8,110 +8,143 @@ #include <cstdlib> // For NULL #include <vector> -namespace ogp { - using std::vector; +namespace ogp +{ + using std::vector; - /** This class reads the given string and parses it as a - * matrix. The matrix is read row by row. The row delimiter is - * either a newline character or semicolon (first newline - * character after the semicolon is ignored), the column delimiter - * is either blank character or comma. A different number of items - * in the row is not reconciliated, we do not construct a matrix - * here. The class provides only an iterator to go through all - * read items, the iterator provides information on row number and - * column number of the item. */ - class MPIterator; - class MatrixParser { - friend class MPIterator; - protected: - /** Raw data as they were read. */ - vector<double> data; - /** Number of items in each row. */ - vector<int> row_lengths; - /** Maximum number of row lengths. */ - int nc; - public: - MatrixParser() - : nc(0) {} - MatrixParser(const MatrixParser& mp) - : data(mp.data), row_lengths(mp.row_lengths), nc(mp.nc) {} - virtual ~MatrixParser() {} - /** Return a number of read rows. */ - int nrows() const - {return (int) row_lengths.size();} - /** Return a maximum number of items in the rows. */ - int ncols() const - {return nc;} - /** Parses a given data. This initializes the object data. */ - void parse(int length, const char* stream); - /** Adds newly read item. This should be called from bison - * parser. */ - void add_item(double v); - /** Starts a new row. This should be called from bison - * parser. */ - void start_row(); - /** Process a parse error from the parser. */ - void error(const char* mes) const; - /** Return begin iterator. */ - MPIterator begin() const; - /** Return end iterator. */ - MPIterator end() const; - protected: - /** Returns an index of the first non-empty row starting at - * start. If the start row is non-empty, returns the start. If - * there is no other non-empty row, returns - * row_lengths.size(). */ - int find_first_non_empty_row(int start = 0) const; - }; + /** This class reads the given string and parses it as a + * matrix. The matrix is read row by row. The row delimiter is + * either a newline character or semicolon (first newline + * character after the semicolon is ignored), the column delimiter + * is either blank character or comma. A different number of items + * in the row is not reconciliated, we do not construct a matrix + * here. The class provides only an iterator to go through all + * read items, the iterator provides information on row number and + * column number of the item. */ + class MPIterator; + class MatrixParser + { + friend class MPIterator; + protected: + /** Raw data as they were read. */ + vector<double> data; + /** Number of items in each row. */ + vector<int> row_lengths; + /** Maximum number of row lengths. */ + int nc; + public: + MatrixParser() + : nc(0) + { + } + MatrixParser(const MatrixParser &mp) + : data(mp.data), row_lengths(mp.row_lengths), nc(mp.nc) + { + } + virtual ~MatrixParser() + { + } + /** Return a number of read rows. */ + int + nrows() const + { + return (int) row_lengths.size(); + } + /** Return a maximum number of items in the rows. */ + int + ncols() const + { + return nc; + } + /** Parses a given data. This initializes the object data. */ + void parse(int length, const char *stream); + /** Adds newly read item. This should be called from bison + * parser. */ + void add_item(double v); + /** Starts a new row. This should be called from bison + * parser. */ + void start_row(); + /** Process a parse error from the parser. */ + void error(const char *mes) const; + /** Return begin iterator. */ + MPIterator begin() const; + /** Return end iterator. */ + MPIterator end() const; + protected: + /** Returns an index of the first non-empty row starting at + * start. If the start row is non-empty, returns the start. If + * there is no other non-empty row, returns + * row_lengths.size(). */ + int find_first_non_empty_row(int start = 0) const; + }; - /** This is an iterator intended to iterate through a matrix parsed - * by MatrixParser. The iterator provides only read-only access. */ - class MPIterator { - friend class MatrixParser; - protected: - /** Reference to the matrix parser. */ - const MatrixParser* p; - /** The index of the pointed item in the matrix parser. */ - unsigned int i; - /** The column number of the pointed item starting from zero. */ - int c; - /** The row number of the pointed item starting from zero. */ - int r; + /** This is an iterator intended to iterate through a matrix parsed + * by MatrixParser. The iterator provides only read-only access. */ + class MPIterator + { + friend class MatrixParser; + protected: + /** Reference to the matrix parser. */ + const MatrixParser *p; + /** The index of the pointed item in the matrix parser. */ + unsigned int i; + /** The column number of the pointed item starting from zero. */ + int c; + /** The row number of the pointed item starting from zero. */ + int r; - public: - MPIterator() : p(NULL), i(0), c(0), r(0) {} - /** Constructs an iterator pointing to the beginning of the - * parsed matrix. */ - MPIterator(const MatrixParser& mp); - /** Constructs an iterator pointing to the past-the-end of the - * parsed matrix. */ - MPIterator(const MatrixParser& mp, const char* dummy); - /** Return read-only reference to the pointed item. */ - const double& operator*() const - {return p->data[i];} - /** Return a row index of the pointed item. */ - int row() const - {return r;} - /** Return a column index of the pointed item. */ - int col() const - {return c;} - /** Assignment operator. */ - const MPIterator& operator=(const MPIterator& it) - {p = it.p; i = it.i; c = it.c; r = it.r; return *this;} - /** Return true if the iterators are the same, this is if they - * have the same underlying object and the same item index. */ - bool operator==(const MPIterator& it) const - {return it.p == p && it.i == i;} - /** Negative of the operator==. */ - bool operator!=(const MPIterator& it) const - {return ! (it == *this);} - /** Increment operator. */ - MPIterator& operator++(); - }; + public: + MPIterator() : p(NULL), i(0), c(0), r(0) + { + } + /** Constructs an iterator pointing to the beginning of the + * parsed matrix. */ + MPIterator(const MatrixParser &mp); + /** Constructs an iterator pointing to the past-the-end of the + * parsed matrix. */ + MPIterator(const MatrixParser &mp, const char *dummy); + /** Return read-only reference to the pointed item. */ + const double & + operator*() const + { + return p->data[i]; + } + /** Return a row index of the pointed item. */ + int + row() const + { + return r; + } + /** Return a column index of the pointed item. */ + int + col() const + { + return c; + } + /** Assignment operator. */ + const MPIterator & + operator=(const MPIterator &it) + { + p = it.p; i = it.i; c = it.c; r = it.r; return *this; + } + /** Return true if the iterators are the same, this is if they + * have the same underlying object and the same item index. */ + bool + operator==(const MPIterator &it) const + { + return it.p == p && it.i == i; + } + /** Negative of the operator==. */ + bool + operator!=(const MPIterator &it) const + { + return !(it == *this); + } + /** Increment operator. */ + MPIterator &operator++(); + }; }; - - #endif // Local Variables: diff --git a/dynare++/parser/cc/namelist.h b/dynare++/parser/cc/namelist.h index 0bde1232582221c4477ddcdb0073f35569d6c486..e704c8f677b785f138ab872366f480f3d2e987e6 100644 --- a/dynare++/parser/cc/namelist.h +++ b/dynare++/parser/cc/namelist.h @@ -5,24 +5,28 @@ #ifndef OGP_NAMELIST #define OGP_NAMELIST -namespace ogp { +namespace ogp +{ - /** Parent class of all parsers parsing a namelist. They must - * implement add_name() method and error() method, which is called - * when an parse error occurs. - * - * Parsing a name list is done as follows: implement - * NameListParser interface, create the object, and call - * NameListParser::namelist_parse(int lengt, const char* - * text). When implementing error(), one may consult global - * location_type namelist_lloc. */ - class NameListParser { - public: - virtual ~NameListParser() {} - virtual void add_name(const char* name) = 0; - virtual void namelist_error(const char* mes) = 0; - void namelist_parse(int length, const char* text); - }; + /** Parent class of all parsers parsing a namelist. They must + * implement add_name() method and error() method, which is called + * when an parse error occurs. + * + * Parsing a name list is done as follows: implement + * NameListParser interface, create the object, and call + * NameListParser::namelist_parse(int lengt, const char* + * text). When implementing error(), one may consult global + * location_type namelist_lloc. */ + class NameListParser + { + public: + virtual ~NameListParser() + { + } + virtual void add_name(const char *name) = 0; + virtual void namelist_error(const char *mes) = 0; + void namelist_parse(int length, const char *text); + }; }; #endif diff --git a/dynare++/parser/cc/parser_exception.h b/dynare++/parser/cc/parser_exception.h index 2a8668a93037fae03dab9acbb1d69fa4772eaf5c..5b77664061996ce7e7664e78c7e891b493788d9a 100644 --- a/dynare++/parser/cc/parser_exception.h +++ b/dynare++/parser/cc/parser_exception.h @@ -7,61 +7,88 @@ #include <string> -namespace ogp { - using std::string; +namespace ogp +{ + using std::string; - /** This is an easy exception, which, besides the message, stores - * also an offset of the parse error. Since we might need to track - * the argument number and for example the filed in the argument - * which caused the error, we add three integers, which have no - * semantics here. They should be documented in the function which - * throws an exception and sets them. Their default value is -1, - * which means they have not been set. */ - class ParserException { - protected: - char* mes; - int off; - int aux_i1; - int aux_i2; - int aux_i3; - public: - ParserException(const char* m, int offset); - ParserException(const string& m, int offset); - ParserException(const string& m, const char* dum, int i1); - ParserException(const string& m, const char* dum, int i1, int i2); - ParserException(const string& m, const char* dum, int i1, int i2, int i3); - ParserException(const ParserException& e, int plus_offset); - /** Makes a copy and pushes given integer to aux_i1 shuffling - * others and forgetting the last. */ - ParserException(const ParserException& e, const char* dum, int i); - /** Makes a copy and pushes given two integers to aux_i1 and aux_i2 shuffling - * others and forgetting the last two. */ - ParserException(const ParserException& e, const char* dum, int i1, int i2); - /** Makes a copy and pushes given three integers to aux_i1, aux_i2, aus_i3 shuffling - * others and forgetting the last three. */ - ParserException(const ParserException& e, const char* dum, int i1, int i2, int i3); - ParserException(const ParserException& e); - virtual ~ParserException(); - void print(FILE* fd) const; - const char* message() const - {return mes;} - int offset() const - {return off;} - const int& i1() const - {return aux_i1;} - int& i1() - {return aux_i1;} - const int& i2() const - {return aux_i2;} - int& i2() - {return aux_i2;} - const int& i3() const - {return aux_i3;} - int& i3() - {return aux_i3;} - protected: - void copy(const ParserException& e); - }; + /** This is an easy exception, which, besides the message, stores + * also an offset of the parse error. Since we might need to track + * the argument number and for example the filed in the argument + * which caused the error, we add three integers, which have no + * semantics here. They should be documented in the function which + * throws an exception and sets them. Their default value is -1, + * which means they have not been set. */ + class ParserException + { + protected: + char *mes; + int off; + int aux_i1; + int aux_i2; + int aux_i3; + public: + ParserException(const char *m, int offset); + ParserException(const string &m, int offset); + ParserException(const string &m, const char *dum, int i1); + ParserException(const string &m, const char *dum, int i1, int i2); + ParserException(const string &m, const char *dum, int i1, int i2, int i3); + ParserException(const ParserException &e, int plus_offset); + /** Makes a copy and pushes given integer to aux_i1 shuffling + * others and forgetting the last. */ + ParserException(const ParserException &e, const char *dum, int i); + /** Makes a copy and pushes given two integers to aux_i1 and aux_i2 shuffling + * others and forgetting the last two. */ + ParserException(const ParserException &e, const char *dum, int i1, int i2); + /** Makes a copy and pushes given three integers to aux_i1, aux_i2, aus_i3 shuffling + * others and forgetting the last three. */ + ParserException(const ParserException &e, const char *dum, int i1, int i2, int i3); + ParserException(const ParserException &e); + virtual + ~ParserException(); + void print(FILE *fd) const; + const char * + message() const + { + return mes; + } + int + offset() const + { + return off; + } + const int & + i1() const + { + return aux_i1; + } + int & + i1() + { + return aux_i1; + } + const int & + i2() const + { + return aux_i2; + } + int & + i2() + { + return aux_i2; + } + const int & + i3() const + { + return aux_i3; + } + int & + i3() + { + return aux_i3; + } + protected: + void copy(const ParserException &e); + }; }; #endif diff --git a/dynare++/parser/cc/static_atoms.h b/dynare++/parser/cc/static_atoms.h index dbe58017a3d2c735658d1aecaeb4ca5d4014fb4a..e94825d2933f49f2f7e5b2c72ce7732ad03a385e 100644 --- a/dynare++/parser/cc/static_atoms.h +++ b/dynare++/parser/cc/static_atoms.h @@ -7,79 +7,95 @@ #include "dynamic_atoms.h" -namespace ogp { +namespace ogp +{ - class StaticAtoms : public Atoms, public Constants { - protected: - typedef map<const char*, int, ltstr> Tvarmap; - typedef map<int, const char*> Tinvmap; - /** Storage for names. */ - NameStorage varnames; - /** Outer order of variables. */ - vector<const char*> varorder; - /** This is the map mapping a variable name to the tree - * index. */ - Tvarmap vars; - /** This is the inverse mapping. It maps a tree index to the - * variable name. */ - Tinvmap indices; - public: - StaticAtoms() : Atoms(), Constants(), varnames(), varorder(), vars() - {} - /* Copy constructor. */ - StaticAtoms(const StaticAtoms& a); - /** Conversion from DynamicAtoms. This takes all atoms from - * the DynamicAtoms and adds its static version. The new tree - * indices are allocated in the passed OperationTree. Whole - * the process is traced in the map mapping old tree indices - * to new tree indices. */ - StaticAtoms(const DynamicAtoms& da, OperationTree& otree, Tintintmap& tmap) - : Atoms(), Constants(), varnames(), varorder(), vars() - {import_atoms(da, otree, tmap);} - /* Destructor. */ - virtual ~StaticAtoms() {} - /** This imports atoms from dynamic atoms inserting the new - * tree indices to the given tree (including constants). The - * mapping from old atoms to new atoms is traced in tmap. */ - void import_atoms(const DynamicAtoms& da, OperationTree& otree, - Tintintmap& tmap); - /** If the name is constant, it returns its tree index if the - * constant is registered in Constants, it returns -1 - * otherwise. If the name is not constant, it returns result - * from check_variable, which is implemented by a subclass. */ - int check(const char* name) const; - /** This assigns a given tree index to the variable name. The - * name should have been checked before the call. */ - void assign(const char* name, int t); - int nvar() const - {return varnames.num();} - /** This returns a vector of all variables. */ - vector<int> variables() const; - /** This returns a tree index of the given variable. */ - int index(const char* name) const; - /** This returns a name from the given tree index. NULL is - * returned if the tree index doesn't exist. */ - const char* inv_index(int t) const; - /** This returns a name in a outer ordering. (There is no other ordering.) */ - const char* name(int i) const - {return varorder[i];} - /** Debug print. */ - void print() const; - /** This registers a variable. A subclass can reimplement - * this, for example, to ensure uniqueness of the - * name. However, this method should be always called in - * overriding methods to do the registering job. */ - virtual void register_name(const char* name); - /** Return the name storage to allow querying to other - * classes. */ - const NameStorage& get_name_storage() const - {return varnames;} - protected: - /** This checks the variable. The implementing subclass might - * want to throw an exception if the variable has not been - * registered. */ - virtual int check_variable(const char* name) const = 0; - }; + class StaticAtoms : public Atoms, public Constants + { + protected: + typedef map<const char *, int, ltstr> Tvarmap; + typedef map<int, const char *> Tinvmap; + /** Storage for names. */ + NameStorage varnames; + /** Outer order of variables. */ + vector<const char *> varorder; + /** This is the map mapping a variable name to the tree + * index. */ + Tvarmap vars; + /** This is the inverse mapping. It maps a tree index to the + * variable name. */ + Tinvmap indices; + public: + StaticAtoms() : Atoms(), Constants(), varnames(), varorder(), vars() + { + } + /* Copy constructor. */ + StaticAtoms(const StaticAtoms &a); + /** Conversion from DynamicAtoms. This takes all atoms from + * the DynamicAtoms and adds its static version. The new tree + * indices are allocated in the passed OperationTree. Whole + * the process is traced in the map mapping old tree indices + * to new tree indices. */ + StaticAtoms(const DynamicAtoms &da, OperationTree &otree, Tintintmap &tmap) + : Atoms(), Constants(), varnames(), varorder(), vars() + { + import_atoms(da, otree, tmap); + } + /* Destructor. */ + virtual ~StaticAtoms() + { + } + /** This imports atoms from dynamic atoms inserting the new + * tree indices to the given tree (including constants). The + * mapping from old atoms to new atoms is traced in tmap. */ + void import_atoms(const DynamicAtoms &da, OperationTree &otree, + Tintintmap &tmap); + /** If the name is constant, it returns its tree index if the + * constant is registered in Constants, it returns -1 + * otherwise. If the name is not constant, it returns result + * from check_variable, which is implemented by a subclass. */ + int check(const char *name) const; + /** This assigns a given tree index to the variable name. The + * name should have been checked before the call. */ + void assign(const char *name, int t); + int + nvar() const + { + return varnames.num(); + } + /** This returns a vector of all variables. */ + vector<int> variables() const; + /** This returns a tree index of the given variable. */ + int index(const char *name) const; + /** This returns a name from the given tree index. NULL is + * returned if the tree index doesn't exist. */ + const char *inv_index(int t) const; + /** This returns a name in a outer ordering. (There is no other ordering.) */ + const char * + name(int i) const + { + return varorder[i]; + } + /** Debug print. */ + void print() const; + /** This registers a variable. A subclass can reimplement + * this, for example, to ensure uniqueness of the + * name. However, this method should be always called in + * overriding methods to do the registering job. */ + virtual void register_name(const char *name); + /** Return the name storage to allow querying to other + * classes. */ + const NameStorage & + get_name_storage() const + { + return varnames; + } + protected: + /** This checks the variable. The implementing subclass might + * want to throw an exception if the variable has not been + * registered. */ + virtual int check_variable(const char *name) const = 0; + }; }; #endif diff --git a/dynare++/parser/cc/static_fine_atoms.h b/dynare++/parser/cc/static_fine_atoms.h index e80af1eaed9becec0ff9ab0e45ef6d9f38190a7a..c4247f4a737b815e08fb00e91b97b4710248c572 100644 --- a/dynare++/parser/cc/static_fine_atoms.h +++ b/dynare++/parser/cc/static_fine_atoms.h @@ -8,165 +8,202 @@ #include "static_atoms.h" #include "fine_atoms.h" -namespace ogp { +namespace ogp +{ - /** This class represents static atoms distinguishing between - * parameters, endogenous and exogenous variables. The class - * maintains also ordering of all three categories (referenced as - * outer or inner, since there is only one ordering). It can be - * constructed either from scratch, or from fine dynamic atoms. In - * the latter case, one can decide if the ordering of this static - * atoms should be internal or external ordering of the original - * dynamic fine atoms. */ - class StaticFineAtoms : public StaticAtoms { - public: - typedef map<int,int> Tintintmap; - protected: - typedef map<const char*, int, ltstr> Tvarintmap; - private: - /** The vector of parameter names, gives the parameter - * ordering. */ - vector<const char*> params; - /** A map mappping a parameter name to an index in the ordering. */ - Tvarintmap param_outer_map; - /** The vector of endogenous variables. This defines the order - * like parameters. */ - vector<const char*> endovars; - /** A map mapping a name of an endogenous variable to an index - * in the ordering. */ - Tvarintmap endo_outer_map; - /** The vector of exogenous variables. Also defines the order - * like parameters and endovars. */ - vector<const char*> exovars; - /** A map mapping a name of an exogenous variable to an index - * in the outer ordering. */ - Tvarintmap exo_outer_map; - /** This vector defines a set of atoms as tree indices used - * for differentiation. The order of the atoms in is the - * concatenation of the outer ordering of endogenous and - * exogenous. This vector is setup by parsing_finished() and - * is returned by variables(). */ - vector<int> der_atoms; - /** This is a mapping from endogenous atoms to all atoms in - * der_atoms member. The mapping maps index in endogenous atom - * ordering to index (not value) in der_atoms. It is useful if - * one wants to evaluate derivatives wrt only endogenous - * variables. It is set by parsing_finished(). By definition, - * it is monotone. */ - vector<int> endo_atoms_map; - /** This is a mapping from exogenous atoms to all atoms in - * der_atoms member. It is the same as endo_atoms_map for - * atoms of exogenous variables. */ - vector<int> exo_atoms_map; - public: - StaticFineAtoms() {} - /** Copy constructor making a new storage for atom names. */ - StaticFineAtoms(const StaticFineAtoms& sfa); - /** Conversion from dynamic FineAtoms taking its outer - * ordering as ordering of parameters, endogenous and - * exogenous. A biproduct is an integer to integer map mapping - * tree indices of the dynamic atoms to tree indices of the - * static atoms. */ - StaticFineAtoms(const FineAtoms& fa, OperationTree& otree, Tintintmap& tmap) - {StaticFineAtoms::import_atoms(fa, otree, tmap);} - /** Conversion from dynamic FineAtoms taking its internal - * ordering as ordering of parameters, endogenous and - * exogenous. A biproduct is an integer to integer map mapping - * tree indices of the dynamic atoms to tree indices of the - * static atoms. */ - StaticFineAtoms(const FineAtoms& fa, OperationTree& otree, Tintintmap& tmap, - const char* dummy) - {StaticFineAtoms::import_atoms(fa, otree, tmap, dummy);} - virtual ~StaticFineAtoms() {} - /** This adds atoms from dynamic atoms inserting new tree - * indices to the given tree and tracing the mapping from old - * atoms to new atoms in tmap. The ordering of the static - * atoms is the same as outer ordering of dynamic atoms. */ - void import_atoms(const FineAtoms& fa, OperationTree& otree, Tintintmap& tmap); - /** This adds atoms from dynamic atoms inserting new tree - * indices to the given tree and tracing the mapping from old - * atoms to new atoms in tmap. The ordering of the static - * atoms is the same as internal ordering of dynamic atoms. */ - void import_atoms(const FineAtoms& fa, OperationTree& otree, Tintintmap& tmap, - const char* dummy); - /** Overrides StaticAtoms::check_variable so that the error - * would be raised if the variable name is not declared. A - * variable is declared by inserting it to - * StaticAtoms::varnames, which is done with registering - * methods. This a responsibility of a subclass. */ - int check_variable(const char* name) const; - /** Return an (external) ordering of parameters. */ - const vector<const char*>& get_params() const - {return params;} - /** Return an external ordering of endogenous variables. */ - const vector<const char*>& get_endovars() const - {return endovars;} - /** Return an external ordering of exogenous variables. */ - const vector<const char*>& get_exovars() const - {return exovars;} - /** This constructs der_atoms, and the endo_endoms_map and - * exo_atoms_map, which can be created only after the parsing - * is finished. */ - void parsing_finished(); - /** Return the atoms with respect to which we are going to - * differentiate. */ - vector<int> variables() const - {return der_atoms;} - /** Return the endo_atoms_map. */ - const vector<int>& get_endo_atoms_map() const - {return endo_atoms_map;} - /** Return the exo_atoms_map. */ - const vector<int>& get_exo_atoms_map() const - {return endo_atoms_map;} - /** Return an index in the outer ordering of a given - * parameter. An exception is thrown if the name is not a - * parameter. */ - int name2outer_param(const char* name) const; - /** Return an index in the outer ordering of a given - * endogenous variable. An exception is thrown if the name is not a - * and endogenous variable. */ - int name2outer_endo(const char* name) const; - /** Return an index in the outer ordering of a given - * exogenous variable. An exception is thrown if the name is not a - * and exogenous variable. */ - int name2outer_exo(const char* name) const; - /** Return the number of endogenous variables. */ - int ny() const - {return endovars.size();} - /** Return the number of exogenous variables. */ - int nexo() const - {return (int)exovars.size();} - /** Return the number of parameters. */ - int np() const - {return (int)(params.size());} - /** Register unique endogenous variable name. The order of - * calls defines the endo outer ordering. The method is - * virtual, since a superclass may want to do some additional - * action. */ - virtual void register_uniq_endo(const char* name); - /** Register unique exogenous variable name. The order of - * calls defines the exo outer ordering. The method is - * virtual, since a superclass may want to do somem additional - * action. */ - virtual void register_uniq_exo(const char* name); - /** Register unique parameter name. The order of calls defines - * the param outer ordering. The method is - * virtual, since a superclass may want to do somem additional - * action. */ - virtual void register_uniq_param(const char* name); - /** Debug print. */ - void print() const; - private: - /** Add endogenous variable name, which is already in the name - * storage. */ - void register_endo(const char* name); - /** Add exogenous variable name, which is already in the name - * storage. */ - void register_exo(const char* name); - /** Add parameter name, which is already in the name - * storage. */ - void register_param(const char* name); - }; + /** This class represents static atoms distinguishing between + * parameters, endogenous and exogenous variables. The class + * maintains also ordering of all three categories (referenced as + * outer or inner, since there is only one ordering). It can be + * constructed either from scratch, or from fine dynamic atoms. In + * the latter case, one can decide if the ordering of this static + * atoms should be internal or external ordering of the original + * dynamic fine atoms. */ + class StaticFineAtoms : public StaticAtoms + { + public: + typedef map<int, int> Tintintmap; + protected: + typedef map<const char *, int, ltstr> Tvarintmap; + private: + /** The vector of parameter names, gives the parameter + * ordering. */ + vector<const char *> params; + /** A map mappping a parameter name to an index in the ordering. */ + Tvarintmap param_outer_map; + /** The vector of endogenous variables. This defines the order + * like parameters. */ + vector<const char *> endovars; + /** A map mapping a name of an endogenous variable to an index + * in the ordering. */ + Tvarintmap endo_outer_map; + /** The vector of exogenous variables. Also defines the order + * like parameters and endovars. */ + vector<const char *> exovars; + /** A map mapping a name of an exogenous variable to an index + * in the outer ordering. */ + Tvarintmap exo_outer_map; + /** This vector defines a set of atoms as tree indices used + * for differentiation. The order of the atoms in is the + * concatenation of the outer ordering of endogenous and + * exogenous. This vector is setup by parsing_finished() and + * is returned by variables(). */ + vector<int> der_atoms; + /** This is a mapping from endogenous atoms to all atoms in + * der_atoms member. The mapping maps index in endogenous atom + * ordering to index (not value) in der_atoms. It is useful if + * one wants to evaluate derivatives wrt only endogenous + * variables. It is set by parsing_finished(). By definition, + * it is monotone. */ + vector<int> endo_atoms_map; + /** This is a mapping from exogenous atoms to all atoms in + * der_atoms member. It is the same as endo_atoms_map for + * atoms of exogenous variables. */ + vector<int> exo_atoms_map; + public: + StaticFineAtoms() + { + } + /** Copy constructor making a new storage for atom names. */ + StaticFineAtoms(const StaticFineAtoms &sfa); + /** Conversion from dynamic FineAtoms taking its outer + * ordering as ordering of parameters, endogenous and + * exogenous. A biproduct is an integer to integer map mapping + * tree indices of the dynamic atoms to tree indices of the + * static atoms. */ + StaticFineAtoms(const FineAtoms &fa, OperationTree &otree, Tintintmap &tmap) + { + StaticFineAtoms::import_atoms(fa, otree, tmap); + } + /** Conversion from dynamic FineAtoms taking its internal + * ordering as ordering of parameters, endogenous and + * exogenous. A biproduct is an integer to integer map mapping + * tree indices of the dynamic atoms to tree indices of the + * static atoms. */ + StaticFineAtoms(const FineAtoms &fa, OperationTree &otree, Tintintmap &tmap, + const char *dummy) + { + StaticFineAtoms::import_atoms(fa, otree, tmap, dummy); + } + virtual ~StaticFineAtoms() + { + } + /** This adds atoms from dynamic atoms inserting new tree + * indices to the given tree and tracing the mapping from old + * atoms to new atoms in tmap. The ordering of the static + * atoms is the same as outer ordering of dynamic atoms. */ + void import_atoms(const FineAtoms &fa, OperationTree &otree, Tintintmap &tmap); + /** This adds atoms from dynamic atoms inserting new tree + * indices to the given tree and tracing the mapping from old + * atoms to new atoms in tmap. The ordering of the static + * atoms is the same as internal ordering of dynamic atoms. */ + void import_atoms(const FineAtoms &fa, OperationTree &otree, Tintintmap &tmap, + const char *dummy); + /** Overrides StaticAtoms::check_variable so that the error + * would be raised if the variable name is not declared. A + * variable is declared by inserting it to + * StaticAtoms::varnames, which is done with registering + * methods. This a responsibility of a subclass. */ + int check_variable(const char *name) const; + /** Return an (external) ordering of parameters. */ + const vector<const char *> & + get_params() const + { + return params; + } + /** Return an external ordering of endogenous variables. */ + const vector<const char *> & + get_endovars() const + { + return endovars; + } + /** Return an external ordering of exogenous variables. */ + const vector<const char *> & + get_exovars() const + { + return exovars; + } + /** This constructs der_atoms, and the endo_endoms_map and + * exo_atoms_map, which can be created only after the parsing + * is finished. */ + void parsing_finished(); + /** Return the atoms with respect to which we are going to + * differentiate. */ + vector<int> + variables() const + { + return der_atoms; + } + /** Return the endo_atoms_map. */ + const vector<int> & + get_endo_atoms_map() const + { + return endo_atoms_map; + } + /** Return the exo_atoms_map. */ + const vector<int> & + get_exo_atoms_map() const + { + return endo_atoms_map; + } + /** Return an index in the outer ordering of a given + * parameter. An exception is thrown if the name is not a + * parameter. */ + int name2outer_param(const char *name) const; + /** Return an index in the outer ordering of a given + * endogenous variable. An exception is thrown if the name is not a + * and endogenous variable. */ + int name2outer_endo(const char *name) const; + /** Return an index in the outer ordering of a given + * exogenous variable. An exception is thrown if the name is not a + * and exogenous variable. */ + int name2outer_exo(const char *name) const; + /** Return the number of endogenous variables. */ + int + ny() const + { + return endovars.size(); + } + /** Return the number of exogenous variables. */ + int + nexo() const + { + return (int) exovars.size(); + } + /** Return the number of parameters. */ + int + np() const + { + return (int) (params.size()); + } + /** Register unique endogenous variable name. The order of + * calls defines the endo outer ordering. The method is + * virtual, since a superclass may want to do some additional + * action. */ + virtual void register_uniq_endo(const char *name); + /** Register unique exogenous variable name. The order of + * calls defines the exo outer ordering. The method is + * virtual, since a superclass may want to do somem additional + * action. */ + virtual void register_uniq_exo(const char *name); + /** Register unique parameter name. The order of calls defines + * the param outer ordering. The method is + * virtual, since a superclass may want to do somem additional + * action. */ + virtual void register_uniq_param(const char *name); + /** Debug print. */ + void print() const; + private: + /** Add endogenous variable name, which is already in the name + * storage. */ + void register_endo(const char *name); + /** Add exogenous variable name, which is already in the name + * storage. */ + void register_exo(const char *name); + /** Add parameter name, which is already in the name + * storage. */ + void register_param(const char *name); + }; }; diff --git a/dynare++/parser/cc/tree.h b/dynare++/parser/cc/tree.h index a01b441fd02602822be6b4f69f089bbd4828be42..d8def988915fe1a64157f923f24fc63ffd993193 100644 --- a/dynare++/parser/cc/tree.h +++ b/dynare++/parser/cc/tree.h @@ -10,442 +10,511 @@ #include <boost/unordered_set.hpp> #include <cstdio> -namespace ogp { - - using boost::unordered_set; - using boost::unordered_map; - using std::vector; - using std::set; - using std::map; - - /** Enumerator representing nulary, unary and binary operation - * codes. For nulary, 'none' is used. When one is adding a new - * codes, he should update the code of #OperationTree::add_unary, - * #OperationTree::add_binary, and of course - * #OperationTree::add_derivative. */ - enum code_t {NONE, UMINUS, LOG, EXP, SIN, COS, TAN, SQRT, ERF, - ERFC, PLUS, MINUS, TIMES, DIVIDE, POWER}; - - /** Class representing a nulary, unary, or binary operation. */ - class Operation { - protected: - /** Code of the operation. */ - code_t code; - /** First operand. If none, then it is -1. */ - int op1; - /** Second operand. If none, then it is -1. */ - int op2; - - public: - /** Constructs a binary operation. */ - Operation(code_t cd, int oper1, int oper2) - : code(cd), op1(oper1), op2(oper2) {} - /** Constructs a unary operation. */ - Operation(code_t cd, int oper1) - : code(cd), op1(oper1), op2(-1) {} - /** Constructs a nulary operation. */ - Operation() - : code(NONE), op1(-1), op2(-1) {} - /** A copy constructor. */ - Operation(const Operation& op) - : code(op.code), op1(op.op1), op2(op.op2) {} - - /** Operator =. */ - const Operation& operator=(const Operation& op) - { - code = op.code; - op1 = op.op1; - op2 = op.op2; - return *this; - } - /** Operator ==. */ - bool operator==(const Operation& op) const - { - return code == op.code && op1 == op.op1 && op2 == op.op2; - } - /** Operator < implementing lexicographic ordering. */ - bool operator<(const Operation& op) const - { - return (code < op.code || - code == op.code && - (op1 < op.op1 || op1 == op.op1 && op2 < op.op2)); - } - /** Returns a number of operands. */ - int nary() const - { - return (op2 == -1)? ((op1 == -1) ? 0 : 1) : 2; - } - /** Returns a hash value of the operation. */ - size_t hashval() const - { - return op2+1 + (op1+1)^15 + code^30; - } - - code_t getCode() const - { return code; } - int getOp1() const - { return op1; } - int getOp2() const - { return op2; } - - }; - - /** This struct is a predicate for ordering of the operations in - * OperationTree class. now obsolete */ - struct ltoper { - bool operator()(const Operation& oper1, const Operation& oper2) const - {return oper1 < oper2;} - }; - - /** Hash function object for Operation. */ - struct ophash { - size_t operator()(const Operation& op) const - { return op.hashval(); } - }; - - /** This struct is a function object selecting some - * operations. The operation is given by a tree index. */ - struct opselector { - virtual bool operator()(int t) const = 0; - virtual ~opselector() {} - }; - - /** Forward declaration of OperationFormatter. */ - class OperationFormatter; - class DefaultOperationFormatter; - - /** Forward declaration of EvalTree to make it friend of OperationTree. */ - class EvalTree; - - /** Class representing a set of trees for terms. Each term is - * given a unique non-negative integer. The terms are basically - * operations whose (integer) operands point to another terms in - * the tree. The terms are stored in the vector. Equivalent unary - * and binary terms are stored only once. This class guarantees - * the uniqueness. The uniqueness of nulary terms is guaranteed by - * the caller, since at this level of Operation abstraction, one - * cannot discriminate between different nulary operations - * (constants, variables). The uniqueness is enforced by the - * unordered_map whose keys are operations and values are integers - * (indices of the terms). - - * This class can also make derivatives of a given term with - * respect to a given nulary term. I order to be able to quickly - * recognize zero derivativates, we maintain a list of nulary - * terms contained in the term. A possible zero derivative is then quickly - * recognized by looking at the list. The list is implemented as a - * unordered_set of integers. - * - * In addition, many term can be differentiated multiple times wrt - * one variable since they can be referenced multiple times. To - * avoid this, for each term we maintain a map mapping variables - * to the derivatives of the term. As the caller will - * differentiate wrt more and more variables, these maps will - * become richer and richer. - */ - class OperationTree { - friend class EvalTree; - friend class DefaultOperationFormatter; - protected: - /** This is the vector of the terms. An index to this vector - * uniquelly determines the term. */ - vector<Operation> terms; - - /** This defines a type for a map mapping the unary and binary - * operations to their indices. */ - typedef unordered_map<Operation, int, ophash> _Topmap; - typedef _Topmap::value_type _Topval; - - /** This is the map mapping the unary and binary operations to - * the indices of the terms.*/ - _Topmap opmap; - - /** This is a type for a set of integers. */ - typedef unordered_set<int> _Tintset; - /** This is a vector of integer sets corresponding to the - * nulary terms contained in the term. */ - vector<_Tintset> nul_incidence; - - /** This is a type of the map from variables (nulary terms) to - * the terms. */ - typedef unordered_map<int, int> _Tderivmap; - /** This is a vector of derivative mappings. For each term, it - * maps variables to the derivatives of the term with respect - * to the variables. */ - vector<_Tderivmap> derivatives; - - /** The tree index of the last nulary term. */ - int last_nulary; - public: - /** This is a number of constants set in the following - * enum. This number reserves space in a vector of terms for - * the constants. */ - static const int num_constants = 4; - /** Enumeration for special terms. We need zero, one, nan and - * 2/pi. These will be always first four terms having indices - * zero, one and two, three. If adding anything to this - * enumeration, make sure you have updated num_constants above.*/ - enum {zero=0, one=1, nan=2, two_over_pi=3}; - - /** The unique constructor which initializes the object to - * contain only zero, one and nan and two_over_pi.*/ - OperationTree(); - - /** Copy constructor. */ - OperationTree(const OperationTree& ot) - : terms(ot.terms), opmap(ot.opmap), nul_incidence(ot.nul_incidence), - derivatives(ot.derivatives), - last_nulary(ot.last_nulary) - {} - - /** Add a nulary operation. The caller is responsible for not - * inserting two semantically equivalent nulary operations. - * @return newly allocated index - */ - int add_nulary(); - - /** Add a unary operation. The uniqness is checked, if it - * already exists, then it is not added. - * @param code the code of the unary operation - * @param op the index of the operand - * @return the index of the operation - */ - int add_unary(code_t code, int op); - - /** Add a binary operation. The uniqueness is checked, if it - * already exists, then it is not added. - * @param code the code of the binary operation - * @param op1 the index of the first operand - * @param op2 the index of the second operand - * @return the index of the operation - */ - int add_binary(code_t code, int op1, int op2); - - /** Add the derivative of the given term with respect to the - * given nulary operation. - * @param t the index of the operation being differentiated - * @param v the index of the nulary operation - * @return the index of the derivative - */ - int add_derivative(int t, int v); - - /** Add the substitution given by the map. This adds a new - * term which is equal to the given term with applied - * substitutions given by the map replacing each term on the - * left by a term on the right. We do not check that the terms - * on the left are not subterms of the terms on the right. If - * so, the substituted terms are not subject of further - * substitution. */ - int add_substitution(int t, const map<int,int>& subst); - - /** Add the substitution given by the map where left sides of - * substitutions come from another tree. The right sides are - * from this tree. The given t is from the given otree. */ - int add_substitution(int t, const map<int,int>& subst, - const OperationTree& otree); - - /** This method turns the given term to a nulary - * operation. This is an only method, which changes already - * existing term (all other methods add something new). User - * should use this with caution and must make sure that - * something similar has happened for atoms. In addition, it - * does not do anything with derivatives, so it should not be - * used after some derivatives were created, and derivatives - * already created and saved in derivatives mappings should be - * forgotten with forget_derivative_maps. */ - void nularify(int t); - - /** Return the set of nulary terms of the given term. */ - const unordered_set<int>& nulary_of_term(int t) const - {return nul_incidence[t];} - - /** Select subterms of the given term according a given - * operation selector and return the set of terms that - * correspond to the compounded operations. The given term is - * a compound function of the returned subterms and the - * function consists only from operations which yield false in - * the selector. */ - unordered_set<int> select_terms(int t, const opselector& sel) const; - - /** Select subterms of the given term according a given - * operation selector and return the set of terms that - * correspond to the compounded operations. The given term is - * a compound function of the returned subterms and the - * subterms are maximal subterms consisting from operations - * yielding true in the selector. */ - unordered_set<int> select_terms_inv(int t, const opselector& sel) const; - - /** This forgets all the derivative mappings. It is used after - * a term has been nularified, and then the derivative - * mappings carry wrong information. Note that the derivatives - * mappings serve only as a tool for quick returns in - * add_derivative. Resseting the mappings is harmless, all the - * information is rebuilt in add_derivative without any - * additional nodes (trees). */ - void forget_derivative_maps(); - - /** This returns an operation of a given term. */ - const Operation& operation(int t) const - {return terms[t];} - - /** This outputs the operation to the given file descriptor - * using the given OperationFormatter. */ - void print_operation_tree(int t, FILE* fd, OperationFormatter& f) const; - - /** Debug print of a given operation: */ - void print_operation(int t) const; - - /** Return the last tree index of a nulary term. */ - int get_last_nulary() const - {return last_nulary;} - - /** Get the number of all operations. */ - int get_num_op() const - {return (int)(terms.size());} - private: - /** This registers a calculated derivative of the term in the - * #derivatives vector. - * @param t the index of the term for which we register the derivative - * @param v the index of the nulary term (variable) to which - * respect the derivative was taken - * @param tder the index of the resulting derivative - */ - void register_derivative(int t, int v, int tder); - /** This does the same job as select_terms with the only - * difference, that it adds the terms to the given set and - * hence can be used recursivelly. */ - void select_terms(int t, const opselector& sel, unordered_set<int>& subterms) const; - /** This does the same job as select_terms_inv with the only - * difference, that it adds the terms to the given set and - * hence can be used recursivelly and returns true if the term - * was selected. */ - bool select_terms_inv(int t, const opselector& sel, unordered_set<int>& subterms) const; - /** This updates nul_incidence information after the term t - * was turned to a nulary term in all terms. It goes through - * the tree from simplest terms to teh more complex ones and - * changes the nul_incidence information where necesary. It - * maintains a set where the changes have been made.*/ - void update_nul_incidence_after_nularify(int t); - }; - - /** EvalTree class allows for an evaluation of the given tree for - * a given values of nulary terms. For each term in the - * OperationTree the class maintains a resulting value and a flag - * if the value has been calculated or set. The life cycle of the - * class is the following: After it is initialized, the user must - * set values for necessary nulary terms. Then the object can be - * requested to evaluate particular terms. During this process, - * the number of evaluated terms is increasing. Then the user can - * request overall reset of evaluation flags, set the nulary terms - * to new values and evaluate a number of terms. - * - * Note that currently the user cannot request a reset of - * evaluation flags only for those terms depending on a given - * nulary term. This might be added in future and handeled by a - * subclasses of OperationTree and EvalTree, since we need a - * support for this in OperationTree. - */ - class EvalTree { - protected: - /** Reference to the OperationTree over which all evaluations - * are done. */ - const OperationTree& otree; - /** The array of values. */ - double* const values; - /** The array of evaluation flags. */ - bool* const flags; - /** The index of last operation in the EvalTree. Length of - * values and flags will be then last_operation+1. */ - int last_operation; - public: - /** Initializes the evaluation tree for the given operation - * tree. If last is greater than -1, that the evaluation tree - * will contain only formulas up to the given last index - * (included). */ - EvalTree(const OperationTree& otree, int last = -1); - virtual ~EvalTree() - { delete [] values; delete [] flags; } - /** Set evaluation flag to all terms (besides the first - * special terms) to false. */ - void reset_all(); - /** Set value for a given nulary term. */ - void set_nulary(int t, double val); - /** Evaluate the given term with nulary terms set so far. */ - double eval(int t); - /** Debug print. */ - void print() const; - /* Return the operation tree. */ - const OperationTree& getOperationTree() const - {return otree;} - private: - EvalTree(const EvalTree&); - }; - - /** This is an interface describing how a given operation is - * formatted for output. */ - class OperationFormatter { - public: - /** Empty virtual destructor. */ - virtual ~OperationFormatter() {} - /** Print the formatted operation op with a given tree index t - * to a given descriptor. (See class OperationTree to know - * what is a tree index.) This prints all the tree. This - * always writes equation, left hand side is a string - * represenation (a variable, temporary, whatever) of the - * term, the right hand side is a string representation of the - * operation (which will refer to other string representation - * of subterms). */ - virtual void format(const Operation& op, int t, FILE* fd)=0; - }; - - /** The default formatter formats the formulas with a usual syntax - * (for example Matlab). A formatting of atoms and terms might be - * reimplemented by a subclass. In addition, during its life, the - * object maintains a set of tree indices which have been output - * and they are not output any more. */ - class DefaultOperationFormatter : public OperationFormatter { - protected: - const OperationTree& otree; - set<int> stop_set; - public: - DefaultOperationFormatter(const OperationTree& ot) - : otree(ot) {} - /** Format the operation with the default syntax. */ - void format(const Operation& op, int t, FILE* fd); - /** This prints a string represenation of the given term, for - * example 'tmp10' for term 10. In this implementation it - * prints $10. */ - virtual void format_term(int t, FILE* fd) const; - /** Print a string representation of the nulary term. */ - virtual void format_nulary(int t, FILE* fd) const; - /** Print a delimiter between two statements. By default it is - * "\n". */ - virtual void print_delim(FILE* fd) const; - }; - - class NularyStringConvertor { - public: - virtual ~NularyStringConvertor() {} - /** Return the string representation of the atom with the tree - * index t. */ - virtual std::string convert(int t) const = 0; - }; - - /** This class converts the given term to its mathematical string representation. */ - class OperationStringConvertor { - protected: - const NularyStringConvertor& nulsc; - const OperationTree& otree; - public: - OperationStringConvertor(const NularyStringConvertor& nsc, const OperationTree& ot) - : nulsc(nsc), otree(ot) {} - /** Empty virtual destructor. */ - virtual ~OperationStringConvertor() {} - /** Convert the operation to the string mathematical - * representation. This does not write any equation, just - * returns a string representation of the formula. */ - std::string convert(const Operation& op, int t) const; - }; +namespace ogp +{ + + using boost::unordered_set; + using boost::unordered_map; + using std::vector; + using std::set; + using std::map; + + /** Enumerator representing nulary, unary and binary operation + * codes. For nulary, 'none' is used. When one is adding a new + * codes, he should update the code of #OperationTree::add_unary, + * #OperationTree::add_binary, and of course + * #OperationTree::add_derivative. */ + enum code_t {NONE, UMINUS, LOG, EXP, SIN, COS, TAN, SQRT, ERF, + ERFC, PLUS, MINUS, TIMES, DIVIDE, POWER}; + + /** Class representing a nulary, unary, or binary operation. */ + class Operation + { + protected: + /** Code of the operation. */ + code_t code; + /** First operand. If none, then it is -1. */ + int op1; + /** Second operand. If none, then it is -1. */ + int op2; + + public: + /** Constructs a binary operation. */ + Operation(code_t cd, int oper1, int oper2) + : code(cd), op1(oper1), op2(oper2) + { + } + /** Constructs a unary operation. */ + Operation(code_t cd, int oper1) + : code(cd), op1(oper1), op2(-1) + { + } + /** Constructs a nulary operation. */ + Operation() + : code(NONE), op1(-1), op2(-1) + { + } + /** A copy constructor. */ + Operation(const Operation &op) + : code(op.code), op1(op.op1), op2(op.op2) + { + } + + /** Operator =. */ + const Operation & + operator=(const Operation &op) + { + code = op.code; + op1 = op.op1; + op2 = op.op2; + return *this; + } + /** Operator ==. */ + bool + operator==(const Operation &op) const + { + return code == op.code && op1 == op.op1 && op2 == op.op2; + } + /** Operator < implementing lexicographic ordering. */ + bool + operator<(const Operation &op) const + { + return (code < op.code + || code == op.code + && (op1 < op.op1 || op1 == op.op1 && op2 < op.op2)); + } + /** Returns a number of operands. */ + int + nary() const + { + return (op2 == -1) ? ((op1 == -1) ? 0 : 1) : 2; + } + /** Returns a hash value of the operation. */ + size_t + hashval() const + { + return op2+1 + (op1+1)^15 + code^30; + } + + code_t + getCode() const + { + return code; + } + int + getOp1() const + { + return op1; + } + int + getOp2() const + { + return op2; + } + + }; + + /** This struct is a predicate for ordering of the operations in + * OperationTree class. now obsolete */ + struct ltoper + { + bool + operator()(const Operation &oper1, const Operation &oper2) const + { + return oper1 < oper2; + } + }; + + /** Hash function object for Operation. */ + struct ophash + { + size_t + operator()(const Operation &op) const + { + return op.hashval(); + } + }; + + /** This struct is a function object selecting some + * operations. The operation is given by a tree index. */ + struct opselector + { + virtual bool operator()(int t) const = 0; + virtual ~opselector() + { + } + }; + + /** Forward declaration of OperationFormatter. */ + class OperationFormatter; + class DefaultOperationFormatter; + + /** Forward declaration of EvalTree to make it friend of OperationTree. */ + class EvalTree; + + /** Class representing a set of trees for terms. Each term is + * given a unique non-negative integer. The terms are basically + * operations whose (integer) operands point to another terms in + * the tree. The terms are stored in the vector. Equivalent unary + * and binary terms are stored only once. This class guarantees + * the uniqueness. The uniqueness of nulary terms is guaranteed by + * the caller, since at this level of Operation abstraction, one + * cannot discriminate between different nulary operations + * (constants, variables). The uniqueness is enforced by the + * unordered_map whose keys are operations and values are integers + * (indices of the terms). + + * This class can also make derivatives of a given term with + * respect to a given nulary term. I order to be able to quickly + * recognize zero derivativates, we maintain a list of nulary + * terms contained in the term. A possible zero derivative is then quickly + * recognized by looking at the list. The list is implemented as a + * unordered_set of integers. + * + * In addition, many term can be differentiated multiple times wrt + * one variable since they can be referenced multiple times. To + * avoid this, for each term we maintain a map mapping variables + * to the derivatives of the term. As the caller will + * differentiate wrt more and more variables, these maps will + * become richer and richer. + */ + class OperationTree + { + friend class EvalTree; + friend class DefaultOperationFormatter; + protected: + /** This is the vector of the terms. An index to this vector + * uniquelly determines the term. */ + vector<Operation> terms; + + /** This defines a type for a map mapping the unary and binary + * operations to their indices. */ + typedef unordered_map<Operation, int, ophash> _Topmap; + typedef _Topmap::value_type _Topval; + + /** This is the map mapping the unary and binary operations to + * the indices of the terms.*/ + _Topmap opmap; + + /** This is a type for a set of integers. */ + typedef unordered_set<int> _Tintset; + /** This is a vector of integer sets corresponding to the + * nulary terms contained in the term. */ + vector<_Tintset> nul_incidence; + + /** This is a type of the map from variables (nulary terms) to + * the terms. */ + typedef unordered_map<int, int> _Tderivmap; + /** This is a vector of derivative mappings. For each term, it + * maps variables to the derivatives of the term with respect + * to the variables. */ + vector<_Tderivmap> derivatives; + + /** The tree index of the last nulary term. */ + int last_nulary; + public: + /** This is a number of constants set in the following + * enum. This number reserves space in a vector of terms for + * the constants. */ + static const int num_constants = 4; + /** Enumeration for special terms. We need zero, one, nan and + * 2/pi. These will be always first four terms having indices + * zero, one and two, three. If adding anything to this + * enumeration, make sure you have updated num_constants above.*/ + enum {zero = 0, one = 1, nan = 2, two_over_pi = 3}; + + /** The unique constructor which initializes the object to + * contain only zero, one and nan and two_over_pi.*/ + OperationTree(); + + /** Copy constructor. */ + OperationTree(const OperationTree &ot) + : terms(ot.terms), opmap(ot.opmap), nul_incidence(ot.nul_incidence), + derivatives(ot.derivatives), + last_nulary(ot.last_nulary) + { + } + + /** Add a nulary operation. The caller is responsible for not + * inserting two semantically equivalent nulary operations. + * @return newly allocated index + */ + int add_nulary(); + + /** Add a unary operation. The uniqness is checked, if it + * already exists, then it is not added. + * @param code the code of the unary operation + * @param op the index of the operand + * @return the index of the operation + */ + int add_unary(code_t code, int op); + + /** Add a binary operation. The uniqueness is checked, if it + * already exists, then it is not added. + * @param code the code of the binary operation + * @param op1 the index of the first operand + * @param op2 the index of the second operand + * @return the index of the operation + */ + int add_binary(code_t code, int op1, int op2); + + /** Add the derivative of the given term with respect to the + * given nulary operation. + * @param t the index of the operation being differentiated + * @param v the index of the nulary operation + * @return the index of the derivative + */ + int add_derivative(int t, int v); + + /** Add the substitution given by the map. This adds a new + * term which is equal to the given term with applied + * substitutions given by the map replacing each term on the + * left by a term on the right. We do not check that the terms + * on the left are not subterms of the terms on the right. If + * so, the substituted terms are not subject of further + * substitution. */ + int add_substitution(int t, const map<int, int> &subst); + + /** Add the substitution given by the map where left sides of + * substitutions come from another tree. The right sides are + * from this tree. The given t is from the given otree. */ + int add_substitution(int t, const map<int, int> &subst, + const OperationTree &otree); + + /** This method turns the given term to a nulary + * operation. This is an only method, which changes already + * existing term (all other methods add something new). User + * should use this with caution and must make sure that + * something similar has happened for atoms. In addition, it + * does not do anything with derivatives, so it should not be + * used after some derivatives were created, and derivatives + * already created and saved in derivatives mappings should be + * forgotten with forget_derivative_maps. */ + void nularify(int t); + + /** Return the set of nulary terms of the given term. */ + const unordered_set<int> & + nulary_of_term(int t) const + { + return nul_incidence[t]; + } + + /** Select subterms of the given term according a given + * operation selector and return the set of terms that + * correspond to the compounded operations. The given term is + * a compound function of the returned subterms and the + * function consists only from operations which yield false in + * the selector. */ + unordered_set<int> select_terms(int t, const opselector &sel) const; + + /** Select subterms of the given term according a given + * operation selector and return the set of terms that + * correspond to the compounded operations. The given term is + * a compound function of the returned subterms and the + * subterms are maximal subterms consisting from operations + * yielding true in the selector. */ + unordered_set<int> select_terms_inv(int t, const opselector &sel) const; + + /** This forgets all the derivative mappings. It is used after + * a term has been nularified, and then the derivative + * mappings carry wrong information. Note that the derivatives + * mappings serve only as a tool for quick returns in + * add_derivative. Resseting the mappings is harmless, all the + * information is rebuilt in add_derivative without any + * additional nodes (trees). */ + void forget_derivative_maps(); + + /** This returns an operation of a given term. */ + const Operation & + operation(int t) const + { + return terms[t]; + } + + /** This outputs the operation to the given file descriptor + * using the given OperationFormatter. */ + void print_operation_tree(int t, FILE *fd, OperationFormatter &f) const; + + /** Debug print of a given operation: */ + void print_operation(int t) const; + + /** Return the last tree index of a nulary term. */ + int + get_last_nulary() const + { + return last_nulary; + } + + /** Get the number of all operations. */ + int + get_num_op() const + { + return (int) (terms.size()); + } + private: + /** This registers a calculated derivative of the term in the + * #derivatives vector. + * @param t the index of the term for which we register the derivative + * @param v the index of the nulary term (variable) to which + * respect the derivative was taken + * @param tder the index of the resulting derivative + */ + void register_derivative(int t, int v, int tder); + /** This does the same job as select_terms with the only + * difference, that it adds the terms to the given set and + * hence can be used recursivelly. */ + void select_terms(int t, const opselector &sel, unordered_set<int> &subterms) const; + /** This does the same job as select_terms_inv with the only + * difference, that it adds the terms to the given set and + * hence can be used recursivelly and returns true if the term + * was selected. */ + bool select_terms_inv(int t, const opselector &sel, unordered_set<int> &subterms) const; + /** This updates nul_incidence information after the term t + * was turned to a nulary term in all terms. It goes through + * the tree from simplest terms to teh more complex ones and + * changes the nul_incidence information where necesary. It + * maintains a set where the changes have been made.*/ + void update_nul_incidence_after_nularify(int t); + }; + + /** EvalTree class allows for an evaluation of the given tree for + * a given values of nulary terms. For each term in the + * OperationTree the class maintains a resulting value and a flag + * if the value has been calculated or set. The life cycle of the + * class is the following: After it is initialized, the user must + * set values for necessary nulary terms. Then the object can be + * requested to evaluate particular terms. During this process, + * the number of evaluated terms is increasing. Then the user can + * request overall reset of evaluation flags, set the nulary terms + * to new values and evaluate a number of terms. + * + * Note that currently the user cannot request a reset of + * evaluation flags only for those terms depending on a given + * nulary term. This might be added in future and handeled by a + * subclasses of OperationTree and EvalTree, since we need a + * support for this in OperationTree. + */ + class EvalTree + { + protected: + /** Reference to the OperationTree over which all evaluations + * are done. */ + const OperationTree &otree; + /** The array of values. */ + double *const values; + /** The array of evaluation flags. */ + bool *const flags; + /** The index of last operation in the EvalTree. Length of + * values and flags will be then last_operation+1. */ + int last_operation; + public: + /** Initializes the evaluation tree for the given operation + * tree. If last is greater than -1, that the evaluation tree + * will contain only formulas up to the given last index + * (included). */ + EvalTree(const OperationTree &otree, int last = -1); + virtual ~EvalTree() + { + delete [] values; delete [] flags; + } + /** Set evaluation flag to all terms (besides the first + * special terms) to false. */ + void reset_all(); + /** Set value for a given nulary term. */ + void set_nulary(int t, double val); + /** Evaluate the given term with nulary terms set so far. */ + double eval(int t); + /** Debug print. */ + void print() const; + /* Return the operation tree. */ + const OperationTree & + getOperationTree() const + { + return otree; + } + private: + EvalTree(const EvalTree &); + }; + + /** This is an interface describing how a given operation is + * formatted for output. */ + class OperationFormatter + { + public: + /** Empty virtual destructor. */ + virtual ~OperationFormatter() + { + } + /** Print the formatted operation op with a given tree index t + * to a given descriptor. (See class OperationTree to know + * what is a tree index.) This prints all the tree. This + * always writes equation, left hand side is a string + * represenation (a variable, temporary, whatever) of the + * term, the right hand side is a string representation of the + * operation (which will refer to other string representation + * of subterms). */ + virtual void format(const Operation &op, int t, FILE *fd) = 0; + }; + + /** The default formatter formats the formulas with a usual syntax + * (for example Matlab). A formatting of atoms and terms might be + * reimplemented by a subclass. In addition, during its life, the + * object maintains a set of tree indices which have been output + * and they are not output any more. */ + class DefaultOperationFormatter : public OperationFormatter + { + protected: + const OperationTree &otree; + set<int> stop_set; + public: + DefaultOperationFormatter(const OperationTree &ot) + : otree(ot) + { + } + /** Format the operation with the default syntax. */ + void format(const Operation &op, int t, FILE *fd); + /** This prints a string represenation of the given term, for + * example 'tmp10' for term 10. In this implementation it + * prints $10. */ + virtual void format_term(int t, FILE *fd) const; + /** Print a string representation of the nulary term. */ + virtual void format_nulary(int t, FILE *fd) const; + /** Print a delimiter between two statements. By default it is + * "\n". */ + virtual void print_delim(FILE *fd) const; + }; + + class NularyStringConvertor + { + public: + virtual ~NularyStringConvertor() + { + } + /** Return the string representation of the atom with the tree + * index t. */ + virtual std::string convert(int t) const = 0; + }; + + /** This class converts the given term to its mathematical string representation. */ + class OperationStringConvertor + { + protected: + const NularyStringConvertor &nulsc; + const OperationTree &otree; + public: + OperationStringConvertor(const NularyStringConvertor &nsc, const OperationTree &ot) + : nulsc(nsc), otree(ot) + { + } + /** Empty virtual destructor. */ + virtual ~OperationStringConvertor() + { + } + /** Convert the operation to the string mathematical + * representation. This does not write any equation, just + * returns a string representation of the formula. */ + std::string convert(const Operation &op, int t) const; + }; }; #endif diff --git a/dynare++/src/dynare3.h b/dynare++/src/dynare3.h index a106f52aa78fb725b289f54c6381250b924d0f62..723060a955b2f5f48a1f5cbd08951feaa1cb5233 100644 --- a/dynare++/src/dynare3.h +++ b/dynare++/src/dynare3.h @@ -18,175 +18,286 @@ class Dynare; -class DynareNameList : public NameList { - vector<const char*> names; +class DynareNameList : public NameList +{ + vector<const char *> names; public: - DynareNameList(const Dynare& dynare); - int getNum() const - {return (int)names.size();} - const char* getName(int i) const - {return names[i];} - /** This for each string of the input vector calculates its index - * in the names. And returns the resulting vector of indices. If - * the name cannot be found, then an exception is raised. */ - vector<int> selectIndices(const vector<const char*>& ns) const; + DynareNameList(const Dynare &dynare); + int + getNum() const + { + return (int) names.size(); + } + const char * + getName(int i) const + { + return names[i]; + } + /** This for each string of the input vector calculates its index + * in the names. And returns the resulting vector of indices. If + * the name cannot be found, then an exception is raised. */ + vector<int> selectIndices(const vector<const char *> &ns) const; }; -class DynareExogNameList : public NameList { - vector<const char*> names; +class DynareExogNameList : public NameList +{ + vector<const char *> names; public: - DynareExogNameList(const Dynare& dynare); - int getNum() const - {return (int)names.size();} - const char* getName(int i) const - {return names[i];} + DynareExogNameList(const Dynare &dynare); + int + getNum() const + { + return (int) names.size(); + } + const char * + getName(int i) const + { + return names[i]; + } }; -class DynareStateNameList : public NameList { - vector<const char*> names; +class DynareStateNameList : public NameList +{ + vector<const char *> names; public: - DynareStateNameList(const Dynare& dynare, const DynareNameList& dnl, - const DynareExogNameList& denl); - int getNum() const - {return (int)names.size();} - const char* getName(int i) const - {return names[i];} + DynareStateNameList(const Dynare &dynare, const DynareNameList &dnl, + const DynareExogNameList &denl); + int + getNum() const + { + return (int) names.size(); + } + const char * + getName(int i) const + { + return names[i]; + } }; // The following only implements DynamicModel with help of ogdyn::DynareModel class DynareJacobian; -class Dynare : public DynamicModel { - friend class DynareNameList; - friend class DynareExogNameList; - friend class DynareStateNameList; - friend class DynareJacobian; - Journal& journal; - ogdyn::DynareModel* model; - Vector* ysteady; - TensorContainer<FSSparseTensor> md; - DynareNameList* dnl; - DynareExogNameList* denl; - DynareStateNameList* dsnl; - ogp::FormulaEvaluator* fe; - ogp::FormulaDerEvaluator* fde; - const double ss_tol; +class Dynare : public DynamicModel +{ + friend class DynareNameList; + friend class DynareExogNameList; + friend class DynareStateNameList; + friend class DynareJacobian; + Journal &journal; + ogdyn::DynareModel *model; + Vector *ysteady; + TensorContainer<FSSparseTensor> md; + DynareNameList *dnl; + DynareExogNameList *denl; + DynareStateNameList *dsnl; + ogp::FormulaEvaluator *fe; + ogp::FormulaDerEvaluator *fde; + const double ss_tol; public: - /** Parses the given model file and uses the given order to - * override order from the model file (if it is != -1). */ - Dynare(const char* modname, int ord, double sstol, Journal& jr); - /** Parses the given equations with explicitly given names. */ - Dynare(const char** endo, int num_endo, - const char** exo, int num_exo, - const char** par, int num_par, - const char* equations, int len, int ord, - double sstol, Journal& jr); - /** Makes a deep copy of the object. */ - Dynare(const Dynare& dyn); - DynamicModel* clone() const - {return new Dynare(*this);} - virtual ~Dynare(); - int nstat() const - {return model->getAtoms().nstat();} - int nboth() const - {return model->getAtoms().nboth();} - int npred() const - {return model->getAtoms().npred();} - int nforw() const - {return model->getAtoms().nforw();} - int nexog() const - {return model->getAtoms().nexo();} - int nys() const - {return model->getAtoms().nys();} - int nyss() const - {return model->getAtoms().nyss();} - int ny() const - {return model->getAtoms().ny();} - int order() const - {return model->getOrder();} - - const NameList& getAllEndoNames() const - {return *dnl;} - const NameList& getStateNames() const - {return *dsnl;} - const NameList& getExogNames() const - {return *denl;} - - TwoDMatrix& getVcov() - {return model->getVcov();} - const TwoDMatrix& getVcov() const - {return model->getVcov();} - Vector& getParams() - {return model->getParams();} - const Vector& getParams() const - {return model->getParams();} - void setInitOuter(const Vector& x) - {model->setInitOuter(x);} - - const TensorContainer<FSSparseTensor>& getModelDerivatives() const - {return md;} - const Vector& getSteady() const - {return *ysteady;} - Vector& getSteady() - {return *ysteady;} - const ogdyn::DynareModel& getModel() const - {return *model;} - - // here is true public interface - void solveDeterministicSteady(Vector& steady); - void solveDeterministicSteady() - {solveDeterministicSteady(*ysteady);} - void evaluateSystem(Vector& out, const Vector& yy, const Vector& xx); - void evaluateSystem(Vector& out, const Vector& yym, const Vector& yy, - const Vector& yyp, const Vector& xx); - void calcDerivatives(const Vector& yy, const Vector& xx); - void calcDerivativesAtSteady(); - - void writeMat(mat_t *fd, const char* prefix) const; - void writeDump(const std::string& basename) const; + /** Parses the given model file and uses the given order to + * override order from the model file (if it is != -1). */ + Dynare(const char *modname, int ord, double sstol, Journal &jr); + /** Parses the given equations with explicitly given names. */ + Dynare(const char **endo, int num_endo, + const char **exo, int num_exo, + const char **par, int num_par, + const char *equations, int len, int ord, + double sstol, Journal &jr); + /** Makes a deep copy of the object. */ + Dynare(const Dynare &dyn); + DynamicModel * + clone() const + { + return new Dynare(*this); + } + virtual + ~Dynare(); + int + nstat() const + { + return model->getAtoms().nstat(); + } + int + nboth() const + { + return model->getAtoms().nboth(); + } + int + npred() const + { + return model->getAtoms().npred(); + } + int + nforw() const + { + return model->getAtoms().nforw(); + } + int + nexog() const + { + return model->getAtoms().nexo(); + } + int + nys() const + { + return model->getAtoms().nys(); + } + int + nyss() const + { + return model->getAtoms().nyss(); + } + int + ny() const + { + return model->getAtoms().ny(); + } + int + order() const + { + return model->getOrder(); + } + + const NameList & + getAllEndoNames() const + { + return *dnl; + } + const NameList & + getStateNames() const + { + return *dsnl; + } + const NameList & + getExogNames() const + { + return *denl; + } + + TwoDMatrix & + getVcov() + { + return model->getVcov(); + } + const TwoDMatrix & + getVcov() const + { + return model->getVcov(); + } + Vector & + getParams() + { + return model->getParams(); + } + const Vector & + getParams() const + { + return model->getParams(); + } + void + setInitOuter(const Vector &x) + { + model->setInitOuter(x); + } + + const TensorContainer<FSSparseTensor> & + getModelDerivatives() const + { + return md; + } + const Vector & + getSteady() const + { + return *ysteady; + } + Vector & + getSteady() + { + return *ysteady; + } + const ogdyn::DynareModel & + getModel() const + { + return *model; + } + + // here is true public interface + void solveDeterministicSteady(Vector &steady); + void + solveDeterministicSteady() + { + solveDeterministicSteady(*ysteady); + } + void evaluateSystem(Vector &out, const Vector &yy, const Vector &xx); + void evaluateSystem(Vector &out, const Vector &yym, const Vector &yy, + const Vector &yyp, const Vector &xx); + void calcDerivatives(const Vector &yy, const Vector &xx); + void calcDerivativesAtSteady(); + + void writeMat(mat_t *fd, const char *prefix) const; + void writeDump(const std::string &basename) const; private: - void writeModelInfo(Journal& jr) const; + void writeModelInfo(Journal &jr) const; }; -class DynareEvalLoader : public ogp::FormulaEvalLoader, public Vector { +class DynareEvalLoader : public ogp::FormulaEvalLoader, public Vector +{ public: - DynareEvalLoader(const ogp::FineAtoms& a, Vector& out); - void load(int i, double res) - {operator[](i) = res;} + DynareEvalLoader(const ogp::FineAtoms &a, Vector &out); + void + load(int i, double res) + { + operator[](i) = res; + } }; -class DynareDerEvalLoader : public ogp::FormulaDerEvalLoader { +class DynareDerEvalLoader : public ogp::FormulaDerEvalLoader +{ protected: - const ogp::FineAtoms& atoms; - TensorContainer<FSSparseTensor>& md; + const ogp::FineAtoms &atoms; + TensorContainer<FSSparseTensor> &md; public: - DynareDerEvalLoader(const ogp::FineAtoms& a, TensorContainer<FSSparseTensor>& mod_ders, - int order); - void load(int i, int iord, const int* vars, double res); + DynareDerEvalLoader(const ogp::FineAtoms &a, TensorContainer<FSSparseTensor> &mod_ders, + int order); + void load(int i, int iord, const int *vars, double res); }; -class DynareJacobian : public ogu::Jacobian, public ogp::FormulaDerEvalLoader { +class DynareJacobian : public ogu::Jacobian, public ogp::FormulaDerEvalLoader +{ protected: - Dynare& d; + Dynare &d; public: - DynareJacobian(Dynare& dyn); - virtual ~DynareJacobian() {} - void load(int i, int iord, const int* vars, double res); - void eval(const Vector& in); + DynareJacobian(Dynare &dyn); + virtual ~DynareJacobian() + { + } + void load(int i, int iord, const int *vars, double res); + void eval(const Vector &in); }; -class DynareVectorFunction : public ogu::VectorFunction { +class DynareVectorFunction : public ogu::VectorFunction +{ protected: - Dynare& d; + Dynare &d; public: - DynareVectorFunction(Dynare& dyn) - : d(dyn) {} - virtual ~DynareVectorFunction() {} - int inDim() const - {return d.ny();} - int outDim() const - {return d.ny();} - void eval(const ConstVector& in, Vector& out); + DynareVectorFunction(Dynare &dyn) + : d(dyn) + { + } + virtual ~DynareVectorFunction() + { + } + int + inDim() const + { + return d.ny(); + } + int + outDim() const + { + return d.ny(); + } + void eval(const ConstVector &in, Vector &out); }; #endif diff --git a/dynare++/src/dynare_atoms.h b/dynare++/src/dynare_atoms.h index 7cdcce6c249392b49a97096c8e1f0458e1c0ef3b..68b9381990a3afbdec4897906e0958001815dad8 100644 --- a/dynare++/src/dynare_atoms.h +++ b/dynare++/src/dynare_atoms.h @@ -15,196 +15,222 @@ #include <map> #include <vector> -namespace ogdyn { - - using std::map; - using std::vector; - - /** A definition of a type mapping a string to an integer. Used as - * a substitution map, saying what names are substituted for what - * expressions represented by tree indices. */ - typedef map<const char*, int, ogp::ltstr> Tsubstmap; - - class DynareStaticAtoms : public ogp::StaticAtoms { - public: - DynareStaticAtoms() - : StaticAtoms() {} - DynareStaticAtoms(const DynareStaticAtoms& a) - : StaticAtoms(a) {} - virtual ~DynareStaticAtoms() {} - /** This registers a unique varname identifier. It throws an - * exception if the variable name is duplicate. It checks the - * uniqueness and then it calls StaticAtoms::register_name. */ - void register_name(const char* name); - protected: - /** This returns a tree index of the given variable, and if - * the variable has not been registered, it throws an - * exception. */ - int check_variable(const char* name) const; - }; - - - class DynareDynamicAtoms : public ogp::SAtoms, public ogp::NularyStringConvertor { - public: - enum atype {endovar, exovar, param}; - protected: - typedef map<const char*, atype, ogp::ltstr> Tatypemap; - /** The map assigining a type to each name. */ - Tatypemap atom_type; - public: - DynareDynamicAtoms() - : ogp::SAtoms() {} - DynareDynamicAtoms(const DynareDynamicAtoms& dda); - virtual ~DynareDynamicAtoms() {} - /** This parses a variable of the forms: varname(+3), - * varname(3), varname, varname(-3), varname(0), varname(+0), - * varname(-0). */ - virtual void parse_variable(const char* in, std::string& out, int& ll) const; - /** Registers unique name of endogenous variable. */ - void register_uniq_endo(const char* name); - /** Registers unique name of exogenous variable. */ - void register_uniq_exo(const char* name); - /** Registers unique name of parameter. */ - void register_uniq_param(const char* name); - /** Return true if the name is a given type. */ - bool is_type(const char* name, atype tp) const; - /** Debug print. */ - void print() const; - /** Implement NularyStringConvertor::convert. */ - std::string convert(int t) const; - }; - - - /** This class represents the atom values for dynare, where - * exogenous variables can occur only at time t, and endogenous at - * times t-1, t, and t+1. */ - class DynareAtomValues : public ogp::AtomValues { - protected: - /** Reference to the atoms (we suppose that they are only at - * t-1,t,t+1. */ - const ogp::FineAtoms& atoms; - /** De facto reference to the values of parameters. */ - const ConstVector paramvals; - /** De facto reference to the values of endogenous at time t-1. Only - * predetermined and both part. */ - const ConstVector yym; - /** De facto reference to the values of endogenous at time t. Ordering - * given by the atoms. */ - const ConstVector yy; - /** De facto reference to the values of endogenous at time t+1. Only - * both and forward looking part. */ - const ConstVector yyp; - /** De facto reference to the values of exogenous at time t. */ - const ConstVector xx; - public: - DynareAtomValues(const ogp::FineAtoms& a, const Vector& pvals, const Vector& ym, - const Vector& y, const Vector& yp, const Vector& x) - : atoms(a), paramvals(pvals), yym(ym), yy(y), yyp(yp), xx(x) {} - DynareAtomValues(const ogp::FineAtoms& a, const Vector& pvals, const ConstVector& ym, - const Vector& y, const ConstVector& yp, const Vector& x) - : atoms(a), paramvals(pvals), yym(ym), yy(y), yyp(yp), xx(x) {} - void setValues(ogp::EvalTree& et) const; - }; - - /** This class represents the atom values at the steady state. It - * makes only appropriate subvector yym and yyp of the y vector, - * makes a vector of zero exogenous variables and uses - * DynareAtomValues with more general interface. */ - class DynareSteadyAtomValues : public ogp::AtomValues { - protected: - /** Subvector of yy. */ - const ConstVector yym; - /** Subvector of yy. */ - const ConstVector yyp; - /** Vector of zeros for exogenous variables. */ - Vector xx; - /** Atom values using this yym, yyp and xx. */ - DynareAtomValues av; - public: - DynareSteadyAtomValues(const ogp::FineAtoms& a, const Vector& pvals, const Vector& y) - : yym(y, a.nstat(), a.nys()), - yyp(y, a.nstat()+a.npred(), a.nyss()), - xx(a.nexo()), - av(a, pvals, yym, y, yyp, xx) - {xx.zeros();} - void setValues(ogp::EvalTree& et) const - {av.setValues(et);} - }; - - class DynareStaticSteadyAtomValues : public ogp::AtomValues { - protected: - /** Reference to static atoms over which the tree, where the - * values go, is defined. */ - const ogp::StaticFineAtoms& atoms_static; - /** Reference to dynamic atoms for which the class gets input - * data. */ - const ogp::FineAtoms& atoms; - /** De facto reference to input data, this is a vector of - * endogenous variables in internal ordering of the dynamic - * atoms. */ - ConstVector yy; - /** De facto reference to input parameters corresponding to - * ordering defined by the dynamic atoms. */ - ConstVector paramvals; - public: - /** Construct the object. */ - DynareStaticSteadyAtomValues(const ogp::FineAtoms& a, const ogp::StaticFineAtoms& sa, - const Vector& pvals, const Vector& yyy) - : atoms_static(sa), - atoms(a), - yy(yyy), - paramvals(pvals) {} - /** Set the values to the tree defined over the static atoms. */ - void setValues(ogp::EvalTree& et) const; - }; - - /** This class takes a vector of endogenous variables and a - * substitution map. It supposes that variables at the right hand - * sides of the substitutions are set in the endogenous vector. It - * evaluates the substitutions and if the variables corresponding - * to left hand sides are not set in the endogenous vector it sets - * them to calculated values. If a variable is already set, it - * does not override its value. It has no methods, everything is - * done in the constructor. */ - class DynareSteadySubstitutions : public ogp::FormulaEvalLoader { - protected: - const ogp::FineAtoms& atoms; - public: - DynareSteadySubstitutions(const ogp::FineAtoms& a, const ogp::OperationTree& tree, - const Tsubstmap& subst, - const Vector& pvals, Vector& yy); - void load(int i, double res); - protected: - Vector& y; - vector<const char*> left_hand_sides; - vector<int> right_hand_sides; - }; - - /** This class is a static version of DynareSteadySustitutions. It - * works for static atoms and static tree and substitution map - * over the static tree. It also needs dynamic version of the - * atoms, since it defines ordering of the vectors pvals, and - * yy. */ - class DynareStaticSteadySubstitutions : public ogp::FormulaEvalLoader { - protected: - const ogp::FineAtoms& atoms; - const ogp::StaticFineAtoms& atoms_static; - public: - DynareStaticSteadySubstitutions(const ogp::FineAtoms& a, - const ogp::StaticFineAtoms& sa, - const ogp::OperationTree& tree, - const Tsubstmap& subst, - const Vector& pvals, Vector& yy); - void load(int i, double res); - protected: - Vector& y; - vector<const char*> left_hand_sides; - vector<int> right_hand_sides; - }; +namespace ogdyn +{ + + using std::map; + using std::vector; + + /** A definition of a type mapping a string to an integer. Used as + * a substitution map, saying what names are substituted for what + * expressions represented by tree indices. */ + typedef map<const char *, int, ogp::ltstr> Tsubstmap; + + class DynareStaticAtoms : public ogp::StaticAtoms + { + public: + DynareStaticAtoms() + : StaticAtoms() + { + } + DynareStaticAtoms(const DynareStaticAtoms &a) + : StaticAtoms(a) + { + } + virtual ~DynareStaticAtoms() + { + } + /** This registers a unique varname identifier. It throws an + * exception if the variable name is duplicate. It checks the + * uniqueness and then it calls StaticAtoms::register_name. */ + void register_name(const char *name); + protected: + /** This returns a tree index of the given variable, and if + * the variable has not been registered, it throws an + * exception. */ + int check_variable(const char *name) const; + }; + + class DynareDynamicAtoms : public ogp::SAtoms, public ogp::NularyStringConvertor + { + public: + enum atype {endovar, exovar, param}; + protected: + typedef map<const char *, atype, ogp::ltstr> Tatypemap; + /** The map assigining a type to each name. */ + Tatypemap atom_type; + public: + DynareDynamicAtoms() + : ogp::SAtoms() + { + } + DynareDynamicAtoms(const DynareDynamicAtoms &dda); + virtual ~DynareDynamicAtoms() + { + } + /** This parses a variable of the forms: varname(+3), + * varname(3), varname, varname(-3), varname(0), varname(+0), + * varname(-0). */ + virtual void parse_variable(const char *in, std::string &out, int &ll) const; + /** Registers unique name of endogenous variable. */ + void register_uniq_endo(const char *name); + /** Registers unique name of exogenous variable. */ + void register_uniq_exo(const char *name); + /** Registers unique name of parameter. */ + void register_uniq_param(const char *name); + /** Return true if the name is a given type. */ + bool is_type(const char *name, atype tp) const; + /** Debug print. */ + void print() const; + /** Implement NularyStringConvertor::convert. */ + std::string convert(int t) const; + }; + + /** This class represents the atom values for dynare, where + * exogenous variables can occur only at time t, and endogenous at + * times t-1, t, and t+1. */ + class DynareAtomValues : public ogp::AtomValues + { + protected: + /** Reference to the atoms (we suppose that they are only at + * t-1,t,t+1. */ + const ogp::FineAtoms &atoms; + /** De facto reference to the values of parameters. */ + const ConstVector paramvals; + /** De facto reference to the values of endogenous at time t-1. Only + * predetermined and both part. */ + const ConstVector yym; + /** De facto reference to the values of endogenous at time t. Ordering + * given by the atoms. */ + const ConstVector yy; + /** De facto reference to the values of endogenous at time t+1. Only + * both and forward looking part. */ + const ConstVector yyp; + /** De facto reference to the values of exogenous at time t. */ + const ConstVector xx; + public: + DynareAtomValues(const ogp::FineAtoms &a, const Vector &pvals, const Vector &ym, + const Vector &y, const Vector &yp, const Vector &x) + : atoms(a), paramvals(pvals), yym(ym), yy(y), yyp(yp), xx(x) + { + } + DynareAtomValues(const ogp::FineAtoms &a, const Vector &pvals, const ConstVector &ym, + const Vector &y, const ConstVector &yp, const Vector &x) + : atoms(a), paramvals(pvals), yym(ym), yy(y), yyp(yp), xx(x) + { + } + void setValues(ogp::EvalTree &et) const; + }; + + /** This class represents the atom values at the steady state. It + * makes only appropriate subvector yym and yyp of the y vector, + * makes a vector of zero exogenous variables and uses + * DynareAtomValues with more general interface. */ + class DynareSteadyAtomValues : public ogp::AtomValues + { + protected: + /** Subvector of yy. */ + const ConstVector yym; + /** Subvector of yy. */ + const ConstVector yyp; + /** Vector of zeros for exogenous variables. */ + Vector xx; + /** Atom values using this yym, yyp and xx. */ + DynareAtomValues av; + public: + DynareSteadyAtomValues(const ogp::FineAtoms &a, const Vector &pvals, const Vector &y) + : yym(y, a.nstat(), a.nys()), + yyp(y, a.nstat()+a.npred(), a.nyss()), + xx(a.nexo()), + av(a, pvals, yym, y, yyp, xx) + { + xx.zeros(); + } + void + setValues(ogp::EvalTree &et) const + { + av.setValues(et); + } + }; + + class DynareStaticSteadyAtomValues : public ogp::AtomValues + { + protected: + /** Reference to static atoms over which the tree, where the + * values go, is defined. */ + const ogp::StaticFineAtoms &atoms_static; + /** Reference to dynamic atoms for which the class gets input + * data. */ + const ogp::FineAtoms &atoms; + /** De facto reference to input data, this is a vector of + * endogenous variables in internal ordering of the dynamic + * atoms. */ + ConstVector yy; + /** De facto reference to input parameters corresponding to + * ordering defined by the dynamic atoms. */ + ConstVector paramvals; + public: + /** Construct the object. */ + DynareStaticSteadyAtomValues(const ogp::FineAtoms &a, const ogp::StaticFineAtoms &sa, + const Vector &pvals, const Vector &yyy) + : atoms_static(sa), + atoms(a), + yy(yyy), + paramvals(pvals) + { + } + /** Set the values to the tree defined over the static atoms. */ + void setValues(ogp::EvalTree &et) const; + }; + + /** This class takes a vector of endogenous variables and a + * substitution map. It supposes that variables at the right hand + * sides of the substitutions are set in the endogenous vector. It + * evaluates the substitutions and if the variables corresponding + * to left hand sides are not set in the endogenous vector it sets + * them to calculated values. If a variable is already set, it + * does not override its value. It has no methods, everything is + * done in the constructor. */ + class DynareSteadySubstitutions : public ogp::FormulaEvalLoader + { + protected: + const ogp::FineAtoms &atoms; + public: + DynareSteadySubstitutions(const ogp::FineAtoms &a, const ogp::OperationTree &tree, + const Tsubstmap &subst, + const Vector &pvals, Vector &yy); + void load(int i, double res); + protected: + Vector &y; + vector<const char *> left_hand_sides; + vector<int> right_hand_sides; + }; + + /** This class is a static version of DynareSteadySustitutions. It + * works for static atoms and static tree and substitution map + * over the static tree. It also needs dynamic version of the + * atoms, since it defines ordering of the vectors pvals, and + * yy. */ + class DynareStaticSteadySubstitutions : public ogp::FormulaEvalLoader + { + protected: + const ogp::FineAtoms &atoms; + const ogp::StaticFineAtoms &atoms_static; + public: + DynareStaticSteadySubstitutions(const ogp::FineAtoms &a, + const ogp::StaticFineAtoms &sa, + const ogp::OperationTree &tree, + const Tsubstmap &subst, + const Vector &pvals, Vector &yy); + void load(int i, double res); + protected: + Vector &y; + vector<const char *> left_hand_sides; + vector<int> right_hand_sides; + }; }; - #endif // Local Variables: diff --git a/dynare++/src/dynare_exception.h b/dynare++/src/dynare_exception.h index c91048a3a8a528656a5da1a44eaa460e864ce181..682b661320c96bedb1ec7d0299fc16b65db86423 100644 --- a/dynare++/src/dynare_exception.h +++ b/dynare++/src/dynare_exception.h @@ -7,31 +7,39 @@ #include <string> -class DynareException { - char* mes; +class DynareException +{ + char *mes; public: - DynareException(const char* m, const char* fname, int line, int col) - { - mes = new char[strlen(m) + strlen(fname) + 100]; - sprintf(mes, "Parse error at %s, line %d, column %d: %s", fname, line, col, m); - } - DynareException(const char* fname, int line, const std::string& m) - { - mes = new char[m.size() + strlen(fname) + 50]; - sprintf(mes, "%s:%d: %s", fname, line, m.c_str()); - } - DynareException(const char* m, int offset) - { - mes = new char[strlen(m) + 100]; - sprintf(mes, "Parse error in provided string at offset %d: %s", offset, m); - } - DynareException(const DynareException& e) - : mes(new char[strlen(e.mes)+1]) - {strcpy(mes, e.mes);} - virtual ~DynareException() - {delete [] mes;} - const char* message() const - {return mes;} + DynareException(const char *m, const char *fname, int line, int col) + { + mes = new char[strlen(m) + strlen(fname) + 100]; + sprintf(mes, "Parse error at %s, line %d, column %d: %s", fname, line, col, m); + } + DynareException(const char *fname, int line, const std::string &m) + { + mes = new char[m.size() + strlen(fname) + 50]; + sprintf(mes, "%s:%d: %s", fname, line, m.c_str()); + } + DynareException(const char *m, int offset) + { + mes = new char[strlen(m) + 100]; + sprintf(mes, "Parse error in provided string at offset %d: %s", offset, m); + } + DynareException(const DynareException &e) + : mes(new char[strlen(e.mes)+1]) + { + strcpy(mes, e.mes); + } + virtual ~DynareException() + { + delete [] mes; + } + const char * + message() const + { + return mes; + } }; #endif diff --git a/dynare++/src/dynare_model.h b/dynare++/src/dynare_model.h index 8fb87ce217ae618c104004ed908b4878ff283429..d5c1834467ed68b38538bec0f5873a4beba05701 100644 --- a/dynare++/src/dynare_model.h +++ b/dynare++/src/dynare_model.h @@ -15,377 +15,463 @@ #include <map> #include <boost/unordered_set.hpp> -namespace ogdyn { - using boost::unordered_set; - using std::map; +namespace ogdyn +{ + using boost::unordered_set; + using std::map; - /** This represents an interval in a string by the pair of - * positions (including the first, excluding the second). A - * position is given by the line and the column within the line - * (both starting from 1). */ - struct PosInterval { - int fl; - int fc; - int ll; - int lc; - PosInterval() {} - PosInterval(int ifl, int ifc, int ill, int ilc) - : fl(ifl), fc(ifc), ll(ill), lc(ilc) {} - const PosInterval& operator=(const PosInterval& pi) - {fl = pi.fl; fc = pi.fc; ll = pi.ll; lc = pi.lc; return *this;} - /** This returns the interval beginning and interval length - * within the given string. */ - void translate(const char* beg, int len, const char*& ibeg, int& ilen) const; - /** Debug print. */ - void print() const - {printf("fl=%d fc=%d ll=%d lc=%d\n",fl,fc,ll,lc);} - }; + /** This represents an interval in a string by the pair of + * positions (including the first, excluding the second). A + * position is given by the line and the column within the line + * (both starting from 1). */ + struct PosInterval + { + int fl; + int fc; + int ll; + int lc; + PosInterval() + { + } + PosInterval(int ifl, int ifc, int ill, int ilc) + : fl(ifl), fc(ifc), ll(ill), lc(ilc) + { + } + const PosInterval & + operator=(const PosInterval &pi) + { + fl = pi.fl; fc = pi.fc; ll = pi.ll; lc = pi.lc; return *this; + } + /** This returns the interval beginning and interval length + * within the given string. */ + void translate(const char *beg, int len, const char * &ibeg, int &ilen) const; + /** Debug print. */ + void + print() const + { + printf("fl=%d fc=%d ll=%d lc=%d\n", fl, fc, ll, lc); + } + }; - /** This class is basically a GeneralMatrix but is created from - * parsed matrix data. */ - class ParsedMatrix : public TwoDMatrix { - public: - /** Construct the object from the parsed data of ogp::MatrixParser. */ - ParsedMatrix(const ogp::MatrixParser& mp); - }; + /** This class is basically a GeneralMatrix but is created from + * parsed matrix data. */ + class ParsedMatrix : public TwoDMatrix + { + public: + /** Construct the object from the parsed data of ogp::MatrixParser. */ + ParsedMatrix(const ogp::MatrixParser &mp); + }; + class PlannerBuilder; + class PlannerInfo; + class ForwSubstBuilder; + class ForwSubstInfo; + class MultInitSS; + class ModelSSWriter; - class PlannerBuilder; - class PlannerInfo; - class ForwSubstBuilder; - class ForwSubstInfo; - class MultInitSS; - class ModelSSWriter; + /** A subclass is responsible for creating param_vals, init_vals, + * and vcov_mat. */ + class DynareModel + { + friend class PlannerBuilder; + friend class ForwSubstBuilder; + friend class MultInitSS; + friend class ModelSSWriter; + protected: + /** All atoms for whole model. */ + DynareDynamicAtoms atoms; + /** Parsed model equations. */ + ogp::FormulaParser eqs; + /** Order of approximation. */ + int order; + /** A vector of parameters values created by a subclass. It + * is stored with natural ordering (outer) of the parameters + * given by atoms. */ + Vector *param_vals; + /** A vector of initial values created by a subclass. It is + * stored with internal ordering given by atoms. */ + Vector *init_vals; + /** A matrix for vcov. It is created by a subclass. */ + TwoDMatrix *vcov_mat; + /** Tree index of the planner objective. If there was no + * planner objective keyword, the value is set to -1. */ + int t_plobjective; + /** Tree index of the planner discount. If there was no + * planner discount keyword, the value is set to -1. */ + int t_pldiscount; + /** Pointer to PlannerBuilder, which is created only if the + * planner's FOC are added to the model. */ + PlannerBuilder *pbuilder; + /** Pointer to an object which builds auxiliary variables and + * equations to rewrite a model containing multiple leads to + * an equivalent model having only +1 leads. */ + ForwSubstBuilder *fbuilder; + /** Pointer to AtomSubstitutions which are created when the + * atoms are being substituted because of multiple lags + * etc. It uses also an old copy of atoms, which is + * created. */ + ogp::AtomSubstitutions *atom_substs; + /** Pointer to a copy of original atoms before substitutions + * took place. */ + ogp::SAtoms *old_atoms; + public: + /** Initializes the object to an empty state. */ + DynareModel(); + /** Construct a new deep copy. */ + DynareModel(const DynareModel &dm); + virtual + ~DynareModel(); + virtual DynareModel *clone() const = 0; + const DynareDynamicAtoms & + getAtoms() const + { + return atoms; + } + const ogp::FormulaParser & + getParser() const + { + return eqs; + } + int + getOrder() const + { + return order; + } + /** Return the vector of parameter values. */ + const Vector & + getParams() const + { + return *param_vals; + } + Vector & + getParams() + { + return *param_vals; + } + /** Return the vector of initial values of endo variables. */ + const Vector & + getInit() const + { + return *init_vals; + } + Vector & + getInit() + { + return *init_vals; + } + /** Return the vcov matrix. */ + const TwoDMatrix & + getVcov() const + { + return *vcov_mat; + } + TwoDMatrix & + getVcov() + { + return *vcov_mat; + } + /** Return planner info. */ + const PlannerInfo *get_planner_info() const; + /** Return forward substitutions info. */ + const ForwSubstInfo *get_forw_subst_info() const; + /** Return substitutions info. */ + const ogp::SubstInfo *get_subst_info() const; + /** This sets initial values given in outer ordering. */ + void setInitOuter(const Vector &x); + /** This returns true if the given term is a function of + * hardwired constants, numerical constants and parameters. */ + bool is_constant_term(int t) const; + /** Debug print. */ + void print() const; + /** Dump the model to the output stream. This includes + * variable declarations, parameter values, model code, + * initval, vcov and order. */ + void dump_model(std::ostream &os) const; + protected: + /** Adds a name of endogenous, exogenous or a parameter. The + * sort is governed by the flag. See dynglob.y for values of + * the flag. This is used by a subclass when declaring the + * names. */ + void add_name(const char *name, int flag); + /** This checks the model consistency. Thus includes: number + * of endo variables and number of equations, min and max lag + * of endogenous variables and occurrrences of exogenous + * variables. It throws an exception, if there is a problem. */ + void check_model() const; + /** This shifts the given variable identified by the tree + * index in time. So if the given tree index represents a(+3) + * and the tshift is -4, the method returns tree index of the + * a(-1). If a(-1) doesn't exist, it is added to the tree. If + * it exists, its tree index is returned. If the tree index + * doesn't correspond to an endogenous nor exogenous variable, + * an exception is thrown. */ + int variable_shift(int t, int tshift); + /** For the given set of atoms identified by tree indices and + * given time shift, this method returns a map mapping each + * variable in the given set to its time shifted variable. The + * map is passed through the reference and is cleared in the + * beginning. */ + void variable_shift_map(const unordered_set<int> &a_set, int tshift, + map<int, int> &s_map); + /** This returns maximum lead and minimum lag of an endogenous + * or exogenous variable in the given term. If there are no + * endo or exo variables, than it returns the least integer as + * max lead and the greatest integer as min lag. */ + void termspan(int t, int &mlead, int &mlag) const; + /** This function returns a set of non-linear subterms of the + * given term, these are terms whose linear combination + * constitutes the given term. */ + unordered_set<int> get_nonlinear_subterms(int t) const; + /** This method assigns already used tree index of some term + * to the not-yet used atom name with the given lead/lag. In + * this way, all occurrences of term t are substituted with + * the atom name(ll). The method handles also rewriting + * operation tree including derivatives of the term t. */ + void substitute_atom_for_term(const char *name, int ll, int t); + /** This performs a final job after the model is parsed. It + * creates the PlannerBuilder object if the planner's FOC are + * needed, then it creates ForwSubstBuilder handling multiple + * leads and finally it creates the substitution object saving + * old atoms and performs the substitutions. */ + void final_job(); + }; - /** A subclass is responsible for creating param_vals, init_vals, - * and vcov_mat. */ - class DynareModel { - friend class PlannerBuilder; - friend class ForwSubstBuilder; - friend class MultInitSS; - friend class ModelSSWriter; - protected: - /** All atoms for whole model. */ - DynareDynamicAtoms atoms; - /** Parsed model equations. */ - ogp::FormulaParser eqs; - /** Order of approximation. */ - int order; - /** A vector of parameters values created by a subclass. It - * is stored with natural ordering (outer) of the parameters - * given by atoms. */ - Vector* param_vals; - /** A vector of initial values created by a subclass. It is - * stored with internal ordering given by atoms. */ - Vector* init_vals; - /** A matrix for vcov. It is created by a subclass. */ - TwoDMatrix* vcov_mat; - /** Tree index of the planner objective. If there was no - * planner objective keyword, the value is set to -1. */ - int t_plobjective; - /** Tree index of the planner discount. If there was no - * planner discount keyword, the value is set to -1. */ - int t_pldiscount; - /** Pointer to PlannerBuilder, which is created only if the - * planner's FOC are added to the model. */ - PlannerBuilder* pbuilder; - /** Pointer to an object which builds auxiliary variables and - * equations to rewrite a model containing multiple leads to - * an equivalent model having only +1 leads. */ - ForwSubstBuilder* fbuilder; - /** Pointer to AtomSubstitutions which are created when the - * atoms are being substituted because of multiple lags - * etc. It uses also an old copy of atoms, which is - * created. */ - ogp::AtomSubstitutions* atom_substs; - /** Pointer to a copy of original atoms before substitutions - * took place. */ - ogp::SAtoms* old_atoms; - public: - /** Initializes the object to an empty state. */ - DynareModel(); - /** Construct a new deep copy. */ - DynareModel(const DynareModel& dm); - virtual ~DynareModel(); - virtual DynareModel* clone() const = 0; - const DynareDynamicAtoms& getAtoms() const - {return atoms;} - const ogp::FormulaParser& getParser() const - {return eqs;} - int getOrder() const - {return order;} - /** Return the vector of parameter values. */ - const Vector& getParams() const - {return *param_vals;} - Vector& getParams() - {return *param_vals;} - /** Return the vector of initial values of endo variables. */ - const Vector& getInit() const - {return *init_vals;} - Vector& getInit() - {return *init_vals;} - /** Return the vcov matrix. */ - const TwoDMatrix& getVcov() const - {return *vcov_mat;} - TwoDMatrix& getVcov() - {return *vcov_mat;} - /** Return planner info. */ - const PlannerInfo* get_planner_info() const; - /** Return forward substitutions info. */ - const ForwSubstInfo* get_forw_subst_info() const; - /** Return substitutions info. */ - const ogp::SubstInfo* get_subst_info() const; - /** This sets initial values given in outer ordering. */ - void setInitOuter(const Vector& x); - /** This returns true if the given term is a function of - * hardwired constants, numerical constants and parameters. */ - bool is_constant_term(int t) const; - /** Debug print. */ - void print() const; - /** Dump the model to the output stream. This includes - * variable declarations, parameter values, model code, - * initval, vcov and order. */ - void dump_model(std::ostream& os) const; - protected: - /** Adds a name of endogenous, exogenous or a parameter. The - * sort is governed by the flag. See dynglob.y for values of - * the flag. This is used by a subclass when declaring the - * names. */ - void add_name(const char* name, int flag); - /** This checks the model consistency. Thus includes: number - * of endo variables and number of equations, min and max lag - * of endogenous variables and occurrrences of exogenous - * variables. It throws an exception, if there is a problem. */ - void check_model() const; - /** This shifts the given variable identified by the tree - * index in time. So if the given tree index represents a(+3) - * and the tshift is -4, the method returns tree index of the - * a(-1). If a(-1) doesn't exist, it is added to the tree. If - * it exists, its tree index is returned. If the tree index - * doesn't correspond to an endogenous nor exogenous variable, - * an exception is thrown. */ - int variable_shift(int t, int tshift); - /** For the given set of atoms identified by tree indices and - * given time shift, this method returns a map mapping each - * variable in the given set to its time shifted variable. The - * map is passed through the reference and is cleared in the - * beginning. */ - void variable_shift_map(const unordered_set<int>& a_set, int tshift, - map<int,int>& s_map); - /** This returns maximum lead and minimum lag of an endogenous - * or exogenous variable in the given term. If there are no - * endo or exo variables, than it returns the least integer as - * max lead and the greatest integer as min lag. */ - void termspan(int t, int& mlead, int& mlag) const; - /** This function returns a set of non-linear subterms of the - * given term, these are terms whose linear combination - * constitutes the given term. */ - unordered_set<int> get_nonlinear_subterms(int t) const; - /** This method assigns already used tree index of some term - * to the not-yet used atom name with the given lead/lag. In - * this way, all occurrences of term t are substituted with - * the atom name(ll). The method handles also rewriting - * operation tree including derivatives of the term t. */ - void substitute_atom_for_term(const char* name, int ll, int t); - /** This performs a final job after the model is parsed. It - * creates the PlannerBuilder object if the planner's FOC are - * needed, then it creates ForwSubstBuilder handling multiple - * leads and finally it creates the substitution object saving - * old atoms and performs the substitutions. */ - void final_job(); - }; + /** This class constructs DynareModel from dynare++ model file. It + * parses variable declarations, model equations, parameter + * assignments, initval assignments, vcov matrix and order of + * approximation. */ + class DynareParser : public DynareModel + { + protected: + /** Static atoms for parameter assignments. */ + DynareStaticAtoms pa_atoms; + /** Assignments for the parameters. */ + ogp::AtomAssignings paramset; + /** Static atoms for initval assignments. */ + DynareStaticAtoms ia_atoms; + /** Assignments for the initval. */ + ogp::AtomAssignings initval; + /** Matrix parser for vcov. */ + ogp::MatrixParser vcov; + public: + /** This, in fact, creates DynareModel from the given string + * of the given length corresponding to the Dynare++ model + * file. If the given ord is not -1, then it overrides setting + * in the model file. */ + DynareParser(const char *str, int len, int ord); + DynareParser(const DynareParser &p); + virtual + ~DynareParser(); + DynareModel * + clone() const + { + return new DynareParser(*this); + } + /** Adds a name of endogenous, exogenous or a parameter. This + * addss the name to the parent class DynareModel and also + * registers the name to either paramset, or initval. */ + void add_name(const char *name, int flag); + /** Sets position of the model section. Called from + * dynglob.y. */ + void + set_model_pos(int off1, int off2) + { + model_beg = off1; model_end = off2; + } + /** Sets position of the section setting parameters. Called + * from dynglob.y. */ + void + set_paramset_pos(int off1, int off2) + { + paramset_beg = off1; paramset_end = off2; + } + /** Sets position of the initval section. Called from + * dynglob.y. */ + void + set_initval_pos(int off1, int off2) + { + initval_beg = off1; initval_end = off2; + } + /** Sets position of the vcov section. Called from + * dynglob.y. */ + void + set_vcov_pos(int off1, int off2) + { + vcov_beg = off1; vcov_end = off2; + } + /** Parser the given string as integer and set to as the + * order. */ + void + set_order_pos(int off1, int off2) + { + order_beg = off1; order_end = off2; + } + /** Sets position of the planner_objective section. Called + * from dynglob.y. */ + void + set_pl_objective_pos(int off1, int off2) + { + plobjective_beg = off1; plobjective_end = off2; + } + /** Sets position of the planner_discount section. Called from + * dynglob.y. */ + void + set_pl_discount_pos(int off1, int off2) + { + pldiscount_beg = off1; pldiscount_end = off2; + } + /** Processes a syntax error from bison. */ + void error(const char *mes); + /** Debug print. */ + void print() const; + protected: + void parse_glob(int length, const char *stream); + int parse_order(int length, const char *stream); + int parse_pldiscount(int length, const char *stream); + /** Evaluate paramset assignings and set param_vals. */ + void calc_params(); + /** Evaluate initval assignings and set init_vals. */ + void calc_init(); + /** Do the final job. This includes building the planner + * problem (if any) and substituting for multiple lags, and + * one period leads of exogenous variables, and calculating + * initial guess of lagrange multipliers in the social planner + * problem. Precondtion: everything parsed and calculated + * parameters, postcondition: calculated initvals vector and + * parsing_finished for expanded vectors. */ + void final_job(); + private: + int model_beg, model_end; + int paramset_beg, paramset_end; + int initval_beg, initval_end; + int vcov_beg, vcov_end; + int order_beg, order_end; + int plobjective_beg, plobjective_end; + int pldiscount_beg, pldiscount_end; + }; - /** This class constructs DynareModel from dynare++ model file. It - * parses variable declarations, model equations, parameter - * assignments, initval assignments, vcov matrix and order of - * approximation. */ - class DynareParser : public DynareModel { - protected: - /** Static atoms for parameter assignments. */ - DynareStaticAtoms pa_atoms; - /** Assignments for the parameters. */ - ogp::AtomAssignings paramset; - /** Static atoms for initval assignments. */ - DynareStaticAtoms ia_atoms; - /** Assignments for the initval. */ - ogp::AtomAssignings initval; - /** Matrix parser for vcov. */ - ogp::MatrixParser vcov; - public: - /** This, in fact, creates DynareModel from the given string - * of the given length corresponding to the Dynare++ model - * file. If the given ord is not -1, then it overrides setting - * in the model file. */ - DynareParser(const char* str, int len, int ord); - DynareParser(const DynareParser& p); - virtual ~DynareParser(); - DynareModel* clone() const - {return new DynareParser(*this);} - /** Adds a name of endogenous, exogenous or a parameter. This - * addss the name to the parent class DynareModel and also - * registers the name to either paramset, or initval. */ - void add_name(const char* name, int flag); - /** Sets position of the model section. Called from - * dynglob.y. */ - void set_model_pos(int off1, int off2) - {model_beg = off1; model_end = off2;} - /** Sets position of the section setting parameters. Called - * from dynglob.y. */ - void set_paramset_pos(int off1, int off2) - {paramset_beg = off1; paramset_end = off2;} - /** Sets position of the initval section. Called from - * dynglob.y. */ - void set_initval_pos(int off1, int off2) - {initval_beg = off1; initval_end = off2;} - /** Sets position of the vcov section. Called from - * dynglob.y. */ - void set_vcov_pos(int off1, int off2) - {vcov_beg = off1; vcov_end = off2;} - /** Parser the given string as integer and set to as the - * order. */ - void set_order_pos(int off1, int off2) - {order_beg = off1; order_end = off2;} - /** Sets position of the planner_objective section. Called - * from dynglob.y. */ - void set_pl_objective_pos(int off1, int off2) - {plobjective_beg = off1; plobjective_end = off2;} - /** Sets position of the planner_discount section. Called from - * dynglob.y. */ - void set_pl_discount_pos(int off1, int off2) - {pldiscount_beg = off1; pldiscount_end = off2;} - /** Processes a syntax error from bison. */ - void error(const char* mes); - /** Debug print. */ - void print() const; - protected: - void parse_glob(int length, const char* stream); - int parse_order(int length, const char* stream); - int parse_pldiscount(int length, const char* stream); - /** Evaluate paramset assignings and set param_vals. */ - void calc_params(); - /** Evaluate initval assignings and set init_vals. */ - void calc_init(); - /** Do the final job. This includes building the planner - * problem (if any) and substituting for multiple lags, and - * one period leads of exogenous variables, and calculating - * initial guess of lagrange multipliers in the social planner - * problem. Precondtion: everything parsed and calculated - * parameters, postcondition: calculated initvals vector and - * parsing_finished for expanded vectors. */ - void final_job(); - private: - int model_beg, model_end; - int paramset_beg, paramset_end; - int initval_beg, initval_end; - int vcov_beg, vcov_end; - int order_beg, order_end; - int plobjective_beg, plobjective_end; - int pldiscount_beg, pldiscount_end; - }; + /** Semiparsed model. The equations are given by a string, + * everything other by C/C++ objects. The initial values are set + * manually after the creation of this object. This implies that + * no automatic substitutions cannot be done here, which in turn + * implies that we cannot do here a social planner nor substitutions + * of multiple lags. */ + class DynareSPModel : public DynareModel + { + public: + DynareSPModel(const char **endo, int num_endo, + const char **exo, int num_exo, + const char **par, int num_par, + const char *equations, int len, int ord); + DynareSPModel(const DynareSPModel &dm) + : DynareModel(dm) + { + } + ~DynareSPModel() + { + } + virtual DynareModel * + clone() const + { + return new DynareSPModel(*this); + } + }; - /** Semiparsed model. The equations are given by a string, - * everything other by C/C++ objects. The initial values are set - * manually after the creation of this object. This implies that - * no automatic substitutions cannot be done here, which in turn - * implies that we cannot do here a social planner nor substitutions - * of multiple lags. */ - class DynareSPModel : public DynareModel { - public: - DynareSPModel(const char** endo, int num_endo, - const char** exo, int num_exo, - const char** par, int num_par, - const char* equations, int len, int ord); - DynareSPModel(const DynareSPModel& dm) - : DynareModel(dm) {} - ~DynareSPModel() {} - virtual DynareModel* clone() const - {return new DynareSPModel(*this);} - }; + /** This class implements a selector of operations which correspond + * to non-linear functions. This inherits from ogp::opselector and + * is used to calculate non-linear subterms in + * DynareModel::get_nonlinear_subterms(). */ + class NLSelector : public ogp::opselector + { + private: + const DynareModel &model; + public: + NLSelector(const DynareModel &m) : model(m) + { + } + bool operator()(int t) const; + }; - /** This class implements a selector of operations which correspond - * to non-linear functions. This inherits from ogp::opselector and - * is used to calculate non-linear subterms in - * DynareModel::get_nonlinear_subterms(). */ - class NLSelector : public ogp::opselector { - private: - const DynareModel& model; - public: - NLSelector(const DynareModel& m) : model(m) {} - bool operator()(int t) const; - }; + /** This class writes a mathematical code evaluating the system of + * equations and the first derivatives at zero shocks and at the + * given (static) state. Static means that lags and leads are + * ignored. */ + class ModelSSWriter : public ogp::DefaultOperationFormatter + { + protected: + const DynareModel &model; + public: + ModelSSWriter(const DynareModel &m) + : DefaultOperationFormatter(m.eqs.getTree()), + model(m) + { + } + /** This writes the evaluation of the system. It calls pure + * virtual methods for writing a preamble, then assignment of + * atoms, and then assignment for resulting object. These are + * language dependent and are implemented in the subclass. */ + void write_der0(FILE *fd); + /** This writes the evaluation of the first order derivative of + the system. It calls pure virtual methods for writing a + preamble, assignment, and assignemnt of the resulting + objects. */ + void write_der1(FILE *fd); + protected: + virtual void write_der0_preamble(FILE *fd) const = 0; + virtual void write_der1_preamble(FILE *fd) const = 0; + virtual void write_atom_assignment(FILE *fd) const = 0; + virtual void write_der0_assignment(FILE *fd) const = 0; + virtual void write_der1_assignment(FILE *fd) const = 0; + }; - /** This class writes a mathematical code evaluating the system of - * equations and the first derivatives at zero shocks and at the - * given (static) state. Static means that lags and leads are - * ignored. */ - class ModelSSWriter : public ogp::DefaultOperationFormatter { - protected: - const DynareModel& model; - public: - ModelSSWriter(const DynareModel& m) - : DefaultOperationFormatter(m.eqs.getTree()), - model(m) {} - /** This writes the evaluation of the system. It calls pure - * virtual methods for writing a preamble, then assignment of - * atoms, and then assignment for resulting object. These are - * language dependent and are implemented in the subclass. */ - void write_der0(FILE* fd); - /** This writes the evaluation of the first order derivative of - the system. It calls pure virtual methods for writing a - preamble, assignment, and assignemnt of the resulting - objects. */ - void write_der1(FILE* fd); - protected: - virtual void write_der0_preamble(FILE* fd) const =0; - virtual void write_der1_preamble(FILE* fd) const =0; - virtual void write_atom_assignment(FILE* fd) const =0; - virtual void write_der0_assignment(FILE* fd) const =0; - virtual void write_der1_assignment(FILE* fd) const =0; - }; + class MatlabSSWriter : public ModelSSWriter + { + protected: + /** Identifier used in function names. */ + char *id; + public: + MatlabSSWriter(const DynareModel &dm, const char *idd); + virtual ~MatlabSSWriter() + { + delete [] id; + } + protected: + // from ModelSSWriter + void write_der0_preamble(FILE *fd) const; + void write_der1_preamble(FILE *fd) const; + /** This writes atom assignments. We have four kinds of atoms + * set here: endogenous vars coming from one parameter, + * parameter values given by the second parameter, constants, + * and the OperationTree::num_constants hardwired constants in + * ogp::OperationTree. */ + void write_atom_assignment(FILE *fd) const; + void write_der0_assignment(FILE *fd) const; + void write_der1_assignment(FILE *fd) const; + /** This prints t10 for t=10. */ + void format_term(int t, FILE *fd) const; + /** This prints a10 for t=10. The atoms a10 are supposed to be + * set by write_atom_assignments(). */ + void format_nulary(int t, FILE *fd) const; + private: + void write_common1_preamble(FILE *fd) const; + void write_common2_preamble(FILE *fd) const; + }; - - class MatlabSSWriter : public ModelSSWriter { - protected: - /** Identifier used in function names. */ - char* id; - public: - MatlabSSWriter(const DynareModel& dm, const char* idd); - virtual ~MatlabSSWriter() - {delete [] id;} - protected: - // from ModelSSWriter - void write_der0_preamble(FILE* fd) const; - void write_der1_preamble(FILE* fd) const; - /** This writes atom assignments. We have four kinds of atoms - * set here: endogenous vars coming from one parameter, - * parameter values given by the second parameter, constants, - * and the OperationTree::num_constants hardwired constants in - * ogp::OperationTree. */ - void write_atom_assignment(FILE* fd) const; - void write_der0_assignment(FILE* fd) const; - void write_der1_assignment(FILE* fd) const; - /** This prints t10 for t=10. */ - void format_term(int t, FILE* fd) const; - /** This prints a10 for t=10. The atoms a10 are supposed to be - * set by write_atom_assignments(). */ - void format_nulary(int t, FILE* fd) const; - private: - void write_common1_preamble(FILE* fd) const; - void write_common2_preamble(FILE* fd) const; - }; - - /** This class implements OperationFormatter for debugging - * purposes. It renders atoms in a more friendly way than the - * ogp::DefaulOperationFormatter. */ - class DebugOperationFormatter : public ogp::DefaultOperationFormatter { - protected: - const DynareModel& model; - public: - DebugOperationFormatter(const DynareModel& m) - : DefaultOperationFormatter(m.getParser().getTree()), - model(m) {} - void format_nulary(int t, FILE* fd) const; - }; + /** This class implements OperationFormatter for debugging + * purposes. It renders atoms in a more friendly way than the + * ogp::DefaulOperationFormatter. */ + class DebugOperationFormatter : public ogp::DefaultOperationFormatter + { + protected: + const DynareModel &model; + public: + DebugOperationFormatter(const DynareModel &m) + : DefaultOperationFormatter(m.getParser().getTree()), + model(m) + { + } + void format_nulary(int t, FILE *fd) const; + }; }; #endif diff --git a/dynare++/src/dynare_params.h b/dynare++/src/dynare_params.h index 594c35ea278a514c0444aea2e08c62a2cd083198..113e48fb0dd886bc40cb551b5f97dee433da4002 100644 --- a/dynare++/src/dynare_params.h +++ b/dynare++/src/dynare_params.h @@ -3,71 +3,87 @@ // Copyright 2004, Ondra Kamenik /* -along shocks: m mult max_evals -ellipse: m mult max_evals (10*m) (0.5*mult) -simul: m max_evals (10*m) + along shocks: m mult max_evals + ellipse: m mult max_evals (10*m) (0.5*mult) + simul: m max_evals (10*m) ---check-scale 2.0 --check-evals 1000 --check-num 10 --check PES - */ + --check-scale 2.0 --check-evals 1000 --check-num 10 --check PES +*/ #include <vector> #include <string> -struct DynareParams { - const char* modname; - std::string basename; - int num_per; - int num_burn; - int num_sim; - int num_rtper; - int num_rtsim; - int num_condper; - int num_condsim; - int num_threads; - int num_steps; - const char* prefix; - int seed; - int order; - /** Tolerance used for steady state calcs. */ - double ss_tol; - bool check_along_path; - bool check_along_shocks; - bool check_on_ellipse; - int check_evals; - int check_num; - double check_scale; - /** Flag for doing IRFs even if the irf_list is empty. */ - bool do_irfs_all; - /** List of shocks for which IRF will be calculated. */ - std::vector<const char*> irf_list; - bool do_centralize; - double qz_criterium; - bool help; - bool version; - DynareParams(int argc, char** argv); - void printHelp() const; - int getCheckShockPoints() const - {return check_num;} - double getCheckShockScale() const - {return check_scale;} - int getCheckEllipsePoints() const - {return 10*check_num;} - double getCheckEllipseScale() const - {return 0.5*check_scale;} - int getCheckPathPoints() const - {return 10*check_num;} +struct DynareParams +{ + const char *modname; + std::string basename; + int num_per; + int num_burn; + int num_sim; + int num_rtper; + int num_rtsim; + int num_condper; + int num_condsim; + int num_threads; + int num_steps; + const char *prefix; + int seed; + int order; + /** Tolerance used for steady state calcs. */ + double ss_tol; + bool check_along_path; + bool check_along_shocks; + bool check_on_ellipse; + int check_evals; + int check_num; + double check_scale; + /** Flag for doing IRFs even if the irf_list is empty. */ + bool do_irfs_all; + /** List of shocks for which IRF will be calculated. */ + std::vector<const char *> irf_list; + bool do_centralize; + double qz_criterium; + bool help; + bool version; + DynareParams(int argc, char **argv); + void printHelp() const; + int + getCheckShockPoints() const + { + return check_num; + } + double + getCheckShockScale() const + { + return check_scale; + } + int + getCheckEllipsePoints() const + { + return 10*check_num; + } + double + getCheckEllipseScale() const + { + return 0.5*check_scale; + } + int + getCheckPathPoints() const + { + return 10*check_num; + } private: - enum {opt_per, opt_burn, opt_sim, opt_rtper, opt_rtsim, opt_condper, opt_condsim, - opt_prefix, opt_threads, - opt_steps, opt_seed, opt_order, opt_ss_tol, opt_check, - opt_check_along_path, opt_check_along_shocks, opt_check_on_ellipse, - opt_check_evals, opt_check_scale, opt_check_num, opt_noirfs, opt_irfs, - opt_help, opt_version, opt_centralize, opt_no_centralize, opt_qz_criterium}; - void processCheckFlags(const char* flags); - /** This gathers strings from argv[optind] and on not starting - * with '-' to the irf_list. It stops one item before the end, - * since this is the model file. */ - void processIRFList(int argc, char** argv); + enum {opt_per, opt_burn, opt_sim, opt_rtper, opt_rtsim, opt_condper, opt_condsim, + opt_prefix, opt_threads, + opt_steps, opt_seed, opt_order, opt_ss_tol, opt_check, + opt_check_along_path, opt_check_along_shocks, opt_check_on_ellipse, + opt_check_evals, opt_check_scale, opt_check_num, opt_noirfs, opt_irfs, + opt_help, opt_version, opt_centralize, opt_no_centralize, opt_qz_criterium}; + void processCheckFlags(const char *flags); + /** This gathers strings from argv[optind] and on not starting + * with '-' to the irf_list. It stops one item before the end, + * since this is the model file. */ + void processIRFList(int argc, char **argv); }; // Local Variables: diff --git a/dynare++/src/forw_subst_builder.h b/dynare++/src/forw_subst_builder.h index 7f703092d8d7bb6d9aa7749ea7d90f79e7000be6..9a51c2cbce1f114aac6ea756ea670dec2c58e091 100644 --- a/dynare++/src/forw_subst_builder.h +++ b/dynare++/src/forw_subst_builder.h @@ -5,75 +5,85 @@ #ifndef FORW_SUBST_BUILDER_H #define FORW_SUBST_BUILDER_H - #include "dynare_model.h" -namespace ogdyn { +namespace ogdyn +{ - /** This struct encapsulates information about the process of - * forward substitutions. */ - struct ForwSubstInfo { - int num_affected_equations; - int num_subst_terms; - int num_aux_variables; - int num_new_terms; - ForwSubstInfo() - : num_affected_equations(0), - num_subst_terms(0), - num_aux_variables(0), - num_new_terms(0) {} - }; + /** This struct encapsulates information about the process of + * forward substitutions. */ + struct ForwSubstInfo + { + int num_affected_equations; + int num_subst_terms; + int num_aux_variables; + int num_new_terms; + ForwSubstInfo() + : num_affected_equations(0), + num_subst_terms(0), + num_aux_variables(0), + num_new_terms(0) + { + } + }; - class ForwSubstBuilder { - typedef map<int, const char*> Ttermauxmap; - protected: - /** Reference to the model, to which we will add equations and - * change some equations. */ - DynareModel& model; - /** A map mapping new auxiliary variables to the terms in the - * tree in the DynareModel. */ - Tsubstmap aux_map; - /** Information about the substitutions. */ - ForwSubstInfo info; - public: - /** Do all the jobs needed. This scans all equations in the - * model, and for equations containing forward looking - * variables greater than 1 lead, it makes corresponding - * substitutions. Basically, it breaks each equation to its - * non-linear components and creates substitutions for these - * components, not for whole equation. This is because the - * expectation operator can go through the linear part of the - * function. This will save us many occurrences of other - * variables involved in the equation. */ - ForwSubstBuilder(DynareModel& m); - /** Copy constructor with a new instance of the model. */ - ForwSubstBuilder(const ForwSubstBuilder& b, DynareModel& m); - /** Return the auxiliary variable mapping. */ - const Tsubstmap& get_aux_map() const - {return aux_map;} - /** Return the information. */ - const ForwSubstInfo& get_info() const - {return info;} - private: - ForwSubstBuilder(const ForwSubstBuilder& b); - /** This method takes a nonlinear term t, and if it has leads - * of greater than 1, then it substitutes the term for the new - * variable (or string of variables). Note that the - * substitution is done by DynamicAtoms::assign_variable. This - * means that the substitution is made for all other - * ocurrences of t in the model. So there is no need of - * tracking already substituted terms. The other two - * parameters are just for identification of the new auxiliary - * variables. When called from the constructor, i is an - * equation number, j is an order of the non-linear term in - * the equation. */ - void substitute_for_term(int t, int i, int j); - /** This is called just at the end of the job. It unassigns - * all nulary terms with a lead greater than 1. */ - void unassign_gt_1_leads(); - /** This unassigns all leads greater than 1 of the given name. */ - void unassign_gt_1_leads(const char* name); - }; + class ForwSubstBuilder + { + typedef map<int, const char *> Ttermauxmap; + protected: + /** Reference to the model, to which we will add equations and + * change some equations. */ + DynareModel &model; + /** A map mapping new auxiliary variables to the terms in the + * tree in the DynareModel. */ + Tsubstmap aux_map; + /** Information about the substitutions. */ + ForwSubstInfo info; + public: + /** Do all the jobs needed. This scans all equations in the + * model, and for equations containing forward looking + * variables greater than 1 lead, it makes corresponding + * substitutions. Basically, it breaks each equation to its + * non-linear components and creates substitutions for these + * components, not for whole equation. This is because the + * expectation operator can go through the linear part of the + * function. This will save us many occurrences of other + * variables involved in the equation. */ + ForwSubstBuilder(DynareModel &m); + /** Copy constructor with a new instance of the model. */ + ForwSubstBuilder(const ForwSubstBuilder &b, DynareModel &m); + /** Return the auxiliary variable mapping. */ + const Tsubstmap & + get_aux_map() const + { + return aux_map; + } + /** Return the information. */ + const ForwSubstInfo & + get_info() const + { + return info; + } + private: + ForwSubstBuilder(const ForwSubstBuilder &b); + /** This method takes a nonlinear term t, and if it has leads + * of greater than 1, then it substitutes the term for the new + * variable (or string of variables). Note that the + * substitution is done by DynamicAtoms::assign_variable. This + * means that the substitution is made for all other + * ocurrences of t in the model. So there is no need of + * tracking already substituted terms. The other two + * parameters are just for identification of the new auxiliary + * variables. When called from the constructor, i is an + * equation number, j is an order of the non-linear term in + * the equation. */ + void substitute_for_term(int t, int i, int j); + /** This is called just at the end of the job. It unassigns + * all nulary terms with a lead greater than 1. */ + void unassign_gt_1_leads(); + /** This unassigns all leads greater than 1 of the given name. */ + void unassign_gt_1_leads(const char *name); + }; }; #endif diff --git a/dynare++/src/nlsolve.h b/dynare++/src/nlsolve.h index 0cd19b1f3d4d3f6986ade8ea5dd921bc19dd0487..b8de181d441d9890ab34f0518e2c4d813fa1e9cb 100644 --- a/dynare++/src/nlsolve.h +++ b/dynare++/src/nlsolve.h @@ -8,82 +8,102 @@ #include "twod_matrix.h" #include "journal.h" -namespace ogu { +namespace ogu +{ - class OneDFunction { - public: - virtual ~OneDFunction() {} - virtual double eval(double) = 0; - }; + class OneDFunction + { + public: + virtual ~OneDFunction() + { + } + virtual double eval(double) = 0; + }; - class GoldenSectionSearch { - protected: - static double tol; - static double golden; - public: - static double search(OneDFunction& f, double x1, double x2); - protected: - /** This initializes a bracket by moving x2 and b (as a golden - * section of x1,x2) so that f(x1)>f(b) && f(b)<f(x2). The point - * x1 is not moved, since it is considered as reliable and f(x1) - * is supposed to be finite. If initialization of a bracket - * succeeded, then [x1, b, x2] is the bracket and true is - * returned. Otherwise, b is the minimum found and false is - * returned. */ - static bool init_bracket(OneDFunction& f, double x1, double& x2, double& b); - /** This supposes that f(x1) is finite and it moves x2 toward x1 - * until x2 and b (as a golden section of x1,x2) are finite. If - * succeeded, the routine returns true and x2, and b. Otherwise, - * it returns false. */ - static bool search_for_finite(OneDFunction& f, double x1, double& x2, double& b); - }; + class GoldenSectionSearch + { + protected: + static double tol; + static double golden; + public: + static double search(OneDFunction &f, double x1, double x2); + protected: + /** This initializes a bracket by moving x2 and b (as a golden + * section of x1,x2) so that f(x1)>f(b) && f(b)<f(x2). The point + * x1 is not moved, since it is considered as reliable and f(x1) + * is supposed to be finite. If initialization of a bracket + * succeeded, then [x1, b, x2] is the bracket and true is + * returned. Otherwise, b is the minimum found and false is + * returned. */ + static bool init_bracket(OneDFunction &f, double x1, double &x2, double &b); + /** This supposes that f(x1) is finite and it moves x2 toward x1 + * until x2 and b (as a golden section of x1,x2) are finite. If + * succeeded, the routine returns true and x2, and b. Otherwise, + * it returns false. */ + static bool search_for_finite(OneDFunction &f, double x1, double &x2, double &b); + }; - class VectorFunction { - public: - VectorFunction() {} - virtual ~VectorFunction() {} - virtual int inDim() const = 0; - virtual int outDim() const = 0; - /** Check dimensions of eval parameters. */ - void check_for_eval(const ConstVector& in, Vector& out) const; - /** Evaluate the vector function. */ - virtual void eval(const ConstVector& in, Vector& out) = 0; - }; + class VectorFunction + { + public: + VectorFunction() + { + } + virtual ~VectorFunction() + { + } + virtual int inDim() const = 0; + virtual int outDim() const = 0; + /** Check dimensions of eval parameters. */ + void check_for_eval(const ConstVector &in, Vector &out) const; + /** Evaluate the vector function. */ + virtual void eval(const ConstVector &in, Vector &out) = 0; + }; - class Jacobian : public TwoDMatrix { - public: - Jacobian(int n) - : TwoDMatrix(n,n) {} - virtual ~Jacobian() {} - virtual void eval(const Vector& in) = 0; - }; + class Jacobian : public TwoDMatrix + { + public: + Jacobian(int n) + : TwoDMatrix(n, n) + { + } + virtual ~Jacobian() + { + } + virtual void eval(const Vector &in) = 0; + }; - class NLSolver : public OneDFunction { - protected: - Journal& journal; - VectorFunction& func; - Jacobian& jacob; - const int max_iter; - const double tol; - private: - Vector xnewton; - Vector xcauchy; - Vector x; - public: - NLSolver(VectorFunction& f, Jacobian& j, int maxit, double tl, Journal& jr) - : journal(jr), func(f), jacob(j), max_iter(maxit), tol(tl), - xnewton(f.inDim()), xcauchy(f.inDim()), x(f.inDim()) - {xnewton.zeros(); xcauchy.zeros(); x.zeros();} - virtual ~NLSolver() {} - /** Returns true if the problem has converged. xx as input is the - * starting value, as output it is a solution. */ - bool solve(Vector& xx, int& iter); - /** To implement OneDFunction interface. It returns - * func(xx)^T*func(xx), where - * xx=x+lambda*xcauchy+(1-lambda)*xnewton. It is non-const only - * because it calls func, x, xnewton, xcauchy is not changed. */ - double eval(double lambda); - }; + class NLSolver : public OneDFunction + { + protected: + Journal &journal; + VectorFunction &func; + Jacobian &jacob; + const int max_iter; + const double tol; + private: + Vector xnewton; + Vector xcauchy; + Vector x; + public: + NLSolver(VectorFunction &f, Jacobian &j, int maxit, double tl, Journal &jr) + : journal(jr), func(f), jacob(j), max_iter(maxit), tol(tl), + xnewton(f.inDim()), xcauchy(f.inDim()), x(f.inDim()) + { + xnewton.zeros(); xcauchy.zeros(); x.zeros(); + } + virtual ~NLSolver() + { + } + /** Returns true if the problem has converged. xx as input is the + * starting value, as output it is a solution. */ + bool solve(Vector &xx, int &iter); + /** To implement OneDFunction interface. It returns + * func(xx)^T*func(xx), where + * xx=x+lambda*xcauchy+(1-lambda)*xnewton. It is non-const only + * because it calls func, x, xnewton, xcauchy is not changed. */ + double eval(double lambda); + }; }; diff --git a/dynare++/src/planner_builder.h b/dynare++/src/planner_builder.h index 9e46832d7396c60318e55bdba3b59081c9eec5ed..4d888d9051c300706761f879890de059d623ed14 100644 --- a/dynare++/src/planner_builder.h +++ b/dynare++/src/planner_builder.h @@ -5,273 +5,322 @@ #include "dynare_model.h" -namespace ogdyn { +namespace ogdyn +{ - using boost::unordered_set; - using std::map; - using std::vector; + using boost::unordered_set; + using std::map; + using std::vector; - /** This is a two dimensional array of integers. Nothing - * difficult. */ - class IntegerMatrix { - protected: - /** Number of rows. */ - int nr; - /** Number of columns. */ - int nc; - /** The pointer to the data. */ - int* data; - public: - /** Construct uninitialized array. */ - IntegerMatrix(int nrr, int ncc) - : nr(nrr), nc(ncc), data(new int[nr*nc]) {} - /** Copy constructor. */ - IntegerMatrix(const IntegerMatrix& im) - : nr(im.nr), nc(im.nc), data(new int[nr*nc]) - {memcpy(data, im.data, nr*nc*sizeof(int));} - virtual ~IntegerMatrix() - {delete [] data;} - /** Assignment operator. It can only assing array with the - * same dimensions. */ - const IntegerMatrix& operator=(const IntegerMatrix& im); - int& operator()(int i, int j) - {return data[i+j*nr];} - const int& operator()(int i, int j) const - {return data[i+j*nr];} - int nrows() const - {return nr;} - int ncols() const - {return nc;} - }; + /** This is a two dimensional array of integers. Nothing + * difficult. */ + class IntegerMatrix + { + protected: + /** Number of rows. */ + int nr; + /** Number of columns. */ + int nc; + /** The pointer to the data. */ + int *data; + public: + /** Construct uninitialized array. */ + IntegerMatrix(int nrr, int ncc) + : nr(nrr), nc(ncc), data(new int[nr*nc]) + { + } + /** Copy constructor. */ + IntegerMatrix(const IntegerMatrix &im) + : nr(im.nr), nc(im.nc), data(new int[nr*nc]) + { + memcpy(data, im.data, nr*nc*sizeof(int)); + } + virtual ~IntegerMatrix() + { + delete [] data; + } + /** Assignment operator. It can only assing array with the + * same dimensions. */ + const IntegerMatrix &operator=(const IntegerMatrix &im); + int & + operator()(int i, int j) + { + return data[i+j*nr]; + } + const int & + operator()(int i, int j) const + { + return data[i+j*nr]; + } + int + nrows() const + { + return nr; + } + int + ncols() const + { + return nc; + } + }; - /** The three dimensional array of integers. Nothing difficult. */ - class IntegerArray3 { - protected: - /** First dimension. */ - int n1; - /** Second dimension. */ - int n2; - /** Third dimension. */ - int n3; - /** The data. */ - int* data; - public: - /** Constrcut unitialized array. */ - IntegerArray3(int nn1, int nn2, int nn3) - : n1(nn1), n2(nn2), n3(nn3), data(new int[n1*n2*n3]) {} - /** Copy constructor. */ - IntegerArray3(const IntegerArray3& ia3) - : n1(ia3.n1), n2(ia3.n2), n3(ia3.n3), data(new int[n1*n2*n3]) - {memcpy(data, ia3.data, n1*n2*n3*sizeof(int));} - virtual ~IntegerArray3() - {delete [] data;} - /** Assignment operator assigning the arrays with the same dimensions. */ - const IntegerArray3& operator=(const IntegerArray3& ia3); - int& operator()(int i, int j, int k) - {return data[i+j*n1+k*n1*n2];} - const int& operator()(int i, int j, int k) const - {return data[i+j*n1+k*n1*n2];} - int dim1() const - {return n1;} - int dim2() const - {return n2;} - int dim3() const - {return n3;} - }; + /** The three dimensional array of integers. Nothing difficult. */ + class IntegerArray3 + { + protected: + /** First dimension. */ + int n1; + /** Second dimension. */ + int n2; + /** Third dimension. */ + int n3; + /** The data. */ + int *data; + public: + /** Constrcut unitialized array. */ + IntegerArray3(int nn1, int nn2, int nn3) + : n1(nn1), n2(nn2), n3(nn3), data(new int[n1*n2*n3]) + { + } + /** Copy constructor. */ + IntegerArray3(const IntegerArray3 &ia3) + : n1(ia3.n1), n2(ia3.n2), n3(ia3.n3), data(new int[n1*n2*n3]) + { + memcpy(data, ia3.data, n1*n2*n3*sizeof(int)); + } + virtual ~IntegerArray3() + { + delete [] data; + } + /** Assignment operator assigning the arrays with the same dimensions. */ + const IntegerArray3 &operator=(const IntegerArray3 &ia3); + int & + operator()(int i, int j, int k) + { + return data[i+j*n1+k*n1*n2]; + } + const int & + operator()(int i, int j, int k) const + { + return data[i+j*n1+k*n1*n2]; + } + int + dim1() const + { + return n1; + } + int + dim2() const + { + return n2; + } + int + dim3() const + { + return n3; + } + }; - /** This struct encapsulates information about the building of a - * planner's problem. */ - struct PlannerInfo { - int num_lagrange_mults; - int num_aux_variables; - int num_new_terms; - PlannerInfo() - : num_lagrange_mults(0), - num_aux_variables(0), - num_new_terms(0) {} - }; + /** This struct encapsulates information about the building of a + * planner's problem. */ + struct PlannerInfo + { + int num_lagrange_mults; + int num_aux_variables; + int num_new_terms; + PlannerInfo() + : num_lagrange_mults(0), + num_aux_variables(0), + num_new_terms(0) + { + } + }; - class MultInitSS; + class MultInitSS; - /** This class builds the first order conditions of the social - * planner problem with constraints being the equations in the - * model. The model is non-const parameter to the constructor - * which adds appropriate FOCs to the system. It also allows for - * an estimation of the lagrange multipliers given all other - * endogenous variables of the static system. For this purpose we - * need to create static atoms and static versions of all the tree - * index matrices. The algorithm and algebra are documented in - * dynare++-ramsey.pdf. */ - class PlannerBuilder { - friend class MultInitSS; - public: - /** Type for a set of variable names. */ - typedef unordered_set<const char*> Tvarset; - /** Type for a set of equations. An equation is identified by - * an index to an equation in the equation vector given by - * DynareModel::eqs. The tree index of the i-th formula is - * retrieved as DynareModel::egs.formula(i). */ - typedef vector<int> Teqset; - protected: - /** This is a set of variables wrt which the planner - * optimizes. These could be all endogenous variables, but it - * is beneficial to exclude all variables which are - * deterministic transformations of past exogenous variables, - * since the planner cannot influence them. This could save a - * few equations. This is not changed after it is constructed, - * but it is constructed manually, so it cannot be declared as - * const. */ - Tvarset yset; - /** These are the equation indices constituing the constraints - * for the planner. Again, it is beneficial to exclude all - * equations defining exogenous variables excluded from - * yset. */ - const Teqset fset; - /** Reference to the model. */ - ogdyn::DynareModel& model; - /** Tree index of the planner objective. */ - int tb; - /** Tree index of the planner discount parameter. */ - int tbeta; - /** The maximum lead in the model including the planner's - * objective before building the planner's FOCs. */ - const int maxlead; - /** The minimum lag in the model including the planner's objective - * before building the planner's FOCs. */ - const int minlag; - /** Tree indices of formulas in the planner FOCs involving - * derivatives of the planner's objective. Rows correspond to the - * endogenous variables, columns correspond to lags in the - * objective function. The contents of the matrix will evolve as - * the algorithm proceeds. */ - IntegerMatrix diff_b; - /** Tree indices of formulas in the planner FOCs involving - * derivatives of the model equations (constraints). The first - * dimension corresponds to endogenous variables, the second to - * the constraints, the third to lags or leads of endogenous - * variables in the constraints. The contents of the array will - * evolve as the algorithm proceeds.*/ - IntegerArray3 diff_f; - /** Static version of the model atoms. It is needed to build - * static version of diff_b and diff_f. */ - ogp::StaticFineAtoms static_atoms; - /** Static version of all the trees of diff_b and diff_f build - * over static_atoms. */ - ogp::OperationTree static_tree; - /** Tree indices of static version of diff_b over static_atoms and static_tree. */ - IntegerMatrix diff_b_static; - /** Tree indices of static version of diff_f over static_atoms - * and static_tree. This member is created before calling - * lagrange_mult_f(), so it does not contain the - * multiplication with the lagrange multipliers. */ - IntegerArray3 diff_f_static; - /** Auxiliary variables mapping. During the algorithm, some - * auxiliary variables for the terms might be created, so we - * remember their names and tree indices of the terms. This - * maps a name to the tree index of an expression equal to the - * auxiliary variable at time zero. The auxiliary variables - * names point to the dynamic atoms storage, tree inidices to - * the dynamic model tree. */ - Tsubstmap aux_map; - /** Static version of aux_map. The names point to static_atoms - * storage, the tree indices to the static_tree. */ - Tsubstmap static_aux_map; - /** Information about the number of various things. */ - PlannerInfo info; - public: - /** Build the planner problem for the given model optimizing - * through the given endogenous variables with the given - * constraints. We allow for a selection of a subset of - * equations and variables in order to eliminate exogenous - * predetermined process which cannot be influenced by the - * social planner. */ - PlannerBuilder(ogdyn::DynareModel& m, const Tvarset& yyset, - const Teqset& ffset); - /** Construct a copy of the builder with provided model, which - * is supposed to be the copy of the model in the builder. */ - PlannerBuilder(const PlannerBuilder& pb, ogdyn::DynareModel& m); - /** Return the information. */ - const PlannerInfo& get_info() const - {return info;} - protected: - /** Differentiate the planner objective wrt endogenous - * variables with different lags. */ - void add_derivatives_of_b(); - /** Differentiate the constraints wrt endogenous variables - * with different lags and leads. */ - void add_derivatives_of_f(); - /** Shift derivatives of diff_b. */ - void shift_derivatives_of_b(); - /** Shift derivatives of diff_ff. */ - void shift_derivatives_of_f(); - /** Multiply with the discount factor terms in diff_b. */ - void beta_multiply_b(); - /** Multiply with the discount factor terms in diff_f. */ - void beta_multiply_f(); - /** Fill static_atoms and static_tree and build diff_b_static, - * diff_f_static and aux_map_static with static versions of diff_b, - * diff_f and aux_map. */ - void make_static_version(); - /** Multiply diff_f with Langrange multipliers. */ - void lagrange_mult_f(); - /** Add the equations to the mode, including equation for auxiliary variables. */ - void form_equations(); - private: - /** Fill yset for a given yyset and given name storage. */ - void fill_yset(const ogp::NameStorage& ns, const Tvarset& yyset); - /** Fill aux_map and aux_map_static for a given aaux_map and - * aaux_map_static for a given storage of dynamic atoms (used - * for aux_map) and static atoms storage from this object for - * aux_map_static. */ - void fill_aux_map(const ogp::NameStorage& ns, const Tsubstmap& aaux_map, - const Tsubstmap& astatic_aux_map); - /** Avoid copying from only PlannerBuilder. */ - PlannerBuilder(const PlannerBuilder& pb); - }; + /** This class builds the first order conditions of the social + * planner problem with constraints being the equations in the + * model. The model is non-const parameter to the constructor + * which adds appropriate FOCs to the system. It also allows for + * an estimation of the lagrange multipliers given all other + * endogenous variables of the static system. For this purpose we + * need to create static atoms and static versions of all the tree + * index matrices. The algorithm and algebra are documented in + * dynare++-ramsey.pdf. */ + class PlannerBuilder + { + friend class MultInitSS; + public: + /** Type for a set of variable names. */ + typedef unordered_set<const char *> Tvarset; + /** Type for a set of equations. An equation is identified by + * an index to an equation in the equation vector given by + * DynareModel::eqs. The tree index of the i-th formula is + * retrieved as DynareModel::egs.formula(i). */ + typedef vector<int> Teqset; + protected: + /** This is a set of variables wrt which the planner + * optimizes. These could be all endogenous variables, but it + * is beneficial to exclude all variables which are + * deterministic transformations of past exogenous variables, + * since the planner cannot influence them. This could save a + * few equations. This is not changed after it is constructed, + * but it is constructed manually, so it cannot be declared as + * const. */ + Tvarset yset; + /** These are the equation indices constituing the constraints + * for the planner. Again, it is beneficial to exclude all + * equations defining exogenous variables excluded from + * yset. */ + const Teqset fset; + /** Reference to the model. */ + ogdyn::DynareModel &model; + /** Tree index of the planner objective. */ + int tb; + /** Tree index of the planner discount parameter. */ + int tbeta; + /** The maximum lead in the model including the planner's + * objective before building the planner's FOCs. */ + const int maxlead; + /** The minimum lag in the model including the planner's objective + * before building the planner's FOCs. */ + const int minlag; + /** Tree indices of formulas in the planner FOCs involving + * derivatives of the planner's objective. Rows correspond to the + * endogenous variables, columns correspond to lags in the + * objective function. The contents of the matrix will evolve as + * the algorithm proceeds. */ + IntegerMatrix diff_b; + /** Tree indices of formulas in the planner FOCs involving + * derivatives of the model equations (constraints). The first + * dimension corresponds to endogenous variables, the second to + * the constraints, the third to lags or leads of endogenous + * variables in the constraints. The contents of the array will + * evolve as the algorithm proceeds.*/ + IntegerArray3 diff_f; + /** Static version of the model atoms. It is needed to build + * static version of diff_b and diff_f. */ + ogp::StaticFineAtoms static_atoms; + /** Static version of all the trees of diff_b and diff_f build + * over static_atoms. */ + ogp::OperationTree static_tree; + /** Tree indices of static version of diff_b over static_atoms and static_tree. */ + IntegerMatrix diff_b_static; + /** Tree indices of static version of diff_f over static_atoms + * and static_tree. This member is created before calling + * lagrange_mult_f(), so it does not contain the + * multiplication with the lagrange multipliers. */ + IntegerArray3 diff_f_static; + /** Auxiliary variables mapping. During the algorithm, some + * auxiliary variables for the terms might be created, so we + * remember their names and tree indices of the terms. This + * maps a name to the tree index of an expression equal to the + * auxiliary variable at time zero. The auxiliary variables + * names point to the dynamic atoms storage, tree inidices to + * the dynamic model tree. */ + Tsubstmap aux_map; + /** Static version of aux_map. The names point to static_atoms + * storage, the tree indices to the static_tree. */ + Tsubstmap static_aux_map; + /** Information about the number of various things. */ + PlannerInfo info; + public: + /** Build the planner problem for the given model optimizing + * through the given endogenous variables with the given + * constraints. We allow for a selection of a subset of + * equations and variables in order to eliminate exogenous + * predetermined process which cannot be influenced by the + * social planner. */ + PlannerBuilder(ogdyn::DynareModel &m, const Tvarset &yyset, + const Teqset &ffset); + /** Construct a copy of the builder with provided model, which + * is supposed to be the copy of the model in the builder. */ + PlannerBuilder(const PlannerBuilder &pb, ogdyn::DynareModel &m); + /** Return the information. */ + const PlannerInfo & + get_info() const + { + return info; + } + protected: + /** Differentiate the planner objective wrt endogenous + * variables with different lags. */ + void add_derivatives_of_b(); + /** Differentiate the constraints wrt endogenous variables + * with different lags and leads. */ + void add_derivatives_of_f(); + /** Shift derivatives of diff_b. */ + void shift_derivatives_of_b(); + /** Shift derivatives of diff_ff. */ + void shift_derivatives_of_f(); + /** Multiply with the discount factor terms in diff_b. */ + void beta_multiply_b(); + /** Multiply with the discount factor terms in diff_f. */ + void beta_multiply_f(); + /** Fill static_atoms and static_tree and build diff_b_static, + * diff_f_static and aux_map_static with static versions of diff_b, + * diff_f and aux_map. */ + void make_static_version(); + /** Multiply diff_f with Langrange multipliers. */ + void lagrange_mult_f(); + /** Add the equations to the mode, including equation for auxiliary variables. */ + void form_equations(); + private: + /** Fill yset for a given yyset and given name storage. */ + void fill_yset(const ogp::NameStorage &ns, const Tvarset &yyset); + /** Fill aux_map and aux_map_static for a given aaux_map and + * aaux_map_static for a given storage of dynamic atoms (used + * for aux_map) and static atoms storage from this object for + * aux_map_static. */ + void fill_aux_map(const ogp::NameStorage &ns, const Tsubstmap &aaux_map, + const Tsubstmap &astatic_aux_map); + /** Avoid copying from only PlannerBuilder. */ + PlannerBuilder(const PlannerBuilder &pb); + }; - /** This class only calculates for the given initial guess of - * endogenous variables, initial guess of the Langrange - * multipliers of the social planner problem yielding the least - * square error. It is used by just calling its constructor. The - * constructor takes non-const reference to the vector of - * endogenous variables, calculates lambdas and put the values of - * lambdas to the vector. The algbera is found in - * dynare++-ramsey.pdf. - * - * The code can be run only after the parsing has been finished in - * atoms. */ - class MultInitSS : public ogp::FormulaEvalLoader { - protected: - /** The constant reference to the builder. */ - const PlannerBuilder& builder; - /** The constant term of the problem. Its length is the number - * of endogenous variable wrt the planner optimizes. */ - Vector b; - /** The matrix of the overdetermined problem. The number of - * rows is equal to the number of endogenous variables wrt - * which the planner optimizes, the number of columns is equal - * to the number of Langrange multipliers which is equal to - * the number of constraints which is smaller than the number - * of endogenous variables. Hence the system b+F*lambda=0 is - * overdetermined. */ - GeneralMatrix F; - public: - /** The constructor of the object which does everything. Its - * main goal is to update yy. Note that if an item of yy - * corresponding to a lagrange multiplier is already set, it - * is not reset. */ - MultInitSS(const PlannerBuilder& pb, const Vector& pvals, Vector& yy); - /** This loads evaluated parts of b or F and decodes i and - * advances b or F depending on the decoded i. The decoding is - * dependent on the way how the terms of builder.diff_b and - * builder.diff_f_save have been put the the - * ogp::FormulaCustomEvaluator. This is documented in the code - * of the constructor. */ - void load(int i, double res); - }; + /** This class only calculates for the given initial guess of + * endogenous variables, initial guess of the Langrange + * multipliers of the social planner problem yielding the least + * square error. It is used by just calling its constructor. The + * constructor takes non-const reference to the vector of + * endogenous variables, calculates lambdas and put the values of + * lambdas to the vector. The algbera is found in + * dynare++-ramsey.pdf. + * + * The code can be run only after the parsing has been finished in + * atoms. */ + class MultInitSS : public ogp::FormulaEvalLoader + { + protected: + /** The constant reference to the builder. */ + const PlannerBuilder &builder; + /** The constant term of the problem. Its length is the number + * of endogenous variable wrt the planner optimizes. */ + Vector b; + /** The matrix of the overdetermined problem. The number of + * rows is equal to the number of endogenous variables wrt + * which the planner optimizes, the number of columns is equal + * to the number of Langrange multipliers which is equal to + * the number of constraints which is smaller than the number + * of endogenous variables. Hence the system b+F*lambda=0 is + * overdetermined. */ + GeneralMatrix F; + public: + /** The constructor of the object which does everything. Its + * main goal is to update yy. Note that if an item of yy + * corresponding to a lagrange multiplier is already set, it + * is not reset. */ + MultInitSS(const PlannerBuilder &pb, const Vector &pvals, Vector &yy); + /** This loads evaluated parts of b or F and decodes i and + * advances b or F depending on the decoded i. The decoding is + * dependent on the way how the terms of builder.diff_b and + * builder.diff_f_save have been put the the + * ogp::FormulaCustomEvaluator. This is documented in the code + * of the constructor. */ + void load(int i, double res); + }; }; - #endif // Local Variables: diff --git a/dynare++/sylv/cc/BlockDiagonal.h b/dynare++/sylv/cc/BlockDiagonal.h index c2b94313a21e5b70c88872ba3ca981acf19804c4..f449653385da4d385d4b7af825d4411784523944 100644 --- a/dynare++/sylv/cc/BlockDiagonal.h +++ b/dynare++/sylv/cc/BlockDiagonal.h @@ -7,47 +7,55 @@ #include "QuasiTriangular.h" - -class BlockDiagonal : public QuasiTriangular { - int* const row_len; - int* const col_len; +class BlockDiagonal : public QuasiTriangular +{ + int *const row_len; + int *const col_len; public: - BlockDiagonal(const double* d, int d_size); - BlockDiagonal(int p, const BlockDiagonal& b); - BlockDiagonal(const BlockDiagonal& b); - BlockDiagonal(const QuasiTriangular& t); - const BlockDiagonal& operator=(const QuasiTriangular& t) - {GeneralMatrix::operator=(t); return *this;} - const BlockDiagonal& operator=(const BlockDiagonal& b); - ~BlockDiagonal() {delete [] row_len; delete [] col_len;} - void setZeroBlockEdge(diag_iter edge); - int getNumZeros() const; - int getNumBlocks() const; - int getLargestBlock() const; - void printInfo() const; - - void multKron(KronVector& x) const; - void multKronTrans(KronVector& x) const; - - const_col_iter col_begin(const DiagonalBlock& b) const; - col_iter col_begin(const DiagonalBlock& b); - const_row_iter row_end(const DiagonalBlock& b) const; - row_iter row_end(const DiagonalBlock& b); - QuasiTriangular* clone() const - {return new BlockDiagonal(*this);} + BlockDiagonal(const double *d, int d_size); + BlockDiagonal(int p, const BlockDiagonal &b); + BlockDiagonal(const BlockDiagonal &b); + BlockDiagonal(const QuasiTriangular &t); + const BlockDiagonal & + operator=(const QuasiTriangular &t) + { + GeneralMatrix::operator=(t); return *this; + } + const BlockDiagonal &operator=(const BlockDiagonal &b); + ~BlockDiagonal() + { + delete [] row_len; delete [] col_len; + } + void setZeroBlockEdge(diag_iter edge); + int getNumZeros() const; + int getNumBlocks() const; + int getLargestBlock() const; + void printInfo() const; + + void multKron(KronVector &x) const; + void multKronTrans(KronVector &x) const; + + const_col_iter col_begin(const DiagonalBlock &b) const; + col_iter col_begin(const DiagonalBlock &b); + const_row_iter row_end(const DiagonalBlock &b) const; + row_iter row_end(const DiagonalBlock &b); + QuasiTriangular * + clone() const + { + return new BlockDiagonal(*this); + } private: - void setZerosToRU(diag_iter edge); - const_diag_iter findBlockStart(const_diag_iter from) const; - static void savePartOfX(int si, int ei, const KronVector& x, Vector& work); - void multKronBlock(const_diag_iter start, const_diag_iter end, - KronVector& x, Vector& work) const; - void multKronBlockTrans(const_diag_iter start, const_diag_iter end, - KronVector& x, Vector& work) const; + void setZerosToRU(diag_iter edge); + const_diag_iter findBlockStart(const_diag_iter from) const; + static void savePartOfX(int si, int ei, const KronVector &x, Vector &work); + void multKronBlock(const_diag_iter start, const_diag_iter end, + KronVector &x, Vector &work) const; + void multKronBlockTrans(const_diag_iter start, const_diag_iter end, + KronVector &x, Vector &work) const; }; #endif /* BLOCK_DIAGONAL_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/GeneralMatrix.h b/dynare++/sylv/cc/GeneralMatrix.h index d24c11cad951535efdce167133c6d72bc9a28b2f..494dcf40677956d9df97d4eada2e5a84b6efc373 100644 --- a/dynare++/sylv/cc/GeneralMatrix.h +++ b/dynare++/sylv/cc/GeneralMatrix.h @@ -11,310 +11,484 @@ class GeneralMatrix; -class ConstGeneralMatrix { - friend class GeneralMatrix; +class ConstGeneralMatrix +{ + friend class GeneralMatrix; protected: - ConstVector data; - int rows; - int cols; - int ld; + ConstVector data; + int rows; + int cols; + int ld; public: - ConstGeneralMatrix(const double* d, int m, int n) - : data(d, m*n), rows(m), cols(n), ld(m) {} - ConstGeneralMatrix(const GeneralMatrix& m); - ConstGeneralMatrix(const GeneralMatrix& m, int i, int j, int nrows, int ncols); - ConstGeneralMatrix(const ConstGeneralMatrix& m, int i, int j, int nrows, int ncols); - virtual ~ConstGeneralMatrix() {} - - const double& get(int i, int j) const - {return data[j*ld+i];} - int numRows() const {return rows;} - int numCols() const {return cols;} - int getLD() const {return ld;} - const double* base() const {return data.base();} - const ConstVector& getData() const {return data;} - - double getNormInf() const; - double getNorm1() const; - /* x = scalar(a)*x + scalar(b)*this*d */ - void multVec(double a, Vector& x, double b, const ConstVector& d) const; - /* x = scalar(a)*x + scalar(b)*this'*d */ - void multVecTrans(double a, Vector& x, double b, const ConstVector& d) const; - /* x = x + this*d */ - void multaVec(Vector& x, const ConstVector& d) const - {multVec(1.0, x, 1.0, d);} - /* x = x + this'*d */ - void multaVecTrans(Vector& x, const ConstVector& d) const - {multVecTrans(1.0, x, 1.0, d);} - /* x = x - this*d */ - void multsVec(Vector& x, const ConstVector& d) const - {multVec(1.0, x, -1.0, d);} - /* x = x - this'*d */ - void multsVecTrans(Vector& x, const ConstVector& d) const - {multVecTrans(1.0, x, -1.0, d);} - /* m = inv(this)*m */ - void multInvLeft(GeneralMatrix& m) const; - /* m = inv(this')*m */ - void multInvLeftTrans(GeneralMatrix& m) const; - /* d = inv(this)*d */ - void multInvLeft(Vector& d) const; - /* d = inv(this')*d */ - void multInvLeftTrans(Vector& d) const; - - bool isFinite() const; - /** Returns true of the matrix is exactly zero. */ - bool isZero() const; - - virtual void print() const; + ConstGeneralMatrix(const double *d, int m, int n) + : data(d, m*n), rows(m), cols(n), ld(m) + { + } + ConstGeneralMatrix(const GeneralMatrix &m); + ConstGeneralMatrix(const GeneralMatrix &m, int i, int j, int nrows, int ncols); + ConstGeneralMatrix(const ConstGeneralMatrix &m, int i, int j, int nrows, int ncols); + virtual ~ConstGeneralMatrix() + { + } + + const double & + get(int i, int j) const + { + return data[j*ld+i]; + } + int + numRows() const + { + return rows; + } + int + numCols() const + { + return cols; + } + int + getLD() const + { + return ld; + } + const double * + base() const + { + return data.base(); + } + const ConstVector & + getData() const + { + return data; + } + + double getNormInf() const; + double getNorm1() const; + /* x = scalar(a)*x + scalar(b)*this*d */ + void multVec(double a, Vector &x, double b, const ConstVector &d) const; + /* x = scalar(a)*x + scalar(b)*this'*d */ + void multVecTrans(double a, Vector &x, double b, const ConstVector &d) const; + /* x = x + this*d */ + void + multaVec(Vector &x, const ConstVector &d) const + { + multVec(1.0, x, 1.0, d); + } + /* x = x + this'*d */ + void + multaVecTrans(Vector &x, const ConstVector &d) const + { + multVecTrans(1.0, x, 1.0, d); + } + /* x = x - this*d */ + void + multsVec(Vector &x, const ConstVector &d) const + { + multVec(1.0, x, -1.0, d); + } + /* x = x - this'*d */ + void + multsVecTrans(Vector &x, const ConstVector &d) const + { + multVecTrans(1.0, x, -1.0, d); + } + /* m = inv(this)*m */ + void multInvLeft(GeneralMatrix &m) const; + /* m = inv(this')*m */ + void multInvLeftTrans(GeneralMatrix &m) const; + /* d = inv(this)*d */ + void multInvLeft(Vector &d) const; + /* d = inv(this')*d */ + void multInvLeftTrans(Vector &d) const; + + bool isFinite() const; + /** Returns true of the matrix is exactly zero. */ + bool isZero() const; + + virtual void print() const; protected: - void multInvLeft(const char* trans, int mrows, int mcols, int mld, double* d) const; + void multInvLeft(const char *trans, int mrows, int mcols, int mld, double *d) const; }; - -class GeneralMatrix { - friend class ConstGeneralMatrix; +class GeneralMatrix +{ + friend class ConstGeneralMatrix; protected: - Vector data; - int rows; - int cols; - int ld; + Vector data; + int rows; + int cols; + int ld; public: - GeneralMatrix(int m, int n) - : data(m*n), rows(m), cols(n), ld(m) {} - GeneralMatrix(const double* d, int m, int n) - : data(d, m*n), rows(m), cols(n), ld(m) {} - GeneralMatrix(double* d, int m, int n) - : data(d, m*n), rows(m), cols(n), ld(m) {} - GeneralMatrix(const GeneralMatrix& m); - GeneralMatrix(const ConstGeneralMatrix& m); - GeneralMatrix(const GeneralMatrix&m, const char* dummy); // transpose - GeneralMatrix(const ConstGeneralMatrix&m, const char* dummy); // transpose - GeneralMatrix(const GeneralMatrix& m, int i, int j, int nrows, int ncols); - GeneralMatrix(GeneralMatrix& m, int i, int j, int nrows, int ncols); - /* this = a*b */ - GeneralMatrix(const GeneralMatrix& a, const GeneralMatrix& b); - /* this = a*b' */ - GeneralMatrix(const GeneralMatrix& a, const GeneralMatrix& b, const char* dum); - /* this = a'*b */ - GeneralMatrix(const GeneralMatrix& a, const char* dum, const GeneralMatrix& b); - /* this = a'*b */ - GeneralMatrix(const GeneralMatrix& a, const char* dum1, - const GeneralMatrix& b, const char* dum2); - - virtual ~GeneralMatrix(); - const GeneralMatrix& operator=(const GeneralMatrix& m) - {data=m.data; rows=m.rows; cols=m.cols; ld=m.ld; return *this;} - - const double& get(int i, int j) const - {return data[j*ld+i];} - double& get(int i, int j) - {return data[j*ld+i];} - int numRows() const {return rows;} - int numCols() const {return cols;} - int getLD() const {return ld;} - double* base() {return data.base();} - const double* base() const {return data.base();} - Vector& getData() {return data;} - const Vector& getData() const {return data;} - - double getNormInf() const - {return ConstGeneralMatrix(*this).getNormInf();} - double getNorm1() const - {return ConstGeneralMatrix(*this).getNorm1();} - - /* place matrix m to the position (i,j) */ - void place(const ConstGeneralMatrix& m, int i, int j); - void place(const GeneralMatrix& m, int i, int j) - {place(ConstGeneralMatrix(m), i, j);} - - /* this = a*b */ - void mult(const ConstGeneralMatrix& a, const ConstGeneralMatrix& b); - void mult(const GeneralMatrix& a, const GeneralMatrix& b) - {mult(ConstGeneralMatrix(a), ConstGeneralMatrix(b));} - - /* this = this + scalar*a*b */ - void multAndAdd(const ConstGeneralMatrix& a, const ConstGeneralMatrix& b, - double mult=1.0); - void multAndAdd(const GeneralMatrix& a, const GeneralMatrix& b, - double mult=1.0) - {multAndAdd(ConstGeneralMatrix(a), ConstGeneralMatrix(b), mult);} - - /* this = this + scalar*a*b' */ - void multAndAdd(const ConstGeneralMatrix& a, const ConstGeneralMatrix& b, - const char* dum, double mult=1.0); - void multAndAdd(const GeneralMatrix& a, const GeneralMatrix& b, - const char* dum, double mult=1.0) - {multAndAdd(ConstGeneralMatrix(a), ConstGeneralMatrix(b), dum, mult);} - - /* this = this + scalar*a'*b */ - void multAndAdd(const ConstGeneralMatrix& a, const char* dum, const ConstGeneralMatrix& b, - double mult=1.0); - void multAndAdd(const GeneralMatrix& a, const char* dum, const GeneralMatrix& b, - double mult=1.0) - {multAndAdd(ConstGeneralMatrix(a), dum, ConstGeneralMatrix(b), mult);} - - /* this = this + scalar*a'*b' */ - void multAndAdd(const ConstGeneralMatrix& a, const char* dum1, - const ConstGeneralMatrix& b, const char* dum2, double mult=1.0); - void multAndAdd(const GeneralMatrix& a, const char* dum1, - const GeneralMatrix& b, const char* dum2, double mult=1.0) - {multAndAdd(ConstGeneralMatrix(a), dum1, ConstGeneralMatrix(b),dum2, mult);} - - /* this = this + scalar*a*a' */ - void addOuter(const ConstVector& a, double mult=1.0); - void addOuter(const Vector& a, double mult=1.0) - {addOuter(ConstVector(a), mult);} - - /* this = this * m */ - void multRight(const ConstGeneralMatrix& m); - void multRight(const GeneralMatrix& m) - {multRight(ConstGeneralMatrix(m));} - - /* this = m * this */ - void multLeft(const ConstGeneralMatrix& m); - void multLeft(const GeneralMatrix& m) - {multLeft(ConstGeneralMatrix(m));} - - /* this = this * m' */ - void multRightTrans(const ConstGeneralMatrix& m); - void multRightTrans(const GeneralMatrix& m) - {multRightTrans(ConstGeneralMatrix(m));} - - /* this = m' * this */ - void multLeftTrans(const ConstGeneralMatrix& m); - void multLeftTrans(const GeneralMatrix& m) - {multLeftTrans(ConstGeneralMatrix(m));} - - /* x = scalar(a)*x + scalar(b)*this*d */ - void multVec(double a, Vector& x, double b, const ConstVector& d) const - {ConstGeneralMatrix(*this).multVec(a, x, b, d);} - - /* x = scalar(a)*x + scalar(b)*this'*d */ - void multVecTrans(double a, Vector& x, double b, const ConstVector& d) const - {ConstGeneralMatrix(*this).multVecTrans(a, x, b, d);} - - /* x = x + this*d */ - void multaVec(Vector& x, const ConstVector& d) const - {ConstGeneralMatrix(*this).multaVec(x, d);} - - /* x = x + this'*d */ - void multaVecTrans(Vector& x, const ConstVector& d) const - {ConstGeneralMatrix(*this).multaVecTrans(x, d);} - - /* x = x - this*d */ - void multsVec(Vector& x, const ConstVector& d) const - {ConstGeneralMatrix(*this).multsVec(x, d);} - - /* x = x - this'*d */ - void multsVecTrans(Vector& x, const ConstVector& d) const - {ConstGeneralMatrix(*this).multsVecTrans(x, d);} - - /* this = zero */ - void zeros(); - - /** this = unit (on main diagonal) */ - void unit(); - - /* this = NaN */ - void nans(); - - /* this = Inf */ - void infs(); - - /* this = scalar*this */ - void mult(double a); - - /* this = this + scalar*m */ - void add(double a, const ConstGeneralMatrix& m); - void add(double a, const GeneralMatrix& m) - {add(a, ConstGeneralMatrix(m));} - - /* this = this + scalar*m' */ - void add(double a, const ConstGeneralMatrix& m, const char* dum); - void add(double a, const GeneralMatrix& m, const char* dum) - {add(a, ConstGeneralMatrix(m), dum);} - - bool isFinite() const - {return (ConstGeneralMatrix(*this)).isFinite();} - - bool isZero() const - {return (ConstGeneralMatrix(*this)).isZero();} - - virtual void print() const - {ConstGeneralMatrix(*this).print();} + GeneralMatrix(int m, int n) + : data(m*n), rows(m), cols(n), ld(m) + { + } + GeneralMatrix(const double *d, int m, int n) + : data(d, m*n), rows(m), cols(n), ld(m) + { + } + GeneralMatrix(double *d, int m, int n) + : data(d, m*n), rows(m), cols(n), ld(m) + { + } + GeneralMatrix(const GeneralMatrix &m); + GeneralMatrix(const ConstGeneralMatrix &m); + GeneralMatrix(const GeneralMatrix &m, const char *dummy); // transpose + GeneralMatrix(const ConstGeneralMatrix &m, const char *dummy); // transpose + GeneralMatrix(const GeneralMatrix &m, int i, int j, int nrows, int ncols); + GeneralMatrix(GeneralMatrix &m, int i, int j, int nrows, int ncols); + /* this = a*b */ + GeneralMatrix(const GeneralMatrix &a, const GeneralMatrix &b); + /* this = a*b' */ + GeneralMatrix(const GeneralMatrix &a, const GeneralMatrix &b, const char *dum); + /* this = a'*b */ + GeneralMatrix(const GeneralMatrix &a, const char *dum, const GeneralMatrix &b); + /* this = a'*b */ + GeneralMatrix(const GeneralMatrix &a, const char *dum1, + const GeneralMatrix &b, const char *dum2); + + virtual + ~GeneralMatrix(); + const GeneralMatrix & + operator=(const GeneralMatrix &m) + { + data = m.data; rows = m.rows; cols = m.cols; ld = m.ld; return *this; + } + + const double & + get(int i, int j) const + { + return data[j*ld+i]; + } + double & + get(int i, int j) + { + return data[j*ld+i]; + } + int + numRows() const + { + return rows; + } + int + numCols() const + { + return cols; + } + int + getLD() const + { + return ld; + } + double * + base() + { + return data.base(); + } + const double * + base() const + { + return data.base(); + } + Vector & + getData() + { + return data; + } + const Vector & + getData() const + { + return data; + } + + double + getNormInf() const + { + return ConstGeneralMatrix(*this).getNormInf(); + } + double + getNorm1() const + { + return ConstGeneralMatrix(*this).getNorm1(); + } + + /* place matrix m to the position (i,j) */ + void place(const ConstGeneralMatrix &m, int i, int j); + void + place(const GeneralMatrix &m, int i, int j) + { + place(ConstGeneralMatrix(m), i, j); + } + + /* this = a*b */ + void mult(const ConstGeneralMatrix &a, const ConstGeneralMatrix &b); + void + mult(const GeneralMatrix &a, const GeneralMatrix &b) + { + mult(ConstGeneralMatrix(a), ConstGeneralMatrix(b)); + } + + /* this = this + scalar*a*b */ + void multAndAdd(const ConstGeneralMatrix &a, const ConstGeneralMatrix &b, + double mult = 1.0); + void + multAndAdd(const GeneralMatrix &a, const GeneralMatrix &b, + double mult = 1.0) + { + multAndAdd(ConstGeneralMatrix(a), ConstGeneralMatrix(b), mult); + } + + /* this = this + scalar*a*b' */ + void multAndAdd(const ConstGeneralMatrix &a, const ConstGeneralMatrix &b, + const char *dum, double mult = 1.0); + void + multAndAdd(const GeneralMatrix &a, const GeneralMatrix &b, + const char *dum, double mult = 1.0) + { + multAndAdd(ConstGeneralMatrix(a), ConstGeneralMatrix(b), dum, mult); + } + + /* this = this + scalar*a'*b */ + void multAndAdd(const ConstGeneralMatrix &a, const char *dum, const ConstGeneralMatrix &b, + double mult = 1.0); + void + multAndAdd(const GeneralMatrix &a, const char *dum, const GeneralMatrix &b, + double mult = 1.0) + { + multAndAdd(ConstGeneralMatrix(a), dum, ConstGeneralMatrix(b), mult); + } + + /* this = this + scalar*a'*b' */ + void multAndAdd(const ConstGeneralMatrix &a, const char *dum1, + const ConstGeneralMatrix &b, const char *dum2, double mult = 1.0); + void + multAndAdd(const GeneralMatrix &a, const char *dum1, + const GeneralMatrix &b, const char *dum2, double mult = 1.0) + { + multAndAdd(ConstGeneralMatrix(a), dum1, ConstGeneralMatrix(b), dum2, mult); + } + + /* this = this + scalar*a*a' */ + void addOuter(const ConstVector &a, double mult = 1.0); + void + addOuter(const Vector &a, double mult = 1.0) + { + addOuter(ConstVector(a), mult); + } + + /* this = this * m */ + void multRight(const ConstGeneralMatrix &m); + void + multRight(const GeneralMatrix &m) + { + multRight(ConstGeneralMatrix(m)); + } + + /* this = m * this */ + void multLeft(const ConstGeneralMatrix &m); + void + multLeft(const GeneralMatrix &m) + { + multLeft(ConstGeneralMatrix(m)); + } + + /* this = this * m' */ + void multRightTrans(const ConstGeneralMatrix &m); + void + multRightTrans(const GeneralMatrix &m) + { + multRightTrans(ConstGeneralMatrix(m)); + } + + /* this = m' * this */ + void multLeftTrans(const ConstGeneralMatrix &m); + void + multLeftTrans(const GeneralMatrix &m) + { + multLeftTrans(ConstGeneralMatrix(m)); + } + + /* x = scalar(a)*x + scalar(b)*this*d */ + void + multVec(double a, Vector &x, double b, const ConstVector &d) const + { + ConstGeneralMatrix(*this).multVec(a, x, b, d); + } + + /* x = scalar(a)*x + scalar(b)*this'*d */ + void + multVecTrans(double a, Vector &x, double b, const ConstVector &d) const + { + ConstGeneralMatrix(*this).multVecTrans(a, x, b, d); + } + + /* x = x + this*d */ + void + multaVec(Vector &x, const ConstVector &d) const + { + ConstGeneralMatrix(*this).multaVec(x, d); + } + + /* x = x + this'*d */ + void + multaVecTrans(Vector &x, const ConstVector &d) const + { + ConstGeneralMatrix(*this).multaVecTrans(x, d); + } + + /* x = x - this*d */ + void + multsVec(Vector &x, const ConstVector &d) const + { + ConstGeneralMatrix(*this).multsVec(x, d); + } + + /* x = x - this'*d */ + void + multsVecTrans(Vector &x, const ConstVector &d) const + { + ConstGeneralMatrix(*this).multsVecTrans(x, d); + } + + /* this = zero */ + void zeros(); + + /** this = unit (on main diagonal) */ + void unit(); + + /* this = NaN */ + void nans(); + + /* this = Inf */ + void infs(); + + /* this = scalar*this */ + void mult(double a); + + /* this = this + scalar*m */ + void add(double a, const ConstGeneralMatrix &m); + void + add(double a, const GeneralMatrix &m) + { + add(a, ConstGeneralMatrix(m)); + } + + /* this = this + scalar*m' */ + void add(double a, const ConstGeneralMatrix &m, const char *dum); + void + add(double a, const GeneralMatrix &m, const char *dum) + { + add(a, ConstGeneralMatrix(m), dum); + } + + bool + isFinite() const + { + return (ConstGeneralMatrix(*this)).isFinite(); + } + + bool + isZero() const + { + return (ConstGeneralMatrix(*this)).isZero(); + } + + virtual void + print() const + { + ConstGeneralMatrix(*this).print(); + } private: - void copy(const ConstGeneralMatrix& m, int ioff = 0, int joff = 0); - void copy(const GeneralMatrix& m, int ioff = 0, int joff = 0) - {copy(ConstGeneralMatrix(m), ioff, joff);} - - void gemm(const char* transa, const ConstGeneralMatrix& a, - const char* transb, const ConstGeneralMatrix& b, - double alpha, double beta); - void gemm(const char* transa, const GeneralMatrix& a, - const char* transb, const GeneralMatrix& b, - double alpha, double beta) - {gemm(transa, ConstGeneralMatrix(a), transb, ConstGeneralMatrix(b), - alpha, beta);} - - /* this = this * op(m) (without whole copy of this) */ - void gemm_partial_right(const char* trans, const ConstGeneralMatrix& m, - double alpha, double beta); - void gemm_partial_right(const char* trans, const GeneralMatrix& m, - double alpha, double beta) - {gemm_partial_right(trans, ConstGeneralMatrix(m), alpha, beta);} - - /* this = op(m) *this (without whole copy of this) */ - void gemm_partial_left(const char* trans, const ConstGeneralMatrix& m, - double alpha, double beta); - void gemm_partial_left(const char* trans, const GeneralMatrix& m, - double alpha, double beta) - {gemm_partial_left(trans, ConstGeneralMatrix(m), alpha, beta);} - - /* number of rows/columns for copy used in gemm_partial_* */ - static int md_length; + void copy(const ConstGeneralMatrix &m, int ioff = 0, int joff = 0); + void + copy(const GeneralMatrix &m, int ioff = 0, int joff = 0) + { + copy(ConstGeneralMatrix(m), ioff, joff); + } + + void gemm(const char *transa, const ConstGeneralMatrix &a, + const char *transb, const ConstGeneralMatrix &b, + double alpha, double beta); + void + gemm(const char *transa, const GeneralMatrix &a, + const char *transb, const GeneralMatrix &b, + double alpha, double beta) + { + gemm(transa, ConstGeneralMatrix(a), transb, ConstGeneralMatrix(b), + alpha, beta); + } + + /* this = this * op(m) (without whole copy of this) */ + void gemm_partial_right(const char *trans, const ConstGeneralMatrix &m, + double alpha, double beta); + void + gemm_partial_right(const char *trans, const GeneralMatrix &m, + double alpha, double beta) + { + gemm_partial_right(trans, ConstGeneralMatrix(m), alpha, beta); + } + + /* this = op(m) *this (without whole copy of this) */ + void gemm_partial_left(const char *trans, const ConstGeneralMatrix &m, + double alpha, double beta); + void + gemm_partial_left(const char *trans, const GeneralMatrix &m, + double alpha, double beta) + { + gemm_partial_left(trans, ConstGeneralMatrix(m), alpha, beta); + } + + /* number of rows/columns for copy used in gemm_partial_* */ + static int md_length; }; -class SVDDecomp { +class SVDDecomp +{ protected: - /** Minimum of number of rows and columns of the decomposed - * matrix. */ - const int minmn; - /** Singular values. */ - Vector sigma; - /** Orthogonal matrix U. */ - GeneralMatrix U; - /** Orthogonal matrix V^T. */ - GeneralMatrix VT; - /** Convered flag. */ - bool conv; + /** Minimum of number of rows and columns of the decomposed + * matrix. */ + const int minmn; + /** Singular values. */ + Vector sigma; + /** Orthogonal matrix U. */ + GeneralMatrix U; + /** Orthogonal matrix V^T. */ + GeneralMatrix VT; + /** Convered flag. */ + bool conv; public: - SVDDecomp(const GeneralMatrix& A) - : minmn(std::min<int>(A.numRows(), A.numCols())), - sigma(minmn), - U(A.numRows(), A.numRows()), - VT(A.numCols(), A.numCols()), - conv(false) - {construct(A);} - const GeneralMatrix& getU() const - {return U;} - const GeneralMatrix& getVT() const - {return VT;} - void solve(const GeneralMatrix& B, GeneralMatrix& X) const; - void solve(const Vector& b, Vector& x) const - { - GeneralMatrix xmat(x.base(), x.length(), 1); - solve(GeneralMatrix(b.base(), b.length(), 1), xmat); - } + SVDDecomp(const GeneralMatrix &A) + : minmn(std::min<int>(A.numRows(), A.numCols())), + sigma(minmn), + U(A.numRows(), A.numRows()), + VT(A.numCols(), A.numCols()), + conv(false) + { + construct(A); + } + const GeneralMatrix & + getU() const + { + return U; + } + const GeneralMatrix & + getVT() const + { + return VT; + } + void solve(const GeneralMatrix &B, GeneralMatrix &X) const; + void + solve(const Vector &b, Vector &x) const + { + GeneralMatrix xmat(x.base(), x.length(), 1); + solve(GeneralMatrix(b.base(), b.length(), 1), xmat); + } private: - void construct(const GeneralMatrix& A); + void construct(const GeneralMatrix &A); }; - - - #endif /* GENERAL_MATRIX_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/GeneralSylvester.h b/dynare++/sylv/cc/GeneralSylvester.h index a81f5a2d4561fdf2e0f51dbedb9f7fc3d4f872c7..9e2603f48ce1580861d224b14738c7ca6cb6223a 100644 --- a/dynare++/sylv/cc/GeneralSylvester.h +++ b/dynare++/sylv/cc/GeneralSylvester.h @@ -10,52 +10,73 @@ #include "SimilarityDecomp.h" #include "SylvesterSolver.h" -class GeneralSylvester { - SylvParams pars; - SylvMemoryDriver mem_driver; - int order; - const SqSylvMatrix a; - const SylvMatrix b; - const SqSylvMatrix c; - SylvMatrix d; - bool solved; - SchurDecompZero* bdecomp; - SimilarityDecomp* cdecomp; - SylvesterSolver* sylv; +class GeneralSylvester +{ + SylvParams pars; + SylvMemoryDriver mem_driver; + int order; + const SqSylvMatrix a; + const SylvMatrix b; + const SqSylvMatrix c; + SylvMatrix d; + bool solved; + SchurDecompZero *bdecomp; + SimilarityDecomp *cdecomp; + SylvesterSolver *sylv; public: - /* construct with my copy of d*/ - GeneralSylvester(int ord, int n, int m, int zero_cols, - const double* da, const double* db, - const double* dc, const double* dd, - const SylvParams& ps); - GeneralSylvester(int ord, int n, int m, int zero_cols, - const double* da, const double* db, - const double* dc, const double* dd, - bool alloc_for_check = false); - /* construct with provided storage for d */ - GeneralSylvester(int ord, int n, int m, int zero_cols, - const double* da, const double* db, - const double* dc, double* dd, - bool alloc_for_check = false); - GeneralSylvester(int ord, int n, int m, int zero_cols, - const double* da, const double* db, - const double* dc, double* dd, - const SylvParams& ps); - virtual ~GeneralSylvester(); - int getM() const {return c.numRows();} - int getN() const {return a.numRows();} - const double* getResult() const {return d.base();} - const SylvParams& getParams() const {return pars;} - SylvParams& getParams() {return pars;} - void solve(); - void check(const double* ds); + /* construct with my copy of d*/ + GeneralSylvester(int ord, int n, int m, int zero_cols, + const double *da, const double *db, + const double *dc, const double *dd, + const SylvParams &ps); + GeneralSylvester(int ord, int n, int m, int zero_cols, + const double *da, const double *db, + const double *dc, const double *dd, + bool alloc_for_check = false); + /* construct with provided storage for d */ + GeneralSylvester(int ord, int n, int m, int zero_cols, + const double *da, const double *db, + const double *dc, double *dd, + bool alloc_for_check = false); + GeneralSylvester(int ord, int n, int m, int zero_cols, + const double *da, const double *db, + const double *dc, double *dd, + const SylvParams &ps); + virtual + ~GeneralSylvester(); + int + getM() const + { + return c.numRows(); + } + int + getN() const + { + return a.numRows(); + } + const double * + getResult() const + { + return d.base(); + } + const SylvParams & + getParams() const + { + return pars; + } + SylvParams & + getParams() + { + return pars; + } + void solve(); + void check(const double *ds); private: - void init(); + void init(); }; #endif /* GENERAL_SYLVESTER_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/IterativeSylvester.h b/dynare++/sylv/cc/IterativeSylvester.h index cb69fbf7cab6b9ec5e03eb0a044f22255f718b43..6e30d75d0939c1054176e9f1efcb81136f9ea3eb 100644 --- a/dynare++/sylv/cc/IterativeSylvester.h +++ b/dynare++/sylv/cc/IterativeSylvester.h @@ -10,24 +10,30 @@ #include "QuasiTriangular.h" #include "SimilarityDecomp.h" -class IterativeSylvester : public SylvesterSolver { +class IterativeSylvester : public SylvesterSolver +{ public: - IterativeSylvester(const QuasiTriangular& k, const QuasiTriangular& f) - : SylvesterSolver(k, f) {} - IterativeSylvester(const SchurDecompZero& kdecomp, const SchurDecomp& fdecomp) - : SylvesterSolver(kdecomp, fdecomp) {} - IterativeSylvester(const SchurDecompZero& kdecomp, const SimilarityDecomp& fdecomp) - : SylvesterSolver(kdecomp, fdecomp) {} - void solve(SylvParams& pars, KronVector& x) const; + IterativeSylvester(const QuasiTriangular &k, const QuasiTriangular &f) + : SylvesterSolver(k, f) + { + } + IterativeSylvester(const SchurDecompZero &kdecomp, const SchurDecomp &fdecomp) + : SylvesterSolver(kdecomp, fdecomp) + { + } + IterativeSylvester(const SchurDecompZero &kdecomp, const SimilarityDecomp &fdecomp) + : SylvesterSolver(kdecomp, fdecomp) + { + } + void solve(SylvParams &pars, KronVector &x) const; private: - double performFirstStep(KronVector& x) const; - static double performStep(const QuasiTriangular& k, const QuasiTriangular& f, - KronVector& x); + double performFirstStep(KronVector &x) const; + static double performStep(const QuasiTriangular &k, const QuasiTriangular &f, + KronVector &x); }; #endif /* ITERATIVE_SYLVESTER_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/KronUtils.h b/dynare++/sylv/cc/KronUtils.h index 2ebeeee30cbd7abd70bf70581aa640c311be9b3f..a0d2339f065bb9fe59a6c6b007cc05387549a0a4 100644 --- a/dynare++/sylv/cc/KronUtils.h +++ b/dynare++/sylv/cc/KronUtils.h @@ -8,21 +8,22 @@ #include "KronVector.h" #include "QuasiTriangular.h" -class KronUtils { +class KronUtils +{ public: - /* multiplies I_m\otimes..\I_m\otimes T\otimes I_m...I_m\otimes I_n - with given b and returns x. T must be (m,m), number of - \otimes is b.getDepth(), level is a number of I_m's between T - and I_n plus 1. If level=0, then we multiply - \I_m\otimes ..\otimes I_m\otimes T, T is (n,n) */ - static void multAtLevel(int level, const QuasiTriangular& t, - KronVector& x); - static void multAtLevelTrans(int level, const QuasiTriangular& t, - KronVector& x); + /* multiplies I_m\otimes..\I_m\otimes T\otimes I_m...I_m\otimes I_n + with given b and returns x. T must be (m,m), number of + \otimes is b.getDepth(), level is a number of I_m's between T + and I_n plus 1. If level=0, then we multiply + \I_m\otimes ..\otimes I_m\otimes T, T is (n,n) */ + static void multAtLevel(int level, const QuasiTriangular &t, + KronVector &x); + static void multAtLevelTrans(int level, const QuasiTriangular &t, + KronVector &x); - /* multiplies x=(F'\otimes F'\otimes..\otimes K)x */ - static void multKron(const QuasiTriangular& f, const QuasiTriangular& k, - KronVector& x); + /* multiplies x=(F'\otimes F'\otimes..\otimes K)x */ + static void multKron(const QuasiTriangular &f, const QuasiTriangular &k, + KronVector &x); }; #endif /* KRON_UTILS_H */ diff --git a/dynare++/sylv/cc/KronVector.h b/dynare++/sylv/cc/KronVector.h index db721c3b73b928b3ae9443d30baece834a6c6069..dc8b6fb919e4f8fe598935d0d3cae29d53a1879d 100644 --- a/dynare++/sylv/cc/KronVector.h +++ b/dynare++/sylv/cc/KronVector.h @@ -9,44 +9,77 @@ class ConstKronVector; -class KronVector : public Vector { +class KronVector : public Vector +{ protected: - int m; - int n; - int depth; + int m; + int n; + int depth; public: - KronVector() : Vector((double*)0, 0), m(0), n(0), depth(0) {} - KronVector(int mm, int nn, int dp); // new instance - KronVector(Vector& v, int mm, int nn, int dp); // conversion - KronVector(KronVector&, int i); // picks i-th subvector - KronVector(const ConstKronVector& v); // new instance and copy - const KronVector& operator=(KronVector& v) - {Vector::operator=(v); m=v.m; n=v.n; depth = v.depth; return *this;} - const KronVector& operator=(const KronVector& v) - {Vector::operator=(v); m=v.m; n=v.n; depth = v.depth; return *this;} - const KronVector& operator=(const ConstKronVector& v); - const KronVector& operator=(const Vector& v); - int getM() const {return m;} - int getN() const {return n;} - int getDepth() const {return depth;} + KronVector() : Vector((double *) 0, 0), m(0), n(0), depth(0) + { + } + KronVector(int mm, int nn, int dp); // new instance + KronVector(Vector &v, int mm, int nn, int dp); // conversion + KronVector(KronVector &, int i); // picks i-th subvector + KronVector(const ConstKronVector &v); // new instance and copy + const KronVector & + operator=(KronVector &v) + { + Vector::operator=(v); m = v.m; n = v.n; depth = v.depth; return *this; + } + const KronVector & + operator=(const KronVector &v) + { + Vector::operator=(v); m = v.m; n = v.n; depth = v.depth; return *this; + } + const KronVector &operator=(const ConstKronVector &v); + const KronVector &operator=(const Vector &v); + int + getM() const + { + return m; + } + int + getN() const + { + return n; + } + int + getDepth() const + { + return depth; + } }; class ConstKronVector : public ConstVector { protected: - int m; - int n; - int depth; + int m; + int n; + int depth; public: - ConstKronVector(const KronVector& v); - ConstKronVector(const ConstKronVector& v); - ConstKronVector(const Vector& v, int mm, int nn, int dp); - ConstKronVector(const ConstVector& v, int mm, int nn, int dp); - ConstKronVector(const KronVector& v, int i); - ConstKronVector(const ConstKronVector& v, int i); - int getM() const {return m;} - int getN() const {return n;} - int getDepth() const {return depth;} + ConstKronVector(const KronVector &v); + ConstKronVector(const ConstKronVector &v); + ConstKronVector(const Vector &v, int mm, int nn, int dp); + ConstKronVector(const ConstVector &v, int mm, int nn, int dp); + ConstKronVector(const KronVector &v, int i); + ConstKronVector(const ConstKronVector &v, int i); + int + getM() const + { + return m; + } + int + getN() const + { + return n; + } + int + getDepth() const + { + return depth; + } }; int power(int m, int depth); diff --git a/dynare++/sylv/cc/QuasiTriangular.h b/dynare++/sylv/cc/QuasiTriangular.h index ff7281141912a1c9e8d15a32e54090ad5f365573..d09fede07021373f32389ee2bb204c01943c4bae 100644 --- a/dynare++/sylv/cc/QuasiTriangular.h +++ b/dynare++/sylv/cc/QuasiTriangular.h @@ -15,325 +15,521 @@ using namespace std; class DiagonalBlock; class Diagonal; -class DiagPair { +class DiagPair +{ private: - double* a1; - double* a2; + double *a1; + double *a2; public: - DiagPair() {} - DiagPair(double* aa1, double* aa2) {a1 = aa1; a2 = aa2;} - DiagPair(const DiagPair& p) {a1 = p.a1; a2 = p.a2;} - const DiagPair& operator=(const DiagPair& p) {a1 = p.a1; a2 = p.a2; return *this;} - const DiagPair& operator=(double v) {*a1 = v; *a2 = v; return *this;} - const double& operator*() const {return *a1;} - /** here we must not define double& operator*(), since it wouldn't - rewrite both values, we use operator= for this */ - friend class Diagonal; - friend class DiagonalBlock; + DiagPair() + { + } + DiagPair(double *aa1, double *aa2) + { + a1 = aa1; a2 = aa2; + } + DiagPair(const DiagPair &p) + { + a1 = p.a1; a2 = p.a2; + } + const DiagPair & + operator=(const DiagPair &p) + { + a1 = p.a1; a2 = p.a2; return *this; + } + const DiagPair & + operator=(double v) + { + *a1 = v; *a2 = v; return *this; + } + const double & + operator*() const + { + return *a1; + } + /** here we must not define double& operator*(), since it wouldn't + rewrite both values, we use operator= for this */ + friend class Diagonal; + friend class DiagonalBlock; }; -class DiagonalBlock { +class DiagonalBlock +{ private: - int jbar; - bool real; - DiagPair alpha; - double* beta1; - double* beta2; + int jbar; + bool real; + DiagPair alpha; + double *beta1; + double *beta2; - void copy(const DiagonalBlock& b) { - jbar = b.jbar; - real = b.real; - alpha = b.alpha; - beta1 = b.beta1; - beta2 = b.beta2; - } + void + copy(const DiagonalBlock &b) + { + jbar = b.jbar; + real = b.real; + alpha = b.alpha; + beta1 = b.beta1; + beta2 = b.beta2; + } public: - DiagonalBlock() {} - DiagonalBlock(int jb, bool r, double* a1, double* a2, - double* b1, double* b2) - : alpha(a1, a2) - { - jbar = jb; - real = r; - beta1 = b1; - beta2 = b2; - } - // construct complex block - DiagonalBlock(int jb, double* a1, double* a2) - : alpha(a1, a2) - { - jbar = jb; - real = false; - beta1 = a2 - 1; - beta2 = a1 + 1; - } - // construct real block - DiagonalBlock(int jb, double* a1) - : alpha(a1, a1) - { - jbar = jb; - real = true; - beta1 = 0; - beta2 = 0; - } - DiagonalBlock(const DiagonalBlock& b) - {copy(b);} - const DiagonalBlock& operator=(const DiagonalBlock& b) - {copy(b); return *this;} - int getIndex() const - {return jbar;} - bool isReal() const - {return real;} - const DiagPair& getAlpha() const - {return alpha;} - DiagPair& getAlpha() - {return alpha;} - double& getBeta1() const - {return *beta1;} - double& getBeta2() const - {return *beta2;} - double getDeterminant() const; - double getSBeta() const; - double getSize() const; - void setReal(); - // for debugging - void checkBlock(const double* d, int d_size); - friend class Diagonal; + DiagonalBlock() + { + } + DiagonalBlock(int jb, bool r, double *a1, double *a2, + double *b1, double *b2) + : alpha(a1, a2) + { + jbar = jb; + real = r; + beta1 = b1; + beta2 = b2; + } + // construct complex block + DiagonalBlock(int jb, double *a1, double *a2) + : alpha(a1, a2) + { + jbar = jb; + real = false; + beta1 = a2 - 1; + beta2 = a1 + 1; + } + // construct real block + DiagonalBlock(int jb, double *a1) + : alpha(a1, a1) + { + jbar = jb; + real = true; + beta1 = 0; + beta2 = 0; + } + DiagonalBlock(const DiagonalBlock &b) + { + copy(b); + } + const DiagonalBlock & + operator=(const DiagonalBlock &b) + { + copy(b); return *this; + } + int + getIndex() const + { + return jbar; + } + bool + isReal() const + { + return real; + } + const DiagPair & + getAlpha() const + { + return alpha; + } + DiagPair & + getAlpha() + { + return alpha; + } + double & + getBeta1() const + { + return *beta1; + } + double & + getBeta2() const + { + return *beta2; + } + double getDeterminant() const; + double getSBeta() const; + double getSize() const; + void setReal(); + // for debugging + void checkBlock(const double *d, int d_size); + friend class Diagonal; }; template <class _Tdiag, class _Tblock, class _Titer> -struct _diag_iter { - typedef _diag_iter<_Tdiag, _Tblock, _Titer> _Self; - _Tdiag diag; - _Titer it; +struct _diag_iter +{ + typedef _diag_iter<_Tdiag, _Tblock, _Titer> _Self; + _Tdiag diag; + _Titer it; public: - _diag_iter(_Tdiag d, _Titer iter) : diag(d), it(iter) {} - _Tblock operator*() const {return *it;} - _Self& operator++() {++it; return *this;} - _Self& operator--() {--it; return *this;} - bool operator==(const _Self& x) const {return x.it == it;} - bool operator!=(const _Self& x) const {return x.it != it;} - const _Self& operator=(const _Self& x) {it = x.it; return *this;} - _Titer iter() const {return it;} + _diag_iter(_Tdiag d, _Titer iter) : diag(d), it(iter) + { + } + _Tblock + operator*() const + { + return *it; + } + _Self & + operator++() + { + ++it; return *this; + } + _Self & + operator--() + { + --it; return *this; + } + bool + operator==(const _Self &x) const + { + return x.it == it; + } + bool + operator!=(const _Self &x) const + { + return x.it != it; + } + const _Self & + operator=(const _Self &x) + { + it = x.it; return *this; + } + _Titer + iter() const + { + return it; + } }; -class Diagonal { +class Diagonal +{ public: - typedef _diag_iter<const Diagonal&, const DiagonalBlock&, list<DiagonalBlock>::const_iterator> const_diag_iter; - typedef _diag_iter<Diagonal&, DiagonalBlock&, list<DiagonalBlock>::iterator> diag_iter; + typedef _diag_iter<const Diagonal &, const DiagonalBlock &, list<DiagonalBlock>::const_iterator> const_diag_iter; + typedef _diag_iter<Diagonal &, DiagonalBlock &, list<DiagonalBlock>::iterator> diag_iter; private: - int num_all; - list<DiagonalBlock> blocks; - int num_real; - void copy(const Diagonal&); + int num_all; + list<DiagonalBlock> blocks; + int num_real; + void copy(const Diagonal &); public: - Diagonal() : num_all(0), num_real(0) {} - Diagonal(double* data, int d_size); - Diagonal(double* data, const Diagonal& d); - Diagonal(const Diagonal& d) {copy(d);} - const Diagonal& operator =(const Diagonal& d) {copy(d); return *this;} - virtual ~Diagonal() {} + Diagonal() : num_all(0), num_real(0) + { + } + Diagonal(double *data, int d_size); + Diagonal(double *data, const Diagonal &d); + Diagonal(const Diagonal &d) + { + copy(d); + } + const Diagonal & + operator=(const Diagonal &d) + { + copy(d); return *this; + } + virtual ~Diagonal() + { + } - int getNumComplex() const {return num_all - num_real;} - int getNumReal() const {return num_real;} - int getSize() const {return getNumReal() + 2*getNumComplex();} - int getNumBlocks() const {return num_all;} - void getEigenValues(Vector& eig) const; - void swapLogically(diag_iter it); - void checkConsistency(diag_iter it); - double getAverageSize(diag_iter start, diag_iter end); - diag_iter findClosestBlock(diag_iter start, diag_iter end, double a); - diag_iter findNextLargerBlock(diag_iter start, diag_iter end, double a); - void print() const; + int + getNumComplex() const + { + return num_all - num_real; + } + int + getNumReal() const + { + return num_real; + } + int + getSize() const + { + return getNumReal() + 2*getNumComplex(); + } + int + getNumBlocks() const + { + return num_all; + } + void getEigenValues(Vector &eig) const; + void swapLogically(diag_iter it); + void checkConsistency(diag_iter it); + double getAverageSize(diag_iter start, diag_iter end); + diag_iter findClosestBlock(diag_iter start, diag_iter end, double a); + diag_iter findNextLargerBlock(diag_iter start, diag_iter end, double a); + void print() const; - diag_iter begin() - {return diag_iter(*this, blocks.begin());} - const_diag_iter begin() const - {return const_diag_iter(*this, blocks.begin());} - diag_iter end() - {return diag_iter(*this, blocks.end());} - const_diag_iter end() const - {return const_diag_iter(*this, blocks.end());} + diag_iter + begin() + { + return diag_iter(*this, blocks.begin()); + } + const_diag_iter + begin() const + { + return const_diag_iter(*this, blocks.begin()); + } + diag_iter + end() + { + return diag_iter(*this, blocks.end()); + } + const_diag_iter + end() const + { + return const_diag_iter(*this, blocks.end()); + } - /* redefine pointers as data start at p */ - void changeBase(double* p); + /* redefine pointers as data start at p */ + void changeBase(double *p); private: - static double EPS; - static int getNumComplex(const double* data, int d_size); - static bool isZero(double p); + static double EPS; + static int getNumComplex(const double *data, int d_size); + static bool isZero(double p); }; template <class _TRef, class _TPtr> -struct _matrix_iter { - typedef _matrix_iter<_TRef, _TPtr> _Self; - int d_size; - bool real; - _TPtr ptr; +struct _matrix_iter +{ + typedef _matrix_iter<_TRef, _TPtr> _Self; + int d_size; + bool real; + _TPtr ptr; public: - _matrix_iter(_TPtr base, int ds, bool r) - {ptr = base; d_size = ds; real = r;} - virtual ~_matrix_iter() {} - const _Self& operator=(const _Self& it) - {ptr = it.ptr; d_size = it.d_size; real = it.real; return *this;} - bool operator==(const _Self& it) const - {return ptr == it.ptr;} - bool operator!=(const _Self& it) const - {return ptr != it.ptr;} - _TRef operator*() const - {return *ptr;} - _TRef a() const - {return *ptr;} - virtual _Self& operator++() =0; + _matrix_iter(_TPtr base, int ds, bool r) + { + ptr = base; d_size = ds; real = r; + } + virtual ~_matrix_iter() + { + } + const _Self & + operator=(const _Self &it) + { + ptr = it.ptr; d_size = it.d_size; real = it.real; return *this; + } + bool + operator==(const _Self &it) const + { + return ptr == it.ptr; + } + bool + operator!=(const _Self &it) const + { + return ptr != it.ptr; + } + _TRef + operator*() const + { + return *ptr; + } + _TRef + a() const + { + return *ptr; + } + virtual _Self &operator++() = 0; }; template <class _TRef, class _TPtr> -class _column_iter : public _matrix_iter<_TRef, _TPtr> { - typedef _matrix_iter<_TRef, _TPtr> _Tparent; - typedef _column_iter<_TRef, _TPtr> _Self; - int row; +class _column_iter : public _matrix_iter<_TRef, _TPtr> +{ + typedef _matrix_iter<_TRef, _TPtr> _Tparent; + typedef _column_iter<_TRef, _TPtr> _Self; + int row; public: - _column_iter(_TPtr base, int ds, bool r, int rw) - : _matrix_iter<_TRef, _TPtr>(base, ds, r), row(rw) {}; - _Self& operator++() - {_Tparent::ptr++; row++; return *this;} - _TRef b() const - { - if (_Tparent::real) { - return *(_Tparent::ptr); - } else { - return *(_Tparent::ptr+_Tparent::d_size); - } - } - int getRow() const {return row;} + _column_iter(_TPtr base, int ds, bool r, int rw) + : _matrix_iter<_TRef, _TPtr>(base, ds, r), row(rw) + { + }; + _Self & + operator++() + { + _Tparent::ptr++; row++; return *this; + } + _TRef + b() const + { + if (_Tparent::real) + { + return *(_Tparent::ptr); + } + else + { + return *(_Tparent::ptr+_Tparent::d_size); + } + } + int + getRow() const + { + return row; + } }; template <class _TRef, class _TPtr> -class _row_iter : public _matrix_iter<_TRef, _TPtr> { - typedef _matrix_iter<_TRef, _TPtr> _Tparent; - typedef _row_iter<_TRef, _TPtr> _Self; - int col; +class _row_iter : public _matrix_iter<_TRef, _TPtr> +{ + typedef _matrix_iter<_TRef, _TPtr> _Tparent; + typedef _row_iter<_TRef, _TPtr> _Self; + int col; public: - _row_iter(_TPtr base, int ds, bool r, int cl) - : _matrix_iter<_TRef, _TPtr>(base, ds, r), col(cl) {}; - _Self& operator++() - {_Tparent::ptr += _Tparent::d_size; col++; return *this;} - virtual _TRef b() const - { - if (_Tparent::real) { - return *(_Tparent::ptr); - }else { - return *(_Tparent::ptr+1); - } - } - int getCol() const {return col;} + _row_iter(_TPtr base, int ds, bool r, int cl) + : _matrix_iter<_TRef, _TPtr>(base, ds, r), col(cl) + { + }; + _Self & + operator++() + { + _Tparent::ptr += _Tparent::d_size; col++; return *this; + } + virtual _TRef + b() const + { + if (_Tparent::real) + { + return *(_Tparent::ptr); + } + else + { + return *(_Tparent::ptr+1); + } + } + int + getCol() const + { + return col; + } }; class SchurDecomp; class SchurDecompZero; -class QuasiTriangular : public SqSylvMatrix { +class QuasiTriangular : public SqSylvMatrix +{ public: - typedef _column_iter<const double&, const double*> const_col_iter; - typedef _column_iter<double&, double*> col_iter; - typedef _row_iter<const double&, const double*> const_row_iter; - typedef _row_iter<double&, double*> row_iter; - typedef Diagonal::const_diag_iter const_diag_iter; - typedef Diagonal::diag_iter diag_iter; + typedef _column_iter<const double &, const double *> const_col_iter; + typedef _column_iter<double &, double *> col_iter; + typedef _row_iter<const double &, const double *> const_row_iter; + typedef _row_iter<double &, double *> row_iter; + typedef Diagonal::const_diag_iter const_diag_iter; + typedef Diagonal::diag_iter diag_iter; protected: - Diagonal diagonal; + Diagonal diagonal; public: - QuasiTriangular(const double* d, int d_size); - QuasiTriangular(double r, const QuasiTriangular& t); - QuasiTriangular(double r, const QuasiTriangular& t, - double rr, const QuasiTriangular& tt); - QuasiTriangular(int p, const QuasiTriangular& t); - QuasiTriangular(const SchurDecomp& decomp); - QuasiTriangular(const SchurDecompZero& decomp); - QuasiTriangular(const QuasiTriangular& t); - virtual ~QuasiTriangular(); - const Diagonal& getDiagonal() const {return diagonal;} - int getNumOffdiagonal() const; - void swapDiagLogically(diag_iter it); - void checkDiagConsistency(diag_iter it); - double getAverageDiagSize(diag_iter start, diag_iter end); - diag_iter findClosestDiagBlock(diag_iter start, diag_iter end, double a); - diag_iter findNextLargerBlock(diag_iter start, diag_iter end, double a); + QuasiTriangular(const double *d, int d_size); + QuasiTriangular(double r, const QuasiTriangular &t); + QuasiTriangular(double r, const QuasiTriangular &t, + double rr, const QuasiTriangular &tt); + QuasiTriangular(int p, const QuasiTriangular &t); + QuasiTriangular(const SchurDecomp &decomp); + QuasiTriangular(const SchurDecompZero &decomp); + QuasiTriangular(const QuasiTriangular &t); + virtual + ~QuasiTriangular(); + const Diagonal & + getDiagonal() const + { + return diagonal; + } + int getNumOffdiagonal() const; + void swapDiagLogically(diag_iter it); + void checkDiagConsistency(diag_iter it); + double getAverageDiagSize(diag_iter start, diag_iter end); + diag_iter findClosestDiagBlock(diag_iter start, diag_iter end, double a); + diag_iter findNextLargerBlock(diag_iter start, diag_iter end, double a); + /* (I+T)y = x, y-->x */ + virtual void solvePre(Vector &x, double &eig_min); + /* (I+T')y = x, y-->x */ + virtual void solvePreTrans(Vector &x, double &eig_min); + /* (I+T)x = b */ + virtual void solve(Vector &x, const ConstVector &b, double &eig_min); + /* (I+T')x = b */ + virtual void solveTrans(Vector &x, const ConstVector &b, double &eig_min); + /* x = Tb */ + virtual void multVec(Vector &x, const ConstVector &b) const; + /* x = T'b */ + virtual void multVecTrans(Vector &x, const ConstVector &b) const; + /* x = x + Tb */ + virtual void multaVec(Vector &x, const ConstVector &b) const; + /* x = x + T'b */ + virtual void multaVecTrans(Vector &x, const ConstVector &b) const; + /* x = (T\otimes I)x */ + virtual void multKron(KronVector &x) const; + /* x = (T'\otimes I)x */ + virtual void multKronTrans(KronVector &x) const; + /* A = T*A */ + virtual void multLeftOther(GeneralMatrix &a) const; + /* A = T'*A */ + virtual void multLeftOtherTrans(GeneralMatrix &a) const; - /* (I+T)y = x, y-->x */ - virtual void solvePre(Vector& x, double& eig_min); - /* (I+T')y = x, y-->x */ - virtual void solvePreTrans(Vector& x, double& eig_min); - /* (I+T)x = b */ - virtual void solve(Vector& x, const ConstVector& b, double& eig_min); - /* (I+T')x = b */ - virtual void solveTrans(Vector& x, const ConstVector& b, double& eig_min); - /* x = Tb */ - virtual void multVec(Vector& x, const ConstVector& b) const; - /* x = T'b */ - virtual void multVecTrans(Vector& x, const ConstVector& b) const; - /* x = x + Tb */ - virtual void multaVec(Vector& x, const ConstVector& b) const; - /* x = x + T'b */ - virtual void multaVecTrans(Vector& x, const ConstVector& b) const; - /* x = (T\otimes I)x */ - virtual void multKron(KronVector& x) const; - /* x = (T'\otimes I)x */ - virtual void multKronTrans(KronVector& x) const; - /* A = T*A */ - virtual void multLeftOther(GeneralMatrix& a) const; - /* A = T'*A */ - virtual void multLeftOtherTrans(GeneralMatrix& a) const; + const_diag_iter + diag_begin() const + { + return diagonal.begin(); + } + diag_iter + diag_begin() + { + return diagonal.begin(); + } + const_diag_iter + diag_end() const + { + return diagonal.end(); + } + diag_iter + diag_end() + { + return diagonal.end(); + } - const_diag_iter diag_begin() const - {return diagonal.begin();} - diag_iter diag_begin() - {return diagonal.begin();} - const_diag_iter diag_end() const - {return diagonal.end();} - diag_iter diag_end() - {return diagonal.end();} + /* iterators for off diagonal elements */ + virtual const_col_iter col_begin(const DiagonalBlock &b) const; + virtual col_iter col_begin(const DiagonalBlock &b); + virtual const_row_iter row_begin(const DiagonalBlock &b) const; + virtual row_iter row_begin(const DiagonalBlock &b); + virtual const_col_iter col_end(const DiagonalBlock &b) const; + virtual col_iter col_end(const DiagonalBlock &b); + virtual const_row_iter row_end(const DiagonalBlock &b) const; + virtual row_iter row_end(const DiagonalBlock &b); - /* iterators for off diagonal elements */ - virtual const_col_iter col_begin(const DiagonalBlock& b) const; - virtual col_iter col_begin(const DiagonalBlock& b); - virtual const_row_iter row_begin(const DiagonalBlock& b) const; - virtual row_iter row_begin(const DiagonalBlock& b); - virtual const_col_iter col_end(const DiagonalBlock& b) const; - virtual col_iter col_end(const DiagonalBlock& b); - virtual const_row_iter row_end(const DiagonalBlock& b) const; - virtual row_iter row_end(const DiagonalBlock& b); - - /* clone */ - virtual QuasiTriangular* clone() const - {return new QuasiTriangular(*this);} - virtual QuasiTriangular* clone(int p, const QuasiTriangular& t) const - {return new QuasiTriangular(p, t);} - virtual QuasiTriangular* clone(double r) const - {return new QuasiTriangular(r, *this);} - virtual QuasiTriangular* clone(double r, double rr, const QuasiTriangular& tt) const - {return new QuasiTriangular(r, *this, rr, tt);} + /* clone */ + virtual QuasiTriangular * + clone() const + { + return new QuasiTriangular(*this); + } + virtual QuasiTriangular * + clone(int p, const QuasiTriangular &t) const + { + return new QuasiTriangular(p, t); + } + virtual QuasiTriangular * + clone(double r) const + { + return new QuasiTriangular(r, *this); + } + virtual QuasiTriangular * + clone(double r, double rr, const QuasiTriangular &tt) const + { + return new QuasiTriangular(r, *this, rr, tt); + } protected: - void setMatrix(double r, const QuasiTriangular& t); - void addMatrix(double r, const QuasiTriangular& t); + void setMatrix(double r, const QuasiTriangular &t); + void addMatrix(double r, const QuasiTriangular &t); private: - void addUnit(); - /* x = x + (T\otimes I)b */ - void multaKron(KronVector& x, const ConstKronVector& b) const; - /* x = x + (T'\otimes I)b */ - void multaKronTrans(KronVector& x, const ConstKronVector& b) const; - /* implementation via iterators, useful for large matrices */ - void setMatrixViaIter(double r, const QuasiTriangular& t); - void addMatrixViaIter(double r, const QuasiTriangular& t); - /* hide noneffective implementations of parents */ - void multsVec(Vector& x, const ConstVector& d) const; - void multsVecTrans(Vector& x, const ConstVector& d) const; + void addUnit(); + /* x = x + (T\otimes I)b */ + void multaKron(KronVector &x, const ConstKronVector &b) const; + /* x = x + (T'\otimes I)b */ + void multaKronTrans(KronVector &x, const ConstKronVector &b) const; + /* implementation via iterators, useful for large matrices */ + void setMatrixViaIter(double r, const QuasiTriangular &t); + void addMatrixViaIter(double r, const QuasiTriangular &t); + /* hide noneffective implementations of parents */ + void multsVec(Vector &x, const ConstVector &d) const; + void multsVecTrans(Vector &x, const ConstVector &d) const; }; #endif /* QUASI_TRIANGULAR_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/QuasiTriangularZero.h b/dynare++/sylv/cc/QuasiTriangularZero.h index 6396eed18e00d7582162336fcc9b85ab31d7505d..243c02123f5ee6fcf05c9d6dc106c6fbf77b8fc7 100644 --- a/dynare++/sylv/cc/QuasiTriangularZero.h +++ b/dynare++/sylv/cc/QuasiTriangularZero.h @@ -8,37 +8,50 @@ #include "QuasiTriangular.h" #include "GeneralMatrix.h" -class QuasiTriangularZero : public QuasiTriangular { - int nz; // number of zero columns - GeneralMatrix ru; // data in right upper part (nz,d_size) +class QuasiTriangularZero : public QuasiTriangular +{ + int nz; // number of zero columns + GeneralMatrix ru; // data in right upper part (nz,d_size) public: - QuasiTriangularZero(int num_zeros, const double* d, int d_size); - QuasiTriangularZero(double r, const QuasiTriangularZero& t); - QuasiTriangularZero(double r, const QuasiTriangularZero& t, - double rr, const QuasiTriangularZero& tt); - QuasiTriangularZero(int p, const QuasiTriangularZero& t); - QuasiTriangularZero(const QuasiTriangular& t); - QuasiTriangularZero(const SchurDecompZero& decomp); - ~QuasiTriangularZero(); - void solvePre(Vector& x, double& eig_min); - void solvePreTrans(Vector& x, double& eig_min); - void multVec(Vector& x, const ConstVector& b) const; - void multVecTrans(Vector& x, const ConstVector& b) const; - void multaVec(Vector& x, const ConstVector& b) const; - void multaVecTrans(Vector& x, const ConstVector& b) const; - void multKron(KronVector& x) const; - void multKronTrans(KronVector& x) const; - void multLeftOther(GeneralMatrix& a) const; - /* clone */ - virtual QuasiTriangular* clone() const - {return new QuasiTriangularZero(*this);} - virtual QuasiTriangular* clone(int p, const QuasiTriangular& t) const - {return new QuasiTriangularZero(p, (const QuasiTriangularZero&)t);} - virtual QuasiTriangular* clone(double r) const - {return new QuasiTriangularZero(r, *this);} - virtual QuasiTriangular* clone(double r, double rr, const QuasiTriangular& tt) const - {return new QuasiTriangularZero(r, *this, rr, (const QuasiTriangularZero&)tt);} - void print() const; + QuasiTriangularZero(int num_zeros, const double *d, int d_size); + QuasiTriangularZero(double r, const QuasiTriangularZero &t); + QuasiTriangularZero(double r, const QuasiTriangularZero &t, + double rr, const QuasiTriangularZero &tt); + QuasiTriangularZero(int p, const QuasiTriangularZero &t); + QuasiTriangularZero(const QuasiTriangular &t); + QuasiTriangularZero(const SchurDecompZero &decomp); + ~QuasiTriangularZero(); + void solvePre(Vector &x, double &eig_min); + void solvePreTrans(Vector &x, double &eig_min); + void multVec(Vector &x, const ConstVector &b) const; + void multVecTrans(Vector &x, const ConstVector &b) const; + void multaVec(Vector &x, const ConstVector &b) const; + void multaVecTrans(Vector &x, const ConstVector &b) const; + void multKron(KronVector &x) const; + void multKronTrans(KronVector &x) const; + void multLeftOther(GeneralMatrix &a) const; + /* clone */ + virtual QuasiTriangular * + clone() const + { + return new QuasiTriangularZero(*this); + } + virtual QuasiTriangular * + clone(int p, const QuasiTriangular &t) const + { + return new QuasiTriangularZero(p, (const QuasiTriangularZero &) t); + } + virtual QuasiTriangular * + clone(double r) const + { + return new QuasiTriangularZero(r, *this); + } + virtual QuasiTriangular * + clone(double r, double rr, const QuasiTriangular &tt) const + { + return new QuasiTriangularZero(r, *this, rr, (const QuasiTriangularZero &) tt); + } + void print() const; }; #endif /* QUASI_TRIANGULAR_ZERO_H */ diff --git a/dynare++/sylv/cc/SchurDecomp.h b/dynare++/sylv/cc/SchurDecomp.h index 644e5d5c5c1233781c6a03404539dddebffd340f..9e83c92219269003bc6f552ec8d8bff0ebd1649e 100644 --- a/dynare++/sylv/cc/SchurDecomp.h +++ b/dynare++/sylv/cc/SchurDecomp.h @@ -9,35 +9,61 @@ #include "QuasiTriangular.h" class QuasiTriangular; -class SchurDecomp { - bool q_destroy; - SqSylvMatrix* q; - bool t_destroy; - QuasiTriangular* t; +class SchurDecomp +{ + bool q_destroy; + SqSylvMatrix *q; + bool t_destroy; + QuasiTriangular *t; public: - SchurDecomp(const SqSylvMatrix& m); - SchurDecomp(const QuasiTriangular& tr); - SchurDecomp(QuasiTriangular& tr); - const SqSylvMatrix& getQ() const {return *q;} - const QuasiTriangular& getT() const {return *t;} - SqSylvMatrix& getQ() {return *q;} - QuasiTriangular& getT() {return *t;} - virtual int getDim() const; - virtual ~SchurDecomp(); + SchurDecomp(const SqSylvMatrix &m); + SchurDecomp(const QuasiTriangular &tr); + SchurDecomp(QuasiTriangular &tr); + const SqSylvMatrix & + getQ() const + { + return *q; + } + const QuasiTriangular & + getT() const + { + return *t; + } + SqSylvMatrix & + getQ() + { + return *q; + } + QuasiTriangular & + getT() + { + return *t; + } + virtual int getDim() const; + virtual + ~SchurDecomp(); }; -class SchurDecompZero : public SchurDecomp { - GeneralMatrix ru; /* right upper matrix */ +class SchurDecompZero : public SchurDecomp +{ + GeneralMatrix ru; /* right upper matrix */ public: - SchurDecompZero(const GeneralMatrix& m); - const GeneralMatrix& getRU() const {return ru;} - int getDim() const; - int getZeroCols() const {return ru.numRows();} + SchurDecompZero(const GeneralMatrix &m); + const GeneralMatrix & + getRU() const + { + return ru; + } + int getDim() const; + int + getZeroCols() const + { + return ru.numRows(); + } }; #endif /* SCHUR_DECOMP_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/SchurDecompEig.h b/dynare++/sylv/cc/SchurDecompEig.h index 0e0da38d5c83ff2c455528ecb2258f9415f52aac..567f457831acd4a8f22fac71c9e575b89b675f37 100644 --- a/dynare++/sylv/cc/SchurDecompEig.h +++ b/dynare++/sylv/cc/SchurDecompEig.h @@ -10,22 +10,27 @@ #include "SchurDecomp.h" #include "QuasiTriangular.h" -class SchurDecompEig : public SchurDecomp { +class SchurDecompEig : public SchurDecomp +{ public: - typedef QuasiTriangular::diag_iter diag_iter; - SchurDecompEig(const SqSylvMatrix& m) : SchurDecomp(m) {} - SchurDecompEig(const QuasiTriangular& tr) : SchurDecomp(tr) {}; - SchurDecompEig(QuasiTriangular& tr) : SchurDecomp(tr) {} - diag_iter bubbleEigen(diag_iter from, diag_iter to); - void orderEigen(); + typedef QuasiTriangular::diag_iter diag_iter; + SchurDecompEig(const SqSylvMatrix &m) : SchurDecomp(m) + { + } + SchurDecompEig(const QuasiTriangular &tr) : SchurDecomp(tr) + { + }; + SchurDecompEig(QuasiTriangular &tr) : SchurDecomp(tr) + { + } + diag_iter bubbleEigen(diag_iter from, diag_iter to); + void orderEigen(); protected: - bool tryToSwap(diag_iter& it, diag_iter& itadd); + bool tryToSwap(diag_iter &it, diag_iter &itadd); }; #endif /* SCHUR_DECOMP_EIG_H */ - // Local Variables: // mode:C++ // End: - diff --git a/dynare++/sylv/cc/SimilarityDecomp.h b/dynare++/sylv/cc/SimilarityDecomp.h index 14f79297a21656827f7173b68fc92954bf4c1a2d..107da24e0cc2dfa43ea2b12d78a818e5938ab868 100644 --- a/dynare++/sylv/cc/SimilarityDecomp.h +++ b/dynare++/sylv/cc/SimilarityDecomp.h @@ -9,33 +9,43 @@ #include "BlockDiagonal.h" #include "SylvParams.h" -class SimilarityDecomp { - SqSylvMatrix* q; - BlockDiagonal* b; - SqSylvMatrix* invq; - typedef BlockDiagonal::diag_iter diag_iter; +class SimilarityDecomp +{ + SqSylvMatrix *q; + BlockDiagonal *b; + SqSylvMatrix *invq; + typedef BlockDiagonal::diag_iter diag_iter; public: - SimilarityDecomp(const double* d, int d_size, double log10norm = 3.0); - virtual ~SimilarityDecomp(); - const SqSylvMatrix& getQ() const - {return *q;} - const SqSylvMatrix& getInvQ() const - {return *invq;} - const BlockDiagonal& getB() const - {return *b;} - void check(SylvParams& pars, const GeneralMatrix& m) const; - void infoToPars(SylvParams& pars) const; + SimilarityDecomp(const double *d, int d_size, double log10norm = 3.0); + virtual + ~SimilarityDecomp(); + const SqSylvMatrix & + getQ() const + { + return *q; + } + const SqSylvMatrix & + getInvQ() const + { + return *invq; + } + const BlockDiagonal & + getB() const + { + return *b; + } + void check(SylvParams &pars, const GeneralMatrix &m) const; + void infoToPars(SylvParams &pars) const; protected: - void getXDim(diag_iter start, diag_iter end, int& rows, int& cols) const; - bool solveX(diag_iter start, diag_iter end, GeneralMatrix& X, double norm) const; - void updateTransform(diag_iter start, diag_iter end, GeneralMatrix& X); - void bringGuiltyBlock(diag_iter start, diag_iter& end); - void diagonalize(double norm); + void getXDim(diag_iter start, diag_iter end, int &rows, int &cols) const; + bool solveX(diag_iter start, diag_iter end, GeneralMatrix &X, double norm) const; + void updateTransform(diag_iter start, diag_iter end, GeneralMatrix &X); + void bringGuiltyBlock(diag_iter start, diag_iter &end); + void diagonalize(double norm); }; #endif /* SIMILARITY_DECOMP_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/SylvException.h b/dynare++/sylv/cc/SylvException.h index f3c22338a673772f3dfb531d6b369a45e8597671..5beb212a370a7d9f20b73f1f5c2b0c010eba6977 100644 --- a/dynare++/sylv/cc/SylvException.h +++ b/dynare++/sylv/cc/SylvException.h @@ -7,33 +7,34 @@ #include "SylvMemory.h" - -class SylvException : public MallocAllocator { +class SylvException : public MallocAllocator +{ protected: - char file[50]; - int line; - const SylvException* source; + char file[50]; + int line; + const SylvException *source; public: - SylvException(const char* f, int l, const SylvException* s); - virtual ~SylvException(); - virtual int printMessage(char* str, int maxlen) const; - void printMessage() const; + SylvException(const char *f, int l, const SylvException *s); + virtual + ~SylvException(); + virtual int printMessage(char *str, int maxlen) const; + void printMessage() const; }; -class SylvExceptionMessage : public SylvException { - char message[500]; +class SylvExceptionMessage : public SylvException +{ + char message[500]; public: - SylvExceptionMessage(const char* f, int l, const char* mes); - virtual int printMessage(char* str, int maxlen) const; + SylvExceptionMessage(const char *f, int l, const char *mes); + virtual int printMessage(char *str, int maxlen) const; }; // define macros: #define SYLV_EXCEPTION(exc) (SylvException(__FILE__, __LINE__, exc)) -#define SYLV_MES_EXCEPTION(mes) (SylvExceptionMessage(__FILE__, __LINE__, mes)) +#define SYLV_MES_EXCEPTION(mes) (SylvExceptionMessage(__FILE__, __LINE__, mes)) #endif /* SYLV_EXCEPTION_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/SylvMatrix.h b/dynare++/sylv/cc/SylvMatrix.h index 99ab504ae0f62e3aa49122cb0bd4aa02594dfe51..063e6b30b75ba3e5a037a62bc5a895eb01162a57 100644 --- a/dynare++/sylv/cc/SylvMatrix.h +++ b/dynare++/sylv/cc/SylvMatrix.h @@ -10,72 +10,100 @@ class SqSylvMatrix; -class SylvMatrix : public GeneralMatrix { +class SylvMatrix : public GeneralMatrix +{ public: - SylvMatrix(int m, int n) - : GeneralMatrix(m,n) {} - SylvMatrix(const double* d, int m, int n) - : GeneralMatrix(d, m, n) {} - SylvMatrix(double* d, int m, int n) - : GeneralMatrix(d, m, n) {} - SylvMatrix(const GeneralMatrix& m) - : GeneralMatrix(m) {} - SylvMatrix(const GeneralMatrix& m, int i, int j, int nrows, int ncols) - : GeneralMatrix(m, i, j, nrows, ncols) {} - SylvMatrix(GeneralMatrix& m, int i, int j, int nrows, int ncols) - : GeneralMatrix(m, i, j, nrows, ncols) {} - SylvMatrix(const GeneralMatrix& a, const GeneralMatrix& b) - : GeneralMatrix(a, b) {} + SylvMatrix(int m, int n) + : GeneralMatrix(m, n) + { + } + SylvMatrix(const double *d, int m, int n) + : GeneralMatrix(d, m, n) + { + } + SylvMatrix(double *d, int m, int n) + : GeneralMatrix(d, m, n) + { + } + SylvMatrix(const GeneralMatrix &m) + : GeneralMatrix(m) + { + } + SylvMatrix(const GeneralMatrix &m, int i, int j, int nrows, int ncols) + : GeneralMatrix(m, i, j, nrows, ncols) + { + } + SylvMatrix(GeneralMatrix &m, int i, int j, int nrows, int ncols) + : GeneralMatrix(m, i, j, nrows, ncols) + { + } + SylvMatrix(const GeneralMatrix &a, const GeneralMatrix &b) + : GeneralMatrix(a, b) + { + } - /* this = |I 0|* this - |0 m| */ - void multLeftI(const SqSylvMatrix& m); - /* this = |I 0|* this - |0 m'| */ - void multLeftITrans(const SqSylvMatrix& m); - /* this = |0 a|*b, so that |0 a| is square */ - void multLeft(int zero_cols, const GeneralMatrix& a, const GeneralMatrix& b); - /* this = this * (m\otimes m..\otimes m) */ - void multRightKron(const SqSylvMatrix& m, int order); - /* this = this * (m'\otimes m'..\otimes m') */ - void multRightKronTrans(const SqSylvMatrix& m, int order); - /* this = P*this, x = P*x, where P is gauss transformation setting - * a given element to zero */ - void eliminateLeft(int row, int col, Vector& x); - /* this = this*P, x = P'*x, where P is gauss transformation setting - * a given element to zero */ - void eliminateRight(int row, int col, Vector& x); + /* this = |I 0|* this + |0 m| */ + void multLeftI(const SqSylvMatrix &m); + /* this = |I 0|* this + |0 m'| */ + void multLeftITrans(const SqSylvMatrix &m); + /* this = |0 a|*b, so that |0 a| is square */ + void multLeft(int zero_cols, const GeneralMatrix &a, const GeneralMatrix &b); + /* this = this * (m\otimes m..\otimes m) */ + void multRightKron(const SqSylvMatrix &m, int order); + /* this = this * (m'\otimes m'..\otimes m') */ + void multRightKronTrans(const SqSylvMatrix &m, int order); + /* this = P*this, x = P*x, where P is gauss transformation setting + * a given element to zero */ + void eliminateLeft(int row, int col, Vector &x); + /* this = this*P, x = P'*x, where P is gauss transformation setting + * a given element to zero */ + void eliminateRight(int row, int col, Vector &x); }; - -class SqSylvMatrix : public SylvMatrix { +class SqSylvMatrix : public SylvMatrix +{ public: - SqSylvMatrix(int m) : SylvMatrix(m, m) {} - SqSylvMatrix(const double* d, int m) : SylvMatrix(d, m, m) {} - SqSylvMatrix(double* d, int m) : SylvMatrix(d, m, m) {} - SqSylvMatrix(const SqSylvMatrix& m) : SylvMatrix(m) {} - SqSylvMatrix(const GeneralMatrix& m, int i, int j, int nrows) - : SylvMatrix(m, i, j, nrows, nrows) {} - SqSylvMatrix(GeneralMatrix& m, int i, int j, int nrows) - : SylvMatrix(m, i, j, nrows, nrows) {} - SqSylvMatrix(const GeneralMatrix& a, const GeneralMatrix& b); - const SqSylvMatrix& operator=(const SqSylvMatrix& m) - {GeneralMatrix::operator=(m); return *this;} - /* x = (this \otimes this..\otimes this)*d */ - void multVecKron(KronVector& x, const KronVector& d) const; - /* x = (this' \otimes this'..\otimes this')*d */ - void multVecKronTrans(KronVector& x, const KronVector& d) const; - /* a = inv(this)*a, b=inv(this)*b */ - void multInvLeft2(GeneralMatrix& a, GeneralMatrix& b, - double& rcond1, double& rcondinf) const; - /* this = I */ - void setUnit(); + SqSylvMatrix(int m) : SylvMatrix(m, m) + { + } + SqSylvMatrix(const double *d, int m) : SylvMatrix(d, m, m) + { + } + SqSylvMatrix(double *d, int m) : SylvMatrix(d, m, m) + { + } + SqSylvMatrix(const SqSylvMatrix &m) : SylvMatrix(m) + { + } + SqSylvMatrix(const GeneralMatrix &m, int i, int j, int nrows) + : SylvMatrix(m, i, j, nrows, nrows) + { + } + SqSylvMatrix(GeneralMatrix &m, int i, int j, int nrows) + : SylvMatrix(m, i, j, nrows, nrows) + { + } + SqSylvMatrix(const GeneralMatrix &a, const GeneralMatrix &b); + const SqSylvMatrix & + operator=(const SqSylvMatrix &m) + { + GeneralMatrix::operator=(m); return *this; + } + /* x = (this \otimes this..\otimes this)*d */ + void multVecKron(KronVector &x, const KronVector &d) const; + /* x = (this' \otimes this'..\otimes this')*d */ + void multVecKronTrans(KronVector &x, const KronVector &d) const; + /* a = inv(this)*a, b=inv(this)*b */ + void multInvLeft2(GeneralMatrix &a, GeneralMatrix &b, + double &rcond1, double &rcondinf) const; + /* this = I */ + void setUnit(); }; - #endif /* SYLV_MATRIX_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/SylvMemory.h b/dynare++/sylv/cc/SylvMemory.h index 187aac0b508b54941593220388f12cd154a2c38d..48a0fcd3dc095779c70d69f230ec0ed6369fa9c9 100644 --- a/dynare++/sylv/cc/SylvMemory.h +++ b/dynare++/sylv/cc/SylvMemory.h @@ -9,55 +9,57 @@ #include <new> -class MallocAllocator { +class MallocAllocator +{ #ifdef USE_MEMORY_POOL public: - void* operator new(size_t size); - void* operator new[](size_t size); - void operator delete(void* p); - void operator delete[](void* p); + void *operator new(size_t size); + void *operator new[](size_t size); + void operator delete(void *p); + void operator delete[](void *p); #endif }; #ifdef USE_MEMORY_POOL -void* operator new(size_t size); -void* operator new[](size_t size); -void operator delete(void* p); -void operator delete[](void* p); +void *operator new(size_t size); +void *operator new[](size_t size); +void operator delete(void *p); +void operator delete[](void *p); #endif -class SylvMemoryPool { - char* base; - size_t length; - size_t allocated; - bool stack_mode; - SylvMemoryPool(const SylvMemoryPool&); - const SylvMemoryPool& operator=(const SylvMemoryPool&); +class SylvMemoryPool +{ + char *base; + size_t length; + size_t allocated; + bool stack_mode; + SylvMemoryPool(const SylvMemoryPool &); + const SylvMemoryPool &operator=(const SylvMemoryPool &); public: - SylvMemoryPool(); - ~SylvMemoryPool(); - void init(size_t size); - void* allocate(size_t size); - void free(void* p); - void reset(); - void setStackMode(bool); + SylvMemoryPool(); + ~SylvMemoryPool(); + void init(size_t size); + void *allocate(size_t size); + void free(void *p); + void reset(); + void setStackMode(bool); }; -class SylvMemoryDriver { - SylvMemoryDriver(const SylvMemoryDriver&); - const SylvMemoryDriver& operator=(const SylvMemoryDriver&); +class SylvMemoryDriver +{ + SylvMemoryDriver(const SylvMemoryDriver &); + const SylvMemoryDriver &operator=(const SylvMemoryDriver &); public: - SylvMemoryDriver(int num_d, int m, int n, int order); - SylvMemoryDriver(const SylvParams& pars, int num_d, int m, int n, int order); - static void setStackMode(bool); - ~SylvMemoryDriver(); + SylvMemoryDriver(int num_d, int m, int n, int order); + SylvMemoryDriver(const SylvParams &pars, int num_d, int m, int n, int order); + static void setStackMode(bool); + ~SylvMemoryDriver(); protected: - void allocate(int num_d, int m, int n, int order); + void allocate(int num_d, int m, int n, int order); }; #endif /* SYLV_MEMORY_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/SylvParams.h b/dynare++/sylv/cc/SylvParams.h index beb292670472a3bd07b16ab51d955668cb0962a2..9b58e92e58118e63bf777b94d16f0fb0ed0bebe7 100644 --- a/dynare++/sylv/cc/SylvParams.h +++ b/dynare++/sylv/cc/SylvParams.h @@ -15,148 +15,217 @@ typedef enum {def, changed, undef} status; template <class _Type> -struct ParamItem { +struct ParamItem +{ protected: - typedef ParamItem<_Type> _Self; - status s; - _Type value; + typedef ParamItem<_Type> _Self; + status s; + _Type value; public: - ParamItem() - {s = undef;} - ParamItem(_Type val) - {value = val; s = def;} - ParamItem(const _Self& item) - {value = item.value; s = item.s;} - const _Self& operator=(const _Self& item) - {value = item.value; s = item.s; return *this;} - const _Self& operator=(const _Type& val) - {value = val; s = changed; return *this;} - _Type operator*() const - {return value;} - status getStatus() const - {return s;} - void print(FILE* f, const char* prefix, const char* str, const char* fmt) const - { - if (s == undef) - return; - char out[1000]; - strcpy(out, prefix); - strcat(out, str); - strcat(out, "= "); - strcat(out, fmt); - if (s == def) - strcat(out, " <default>"); - strcat(out,"\n"); - fprintf(f, out, value); - } + ParamItem() + { + s = undef; + } + ParamItem(_Type val) + { + value = val; s = def; + } + ParamItem(const _Self &item) + { + value = item.value; s = item.s; + } + const _Self & + operator=(const _Self &item) + { + value = item.value; s = item.s; return *this; + } + const _Self & + operator=(const _Type &val) + { + value = val; s = changed; return *this; + } + _Type + operator*() const + { + return value; + } + status + getStatus() const + { + return s; + } + void + print(FILE *f, const char *prefix, const char *str, const char *fmt) const + { + if (s == undef) + return; + char out[1000]; + strcpy(out, prefix); + strcat(out, str); + strcat(out, "= "); + strcat(out, fmt); + if (s == def) + strcat(out, " <default>"); + strcat(out, "\n"); + fprintf(f, out, value); + } }; -class SylvParams { +class SylvParams +{ public: - typedef enum {iter, recurse} solve_method; + typedef enum {iter, recurse} solve_method; protected: - class DoubleParamItem : public ParamItem<double> { - public: - DoubleParamItem() : ParamItem<double>() {} - DoubleParamItem(double val) : ParamItem<double>(val) {} - DoubleParamItem(const DoubleParamItem& item) : ParamItem<double>(item) {} - const DoubleParamItem& operator=(const double& val) - {ParamItem<double>::operator=(val); return *this;} + class DoubleParamItem : public ParamItem<double> + { + public: + DoubleParamItem() : ParamItem<double>() + { + } + DoubleParamItem(double val) : ParamItem<double>(val) + { + } + DoubleParamItem(const DoubleParamItem &item) : ParamItem<double>(item) + { + } + const DoubleParamItem & + operator=(const double &val) + { + ParamItem<double>::operator=(val); return *this; + } #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) - mxArray* createMatlabArray() const; + mxArray *createMatlabArray() const; #endif - }; - - class IntParamItem : public ParamItem<int> { - public: - IntParamItem() : ParamItem<int>() {} - IntParamItem(int val) : ParamItem<int>(val) {} - IntParamItem(const IntParamItem& item) : ParamItem<int>(item) {} - const IntParamItem& operator=(const int& val) - {ParamItem<int>::operator=(val); return *this;} + }; + + class IntParamItem : public ParamItem<int> + { + public: + IntParamItem() : ParamItem<int>() + { + } + IntParamItem(int val) : ParamItem<int>(val) + { + } + IntParamItem(const IntParamItem &item) : ParamItem<int>(item) + { + } + const IntParamItem & + operator=(const int &val) + { + ParamItem<int>::operator=(val); return *this; + } #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) - mxArray* createMatlabArray() const; + mxArray *createMatlabArray() const; #endif - }; - - class BoolParamItem : public ParamItem<bool> { - public: - BoolParamItem() : ParamItem<bool>() {} - BoolParamItem(bool val) : ParamItem<bool>(val) {} - BoolParamItem(const BoolParamItem& item) : ParamItem<bool>(item) {} - const BoolParamItem& operator=(const bool& val) - {ParamItem<bool>::operator=(val); return *this;} + }; + + class BoolParamItem : public ParamItem<bool> + { + public: + BoolParamItem() : ParamItem<bool>() + { + } + BoolParamItem(bool val) : ParamItem<bool>(val) + { + } + BoolParamItem(const BoolParamItem &item) : ParamItem<bool>(item) + { + } + const BoolParamItem & + operator=(const bool &val) + { + ParamItem<bool>::operator=(val); return *this; + } #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) - mxArray* createMatlabArray() const; + mxArray *createMatlabArray() const; #endif - }; - - class MethodParamItem : public ParamItem<solve_method> { - public: - MethodParamItem() : ParamItem<solve_method>() {} - MethodParamItem(solve_method val) : ParamItem<solve_method>(val) {} - MethodParamItem(const MethodParamItem& item) : ParamItem<solve_method>(item) {} - const MethodParamItem operator=(const solve_method& val) - {ParamItem<solve_method>::operator=(val); return *this;} + }; + + class MethodParamItem : public ParamItem<solve_method> + { + public: + MethodParamItem() : ParamItem<solve_method>() + { + } + MethodParamItem(solve_method val) : ParamItem<solve_method>(val) + { + } + MethodParamItem(const MethodParamItem &item) : ParamItem<solve_method>(item) + { + } + const MethodParamItem + operator=(const solve_method &val) + { + ParamItem<solve_method>::operator=(val); return *this; + } #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) - mxArray* createMatlabArray() const; + mxArray *createMatlabArray() const; #endif - }; + }; public: - // input parameters - MethodParamItem method; // method of solution: iter/recurse - DoubleParamItem convergence_tol; // norm for what we consider converged - IntParamItem max_num_iter; // max number of iterations - DoubleParamItem bs_norm; // Bavely Stewart log10 of norm for diagonalization - BoolParamItem want_check; // true => allocate extra space for checks - // output parameters - BoolParamItem converged; // true if converged - DoubleParamItem iter_last_norm; // norm of the last iteration - IntParamItem num_iter; // number of iterations - DoubleParamItem f_err1; // norm 1 of diagonalization abs. error C-V*F*inv(V) - DoubleParamItem f_errI; // norm Inf of diagonalization abs. error C-V*F*inv(V) - DoubleParamItem viv_err1; // norm 1 of error I-V*inv(V) - DoubleParamItem viv_errI; // norm Inf of error I-V*inv(V) - DoubleParamItem ivv_err1; // norm 1 of error I-inv(V)*V - DoubleParamItem ivv_errI; // norm Inf of error I-inv(V)*V - IntParamItem f_blocks; // number of diagonal blocks of F - IntParamItem f_largest; // size of largest diagonal block in F - IntParamItem f_zeros; // number of off diagonal zeros in F - IntParamItem f_offdiag; // number of all off diagonal elements in F - DoubleParamItem rcondA1; // reciprocal cond 1 number of A - DoubleParamItem rcondAI; // reciprocal cond Inf number of A - DoubleParamItem eig_min; // minimum eigenvalue of the solved system - DoubleParamItem mat_err1; // rel. matrix 1 norm of A*X-B*X*kron(C,..,C)-D - DoubleParamItem mat_errI; // rel. matrix Inf norm of A*X-B*X*kron(C,..,C)-D - DoubleParamItem mat_errF; // rel. matrix Frob. norm of A*X-B*X*kron(C,..,C)-D - DoubleParamItem vec_err1; // rel. vector 1 norm of A*X-B*X*kron(C,..,C)-D - DoubleParamItem vec_errI; // rel. vector Inf norm of A*X-B*X*kron(C,..,C)-D - DoubleParamItem cpu_time; // time of the job in CPU seconds - // note: remember to change copy() if adding/removing member - - SylvParams(bool wc = false) - : method(recurse), convergence_tol(1.e-30), max_num_iter(15), - bs_norm(1.3), want_check(wc) {} - SylvParams(const SylvParams& p) - {copy(p);} - const SylvParams& operator=(const SylvParams& p) - {copy(p); return *this;} - ~SylvParams() {} - void print(const char* prefix) const; - void print(FILE* fdesc, const char* prefix) const; - void setArrayNames(int& num, const char** names) const; + // input parameters + MethodParamItem method; // method of solution: iter/recurse + DoubleParamItem convergence_tol; // norm for what we consider converged + IntParamItem max_num_iter; // max number of iterations + DoubleParamItem bs_norm; // Bavely Stewart log10 of norm for diagonalization + BoolParamItem want_check; // true => allocate extra space for checks + // output parameters + BoolParamItem converged; // true if converged + DoubleParamItem iter_last_norm; // norm of the last iteration + IntParamItem num_iter; // number of iterations + DoubleParamItem f_err1; // norm 1 of diagonalization abs. error C-V*F*inv(V) + DoubleParamItem f_errI; // norm Inf of diagonalization abs. error C-V*F*inv(V) + DoubleParamItem viv_err1; // norm 1 of error I-V*inv(V) + DoubleParamItem viv_errI; // norm Inf of error I-V*inv(V) + DoubleParamItem ivv_err1; // norm 1 of error I-inv(V)*V + DoubleParamItem ivv_errI; // norm Inf of error I-inv(V)*V + IntParamItem f_blocks; // number of diagonal blocks of F + IntParamItem f_largest; // size of largest diagonal block in F + IntParamItem f_zeros; // number of off diagonal zeros in F + IntParamItem f_offdiag; // number of all off diagonal elements in F + DoubleParamItem rcondA1; // reciprocal cond 1 number of A + DoubleParamItem rcondAI; // reciprocal cond Inf number of A + DoubleParamItem eig_min; // minimum eigenvalue of the solved system + DoubleParamItem mat_err1; // rel. matrix 1 norm of A*X-B*X*kron(C,..,C)-D + DoubleParamItem mat_errI; // rel. matrix Inf norm of A*X-B*X*kron(C,..,C)-D + DoubleParamItem mat_errF; // rel. matrix Frob. norm of A*X-B*X*kron(C,..,C)-D + DoubleParamItem vec_err1; // rel. vector 1 norm of A*X-B*X*kron(C,..,C)-D + DoubleParamItem vec_errI; // rel. vector Inf norm of A*X-B*X*kron(C,..,C)-D + DoubleParamItem cpu_time; // time of the job in CPU seconds + // note: remember to change copy() if adding/removing member + + SylvParams(bool wc = false) + : method(recurse), convergence_tol(1.e-30), max_num_iter(15), + bs_norm(1.3), want_check(wc) + { + } + SylvParams(const SylvParams &p) + { + copy(p); + } + const SylvParams & + operator=(const SylvParams &p) + { + copy(p); return *this; + } + ~SylvParams() + { + } + void print(const char *prefix) const; + void print(FILE *fdesc, const char *prefix) const; + void setArrayNames(int &num, const char **names) const; #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) - mxArray* createStructArray() const; + mxArray *createStructArray() const; #endif private: - void copy(const SylvParams& p); + void copy(const SylvParams &p); }; #endif /* SYLV_PARAMS_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/SylvesterSolver.h b/dynare++/sylv/cc/SylvesterSolver.h index df9bcce4520476fbb131628967a3f3f5cea2322c..344abd12740edc668aae6eb132191fe802677a0a 100644 --- a/dynare++/sylv/cc/SylvesterSolver.h +++ b/dynare++/sylv/cc/SylvesterSolver.h @@ -12,40 +12,47 @@ #include "SylvParams.h" #include "SchurDecomp.h" -class SylvesterSolver { +class SylvesterSolver +{ protected: - const QuasiTriangular* const matrixK; - const QuasiTriangular* const matrixF; + const QuasiTriangular *const matrixK; + const QuasiTriangular *const matrixF; private: - /* return true when it is more efficient to use QuasiTriangular - * than QuasiTriangularZero */ - static bool zeroPad(const SchurDecompZero& kdecomp) { - return ((kdecomp.getZeroCols()*3 < kdecomp.getDim()*2) || - (kdecomp.getZeroCols() < 10)); - } + /* return true when it is more efficient to use QuasiTriangular + * than QuasiTriangularZero */ + static bool + zeroPad(const SchurDecompZero &kdecomp) + { + return ((kdecomp.getZeroCols()*3 < kdecomp.getDim()*2) + || (kdecomp.getZeroCols() < 10)); + } public: - SylvesterSolver(const QuasiTriangular& k, const QuasiTriangular& f) - : matrixK(new QuasiTriangular(k)), - matrixF(new QuasiTriangular(f)) - {} - SylvesterSolver(const SchurDecompZero& kdecomp, const SchurDecomp& fdecomp) - : matrixK((zeroPad(kdecomp)) ? - new QuasiTriangular(kdecomp) : new QuasiTriangularZero(kdecomp)), - matrixF(new QuasiTriangular(fdecomp)) - {} - SylvesterSolver(const SchurDecompZero& kdecomp, const SimilarityDecomp& fdecomp) - : matrixK((zeroPad(kdecomp)) ? - new QuasiTriangular(kdecomp) : new QuasiTriangularZero(kdecomp)), - matrixF(new BlockDiagonal(fdecomp.getB())) - {} - virtual ~SylvesterSolver() - {delete matrixK; delete matrixF;} - virtual void solve(SylvParams& pars, KronVector& x) const = 0; + SylvesterSolver(const QuasiTriangular &k, const QuasiTriangular &f) + : matrixK(new QuasiTriangular(k)), + matrixF(new QuasiTriangular(f)) + { + } + SylvesterSolver(const SchurDecompZero &kdecomp, const SchurDecomp &fdecomp) + : matrixK((zeroPad(kdecomp)) ? + new QuasiTriangular(kdecomp) : new QuasiTriangularZero(kdecomp)), + matrixF(new QuasiTriangular(fdecomp)) + { + } + SylvesterSolver(const SchurDecompZero &kdecomp, const SimilarityDecomp &fdecomp) + : matrixK((zeroPad(kdecomp)) ? + new QuasiTriangular(kdecomp) : new QuasiTriangularZero(kdecomp)), + matrixF(new BlockDiagonal(fdecomp.getB())) + { + } + virtual ~SylvesterSolver() + { + delete matrixK; delete matrixF; + } + virtual void solve(SylvParams &pars, KronVector &x) const = 0; }; #endif /* SYLVESTER_SOLVER_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/SymSchurDecomp.h b/dynare++/sylv/cc/SymSchurDecomp.h index 7840421118a55fdb68f6e196c2ef3cd391153d69..9b95f36bff767acc212f1a47d3cebd5e9d24488b 100644 --- a/dynare++/sylv/cc/SymSchurDecomp.h +++ b/dynare++/sylv/cc/SymSchurDecomp.h @@ -7,35 +7,45 @@ #include "SylvMatrix.h" -class SymSchurDecomp { +class SymSchurDecomp +{ protected: - Vector lambda; - SqSylvMatrix q; + Vector lambda; + SqSylvMatrix q; public: - /** Calculates A = Q*Lambda*Q^T, where A is assummed to be - * symmetric and Lambda real diagonal, hence a vector. */ - SymSchurDecomp(const GeneralMatrix& a); - SymSchurDecomp(const SymSchurDecomp& ssd) - : lambda(ssd.lambda), q(ssd.q) {} - virtual ~SymSchurDecomp() {} - const Vector& getLambda() const - {return lambda;} - const SqSylvMatrix& getQ() const - {return q;} - /** Return factor F*F^T = A, raises and exception if A is not - * positive semidefinite, F must be square. */ - void getFactor(GeneralMatrix& f) const; - /** Returns true if A is positive semidefinite. */ - bool isPositiveSemidefinite() const; - /** Correct definitness. This sets all eigenvalues between minus - * tolerance and zero to zero. */ - void correctDefinitness(double tol); + /** Calculates A = Q*Lambda*Q^T, where A is assummed to be + * symmetric and Lambda real diagonal, hence a vector. */ + SymSchurDecomp(const GeneralMatrix &a); + SymSchurDecomp(const SymSchurDecomp &ssd) + : lambda(ssd.lambda), q(ssd.q) + { + } + virtual ~SymSchurDecomp() + { + } + const Vector & + getLambda() const + { + return lambda; + } + const SqSylvMatrix & + getQ() const + { + return q; + } + /** Return factor F*F^T = A, raises and exception if A is not + * positive semidefinite, F must be square. */ + void getFactor(GeneralMatrix &f) const; + /** Returns true if A is positive semidefinite. */ + bool isPositiveSemidefinite() const; + /** Correct definitness. This sets all eigenvalues between minus + * tolerance and zero to zero. */ + void correctDefinitness(double tol); }; #endif - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/TriangularSylvester.h b/dynare++/sylv/cc/TriangularSylvester.h index b4908729e1044826ce43b72983c6f2246151e7fa..fa652bc12f70c676e15c68ceb02a0997ee998fc9 100644 --- a/dynare++/sylv/cc/TriangularSylvester.h +++ b/dynare++/sylv/cc/TriangularSylvester.h @@ -11,105 +11,112 @@ #include "QuasiTriangularZero.h" #include "SimilarityDecomp.h" -class TriangularSylvester : public SylvesterSolver { - const QuasiTriangular* const matrixKK; - const QuasiTriangular* const matrixFF; +class TriangularSylvester : public SylvesterSolver +{ + const QuasiTriangular *const matrixKK; + const QuasiTriangular *const matrixFF; public: - TriangularSylvester(const QuasiTriangular& k, const QuasiTriangular& f); - TriangularSylvester(const SchurDecompZero& kdecomp, const SchurDecomp& fdecomp); - TriangularSylvester(const SchurDecompZero& kdecomp, const SimilarityDecomp& fdecomp); - virtual ~TriangularSylvester(); - void print() const; - void solve(SylvParams& pars, KronVector& d) const; + TriangularSylvester(const QuasiTriangular &k, const QuasiTriangular &f); + TriangularSylvester(const SchurDecompZero &kdecomp, const SchurDecomp &fdecomp); + TriangularSylvester(const SchurDecompZero &kdecomp, const SimilarityDecomp &fdecomp); + virtual + ~TriangularSylvester(); + void print() const; + void solve(SylvParams &pars, KronVector &d) const; - void solvi(double r, KronVector& d, double& eig_min) const; - void solvii(double alpha, double beta1, double beta2, - KronVector& d1, KronVector& d2, - double& eig_min) const; - void solviip(double alpha, double betas, - KronVector& d, double& eig_min) const; - /* evaluates: - |x1| |d1| |alpha -beta1| |d1| - | | = | |+| |\otimes F'...\otimes K | | - |x2| |d2| |beta2 alpha| |d2| - */ - void linEval(double alpha, double beta1, double beta2, - KronVector& x1, KronVector& x2, - const ConstKronVector& d1, const ConstKronVector& d2) const; - void linEval(double alpha, double beta1, double beta2, - KronVector& x1, KronVector& x2, - const KronVector& d1, const KronVector& d2) const - {linEval(alpha, beta1, beta2, x1, x2, - ConstKronVector(d1), ConstKronVector(d2));} + void solvi(double r, KronVector &d, double &eig_min) const; + void solvii(double alpha, double beta1, double beta2, + KronVector &d1, KronVector &d2, + double &eig_min) const; + void solviip(double alpha, double betas, + KronVector &d, double &eig_min) const; + /* evaluates: + |x1| |d1| |alpha -beta1| |d1| + | | = | |+| |\otimes F'...\otimes K | | + |x2| |d2| |beta2 alpha| |d2| + */ + void linEval(double alpha, double beta1, double beta2, + KronVector &x1, KronVector &x2, + const ConstKronVector &d1, const ConstKronVector &d2) const; + void + linEval(double alpha, double beta1, double beta2, + KronVector &x1, KronVector &x2, + const KronVector &d1, const KronVector &d2) const + { + linEval(alpha, beta1, beta2, x1, x2, + ConstKronVector(d1), ConstKronVector(d2)); + } - /* evaluates: - |x1| |d1| |gamma -delta1| |d1| - | | = | | + 2alpha*| |\otimes F'...\otimes K | | + - |x2| |d2| |delta2 gamma| |d2| + /* evaluates: + |x1| |d1| |gamma -delta1| |d1| + | | = | | + 2alpha*| |\otimes F'...\otimes K | | + + |x2| |d2| |delta2 gamma| |d2| - |gamma -delta1|^2 |d1| - + (alpha^2+betas)*| |\otimes F'2...\otimes K2 | | - |delta2 gamma| |d2| - */ - void quaEval(double alpha, double betas, - double gamma, double delta1, double delta2, - KronVector& x1, KronVector& x2, - const ConstKronVector& d1, const ConstKronVector& d2) const; - void quaEval(double alpha, double betas, - double gamma, double delta1, double delta2, - KronVector& x1, KronVector& x2, - const KronVector& d1, const KronVector& d2) const - {quaEval(alpha, betas, gamma, delta1, delta2, x1, x2, - ConstKronVector(d1), ConstKronVector(d2));} + |gamma -delta1|^2 |d1| + + (alpha^2+betas)*| |\otimes F'2...\otimes K2 | | + |delta2 gamma| |d2| + */ + void quaEval(double alpha, double betas, + double gamma, double delta1, double delta2, + KronVector &x1, KronVector &x2, + const ConstKronVector &d1, const ConstKronVector &d2) const; + void + quaEval(double alpha, double betas, + double gamma, double delta1, double delta2, + KronVector &x1, KronVector &x2, + const KronVector &d1, const KronVector &d2) const + { + quaEval(alpha, betas, gamma, delta1, delta2, x1, x2, + ConstKronVector(d1), ConstKronVector(d2)); + } private: - /* returns square of size of minimal eigenvalue of the system solved, - now obsolete */ - double getEigSep(int depth) const; - /* recursivelly calculates kronecker product of complex vectors (used in getEigSep) */ - static void multEigVector(KronVector& eig, const Vector& feig, const Vector& keig); - /* auxiliary typedefs */ - typedef QuasiTriangular::const_diag_iter const_diag_iter; - typedef QuasiTriangular::const_row_iter const_row_iter; - /* called from solvi */ - void solviRealAndEliminate(double r, const_diag_iter di, - KronVector& d, double& eig_min) const; - void solviComplexAndEliminate(double r, const_diag_iter di, - KronVector& d, double& eig_min) const; - /* called from solviip */ - void solviipRealAndEliminate(double alpha, double betas, - const_diag_iter di, const_diag_iter dsi, - KronVector& d, double& eig_min) const; - void solviipComplexAndEliminate(double alpha, double betas, - const_diag_iter di, const_diag_iter dsi, - KronVector& d, double& eig_min) const; - /* eliminations */ - void solviEliminateReal(const_diag_iter di, KronVector& d, - const KronVector& y, double divisor) const; - void solviEliminateComplex(const_diag_iter di, KronVector& d, - const KronVector& y1, const KronVector& y2, - double divisor) const; - void solviipEliminateReal(const_diag_iter di, const_diag_iter dsi, - KronVector& d, - const KronVector& y1, const KronVector& y2, - double divisor, double divisor2) const; - void solviipEliminateComplex(const_diag_iter di, const_diag_iter dsi, - KronVector& d, - const KronVector& y1, const KronVector& y11, - const KronVector& y2, const KronVector& y22, - double divisor) const; - /* Lemma 2 */ - void solviipComplex(double alpha, double betas, double gamma, - double delta1, double delta2, - KronVector& d1, KronVector& d2, - double& eig_min) const; - /* norms for what we consider zero on diagonal of F */ - static double diag_zero; - static double diag_zero_sq; // square of diag_zero + /* returns square of size of minimal eigenvalue of the system solved, + now obsolete */ + double getEigSep(int depth) const; + /* recursivelly calculates kronecker product of complex vectors (used in getEigSep) */ + static void multEigVector(KronVector &eig, const Vector &feig, const Vector &keig); + /* auxiliary typedefs */ + typedef QuasiTriangular::const_diag_iter const_diag_iter; + typedef QuasiTriangular::const_row_iter const_row_iter; + /* called from solvi */ + void solviRealAndEliminate(double r, const_diag_iter di, + KronVector &d, double &eig_min) const; + void solviComplexAndEliminate(double r, const_diag_iter di, + KronVector &d, double &eig_min) const; + /* called from solviip */ + void solviipRealAndEliminate(double alpha, double betas, + const_diag_iter di, const_diag_iter dsi, + KronVector &d, double &eig_min) const; + void solviipComplexAndEliminate(double alpha, double betas, + const_diag_iter di, const_diag_iter dsi, + KronVector &d, double &eig_min) const; + /* eliminations */ + void solviEliminateReal(const_diag_iter di, KronVector &d, + const KronVector &y, double divisor) const; + void solviEliminateComplex(const_diag_iter di, KronVector &d, + const KronVector &y1, const KronVector &y2, + double divisor) const; + void solviipEliminateReal(const_diag_iter di, const_diag_iter dsi, + KronVector &d, + const KronVector &y1, const KronVector &y2, + double divisor, double divisor2) const; + void solviipEliminateComplex(const_diag_iter di, const_diag_iter dsi, + KronVector &d, + const KronVector &y1, const KronVector &y11, + const KronVector &y2, const KronVector &y22, + double divisor) const; + /* Lemma 2 */ + void solviipComplex(double alpha, double betas, double gamma, + double delta1, double delta2, + KronVector &d1, KronVector &d2, + double &eig_min) const; + /* norms for what we consider zero on diagonal of F */ + static double diag_zero; + static double diag_zero_sq; // square of diag_zero }; #endif /* TRIANGULAR_SYLVESTER_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/cc/Vector.h b/dynare++/sylv/cc/Vector.h index dc4acd532d5ad7026ee2e6dc33d1c1f6e772c6a7..3afd5d38948aa04a3e3d10d32ac746718e2e133a 100644 --- a/dynare++/sylv/cc/Vector.h +++ b/dynare++/sylv/cc/Vector.h @@ -7,169 +7,252 @@ /* NOTE! Vector and ConstVector have not common super class in order * to avoid running virtual method invokation mechanism. Some - * members, and methods are thus duplicated */ + * members, and methods are thus duplicated */ #include <cstdio> class GeneralMatrix; class ConstVector; -class Vector { +class Vector +{ protected: - int len; - int s; - double* data; - bool destroy; + int len; + int s; + double *data; + bool destroy; public: - Vector() : len(0), s(1), data(0), destroy(false) {} - Vector(int l) : len(l), s(1), data(new double[l]), destroy(true) {} - Vector(Vector& v) : len(v.length()), s(v.skip()), data(v.base()), destroy(false) {} - Vector(const Vector& v); - Vector(const ConstVector& v); - Vector(const double* d, int l) - : len(l), s(1), data(new double[len]), destroy(true) - {copy(d, 1);} - Vector(double* d, int l) - : len(l), s(1), data(d), destroy(false) {} - Vector(double* d, int skip, int l) - : len(l), s(skip), data(d), destroy(false) {} - Vector(Vector& v, int off, int l); - Vector(const Vector& v, int off, int l); - Vector(GeneralMatrix& m, int col); - Vector(int row, GeneralMatrix& m); - const Vector& operator=(const Vector& v); - const Vector& operator=(const ConstVector& v); - double& operator[](int i) - {return data[s*i];} - const double& operator[](int i) const - {return data[s*i];} - const double* base() const - {return data;} - double* base() - {return data;} - int length() const - {return len;} - int skip() const - {return s;} - - /** Exact equality. */ - bool operator==(const Vector& y) const; - bool operator!=(const Vector& y) const; - /** Lexicographic ordering. */ - bool operator<(const Vector& y) const; - bool operator<=(const Vector& y) const; - bool operator>(const Vector& y) const; - bool operator>=(const Vector& y) const; - - virtual ~Vector(); - void zeros(); - void nans(); - void infs(); - bool toBeDestroyed() const {return destroy;} - void rotatePair(double alpha, double beta1, double beta2, int i); - void add(double r, const Vector& v); - void add(double r, const ConstVector& v); - void add(const double* z, const Vector& v); - void add(const double* z, const ConstVector& v); - void mult(double r); - double getNorm() const; - double getMax() const; - double getNorm1() const; - double dot(const Vector& y) const; - bool isFinite() const; - void print() const; - - /* multiplies | alpha -beta1| |b1| |x1| - | |\otimes I .| | = | | - | -beta2 alpha| |b2| |x2| - */ - static void mult2(double alpha, double beta1, double beta2, - Vector& x1, Vector& x2, - const Vector& b1, const Vector& b2); - /* same, but adds instead of set */ - static void mult2a(double alpha, double beta1, double beta2, - Vector& x1, Vector& x2, - const Vector& b1, const Vector& b2); - /* same, but subtracts instead of add */ - static void mult2s(double alpha, double beta1, double beta2, - Vector& x1, Vector& x2, - const Vector& b1, const Vector& b2) - {mult2a(-alpha, -beta1, -beta2, x1, x2, b1, b2);} + Vector() : len(0), s(1), data(0), destroy(false) + { + } + Vector(int l) : len(l), s(1), data(new double[l]), destroy(true) + { + } + Vector(Vector &v) : len(v.length()), s(v.skip()), data(v.base()), destroy(false) + { + } + Vector(const Vector &v); + Vector(const ConstVector &v); + Vector(const double *d, int l) + : len(l), s(1), data(new double[len]), destroy(true) + { + copy(d, 1); + } + Vector(double *d, int l) + : len(l), s(1), data(d), destroy(false) + { + } + Vector(double *d, int skip, int l) + : len(l), s(skip), data(d), destroy(false) + { + } + Vector(Vector &v, int off, int l); + Vector(const Vector &v, int off, int l); + Vector(GeneralMatrix &m, int col); + Vector(int row, GeneralMatrix &m); + const Vector &operator=(const Vector &v); + const Vector &operator=(const ConstVector &v); + double & + operator[](int i) + { + return data[s*i]; + } + const double & + operator[](int i) const + { + return data[s*i]; + } + const double * + base() const + { + return data; + } + double * + base() + { + return data; + } + int + length() const + { + return len; + } + int + skip() const + { + return s; + } + + /** Exact equality. */ + bool operator==(const Vector &y) const; + bool operator!=(const Vector &y) const; + /** Lexicographic ordering. */ + bool operator<(const Vector &y) const; + bool operator<=(const Vector &y) const; + bool operator>(const Vector &y) const; + bool operator>=(const Vector &y) const; + + virtual + ~Vector(); + void zeros(); + void nans(); + void infs(); + bool + toBeDestroyed() const + { + return destroy; + } + void rotatePair(double alpha, double beta1, double beta2, int i); + void add(double r, const Vector &v); + void add(double r, const ConstVector &v); + void add(const double *z, const Vector &v); + void add(const double *z, const ConstVector &v); + void mult(double r); + double getNorm() const; + double getMax() const; + double getNorm1() const; + double dot(const Vector &y) const; + bool isFinite() const; + void print() const; + + /* multiplies | alpha -beta1| |b1| |x1| + | |\otimes I .| | = | | + | -beta2 alpha| |b2| |x2| + */ + static void mult2(double alpha, double beta1, double beta2, + Vector &x1, Vector &x2, + const Vector &b1, const Vector &b2); + /* same, but adds instead of set */ + static void mult2a(double alpha, double beta1, double beta2, + Vector &x1, Vector &x2, + const Vector &b1, const Vector &b2); + /* same, but subtracts instead of add */ + static void + mult2s(double alpha, double beta1, double beta2, + Vector &x1, Vector &x2, + const Vector &b1, const Vector &b2) + { + mult2a(-alpha, -beta1, -beta2, x1, x2, b1, b2); + } private: - void copy(const double* d, int inc); - const Vector& operator=(int); // must not be used (not implemented) - const Vector& operator=(double); // must not be used (not implemented) + void copy(const double *d, int inc); + const Vector &operator=(int); // must not be used (not implemented) + const Vector &operator=(double); // must not be used (not implemented) }; - -class BaseConstVector { +class BaseConstVector +{ protected: - int len; - int s; - const double* data; + int len; + int s; + const double *data; public: - BaseConstVector(int l, int si, const double* d) : len(l), s(si), data(d) {} - BaseConstVector(const BaseConstVector& v) : len(v.len), s(v.s), data(v.data) {} - const BaseConstVector& operator=(const BaseConstVector& v) - {len = v.len; s = v.s; data = v.data; return *this;} - const double& operator[](int i) const - {return data[s*i];} - const double* base() const - {return data;} - int length() const - {return len;} - int skip() const - {return s;} + BaseConstVector(int l, int si, const double *d) : len(l), s(si), data(d) + { + } + BaseConstVector(const BaseConstVector &v) : len(v.len), s(v.s), data(v.data) + { + } + const BaseConstVector & + operator=(const BaseConstVector &v) + { + len = v.len; s = v.s; data = v.data; return *this; + } + const double & + operator[](int i) const + { + return data[s*i]; + } + const double * + base() const + { + return data; + } + int + length() const + { + return len; + } + int + skip() const + { + return s; + } }; class ConstGeneralMatrix; -class ConstVector : public BaseConstVector { +class ConstVector : public BaseConstVector +{ public: - ConstVector(const Vector& v) : BaseConstVector(v.length(), v.skip(), v.base()) {} - ConstVector(const ConstVector& v) : BaseConstVector(v) {} - ConstVector(const double* d, int l) : BaseConstVector(l, 1, d) {} - ConstVector(const Vector& v, int off, int l); - ConstVector(const ConstVector& v, int off, int l); - ConstVector(const double* d, int skip, int l); - ConstVector(const ConstGeneralMatrix& m, int col); - ConstVector(int row, const ConstGeneralMatrix& m); - - virtual ~ConstVector() {} - /** Exact equality. */ - bool operator==(const ConstVector& y) const; - bool operator!=(const ConstVector& y) const - {return ! operator==(y);} - /** Lexicographic ordering. */ - bool operator<(const ConstVector& y) const; - bool operator<=(const ConstVector& y) const - {return operator<(y) || operator==(y);} - bool operator>(const ConstVector& y) const - {return ! operator<=(y);} - bool operator>=(const ConstVector& y) const - {return ! operator<(y);} - - double getNorm() const; - double getMax() const; - double getNorm1() const; - double dot(const ConstVector& y) const; - bool isFinite() const; - void print() const; + ConstVector(const Vector &v) : BaseConstVector(v.length(), v.skip(), v.base()) + { + } + ConstVector(const ConstVector &v) : BaseConstVector(v) + { + } + ConstVector(const double *d, int l) : BaseConstVector(l, 1, d) + { + } + ConstVector(const Vector &v, int off, int l); + ConstVector(const ConstVector &v, int off, int l); + ConstVector(const double *d, int skip, int l); + ConstVector(const ConstGeneralMatrix &m, int col); + ConstVector(int row, const ConstGeneralMatrix &m); + + virtual ~ConstVector() + { + } + /** Exact equality. */ + bool operator==(const ConstVector &y) const; + bool + operator!=(const ConstVector &y) const + { + return !operator==(y); + } + /** Lexicographic ordering. */ + bool operator<(const ConstVector &y) const; + bool + operator<=(const ConstVector &y) const + { + return operator<(y) || operator==(y); + } + bool + operator>(const ConstVector &y) const + { + return !operator<=(y); + } + bool + operator>=(const ConstVector &y) const + { + return !operator<(y); + } + + double getNorm() const; + double getMax() const; + double getNorm1() const; + double dot(const ConstVector &y) const; + bool isFinite() const; + void print() const; }; -class ZeroPad { +class ZeroPad +{ public: - static const int length = 16; + static const int length = 16; private: - double pad[16]; + double pad[16]; public: - ZeroPad(); - const double* getBase() const {return pad;} + ZeroPad(); + const double * + getBase() const + { + return pad; + } }; #endif /* VECTOR_H */ - // Local Variables: // mode:C++ // End: diff --git a/dynare++/sylv/testing/MMMatrix.h b/dynare++/sylv/testing/MMMatrix.h index e30842caf544d40816ac9671f2e08a9196502075..f6afaa30dc2183d32908ea176cf786a8d6d341d8 100644 --- a/dynare++/sylv/testing/MMMatrix.h +++ b/dynare++/sylv/testing/MMMatrix.h @@ -12,31 +12,58 @@ using namespace std; -class MMException : public MallocAllocator { - string message; +class MMException : public MallocAllocator +{ + string message; public: - MMException(string mes) : message(mes) {} - MMException(const char* mes) : message(mes) {} - const char* getMessage() const {return message.data();} + MMException(string mes) : message(mes) + { + } + MMException(const char *mes) : message(mes) + { + } + const char * + getMessage() const + { + return message.data(); + } }; -class MMMatrixIn : public MallocAllocator { - double* data; - int rows; - int cols; +class MMMatrixIn : public MallocAllocator +{ + double *data; + int rows; + int cols; public: - MMMatrixIn(const char* fname); - ~MMMatrixIn(); - const double* getData() const {return data;} - int size() const {return rows*cols;} - int row() const {return rows;} - int col() const {return cols;} + MMMatrixIn(const char *fname); + ~MMMatrixIn(); + const double * + getData() const + { + return data; + } + int + size() const + { + return rows*cols; + } + int + row() const + { + return rows; + } + int + col() const + { + return cols; + } }; -class MMMatrixOut : public MallocAllocator { +class MMMatrixOut : public MallocAllocator +{ public: - static void write(const char* fname, int rows, int cols, const double* data); - static void write(const char* fname, const GeneralMatrix& m); + static void write(const char *fname, int rows, int cols, const double *data); + static void write(const char *fname, const GeneralMatrix &m); }; #endif /* MM_MATRIX_H */ diff --git a/dynare++/tl/testing/factory.h b/dynare++/tl/testing/factory.h index fea2230110c80709aecdcd01d7484b410a6f7bee..89f0b6be825b394a250d17b65325d932051a3308 100644 --- a/dynare++/tl/testing/factory.h +++ b/dynare++/tl/testing/factory.h @@ -2,7 +2,7 @@ /* Copyright 2004, Ondra Kamenik */ #ifndef FACTORY_H -#define FACTORY_H +#define FACTORY_H #include "symmetry.h" #include "int_sequence.h" @@ -11,67 +11,78 @@ #include "rfs_tensor.h" #include "t_container.h" -class Factory { - void init(const Symmetry& s, const IntSequence& nvs); - void init(int dim, int nv); - void fillMatrix(TwoDMatrix& m) const; +class Factory +{ + void init(const Symmetry &s, const IntSequence &nvs); + void init(int dim, int nv); + void fillMatrix(TwoDMatrix &m) const; public: - double get() const; - // this can be used with UGSTensor, FGSTensor - template <class _Ttype> - _Ttype* make(int r, const Symmetry& s, const IntSequence& nvs) - { - _Ttype* res = new _Ttype(r, TensorDimens(s, nvs)); - init(s, nvs); - fillMatrix(*res); - return res; - } + double get() const; + // this can be used with UGSTensor, FGSTensor + template <class _Ttype> + _Ttype * + make(int r, const Symmetry &s, const IntSequence &nvs) + { + _Ttype *res = new _Ttype(r, TensorDimens(s, nvs)); + init(s, nvs); + fillMatrix(*res); + return res; + } - // this can be used with FFSTensor, UFSTensor, FRTensor, URTensor - template <class _Ttype> - _Ttype* make(int r, int nv, int dim) - { - _Ttype* res = new _Ttype(r, nv, dim); - init(dim, nv); - fillMatrix(*res); - return res; - } + // this can be used with FFSTensor, UFSTensor, FRTensor, URTensor + template <class _Ttype> + _Ttype * + make(int r, int nv, int dim) + { + _Ttype *res = new _Ttype(r, nv, dim); + init(dim, nv); + fillMatrix(*res); + return res; + } - template <class _Ttype, class _Ctype> - _Ctype* makeCont(int r, const IntSequence& nvs, int maxdim) - { - int symnum = nvs.size(); - _Ctype* res = new _Ctype(symnum); - for (int dim = 1; dim <= maxdim; dim++) { - if (symnum == 1) { - // full symmetry - Symmetry sym(dim); - _Ttype* t = make<_Ttype>(r, sym, nvs); - res->insert(t); - } else { - // general symmetry - for (int i = 0; i <= dim; i++) { - Symmetry sym(i, dim-i); - _Ttype* t = make<_Ttype>(r, sym, nvs); - res->insert(t); - } - } - } - return res; - } + template <class _Ttype, class _Ctype> + _Ctype * + makeCont(int r, const IntSequence &nvs, int maxdim) + { + int symnum = nvs.size(); + _Ctype *res = new _Ctype(symnum); + for (int dim = 1; dim <= maxdim; dim++) + { + if (symnum == 1) + { + // full symmetry + Symmetry sym(dim); + _Ttype *t = make<_Ttype>(r, sym, nvs); + res->insert(t); + } + else + { + // general symmetry + for (int i = 0; i <= dim; i++) + { + Symmetry sym(i, dim-i); + _Ttype *t = make<_Ttype>(r, sym, nvs); + res->insert(t); + } + } + } + return res; + } - template <class _Ttype, class _Ptype> - _Ptype* makePoly(int r, int nv, int maxdim) - { - _Ptype* p = new _Ptype(r, nv); - for (int d = 1; d <= maxdim; d++) { - _Ttype* t = make<_Ttype>(r, nv, d); - p->insert(t); - } - return p; - } + template <class _Ttype, class _Ptype> + _Ptype * + makePoly(int r, int nv, int maxdim) + { + _Ptype *p = new _Ptype(r, nv); + for (int d = 1; d <= maxdim; d++) + { + _Ttype *t = make<_Ttype>(r, nv, d); + p->insert(t); + } + return p; + } - Vector* makeVector(int n); + Vector *makeVector(int n); }; #endif diff --git a/dynare++/tl/testing/monoms.h b/dynare++/tl/testing/monoms.h index 94b34a3da002ae4ec786ecfa9e784bf5298989f8..76c56e2a7d391cc41a703973884acd9ca6fc6021 100644 --- a/dynare++/tl/testing/monoms.h +++ b/dynare++/tl/testing/monoms.h @@ -10,115 +10,121 @@ #include "sparse_tensor.h" #include "Vector.h" -class IntGenerator { - int maxim; - double probab; +class IntGenerator +{ + int maxim; + double probab; public: - IntGenerator() - : maxim(5), probab(0.3) {} - void init(int nf, int ny, int nv, int nw, int nu, int mx, double prob); - int get() const; + IntGenerator() + : maxim(5), probab(0.3) + { + } + void init(int nf, int ny, int nv, int nw, int nu, int mx, double prob); + int get() const; }; extern IntGenerator intgen; - -class Monom : public IntSequence { +class Monom : public IntSequence +{ public: - Monom(int len); // generate a random monom - Monom(int len, int item); // generate monom whose items are the given item - double deriv(const IntSequence& vars) const; - // this = this*m^ex (in monomial sense) - void multiplyWith(int ex, const Monom& m); - void print() const; + Monom(int len); // generate a random monom + Monom(int len, int item); // generate monom whose items are the given item + double deriv(const IntSequence &vars) const; + // this = this*m^ex (in monomial sense) + void multiplyWith(int ex, const Monom &m); + void print() const; }; class Monom2Vector; -class Monom1Vector { - friend class Monom2Vector; - int nx; - int len; - Monom** const x; +class Monom1Vector +{ + friend class Monom2Vector; + int nx; + int len; + Monom **const x; public: - Monom1Vector(int nxx, int l); - ~Monom1Vector(); - void deriv(const IntSequence& c, Vector& out) const; - FGSTensor* deriv(int dim) const; - void print() const; + Monom1Vector(int nxx, int l); + ~Monom1Vector(); + void deriv(const IntSequence &c, Vector &out) const; + FGSTensor *deriv(int dim) const; + void print() const; }; //class Monom3Vector; -class Monom2Vector { - int ny; - int nu; - int len; - Monom** const y; - Monom** const u; +class Monom2Vector +{ + int ny; + int nu; + int len; + Monom **const y; + Monom **const u; public: - // generate random vector of monom two vector - Monom2Vector(int nyy, int nuu, int l); - // calculate g(x(y,u)) - Monom2Vector(const Monom1Vector& g, const Monom2Vector& xmon); - ~Monom2Vector(); - void deriv(const Symmetry& s, const IntSequence& c, Vector& out) const; - FGSTensor* deriv(const Symmetry& s) const; - FGSContainer* deriv(int maxdim) const; - void print() const; + // generate random vector of monom two vector + Monom2Vector(int nyy, int nuu, int l); + // calculate g(x(y,u)) + Monom2Vector(const Monom1Vector &g, const Monom2Vector &xmon); + ~Monom2Vector(); + void deriv(const Symmetry &s, const IntSequence &c, Vector &out) const; + FGSTensor *deriv(const Symmetry &s) const; + FGSContainer *deriv(int maxdim) const; + void print() const; }; -class Monom4Vector { - int len; - int nx1; - int nx2; - int nx3; - int nx4; - Monom** const x1; - Monom** const x2; - Monom** const x3; - Monom** const x4; +class Monom4Vector +{ + int len; + int nx1; + int nx2; + int nx3; + int nx4; + Monom **const x1; + Monom **const x2; + Monom **const x3; + Monom **const x4; public: - /* random for g(y,u,sigma) */ - Monom4Vector(int l, int ny, int nu); - /* random for G(y,u,u',sigma) */ - Monom4Vector(int l, int ny, int nu, int nup); - /* random for f(y+,y,y-,u) */ - Monom4Vector(int l, int nbigg, int ng, int ny, int nu); - /* substitution f(G(y,u,u',sigma),g(y,u,sigma),y,u) */ - Monom4Vector(const Monom4Vector& f, const Monom4Vector& bigg, - const Monom4Vector& g); - ~Monom4Vector(); - FSSparseTensor* deriv(int dim) const; - FGSTensor* deriv(const Symmetry& s) const; - void deriv(const Symmetry& s, const IntSequence& coor, Vector& out) const; - void print() const; + /* random for g(y,u,sigma) */ + Monom4Vector(int l, int ny, int nu); + /* random for G(y,u,u',sigma) */ + Monom4Vector(int l, int ny, int nu, int nup); + /* random for f(y+,y,y-,u) */ + Monom4Vector(int l, int nbigg, int ng, int ny, int nu); + /* substitution f(G(y,u,u',sigma),g(y,u,sigma),y,u) */ + Monom4Vector(const Monom4Vector &f, const Monom4Vector &bigg, + const Monom4Vector &g); + ~Monom4Vector(); + FSSparseTensor *deriv(int dim) const; + FGSTensor *deriv(const Symmetry &s) const; + void deriv(const Symmetry &s, const IntSequence &coor, Vector &out) const; + void print() const; protected: - void init_random(); + void init_random(); }; - -struct SparseDerivGenerator { - int maxdimen; - FGSContainer* bigg; - FGSContainer* g; - FGSContainer* rcont; - FSSparseTensor** const ts; - SparseDerivGenerator(int nf, int ny, int nu, int nup, int nbigg, int ng, - int mx, double prob, int maxdim); - ~SparseDerivGenerator(); +struct SparseDerivGenerator +{ + int maxdimen; + FGSContainer *bigg; + FGSContainer *g; + FGSContainer *rcont; + FSSparseTensor **const ts; + SparseDerivGenerator(int nf, int ny, int nu, int nup, int nbigg, int ng, + int mx, double prob, int maxdim); + ~SparseDerivGenerator(); }; - -struct DenseDerivGenerator { - int maxdimen; - FGSContainer* xcont; - FGSContainer* rcont; - FGSTensor** const ts; - UGSContainer* uxcont; - UGSTensor** const uts; - DenseDerivGenerator(int ng, int nx, int ny, int nu, - int mx, double prob, int maxdim); - void unfold(); - ~DenseDerivGenerator(); +struct DenseDerivGenerator +{ + int maxdimen; + FGSContainer *xcont; + FGSContainer *rcont; + FGSTensor **const ts; + UGSContainer *uxcont; + UGSTensor **const uts; + DenseDerivGenerator(int ng, int nx, int ny, int nu, + int mx, double prob, int maxdim); + void unfold(); + ~DenseDerivGenerator(); }; #endif diff --git a/dynare++/utils/cc/exception.h b/dynare++/utils/cc/exception.h index 7f843b3ae78b86062262abe899f7fb7c4cf23c0f..97de4863e1b297791f2a0f3fda47d54b0e52e610 100644 --- a/dynare++/utils/cc/exception.h +++ b/dynare++/utils/cc/exception.h @@ -11,41 +11,54 @@ #include <string> #include <algorithm> -namespace ogu { - - /** A primitive exception. */ - class Exception { - static const int file_length = 100; - static const int mes_length = 500; - protected: - char file[file_length]; - int line; - char mes[mes_length]; - public: - Exception(const char* f, int l, const char* m) - { - strncpy(file, f, file_length-1); - file[file_length-1] = '\0'; - line = l; - strncpy(mes, m, std::min(mes_length-1,(int)strlen(m))); - mes[mes_length-1] = '\0'; - } - Exception(const char* f, int l, const std::string& m) - { - strncpy(file, f, file_length-1); - file[file_length-1] = '\0'; - line = l; - strncpy(mes, m.c_str(), std::min(mes_length-1,(int)m.length())); - mes[mes_length-1] = '\0'; - } - virtual ~Exception() {} - void print(FILE* fd) const - { fprintf(fd, "%s:%d: %s\n", file, line, mes); } - void print() const - { print(stdout); } - const char* message() const - { return mes; } - }; +namespace ogu +{ + + /** A primitive exception. */ + class Exception + { + static const int file_length = 100; + static const int mes_length = 500; + protected: + char file[file_length]; + int line; + char mes[mes_length]; + public: + Exception(const char *f, int l, const char *m) + { + strncpy(file, f, file_length-1); + file[file_length-1] = '\0'; + line = l; + strncpy(mes, m, std::min(mes_length-1, (int) strlen(m))); + mes[mes_length-1] = '\0'; + } + Exception(const char *f, int l, const std::string &m) + { + strncpy(file, f, file_length-1); + file[file_length-1] = '\0'; + line = l; + strncpy(mes, m.c_str(), std::min(mes_length-1, (int) m.length())); + mes[mes_length-1] = '\0'; + } + virtual ~Exception() + { + } + void + print(FILE *fd) const + { + fprintf(fd, "%s:%d: %s\n", file, line, mes); + } + void + print() const + { + print(stdout); + } + const char * + message() const + { + return mes; + } + }; }; #endif diff --git a/dynare++/utils/cc/memory_file.h b/dynare++/utils/cc/memory_file.h index 79f08717ebc140c9b08a15ba5fe5fa055df04cb6..a4937d14a0a9d25925c6cdc998980c67d647482a 100644 --- a/dynare++/utils/cc/memory_file.h +++ b/dynare++/utils/cc/memory_file.h @@ -5,51 +5,69 @@ #ifndef OGU_MEMORY_FILE #define OGU_MEMORY_FILE -namespace ogu { - /** This function calculates an offset of a given position in a - * given string. The position is given by the line number and by - * the offset in the line (both starting from 1). */ - int calc_pos_offset(int length, const char* str, int line, int col); - /** This function calculates a line number and column number of a - * character given by the offset in the string. It is inverse to - * calc_pos_offset. */ - void calc_pos_line_and_col(int length, const char* str, int offset, - int& line, int& col); +namespace ogu +{ + /** This function calculates an offset of a given position in a + * given string. The position is given by the line number and by + * the offset in the line (both starting from 1). */ + int calc_pos_offset(int length, const char *str, int line, int col); + /** This function calculates a line number and column number of a + * character given by the offset in the string. It is inverse to + * calc_pos_offset. */ + void calc_pos_line_and_col(int length, const char *str, int offset, + int &line, int &col); - /** This class opens a given file and makes its copy in memory and - * appends it with the '\0' character. Since the type of length is - * int, it can store files with size at most 4GB. If the file - * could be opened for reading, data is NULL and length is -1. If - * the file is empty but exists, len is zero and data points to a - * newly allocated memory containing '\0' character at the end. */ - class MemoryFile { - protected: - int len; - char* data; - public: - MemoryFile(const char* fname); - virtual ~MemoryFile() - {if (data) delete [] data;} - int length() const - {return len;} - const char* base() const - {return data;} - bool exists() const - {return len != -1;} - /** Return the offset of a character in the given line - * (starting from 1) with the given offset in the line. */ - int offset(int line, int lineoff) const - {return calc_pos_offset(len, data, line, lineoff);} - /** Return the line number and column number of the character - * defined by the offset. */ - void line_and_col(int offset, int& line, int& col) const - {calc_pos_line_and_col(len, data, offset, line, col);} - }; + /** This class opens a given file and makes its copy in memory and + * appends it with the '\0' character. Since the type of length is + * int, it can store files with size at most 4GB. If the file + * could be opened for reading, data is NULL and length is -1. If + * the file is empty but exists, len is zero and data points to a + * newly allocated memory containing '\0' character at the end. */ + class MemoryFile + { + protected: + int len; + char *data; + public: + MemoryFile(const char *fname); + virtual ~MemoryFile() + { + if (data) + delete [] data; + } + int + length() const + { + return len; + } + const char * + base() const + { + return data; + } + bool + exists() const + { + return len != -1; + } + /** Return the offset of a character in the given line + * (starting from 1) with the given offset in the line. */ + int + offset(int line, int lineoff) const + { + return calc_pos_offset(len, data, line, lineoff); + } + /** Return the line number and column number of the character + * defined by the offset. */ + void + line_and_col(int offset, int &line, int &col) const + { + calc_pos_line_and_col(len, data, offset, line, col); + } + }; - }; - #endif // Local Variables: diff --git a/dynare++/utils/cc/pascal_triangle.h b/dynare++/utils/cc/pascal_triangle.h index 2e989aa5723cf21dd042f2bffc021884cf8ffb51..66b4bac6b2a03ade3f9867a1a3be7dab55d96500 100644 --- a/dynare++/utils/cc/pascal_triangle.h +++ b/dynare++/utils/cc/pascal_triangle.h @@ -7,43 +7,54 @@ #include <vector> -namespace ogu { - - using std::vector; - - class PascalRow : public vector<int> { - int k; - public: - PascalRow() - : vector<int>(), k(1) - { push_back(2); } - void setFromPrevious(const PascalRow& prev); - void prolong(const PascalRow& prev); - void prolongFirst(int n); - void print() const; - }; - - class PascalTriangle { - vector<PascalRow> tr; - public: - PascalTriangle() - {tr.push_back(PascalRow());} - PascalTriangle(const PascalTriangle& triang) - : tr(triang.tr) {} - const PascalTriangle& operator=(const PascalTriangle& triang) - { tr = triang.tr; return *this;} - int noverk(int n, int k); - void print() const; - protected: - void ensure(int n, int k); - int max_n() const; - int max_k() const; - }; +namespace ogu +{ + + using std::vector; + + class PascalRow : public vector<int> + { + int k; + public: + PascalRow() + : vector<int>(), k(1) + { + push_back(2); + } + void setFromPrevious(const PascalRow &prev); + void prolong(const PascalRow &prev); + void prolongFirst(int n); + void print() const; + }; + + class PascalTriangle + { + vector<PascalRow> tr; + public: + PascalTriangle() + { + tr.push_back(PascalRow()); + } + PascalTriangle(const PascalTriangle &triang) + : tr(triang.tr) + { + } + const PascalTriangle & + operator=(const PascalTriangle &triang) + { + tr = triang.tr; return *this; + } + int noverk(int n, int k); + void print() const; + protected: + void ensure(int n, int k); + int max_n() const; + int max_k() const; + }; }; extern ogu::PascalTriangle ptriang; - #endif // Local Variables: diff --git a/mex/sources/block_kalman_filter/block_kalman_filter.cc b/mex/sources/block_kalman_filter/block_kalman_filter.cc index 6104feb12db2a425d5c626bc38f9e87faaccba2d..6ef1087a693fce8f41665b4a1f0d67c2ed9ce284 100644 --- a/mex/sources/block_kalman_filter/block_kalman_filter.cc +++ b/mex/sources/block_kalman_filter/block_kalman_filter.cc @@ -30,11 +30,11 @@ using namespace std; //#define CUBLAS #ifdef CUBLAS - #include <cuda_runtime.h> - #include <cublas_v2.h> +# include <cuda_runtime.h> +# include <cublas_v2.h> #endif void -mexDisp(mxArray* P) +mexDisp(mxArray *P) { unsigned int n = mxGetN(P); unsigned int m = mxGetM(P); @@ -44,97 +44,95 @@ mexDisp(mxArray* P) for (unsigned int i = 0; i < m; i++) { for (unsigned int j = 0; j < n; j++) - mexPrintf(" %9.4f",M[i+ j * m]); + mexPrintf(" %9.4f", M[i+ j * m]); mexPrintf("\n"); } mexEvalString("drawnow;"); } - void -mexDisp(double* M, int m, int n) +mexDisp(double *M, int m, int n) { mexPrintf("%d x %d\n", m, n); mexEvalString("drawnow;"); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) - mexPrintf(" %9.4f",M[i+ j * m]); + mexPrintf(" %9.4f", M[i+ j * m]); mexPrintf("\n"); } mexEvalString("drawnow;"); } /*if block - %nz_state_var = M_.nz_state_var; - while notsteady && t<smpl - t = t+1; - v = Y(:,t)-a(mf); - F = P(mf,mf) + H; - if rcond(F) < kalman_tol - if ~all(abs(F(:))<kalman_tol) - return - else - a = T*a; - P = T*P*transpose(T)+QQ; - end - else - F_singular = 0; - dF = det(F); - iF = inv(F); - lik(t) = log(dF)+transpose(v)*iF*v; - K = P(:,mf)*iF; - a = T*(a+K*v); - P = block_pred_Vcov_KF(mf, P, K, T, QQ); - %P = T*(P-K*P(mf,:))*transpose(T)+QQ; - notsteady = max(abs(K(:)-oldK)) > riccati_tol; - oldK = K(:); - end - end; -else - while notsteady && t<smpl - t = t+1; - v = Y(:,t)-a(mf); - F = P(mf,mf) + H; - if rcond(F) < kalman_tol - if ~all(abs(F(:))<kalman_tol) - return - else - a = T*a; - P = T*P*transpose(T)+QQ; - end - else - F_singular = 0; - dF = det(F); - iF = inv(F); - lik(t) = log(dF)+transpose(v)*iF*v; - K = P(:,mf)*iF; - a = T*(a+K*v); - P = T*(P-K*P(mf,:))*transpose(T)+QQ; - notsteady = max(abs(K(:)-oldK)) > riccati_tol; - oldK = K(:); - - end - end -end + %nz_state_var = M_.nz_state_var; + while notsteady && t<smpl + t = t+1; + v = Y(:,t)-a(mf); + F = P(mf,mf) + H; + if rcond(F) < kalman_tol + if ~all(abs(F(:))<kalman_tol) + return + else + a = T*a; + P = T*P*transpose(T)+QQ; + end + else + F_singular = 0; + dF = det(F); + iF = inv(F); + lik(t) = log(dF)+transpose(v)*iF*v; + K = P(:,mf)*iF; + a = T*(a+K*v); + P = block_pred_Vcov_KF(mf, P, K, T, QQ); + %P = T*(P-K*P(mf,:))*transpose(T)+QQ; + notsteady = max(abs(K(:)-oldK)) > riccati_tol; + oldK = K(:); + end + end; + else + while notsteady && t<smpl + t = t+1; + v = Y(:,t)-a(mf); + F = P(mf,mf) + H; + if rcond(F) < kalman_tol + if ~all(abs(F(:))<kalman_tol) + return + else + a = T*a; + P = T*P*transpose(T)+QQ; + end + else + F_singular = 0; + dF = det(F); + iF = inv(F); + lik(t) = log(dF)+transpose(v)*iF*v; + K = P(:,mf)*iF; + a = T*(a+K*v); + P = T*(P-K*P(mf,:))*transpose(T)+QQ; + notsteady = max(abs(K(:)-oldK)) > riccati_tol; + oldK = K(:); + + end + end + end */ bool -not_all_abs_F_bellow_crit(double* F, int size, double crit) +not_all_abs_F_bellow_crit(double *F, int size, double crit) { - int i = 0; - while (i < size && abs(F[i])<crit) - { - i++; - } - if (i < size) - return false; - else - return true; + int i = 0; + while (i < size && abs(F[i]) < crit) + { + i++; + } + if (i < size) + return false; + else + return true; } - double -det(double* F, int dim, lapack_int* ipiv) +det(double *F, int dim, lapack_int *ipiv) { double det = 1.0; for (int i = 0; i < dim; i++) @@ -145,27 +143,25 @@ det(double* F, int dim, lapack_int* ipiv) return det; } - - BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[], double *P_mf[], double *v_pp[], double *K[], double *v_n[], double *a[], double *K_P[], double *P_t_t1[], double *tmp[], double *P[]) { if (nlhs > 3) DYN_MEX_FUNC_ERR_MSG_TXT("block_kalman_filter provides at most 3 output argument."); if (nrhs != 13 && nrhs != 16) DYN_MEX_FUNC_ERR_MSG_TXT("block_kalman_filter requires exactly \n 13 input arguments for standard Kalman filter \nor\n 16 input arguments for missing observations Kalman filter."); - if (nrhs == 16) + if (nrhs == 16) missing_observations = true; else missing_observations = false; if (missing_observations) { - if (! mxIsCell (prhs[0])) + if (!mxIsCell(prhs[0])) DYN_MEX_FUNC_ERR_MSG_TXT("the first input argument of block_missing_observations_kalman_filter must be a Cell Array."); pdata_index = prhs[0]; - if (! mxIsDouble (prhs[1])) + if (!mxIsDouble(prhs[1])) DYN_MEX_FUNC_ERR_MSG_TXT("the second input argument of block_missing_observations_kalman_filter must be a scalar."); number_of_observations = ceil(mxGetScalar(prhs[1])); - if (! mxIsDouble (prhs[2])) + if (!mxIsDouble(prhs[2])) DYN_MEX_FUNC_ERR_MSG_TXT("the third input argument of block_missing_observations_kalman_filter must be a scalar."); no_more_missing_observations = ceil(mxGetScalar(prhs[2])); pT = mxDuplicateArray(prhs[3]); @@ -175,10 +171,10 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const pP = mxDuplicateArray(prhs[7]); pY = mxDuplicateArray(prhs[8]); start = mxGetScalar(prhs[9]); - mfd = (double*)mxGetData(prhs[10]); + mfd = (double *) mxGetData(prhs[10]); kalman_tol = mxGetScalar(prhs[11]); riccati_tol = mxGetScalar(prhs[12]); - nz_state_var = (double*)mxGetData(prhs[13]); + nz_state_var = (double *) mxGetData(prhs[13]); n_diag = mxGetScalar(prhs[14]); pure_obs = mxGetScalar(prhs[15]); } @@ -196,10 +192,10 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const n = mxGetN(pT); // Number of state variables. pp = mxGetM(pY); // Maximum number of observed variables. smpl = mxGetN(pY); // Sample size. ; - mfd = (double*)mxGetData(prhs[7]); + mfd = (double *) mxGetData(prhs[7]); kalman_tol = mxGetScalar(prhs[8]); riccati_tol = mxGetScalar(prhs[9]); - nz_state_var = (double*)mxGetData(prhs[10]); + nz_state_var = (double *) mxGetData(prhs[10]); n_diag = mxGetScalar(prhs[11]); pure_obs = mxGetScalar(prhs[12]); } @@ -209,35 +205,32 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const H = mxGetPr(pH); *P = mxGetPr(pP); Y = mxGetPr(pY); - + n = mxGetN(pT); // Number of state variables. pp = mxGetM(pY); // Maximum number of observed variables. smpl = mxGetN(pY); // Sample size. ; n_state = n - pure_obs; - - /*mexPrintf("T\n"); - mexDisp(pT);*/ + mexDisp(pT);*/ H_size = mxGetN(pH) * mxGetM(pH); - - + n_shocks = mxGetM(pQ); - + if (missing_observations) - if (mxGetNumberOfElements(pdata_index) != (unsigned int)smpl) + if (mxGetNumberOfElements(pdata_index) != (unsigned int) smpl) DYN_MEX_FUNC_ERR_MSG_TXT("the number of element in the cell array passed to block_missing_observation_kalman_filter as first argument has to be equal to the smpl size"); - - i_nz_state_var = (int*)mxMalloc(n*sizeof(int)); + + i_nz_state_var = (int *) mxMalloc(n*sizeof(int)); for (int i = 0; i < n; i++) i_nz_state_var[i] = nz_state_var[i]; pa = mxCreateDoubleMatrix(n, 1, mxREAL); // State vector. *a = mxGetPr(pa); - tmp_a = (double*)mxMalloc(n * sizeof(double)); + tmp_a = (double *) mxMalloc(n * sizeof(double)); dF = 0.0; // det(F). - + p_tmp1 = mxCreateDoubleMatrix(n, n_shocks, mxREAL); tmp1 = mxGetPr(p_tmp1); t = 0; // Initialization of the time index. @@ -247,13 +240,13 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const LIK = 0.0; // Default value of the log likelihood. notsteady = true; // Steady state flag. F_singular = true; - *v_pp = (double*)mxMalloc(pp * sizeof(double)); - *v_n = (double*)mxMalloc(n * sizeof(double)); - mf = (int*)mxMalloc(pp * sizeof(int)); + *v_pp = (double *) mxMalloc(pp * sizeof(double)); + *v_n = (double *) mxMalloc(n * sizeof(double)); + mf = (int *) mxMalloc(pp * sizeof(int)); for (int i = 0; i < pp; i++) mf[i] = mfd[i] - 1; - pi = atan2((double)0.0,(double)-1.0); - + pi = atan2((double) 0.0, (double) -1.0); + /*compute QQ = R*Q*transpose(R)*/ // Variance of R times the vector of structural innovations.; // tmp = R * Q; for (int i = 0; i < n; i++) @@ -277,7 +270,7 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const QQ[i + j * n] = QQ[j + i * n] = res; } mxDestroyArray(p_tmp1); - + pv = mxCreateDoubleMatrix(pp, 1, mxREAL); v = mxGetPr(pv); pF = mxCreateDoubleMatrix(pp, pp, mxREAL); @@ -285,9 +278,9 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const piF = mxCreateDoubleMatrix(pp, pp, mxREAL); iF = mxGetPr(piF); lw = pp * 4; - w = (double*)mxMalloc(lw * sizeof(double)); - iw = (lapack_int*)mxMalloc(pp * sizeof(lapack_int)); - ipiv = (lapack_int*)mxMalloc(pp * sizeof(lapack_int)); + w = (double *) mxMalloc(lw * sizeof(double)); + iw = (lapack_int *) mxMalloc(pp * sizeof(lapack_int)); + ipiv = (lapack_int *) mxMalloc(pp * sizeof(lapack_int)); info = 0; #if defined(BLAS) || defined(CUBLAS) p_tmp = mxCreateDoubleMatrix(n, n, mxREAL); @@ -298,8 +291,8 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const *K = mxGetPr(pK); p_K_P = mxCreateDoubleMatrix(n, n, mxREAL); *K_P = mxGetPr(p_K_P); - oldK = (double*)mxMalloc(n * n * sizeof(double)); - *P_mf = (double*)mxMalloc(n * n * sizeof(double)); + oldK = (double *) mxMalloc(n * n * sizeof(double)); + *P_mf = (double *) mxMalloc(n * n * sizeof(double)); for (int i = 0; i < n * n; i++) oldK[i] = Inf; #else @@ -311,14 +304,14 @@ BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const *K = mxGetPr(pK); p_K_P = mxCreateDoubleMatrix(n_state, n_state, mxREAL); *K_P = mxGetPr(p_K_P); - oldK = (double*)mxMalloc(n * pp * sizeof(double)); - *P_mf = (double*)mxMalloc(n * pp * sizeof(double)); + oldK = (double *) mxMalloc(n * pp * sizeof(double)); + *P_mf = (double *) mxMalloc(n * pp * sizeof(double)); for (int i = 0; i < n * pp; i++) oldK[i] = Inf; #endif } -void +void BlockKalmanFilter::block_kalman_filter_ss(double *P_mf, double *v_pp, double *K, double *v_n, double *a, double *K_P, double *P_t_t1, double *tmp, double *P) { if (t+1 < smpl) @@ -328,7 +321,7 @@ BlockKalmanFilter::block_kalman_filter_ss(double *P_mf, double *v_pp, double *K, //v = Y(:,t)-a(mf); for (int i = 0; i < pp; i++) v[i] = Y[i + t * pp] - a[mf[i]]; - + //a = T*(a+K*v); for (int i = pure_obs; i < n; i++) { @@ -344,7 +337,7 @@ BlockKalmanFilter::block_kalman_filter_ss(double *P_mf, double *v_pp, double *K, res += T[j * n + i] * v_n[j]; a[i] = res; } - + //lik(t) = transpose(v)*iF*v; for (int i = 0; i < pp; i++) { @@ -371,19 +364,19 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, { while (notsteady && t < smpl) { - if(missing_observations) + if (missing_observations) { // retrieve the d_index - pd_index = mxGetCell( pdata_index, t); - dd_index = (double*)mxGetData(pd_index); + pd_index = mxGetCell(pdata_index, t); + dd_index = (double *) mxGetData(pd_index); size_d_index = mxGetM(pd_index); d_index.resize(size_d_index); for (int i = 0; i < size_d_index; i++) { d_index[i] = ceil(dd_index[i]) - 1; } - + //v = Y(:,t) - a(mf) int i_i = 0; //#pragma omp parallel for shared(v, i_i, d_index) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) @@ -393,8 +386,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, v[i_i] = Y[*i + t * pp] - a[mf[*i]]; i_i++; } - - + //F = P(mf,mf) + H; i_i = 0; if (H_size == 1) @@ -417,16 +409,16 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, iF[i_i + j_j * size_d_index] = F[i_i + j_j * size_d_index] = P[mf[*i] + mf[*j] * n] + H[*i + *j * pp]; } } - + } else { size_d_index = pp; - + //v = Y(:,t) - a(mf) for (int i = 0; i < pp; i++) v[i] = Y[i + t * pp] - a[mf[i]]; - + //F = P(mf,mf) + H; if (H_size == 1) { @@ -441,20 +433,21 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, iF[i + j * pp] = F[i + j * pp] = P[mf[i] + mf[j] * n] + H[i + j * pp]; } } - - + /* Computes the norm of iF */ double anorm = dlange("1", &size_d_index, &size_d_index, iF, &size_d_index, w); //mexPrintf("anorm = %f\n",anorm); /* Modifies F in place with a LU decomposition */ dgetrf(&size_d_index, &size_d_index, iF, &size_d_index, ipiv, &info); - if (info != 0) mexPrintf("dgetrf failure with error %d\n", (int) info); - + if (info != 0) + mexPrintf("dgetrf failure with error %d\n", (int) info); + /* Computes the reciprocal norm */ dgecon("1", &size_d_index, iF, &size_d_index, &anorm, &rcond, w, iw, &info); - if (info != 0) mexPrintf("dgecon failure with error %d\n", (int) info); - + if (info != 0) + mexPrintf("dgecon failure with error %d\n", (int) info); + if (rcond < kalman_tol) if (not_all_abs_F_bellow_crit(F, size_d_index * size_d_index, kalman_tol)) //~all(abs(F(:))<kalman_tol) { @@ -481,55 +474,56 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, res += T[i + j *n] * a[j]; tmp_a[i] = res; } - memcpy(a, tmp_a, n * sizeof(double)); + memcpy(a, tmp_a, n * sizeof(double)); - //P = T*P*transpose(T)+QQ; - memset(tmp, 0, n * n_state * sizeof(double)); + //P = T*P*transpose(T)+QQ; + memset(tmp, 0, n * n_state * sizeof(double)); - for (int i = 0; i < n; i++) - for (int j = pure_obs; j < n; j++) - { - int j1 = j - pure_obs; - int j1_n_state = j1 * n_state - pure_obs; - for (int k = pure_obs; k < i_nz_state_var[i]; k++) - tmp[i + j1 * n ] += T[i + k * n] * P[k + j1_n_state]; - } + for (int i = 0; i < n; i++) + for (int j = pure_obs; j < n; j++) + { + int j1 = j - pure_obs; + int j1_n_state = j1 * n_state - pure_obs; + for (int k = pure_obs; k < i_nz_state_var[i]; k++) + tmp[i + j1 * n ] += T[i + k * n] * P[k + j1_n_state]; + } - memset(P, 0, n * n * sizeof(double)); - int n_n_obs = n * pure_obs; - for (int i = 0; i < n; i++) - for (int j = i; j < n; j++) + memset(P, 0, n * n * sizeof(double)); + int n_n_obs = n * pure_obs; + for (int i = 0; i < n; i++) + for (int j = i; j < n; j++) + { + for (int k = pure_obs; k < i_nz_state_var[j]; k++) + { + int k_n = k * n; + P[i * n + j] += tmp[i + k_n - n_n_obs] * T[j + k_n]; + } + } + + for (int i = 0; i < n; i++) { - for (int k = pure_obs; k < i_nz_state_var[j]; k++) - { - int k_n = k * n; - P[i * n + j] += tmp[i + k_n - n_n_obs] * T[j + k_n]; - } + for (int j = i; j < n; j++) + P[j + i * n] += QQ[j + i * n]; + for (int j = i + 1; j < n; j++) + P[i + j * n] = P[j + i * n]; } - - for ( int i = 0; i < n; i++) - { - for ( int j = i ; j < n; j++) - P[j + i * n] += QQ[j + i * n]; - for ( int j = i + 1; j < n; j++) - P[i + j * n] = P[j + i * n]; - } - } + } else { F_singular = false; - + //dF = det(F); dF = det(iF, size_d_index, ipiv); //iF = inv(F); //int lwork = 4/*2*/* pp; dgetri(&size_d_index, iF, &size_d_index, ipiv, w, &lw, &info); - if (info != 0) mexPrintf("dgetri failure with error %d\n", (int) info); + if (info != 0) + mexPrintf("dgetri failure with error %d\n", (int) info); //lik(t) = log(dF)+transpose(v)*iF*v; #ifdef USE_OMP -#pragma omp parallel for shared(v_pp) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) +# pragma omp parallel for shared(v_pp) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) #endif for (int i = 0; i < size_d_index; i++) { @@ -550,7 +544,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, { //K = P(:,mf)*iF; #ifdef USE_OMP -#pragma omp parallel for shared(P_mf) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) +# pragma omp parallel for shared(P_mf) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) #endif for (int i = 0; i < n; i++) { @@ -567,9 +561,9 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, for (int j = 0; j < pp; j++) P_mf[i + j * n] = P[i + mf[j] * n]; } - + #ifdef USE_OMP -#pragma omp parallel for shared(K) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) +# pragma omp parallel for shared(K) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) #endif for (int i = 0; i < n; i++) for (int j = 0; j < size_d_index; j++) @@ -580,10 +574,10 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, res += P_mf[i + k * n] * iF[j_pp + k]; K[i + j * n] = res; } - + //a = T*(a+K*v); #ifdef USE_OMP -#pragma omp parallel for shared(v_n) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) +# pragma omp parallel for shared(v_n) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) #endif for (int i = pure_obs; i < n; i++) { @@ -592,9 +586,9 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, res += K[j * n + i] * v[j]; v_n[i] = res + a[i]; } - + #ifdef USE_OMP -#pragma omp parallel for shared(a) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) +# pragma omp parallel for shared(a) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) #endif for (int i = 0; i < n; i++) { @@ -603,7 +597,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, res += T[j * n + i] * v_n[j]; a[i] = res; } - + if (missing_observations) { //P = T*(P-K*P(mf,:))*transpose(T)+QQ; @@ -617,17 +611,17 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, { //P = T*(P-K*P(mf,:))*transpose(T)+QQ; #ifdef USE_OMP -#pragma omp parallel for shared(P_mf) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) +# pragma omp parallel for shared(P_mf) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) #endif for (int i = 0; i < pp; i++) for (int j = pure_obs; j < n; j++) P_mf[i + j * pp] = P[mf[i] + j * n]; } - + #ifdef BLAS -#ifdef USE_OMP -#pragma omp parallel for shared(K_P) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) -#endif +# ifdef USE_OMP +# pragma omp parallel for shared(K_P) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) +# endif for (int i = 0; i < n; i++) for (int j = i; j < n; j++) { @@ -649,7 +643,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, memcpy(P, QQ, n * n *sizeof(double)); blas_int n_b = n; /*mexPrintf("sizeof(n_b)=%d, n_b=%d, sizeof(n)=%d, n=%d\n",sizeof(n_b),n_b,sizeof(n),n); - mexEvalString("drawnow;");*/ + mexEvalString("drawnow;");*/ dsymm("R", "U", &n_b, &n_b, &one, P_t_t1, &n_b, T, &n_b, &zero, @@ -659,8 +653,8 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, T, &n_b, &one, P, &n_b); #else -#ifdef CUBLAS - for (int i = 0; i < n; i++) +# ifdef CUBLAS + for (int i = 0; i < n; i++) for (int j = i; j < n; j++) { double res = 0.0; @@ -689,29 +683,29 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, return false; } /*int device; - cudaGetDevice(&device);*/ + cudaGetDevice(&device);*/ int n2 = n * n; - double* d_A = 0; - double* d_B = 0; - double* d_C = 0; - double* d_D = 0; + double *d_A = 0; + double *d_B = 0; + double *d_C = 0; + double *d_D = 0; // Allocate device memory for the matrices - if (cudaMalloc((void**)&d_A, n2 * sizeof(double)) != cudaSuccess) + if (cudaMalloc((void **) &d_A, n2 * sizeof(double)) != cudaSuccess) { mexPrintf("!!!! device memory allocation error (allocate A)\n"); return false; } - if (cudaMalloc((void**)&d_B, n2 * sizeof(d_B[0])) != cudaSuccess) + if (cudaMalloc((void **) &d_B, n2 * sizeof(d_B[0])) != cudaSuccess) { mexPrintf("!!!! device memory allocation error (allocate B)\n"); return false; } - if (cudaMalloc((void**)&d_C, n2 * sizeof(d_C[0])) != cudaSuccess) + if (cudaMalloc((void **) &d_C, n2 * sizeof(d_C[0])) != cudaSuccess) { mexPrintf("!!!! device memory allocation error (allocate C)\n"); return false; } - if (cudaMalloc((void**)&d_D, n2 * sizeof(d_D[0])) != cudaSuccess) + if (cudaMalloc((void **) &d_D, n2 * sizeof(d_D[0])) != cudaSuccess) { mexPrintf("!!!! device memory allocation error (allocate D)\n"); return false; @@ -734,7 +728,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, { mexPrintf("!!!! device access error (write C)\n"); return false; - } + } mexPrintf("just before calling\n"); mexEvalString("drawnow;"); status = cublasSetVector(n2, sizeof(QQ[0]), QQ, 1, d_D, 1); @@ -742,22 +736,22 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, { mexPrintf("!!!! device access error (write D)\n"); return false; - } + } // Performs operation using plain C code cublasDsymm(handle, CUBLAS_SIDE_RIGHT, CUBLAS_FILL_MODE_UPPER, n, n, - &one, d_A, n, - d_B, n, &zero, - d_C, n); + &one, d_A, n, + d_B, n, &zero, + d_C, n); /*dgemm("N", "T", &n_b, &n_b, - &n_b, &one, tmp, &n_b, - T, &n_b, &one, - P, &n_b);*/ + &n_b, &one, tmp, &n_b, + T, &n_b, &one, + P, &n_b);*/ cublasDgemm(handle, CUBLAS_OP_N, CUBLAS_OP_T, n, n, - n, &one, d_C, n, - d_B, n, &one, - d_D, n); + n, &one, d_C, n, + d_B, n, &one, + d_D, n); //double_symm(n, &one, h_A, h_B, &zero, h_C); status = cublasGetVector(n2, sizeof(P[0]), d_D, 1, P, 1); @@ -767,14 +761,14 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, return false; } -#else -#ifdef USE_OMP -#pragma omp parallel for shared(K_P) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) -#endif +# else +# ifdef USE_OMP +# pragma omp parallel for shared(K_P) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) +# endif for (int i = pure_obs; i < n; i++) { unsigned int i1 = i - pure_obs; - for (int j = i ; j < n; j++) + for (int j = i; j < n; j++) { unsigned int j1 = j - pure_obs; double res = 0.0; @@ -785,9 +779,9 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, } } -#ifdef USE_OMP -#pragma omp parallel for shared(P_t_t1) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) -#endif +# ifdef USE_OMP +# pragma omp parallel for shared(P_t_t1) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) +# endif for (int i = pure_obs; i < n; i++) { unsigned int i1 = i - pure_obs; @@ -801,9 +795,9 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, memset(tmp, 0, n * n_state * sizeof(double)); -#ifdef USE_OMP -#pragma omp parallel for shared(tmp) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) -#endif +# ifdef USE_OMP +# pragma omp parallel for shared(tmp) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) +# endif for (int i = 0; i < n; i++) { int max_k = i_nz_state_var[i]; @@ -811,7 +805,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, { int j1 = j - pure_obs; int j1_n_state = j1 * n_state - pure_obs; - int indx_tmp = i + j1 * n ; + int indx_tmp = i + j1 * n; for (int k = pure_obs; k < max_k; k++) tmp[indx_tmp] += T[i + k * n] * P_t_t1[k + j1_n_state]; } @@ -819,10 +813,10 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, memset(P, 0, n * n * sizeof(double)); - int n_n_obs = - n * pure_obs; -#ifdef USE_OMP -#pragma omp parallel for shared(P) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) -#endif + int n_n_obs = -n * pure_obs; +# ifdef USE_OMP +# pragma omp parallel for shared(P) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) +# endif for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) @@ -837,17 +831,17 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, } } -#ifdef USE_OMP -#pragma omp parallel for shared(P) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) -#endif - for ( int i = 0; i < n; i++) +# ifdef USE_OMP +# pragma omp parallel for shared(P) num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) +# endif + for (int i = 0; i < n; i++) { - for ( int j = i ; j < n; j++) + for (int j = i; j < n; j++) P[j + i * n] += QQ[j + i * n]; - for ( int j = i + 1; j < n; j++) + for (int j = i + 1; j < n; j++) P[i + j * n] = P[j + i * n]; } -#endif +# endif #endif if (t >= no_more_missing_observations) { @@ -861,7 +855,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, notsteady = max_abs > riccati_tol; //oldK = K(:); - + memcpy(oldK, K, n * pp * sizeof(double)); } } @@ -875,8 +869,7 @@ BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, return true; } - -void +void BlockKalmanFilter::return_results_and_clean(int nlhs, mxArray *plhs[], double *P_mf[], double *v_pp[], double *K[], double *v_n[], double *a[], double *K_P[], double *P_t_t1[], double *tmp[], double *P[]) { plhs[0] = mxCreateDoubleScalar(0); @@ -884,7 +877,7 @@ BlockKalmanFilter::return_results_and_clean(int nlhs, mxArray *plhs[], double *P if (nlhs >= 2) { plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL); - double* pind = mxGetPr(plhs[1]); + double *pind = mxGetPr(plhs[1]); pind[0] = LIK; } @@ -903,7 +896,7 @@ BlockKalmanFilter::return_results_and_clean(int nlhs, mxArray *plhs[], double *P mxFree(ipiv); mxFree(oldK); //mxFree(P_mf); - + mxDestroyArray(pa); mxDestroyArray(p_tmp); mxDestroyArray(pQQ); @@ -918,9 +911,8 @@ BlockKalmanFilter::return_results_and_clean(int nlhs, mxArray *plhs[], double *P void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { - double *P_mf, * v_pp, *v_n, *a, *K, *K_P, *P_t_t1, *tmp, *P; + double *P_mf, *v_pp, *v_n, *a, *K, *K_P, *P_t_t1, *tmp, *P; BlockKalmanFilter block_kalman_filter(nlhs, plhs, nrhs, prhs, &P_mf, &v_pp, &K, &v_n, &a, &K_P, &P_t_t1, &tmp, &P); if (block_kalman_filter.block_kalman_filter(nlhs, plhs, P_mf, v_pp, K, K_P, a, K_P, P_t_t1, tmp, P)) block_kalman_filter.return_results_and_clean(nlhs, plhs, &P_mf, &v_pp, &K, &K_P, &a, &K_P, &P_t_t1, &tmp, &P); } - diff --git a/mex/sources/block_kalman_filter/block_kalman_filter.h b/mex/sources/block_kalman_filter/block_kalman_filter.h index 98803e02440f016df26be3f5631ed4675fda883f..83eac9a4499f3f61529a084c825e431208f7c91a 100644 --- a/mex/sources/block_kalman_filter/block_kalman_filter.h +++ b/mex/sources/block_kalman_filter/block_kalman_filter.h @@ -32,30 +32,30 @@ using namespace std; class BlockKalmanFilter { - public: - mxArray *pT , *pR, *pQ, *pH, *pP, *pY, *pQQ, *pv, *pF, *piF, *p_P_t_t1, *pK, *p_K_P; - double *T , *R, *Q , *H, *Y, *mfd, *QQ, *v, *F, *iF; +public: + mxArray *pT, *pR, *pQ, *pH, *pP, *pY, *pQQ, *pv, *pF, *piF, *p_P_t_t1, *pK, *p_K_P; + double *T, *R, *Q, *H, *Y, *mfd, *QQ, *v, *F, *iF; int start, pure_obs, smpl, n, n_state, n_shocks, H_size; double kalman_tol, riccati_tol, dF, LIK, Inf, pi; lapack_int pp, lw, info; - double* nz_state_var; + double *nz_state_var; int *i_nz_state_var, *mf; int n_diag, t; mxArray *M_; - mxArray* pa, *p_tmp, *p_tmp1, *plik; + mxArray *pa, *p_tmp, *p_tmp1, *plik; double *tmp_a, *tmp1, *lik, *v_n, *w, *oldK; bool notsteady, F_singular, missing_observations; lapack_int *iw, *ipiv; double anorm, rcond; lapack_int size_d_index; int no_more_missing_observations, number_of_observations; - const mxArray* pdata_index; + const mxArray *pdata_index; vector<int> d_index; - const mxArray* pd_index; - double* dd_index; + const mxArray *pd_index; + double *dd_index; - public: +public: BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[], double *P_mf[], double *v_pp[], double *K[], double *v_n[], double *a[], double *K_P[], double *P_t_t1[], double *tmp[], double *P[]); bool block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, double *v_pp, double *K, double *v_n, double *a, double *K_P, double *P_t_t1, double *tmp, double *P); void block_kalman_filter_ss(double *P_mf, double *v_pp, double *K, double *v_n, double *a, double *K_P, double *P_t_t1, double *tmp, double *P); diff --git a/mex/sources/bytecode/ErrorHandling.hh b/mex/sources/bytecode/ErrorHandling.hh index 7429a877c7e232d042f828ec070ca16bd45fbe91..b03599444164566125186d40e0aad4c62e9ebcb7 100644 --- a/mex/sources/bytecode/ErrorHandling.hh +++ b/mex/sources/bytecode/ErrorHandling.hh @@ -31,11 +31,11 @@ #define _USE_MATH_DEFINES #include <math.h> #ifndef M_PI -#define M_PI (3.14159265358979323846) +# define M_PI (3.14159265358979323846) #endif #ifndef M_SQRT2 -#define M_SQRT2 1.41421356237309504880 +# define M_SQRT2 1.41421356237309504880 #endif #ifdef DEBUG_EX @@ -50,114 +50,114 @@ #endif #ifdef _MSC_VER -#include <limits> -#define M_E 2.71828182845904523536 -#define M_LOG2E 1.44269504088896340736 -#define M_LOG10E 0.434294481903251827651 -#define M_LN2 0.693147180559945309417 -#define M_LN10 2.30258509299404568402 -#define M_PI 3.14159265358979323846 -#define M_PI_2 1.57079632679489661923 -#define M_PI_4 0.785398163397448309616 -#define M_1_PI 0.318309886183790671538 -#define M_2_PI 0.636619772367581343076 -#define M_1_SQRTPI 0.564189583547756286948 -#define M_2_SQRTPI 1.12837916709551257390 -#define M_SQRT2 1.41421356237309504880 -#define M_SQRT_2 0.707106781186547524401 -#define NAN numeric_limits<double>::quiet_NaN() +# include <limits> +# define M_E 2.71828182845904523536 +# define M_LOG2E 1.44269504088896340736 +# define M_LOG10E 0.434294481903251827651 +# define M_LN2 0.693147180559945309417 +# define M_LN10 2.30258509299404568402 +# define M_PI 3.14159265358979323846 +# define M_PI_2 1.57079632679489661923 +# define M_PI_4 0.785398163397448309616 +# define M_1_PI 0.318309886183790671538 +# define M_2_PI 0.636619772367581343076 +# define M_1_SQRTPI 0.564189583547756286948 +# define M_2_SQRTPI 1.12837916709551257390 +# define M_SQRT2 1.41421356237309504880 +# define M_SQRT_2 0.707106781186547524401 +# define NAN numeric_limits<double>::quiet_NaN() -#define isnan(x) _isnan(x) -#define isinf(x) (!_finite(x)) -#define fpu_error(x) (isinf(x) || isnan(x)) +# define isnan(x) _isnan(x) +# define isinf(x) (!_finite(x)) +# define fpu_error(x) (isinf(x) || isnan(x)) -#define finite(x) _finite(x) +# define finite(x) _finite(x) class MSVCpp_missings { - public: +public: inline double asinh(double x) const - { - if(x==0.0) - return 0.0; - double ax = abs(x); - return log(x+ax*sqrt(1.+1./(ax*ax))); - } + { + if (x == 0.0) + return 0.0; + double ax = abs(x); + return log(x+ax*sqrt(1.+1./(ax*ax))); + } inline double acosh(double x) const - { - if(x==0.0) - return 0.0; - double ax = abs(x); - return log(x+ax*sqrt(1.-1./(ax*ax))); - } + { + if (x == 0.0) + return 0.0; + double ax = abs(x); + return log(x+ax*sqrt(1.-1./(ax*ax))); + } inline double atanh(double x) const - { - return log((1+x)/(1-x))/2; - } + { + return log((1+x)/(1-x))/2; + } inline double erf(double x) const - { - const double a1 = -1.26551223, a2 = 1.00002368, - a3 = 0.37409196, a4 = 0.09678418, - a5 = -0.18628806, a6 = 0.27886807, - a7 = -1.13520398, a8 = 1.48851587, - a9 = -0.82215223, a10 = 0.17087277; - double v = 1; - double z = abs(x); - if (z <= 0) - return v; - double t = 1 / (1 + 0.5 * z); - v = t*exp((-z*z) +a1+t*(a2+t*(a3+t*(a4+t*(a5+t*(a6+t*(a7+t*(a8+t*(a9+t*a10))))))))); - if (x < 0) - v = 2 - v; - return 1 - v; - } + { + const double a1 = -1.26551223, a2 = 1.00002368, + a3 = 0.37409196, a4 = 0.09678418, + a5 = -0.18628806, a6 = 0.27886807, + a7 = -1.13520398, a8 = 1.48851587, + a9 = -0.82215223, a10 = 0.17087277; + double v = 1; + double z = abs(x); + if (z <= 0) + return v; + double t = 1 / (1 + 0.5 * z); + v = t*exp((-z*z) +a1+t*(a2+t*(a3+t*(a4+t*(a5+t*(a6+t*(a7+t*(a8+t*(a9+t*a10))))))))); + if (x < 0) + v = 2 - v; + return 1 - v; + } inline double nearbyint(double x) const - { - return floor(x + 0.5); - } + { + return floor(x + 0.5); + } inline double fmax(double x, double y) const - { - if (x > y) - return x; - else - return y; - } + { + if (x > y) + return x; + else + return y; + } inline double fmin(double x, double y) const - { - if (x < y) - return x; - else - return y; - } + { + if (x < y) + return x; + else + return y; + } }; #endif #ifdef __MINGW32__ -#define __CROSS_COMPILATION__ +# define __CROSS_COMPILATION__ #endif #ifdef __MINGW64__ -#define __CROSS_COMPILATION__ +# define __CROSS_COMPILATION__ #endif #ifdef __CROSS_COMPILATION__ -#define M_PI 3.14159265358979323846 -#define M_SQRT2 1.41421356237309504880 -#define finite(x) !std::isfinite(x) +# define M_PI 3.14159265358979323846 +# define M_SQRT2 1.41421356237309504880 +# define finite(x) !std::isfinite(x) #endif //#define DEBUG @@ -166,11 +166,9 @@ using namespace std; const int NO_ERROR_ON_EXIT = 0; const int ERROR_ON_EXIT = 1; - typedef vector<pair<Tags, void * > > code_liste_type; typedef code_liste_type::const_iterator it_code_type; - class GeneralExceptionHandling { string ErrorMsg; @@ -253,7 +251,7 @@ public: value2(value2_arg) { ostringstream tmp; - if (fabs(value1) > 1e-10 ) + if (fabs(value1) > 1e-10) tmp << " with X=" << value1 << "\n"; else tmp << " with X=" << value1 << " and a=" << value2 << "\n"; @@ -292,11 +290,11 @@ struct s_plan }; struct table_conditional_local_type - { - bool is_cond; - int var_exo, var_endo; - double constrained_value; - }; +{ + bool is_cond; + int var_exo, var_endo; + double constrained_value; +}; typedef vector<table_conditional_local_type> vector_table_conditional_local_type; typedef map< int, vector_table_conditional_local_type > table_conditional_global_type; #ifdef MATLAB_MEX_FILE @@ -330,9 +328,9 @@ public: ExpressionType EQN_type; it_code_type it_code_expr; - /*unsigned int*/size_t nb_endo, nb_exo, nb_param; + /*unsigned int*/ size_t nb_endo, nb_exo, nb_param; char *P_endo_names, *P_exo_names, *P_param_names; - size_t/*unsigned int*/ endo_name_length, exo_name_length, param_name_length; + size_t /*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; vector<pair<string, pair<SymbolType, unsigned int> > > Variable_list; @@ -388,7 +386,7 @@ public: string tmp_n(str.length(), ' '); string dollar, pound, tilde; dollar = "$"; - pound = "�"; + pound = "£"; tilde = "~"; for (unsigned int i = 0; i < str.length(); i++) { @@ -397,9 +395,9 @@ public: else { if (dollar.compare(&str[i]) == 0) - pos1 = int(temp.length()); + pos1 = int (temp.length()); else - pos2 = int(temp.length()); + pos2 = int (temp.length()); if (pos1 >= 0 && pos2 >= 0) { tmp_n.erase(pos1, pos2-pos1+1); @@ -416,14 +414,14 @@ public: load_variable_list() { ostringstream res; - for (unsigned int variable_num = 0; variable_num < (unsigned int)nb_endo; variable_num++) + for (unsigned int variable_num = 0; variable_num < (unsigned int) nb_endo; variable_num++) { 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)]; Variable_list.push_back(make_pair(res.str(), make_pair(eEndogenous, variable_num))); } - for (unsigned int variable_num = 0; variable_num < (unsigned int)nb_exo; variable_num++) + for (unsigned int variable_num = 0; variable_num < (unsigned int) nb_exo; variable_num++) { for (unsigned int i = 0; i < exo_name_length; i++) if (P_exo_names[CHAR_LENGTH*(variable_num+i*nb_exo)] != ' ') @@ -453,7 +451,7 @@ public: } i++; } - return(-1); + return (-1); } inline string @@ -634,8 +632,8 @@ public: while (go_on) { #ifdef MATLAB_MEX_FILE - if ( utIsInterruptPending() ) - throw UserExceptionHandling(); + if (utIsInterruptPending()) + throw UserExceptionHandling(); #endif switch (it_code->first) { @@ -701,7 +699,7 @@ public: var = ((FLDV_ *) it_code->second)->get_pos(); #ifdef DEBUG mexPrintf("FLDV_ Param var=%d\n", var); - mexPrintf("get_variable(eParameter, var)=%s\n",get_variable(eParameter, var).c_str()); + mexPrintf("get_variable(eParameter, var)=%s\n", get_variable(eParameter, var).c_str()); mexEvalString("drawnow;"); #endif Stack.push(get_variable(eParameter, var)); @@ -713,7 +711,7 @@ public: lag = ((FLDV_ *) it_code->second)->get_lead_lag(); #ifdef DEBUG mexPrintf("FLDV_ endo var=%d, lag=%d\n", var, lag); - mexPrintf("get_variable(eEndogenous, var)=%s, compute=%d\n",get_variable(eEndogenous, var).c_str(), compute); + mexPrintf("get_variable(eEndogenous, var)=%s, compute=%d\n", get_variable(eEndogenous, var).c_str(), compute); mexPrintf("it_=%d, lag=%d, y_size=%d, var=%d, y=%x\n", it_, lag, y_size, var, y); mexEvalString("drawnow;"); #endif @@ -1331,7 +1329,7 @@ public: tmp_out << "$"; tmp_out << " / "; if (isinf(r)) - tmp_out << "�"; + tmp_out << "£"; } else tmp_out << " / "; @@ -1494,7 +1492,7 @@ public: if (compute) { if (isnan(r)) - tmp_out << "$ ^ " << "�"; + tmp_out << "$ ^ " << "£"; else tmp_out << " ^ "; } @@ -1514,7 +1512,7 @@ public: Stack.pop(); if (compute) { - int derivOrder = int(nearbyint(Stackf.top())); + int derivOrder = int (nearbyint(Stackf.top())); Stackf.pop(); if (fabs(v1f) < NEAR_ZERO && v2f > 0 && derivOrder > v2f @@ -1536,7 +1534,7 @@ public: if (compute) { if (isnan(r)) - tmp_out << "$ PowerDeriv " << "�"; + tmp_out << "$ PowerDeriv " << "£"; else tmp_out << "PowerDeriv"; } @@ -1610,7 +1608,7 @@ public: if (compute) { if (isnan(r)) - tmp_out << "$log" << "�" << "(" << v1 << ")"; + tmp_out << "$log" << "£" << "(" << v1 << ")"; else tmp_out << "log(" << v1 << ")"; } @@ -1628,7 +1626,7 @@ public: if (compute) { if (isnan(r)) - tmp_out << "$log10" << "�" << "(" << v1 << ")"; + tmp_out << "$log10" << "£" << "(" << v1 << ")"; else tmp_out << "log10(" << v1 << ")"; } @@ -2234,17 +2232,18 @@ public: it_code_ret = it_code; return (tmp_out.str()); } - void - -inline test_mxMalloc(void* z, int line, string file, string func, int amount) -{ - if (!z && (amount > 0)) - { - ostringstream tmp; - tmp << " mxMalloc: out of memory " << amount << " bytes required at line " << line << " in function " << func << " (file " << file; - throw FatalExceptionHandling(tmp.str()); - } -} + void + + inline + test_mxMalloc(void *z, int line, string file, string func, int amount) + { + if (!z && (amount > 0)) + { + ostringstream tmp; + tmp << " mxMalloc: out of memory " << amount << " bytes required at line " << line << " in function " << func << " (file " << file; + throw FatalExceptionHandling(tmp.str()); + } + } }; diff --git a/mex/sources/bytecode/Evaluate.cc b/mex/sources/bytecode/Evaluate.cc index b9a2944456982b9146de0ab15d62392822208400..c0860b011451240bed25e427dda82dd5a9313f76 100644 --- a/mex/sources/bytecode/Evaluate.cc +++ b/mex/sources/bytecode/Evaluate.cc @@ -35,8 +35,8 @@ Evaluate::Evaluate() block = -1; } -Evaluate::Evaluate(const int y_size_arg, const int y_kmin_arg, const int y_kmax_arg, const bool print_it_arg, const bool steady_state_arg, const int periods_arg, const int minimal_solving_periods_arg, const double slowc_arg): -print_it(print_it_arg), minimal_solving_periods(minimal_solving_periods_arg) +Evaluate::Evaluate(const int y_size_arg, const int y_kmin_arg, const int y_kmax_arg, const bool print_it_arg, const bool steady_state_arg, const int periods_arg, const int minimal_solving_periods_arg, const double slowc_arg) : + print_it(print_it_arg), minimal_solving_periods(minimal_solving_periods_arg) { symbol_table_endo_nbr = 0; Block_List_Max_Lag = 0; @@ -107,7 +107,6 @@ Evaluate::log10_1(double a) return r; } - void Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int block_num, const int size, const bool steady_state,*/ const bool no_derivative) { @@ -137,14 +136,14 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int } } #ifdef MATLAB_MEX_FILE - if ( utIsInterruptPending() ) - throw UserExceptionHandling(); + if (utIsInterruptPending()) + throw UserExceptionHandling(); #endif while (go_on) { #ifdef DEBUG - mexPrintf("it_code->first=%d\n",it_code->first); + mexPrintf("it_code->first=%d\n", it_code->first); #endif switch (it_code->first) { @@ -738,7 +737,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int pos_col = ((FSTPG3_ *) it_code->second)->get_col_pos(); #ifdef DEBUG mexPrintf("Endo eq=%d, pos_col=%d, size=%d, jacob=%x\n", eq, pos_col, size, jacob); - mexPrintf("jacob=%x\n",jacob); + mexPrintf("jacob=%x\n", jacob); #endif jacob[eq + size*pos_col] = rr; break; @@ -843,7 +842,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int case oLess: Stack.push(double (v1 < v2)); #ifdef DEBUG - mexPrintf("v1=%f v2=%f v1 < v2 = %f\n",v1,v2,double(v1 < v2)); + mexPrintf("v1=%f v2=%f v1 < v2 = %f\n", v1, v2, double (v1 < v2)); #endif break; case oGreater: @@ -897,7 +896,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int break; case oPowerDeriv: { - int derivOrder = int(nearbyint(Stack.top())); + int derivOrder = int (nearbyint(Stack.top())); Stack.pop(); try { @@ -1216,7 +1215,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int case ExternalFunctionNumericalFirstDerivative: { input_arguments = (mxArray **) mxMalloc((nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray *)); - test_mxMalloc(input_arguments, __LINE__, __FILE__, __func__, (nb_input_arguments+1+nb_add_input_arguments) * sizeof(mxArray *)); + test_mxMalloc(input_arguments, __LINE__, __FILE__, __func__, (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()); @@ -1489,7 +1488,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int throw FatalExceptionHandling(tmp.str()); } #ifdef DEBUG - mexPrintf("it_code++=%d\n",it_code); + mexPrintf("it_code++=%d\n", it_code); #endif it_code++; } @@ -1499,8 +1498,6 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int #endif } - - void Evaluate::evaluate_over_periods(const bool forward) { @@ -1533,7 +1530,7 @@ Evaluate::solve_simple_one_periods() { bool cvg = false; int iter = 0; - double ya ; + double ya; double slowc_save = slowc; res1 = 0; while (!(cvg || (iter > maxit_))) @@ -1545,7 +1542,7 @@ Evaluate::solve_simple_one_periods() if (!finite(res1)) { res1 = NAN; - while ((isinf(res1) || isnan(res1)) && (slowc > 1e-9) ) + while ((isinf(res1) || isnan(res1)) && (slowc > 1e-9)) { it_code = start_code; compute_block_time(0, false, false); @@ -1565,7 +1562,7 @@ Evaluate::solve_simple_one_periods() continue; try { - y[Block_Contain[0].Variable + Per_y_] += - slowc * divide(rr, g1[0]); + y[Block_Contain[0].Variable + Per_y_] += -slowc *divide(rr, g1[0]); } catch (FloatingPointExceptionHandling &fpeh) { @@ -1583,7 +1580,6 @@ Evaluate::solve_simple_one_periods() } } - void Evaluate::solve_simple_over_periods(const bool forward) { @@ -1612,7 +1608,7 @@ Evaluate::solve_simple_over_periods(const bool forward) void Evaluate::set_block(const int size_arg, const int type_arg, string file_name_arg, string bin_base_name_arg, const int block_num_arg, - const bool is_linear_arg, const int symbol_table_endo_nbr_arg, const int Block_List_Max_Lag_arg, const int Block_List_Max_Lead_arg, const int u_count_int_arg, const int block_arg) + const bool is_linear_arg, const int symbol_table_endo_nbr_arg, const int Block_List_Max_Lag_arg, const int Block_List_Max_Lead_arg, const int u_count_int_arg, const int block_arg) { size = size_arg; type = type_arg; @@ -1634,7 +1630,6 @@ Evaluate::evaluate_complete(const bool no_derivatives) compute_block_time(0, false, no_derivatives); } - void Evaluate::compute_complete_2b(const bool no_derivatives, double *_res1, double *_res2, double *_max_res, int *_max_res_idx) { @@ -1651,21 +1646,21 @@ Evaluate::compute_complete_2b(const bool no_derivatives, double *_res1, double * compute_block_time(Per_u_, false, no_derivatives); if (!(isnan(res1) || isinf(res1))) { - { - for (int i = 0; i < size; i++) - { - double rr; - rr = r[i]; - res[i+shift] = rr; - if (max_res < fabs(rr)) - { - *_max_res = fabs(rr); - *_max_res_idx = i; - } - *_res2 += rr*rr; - *_res1 += fabs(rr); - } - } + { + for (int i = 0; i < size; i++) + { + double rr; + rr = r[i]; + res[i+shift] = rr; + if (max_res < fabs(rr)) + { + *_max_res = fabs(rr); + *_max_res_idx = i; + } + *_res2 += rr*rr; + *_res1 += fabs(rr); + } + } } else return; @@ -1673,7 +1668,6 @@ Evaluate::compute_complete_2b(const bool no_derivatives, double *_res1, double * return; } - bool Evaluate::compute_complete(const bool no_derivatives, double &_res1, double &_res2, double &_max_res, int &_max_res_idx) { @@ -1683,23 +1677,23 @@ Evaluate::compute_complete(const bool no_derivatives, double &_res1, double &_re compute_block_time(0, false, no_derivatives); if (!(isnan(res1) || isinf(res1))) { - { - _res1 = 0; - _res2 = 0; - _max_res = 0; - for (int i = 0; i < size; i++) - { - double rr; - rr = r[i]; - if (max_res < fabs(rr)) - { - _max_res = fabs(rr); - _max_res_idx = i; - } - _res2 += rr*rr; - _res1 += fabs(rr); - } - } + { + _res1 = 0; + _res2 = 0; + _max_res = 0; + for (int i = 0; i < size; i++) + { + double rr; + rr = r[i]; + if (max_res < fabs(rr)) + { + _max_res = fabs(rr); + _max_res_idx = i; + } + _res2 += rr*rr; + _res1 += fabs(rr); + } + } result = true; } else @@ -1707,7 +1701,6 @@ Evaluate::compute_complete(const bool no_derivatives, double &_res1, double &_re return result; } - bool Evaluate::compute_complete(double lambda, double *crit) { @@ -1728,10 +1721,10 @@ Evaluate::compute_complete(double lambda, double *crit) { res2_ = res2; /*res1_ = res1; - if (max_res > max_res_) + if (max_res > max_res_) { - max_res = max_res_; - max_res_idx = max_res_idx_; + max_res = max_res_; + max_res_idx = max_res_idx_; }*/ } else @@ -1765,7 +1758,7 @@ Evaluate::compute_complete(double lambda, double *crit) return false; } } - mexPrintf(" lambda=%e, res2=%e\n", lambda, res2_); + mexPrintf(" lambda=%e, res2=%e\n", lambda, res2_); *crit = res2_/2; return true; } diff --git a/mex/sources/bytecode/Evaluate.hh b/mex/sources/bytecode/Evaluate.hh index 68635a5d7843ad7eed3c755c72dc9bdb2926075a..bcf62824bad7134cd9bfbbb22177fa40df641490 100644 --- a/mex/sources/bytecode/Evaluate.hh +++ b/mex/sources/bytecode/Evaluate.hh @@ -63,13 +63,13 @@ protected: double solve_tolf; bool GaussSeidel; map<pair<pair<int, int>, int>, int> IM_i; - int equation, derivative_equation, derivative_variable; + int equation, derivative_equation, derivative_variable; string filename; int stack_solve_algo, solve_algo; bool global_temporary_terms; bool print, print_error; double res1, res2, max_res; - int max_res_idx; + int max_res_idx; vector<Block_contain_type> Block_Contain; int size; @@ -87,7 +87,7 @@ public: Evaluate(const int y_size_arg, const int y_kmin_arg, const int y_kmax_arg, const bool print_it_arg, const bool steady_state_arg, const int periods_arg, const int minimal_solving_periods_arg, const double slowc); //typedef void (Interpreter::*InterfpreterMemFn)(const int block_num, const int size, const bool steady_state, int it); void set_block(const int size_arg, const int type_arg, string file_name_arg, string bin_base_name_arg, const int block_num_arg, - const bool is_linear_arg, const int symbol_table_endo_nbr_arg, const int Block_List_Max_Lag_arg, const int Block_List_Max_Lead_arg, const int u_count_int_arg, const int block_arg); + const bool is_linear_arg, const int symbol_table_endo_nbr_arg, const int Block_List_Max_Lag_arg, const int Block_List_Max_Lead_arg, const int u_count_int_arg, const int block_arg); void evaluate_complete(const bool no_derivatives); bool compute_complete(const bool no_derivatives, double &res1, double &res2, double &max_res, int &max_res_idx); void compute_complete_2b(const bool no_derivatives, double *_res1, double *_res2, double *_max_res, int *_max_res_idx); diff --git a/mex/sources/bytecode/Interpreter.cc b/mex/sources/bytecode/Interpreter.cc index 75f0e02ff0f66fe11049f75b95c9322435f61995..1c36f5a86783bb8552fb445753e97d11263456f5 100644 --- a/mex/sources/bytecode/Interpreter.cc +++ b/mex/sources/bytecode/Interpreter.cc @@ -40,11 +40,11 @@ Interpreter::Interpreter(double *params_arg, double *y_arg, double *ya_arg, doub , const int CUDA_device_arg, cublasHandle_t cublas_handle_arg, cusparseHandle_t cusparse_handle_arg, cusparseMatDescr_t descr_arg #endif ) - : dynSparseMatrix(y_size_arg, y_kmin_arg, y_kmax_arg, print_it_arg, steady_state_arg, periods_arg, minimal_solving_periods_arg, slowc_arg +: dynSparseMatrix(y_size_arg, y_kmin_arg, y_kmax_arg, print_it_arg, steady_state_arg, periods_arg, minimal_solving_periods_arg, slowc_arg #ifdef CUDA - , CUDA_device_arg, cublas_handle_arg, cusparse_handle_arg, descr_arg + , CUDA_device_arg, cublas_handle_arg, cusparse_handle_arg, descr_arg #endif - ) + ) { params = params_arg; y = y_arg; @@ -73,12 +73,12 @@ Interpreter::Interpreter(double *params_arg, double *y_arg, double *ya_arg, doub solve_algo = solve_algo_arg; global_temporary_terms = global_temporary_terms_arg; print = print_arg; - col_x = col_x_arg; + col_x = col_x_arg; col_y = col_y_arg; GlobalTemporaryTerms = GlobalTemporaryTerms_arg; print_error = print_error_arg; //steady_state = steady_state_arg; - print_it = print_it_arg; + print_it = print_it_arg; } @@ -92,7 +92,7 @@ Interpreter::evaluate_a_block(bool initialization) case EVALUATE_FORWARD: if (steady_state) { - compute_block_time(0, true, /*block_num, size, steady_state, */false); + compute_block_time(0, true, /*block_num, size, steady_state, */ false); if (block >= 0) for (int j = 0; j < size; j++) residual[j] = y[Block_Contain[j].Variable] - ya[Block_Contain[j].Variable]; @@ -107,7 +107,7 @@ Interpreter::evaluate_a_block(bool initialization) { it_code = begining; Per_y_ = it_*y_size; - compute_block_time(0, true, /*block_num, size, steady_state, */false); + compute_block_time(0, true, /*block_num, size, steady_state, */ false); if (block >= 0) for (int j = 0; j < size; j++) residual[it_*size+j] = y[it_*y_size+Block_Contain[j].Variable] - ya[it_*y_size+Block_Contain[j].Variable]; @@ -118,9 +118,9 @@ Interpreter::evaluate_a_block(bool initialization) } break; case SOLVE_FORWARD_SIMPLE: - g1 = (double *) mxMalloc(size*size*sizeof(double)); + g1 = (double *) mxMalloc(size*size*sizeof(double)); test_mxMalloc(g1, __LINE__, __FILE__, __func__, size*size*sizeof(double)); - r = (double *) mxMalloc(size*sizeof(double)); + r = (double *) mxMalloc(size*sizeof(double)); test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double)); if (steady_state) { @@ -147,20 +147,20 @@ Interpreter::evaluate_a_block(bool initialization) for (int j = 0; j < size; j++) residual[it_*size+j] = r[j]; } - } - mxFree(g1); + } + mxFree(g1); mxFree(r); break; case SOLVE_FORWARD_COMPLETE: if (initialization) - { - fixe_u(&u, u_count_int, u_count_int); - Read_SparseMatrix(bin_base_name, size, 1, 0, 0, false, stack_solve_algo, solve_algo); - } + { + fixe_u(&u, u_count_int, u_count_int); + Read_SparseMatrix(bin_base_name, size, 1, 0, 0, false, stack_solve_algo, solve_algo); + } #ifdef DEBUG mexPrintf("in SOLVE_FORWARD_COMPLETE r = mxMalloc(%d*sizeof(double))\n", size); #endif - r = (double *) mxMalloc(size*sizeof(double)); + r = (double *) mxMalloc(size*sizeof(double)); test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double)); if (steady_state) { @@ -219,9 +219,9 @@ Interpreter::evaluate_a_block(bool initialization) } break; case SOLVE_BACKWARD_SIMPLE: - g1 = (double *) mxMalloc(size*size*sizeof(double)); + g1 = (double *) mxMalloc(size*size*sizeof(double)); test_mxMalloc(g1, __LINE__, __FILE__, __func__, size*size*sizeof(double)); - r = (double *) mxMalloc(size*sizeof(double)); + r = (double *) mxMalloc(size*sizeof(double)); test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double)); if (steady_state) { @@ -258,7 +258,7 @@ Interpreter::evaluate_a_block(bool initialization) fixe_u(&u, u_count_int, u_count_int); Read_SparseMatrix(bin_base_name, size, 1, 0, 0, false, stack_solve_algo, solve_algo); } - r = (double *) mxMalloc(size*sizeof(double)); + r = (double *) mxMalloc(size*sizeof(double)); test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double)); if (steady_state) { @@ -277,7 +277,7 @@ Interpreter::evaluate_a_block(bool initialization) { it_code = begining; Per_y_ = it_*y_size; - compute_block_time(0, true, /*block_num, size, steady_state, */false); + compute_block_time(0, true, /*block_num, size, steady_state, */ false); if (block < 0) for (int j = 0; j < size; j++) residual[Per_y_+Block_Contain[j].Equation] = r[j]; @@ -296,7 +296,7 @@ Interpreter::evaluate_a_block(bool initialization) Read_SparseMatrix(bin_base_name, size, periods, y_kmin, y_kmax, true, stack_solve_algo, solve_algo); } u_count = u_count_int*(periods+y_kmax+y_kmin); - r = (double *) mxMalloc(size*sizeof(double)); + r = (double *) mxMalloc(size*sizeof(double)); test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double)); begining = it_code; for (it_ = y_kmin; it_ < periods+y_kmin; it_++) @@ -317,8 +317,6 @@ Interpreter::evaluate_a_block(bool initialization) } } - - int Interpreter::simulate_a_block(vector_table_conditional_local_type vector_table_conditional_local) { @@ -338,14 +336,14 @@ Interpreter::simulate_a_block(vector_table_conditional_local_type vector_table_c mexPrintf("EVALUATE_FORWARD\n"); mexEvalString("drawnow;"); #endif - evaluate_over_periods(true); + evaluate_over_periods(true); break; case EVALUATE_BACKWARD: #ifdef DEBUG mexPrintf("EVALUATE_BACKWARD\n"); mexEvalString("drawnow;"); #endif - evaluate_over_periods(false); + evaluate_over_periods(false); break; case SOLVE_FORWARD_SIMPLE: #ifdef DEBUG @@ -438,11 +436,11 @@ Interpreter::simulate_a_block(vector_table_conditional_local_type vector_table_c Read_SparseMatrix(bin_base_name, size, periods, y_kmin, y_kmax, true, stack_solve_algo, solve_algo); } u_count = u_count_int*(periods+y_kmax+y_kmin); - r = (double *) mxMalloc(size*sizeof(double)); + r = (double *) mxMalloc(size*sizeof(double)); test_mxMalloc(r, __LINE__, __FILE__, __func__, size*sizeof(double)); - res = (double *) mxMalloc(size*periods*sizeof(double)); + res = (double *) mxMalloc(size*periods*sizeof(double)); test_mxMalloc(res, __LINE__, __FILE__, __func__, size*periods*sizeof(double)); - y_save = (double *) mxMalloc(y_size*sizeof(double)*(periods+y_kmax+y_kmin)); + y_save = (double *) mxMalloc(y_size*sizeof(double)*(periods+y_kmax+y_kmin)); test_mxMalloc(y_save, __LINE__, __FILE__, __func__, y_size*sizeof(double)*(periods+y_kmax+y_kmin)); start_code = it_code; iter = 0; @@ -461,7 +459,7 @@ Interpreter::simulate_a_block(vector_table_conditional_local_type vector_table_c memcpy(y_save, y, y_size*sizeof(double)*(periods+y_kmax+y_kmin)); if (vector_table_conditional_local.size()) { - for (vector_table_conditional_local_type::iterator it1 = vector_table_conditional_local.begin(); it1 != vector_table_conditional_local.end() ; it1++) + for (vector_table_conditional_local_type::iterator it1 = vector_table_conditional_local.begin(); it1 != vector_table_conditional_local.end(); it1++) { if (it1->is_cond) { @@ -476,7 +474,7 @@ Interpreter::simulate_a_block(vector_table_conditional_local_type vector_table_c if (!(isnan(res1) || isinf(res1))) cvg = (max_res < solve_tolf); if (isnan(res1) || isinf(res1) || (stack_solve_algo == 4 && iter > 0)) - memcpy(y, y_save, y_size*sizeof(double)*(periods+y_kmax+y_kmin)); + memcpy(y, y_save, y_size*sizeof(double)*(periods+y_kmax+y_kmin)); u_count = u_count_saved; int prev_iter = iter; Simulate_Newton_Two_Boundaries(block_num, symbol_table_endo_nbr, y_kmin, y_kmax, size, periods, cvg, minimal_solving_periods, stack_solve_algo, endo_name_length, P_endo_names, vector_table_conditional_local); @@ -509,17 +507,17 @@ Interpreter::simulate_a_block(vector_table_conditional_local_type vector_table_c Simulate_Newton_Two_Boundaries(block_num, symbol_table_endo_nbr, y_kmin, y_kmax, size, periods, cvg, minimal_solving_periods, stack_solve_algo, endo_name_length, P_endo_names, vector_table_conditional_local); max_res = 0; max_res_idx = 0; } - it_code = end_code; + it_code = end_code; if (r) - mxFree(r); + mxFree(r); if (y_save) - mxFree(y_save); + mxFree(y_save); if (u) - mxFree(u); + mxFree(u); if (index_vara) - mxFree(index_vara); + mxFree(index_vara); if (index_equa) - mxFree(index_equa); + mxFree(index_equa); if (res) mxFree(res); memset(direction, 0, size_of_direction); @@ -601,9 +599,8 @@ Interpreter::ReadCodeFile(string file_name, CodeLoad &code) } - void -Interpreter::check_for_controlled_exo_validity(FBEGINBLOCK_ *fb,vector<s_plan> sconstrained_extended_path) +Interpreter::check_for_controlled_exo_validity(FBEGINBLOCK_ *fb, vector<s_plan> sconstrained_extended_path) { vector<unsigned int> exogenous = fb->get_exogenous(); vector<int> endogenous = fb->get_endogenous(); @@ -632,8 +629,6 @@ Interpreter::check_for_controlled_exo_validity(FBEGINBLOCK_ *fb,vector<s_plan> s previous_block_exogenous.push_back(*it); } - - bool Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int block, bool last_call, bool constrained, vector<s_plan> sconstrained_extended_path, vector_table_conditional_local_type vector_table_conditional_local) { @@ -670,7 +665,7 @@ Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int blo Block_Contain = fb->get_Block_Contain(); it_code++; if (constrained) - check_for_controlled_exo_validity(fb,sconstrained_extended_path); + check_for_controlled_exo_validity(fb, sconstrained_extended_path); set_block(fb->get_size(), fb->get_type(), file_name, bin_basename, Block_Count, fb->get_is_linear(), fb->get_endo_nbr(), fb->get_Max_Lag(), fb->get_Max_Lead(), fb->get_u_count_int(), block); if (print) print_a_block(); @@ -761,8 +756,8 @@ Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int blo #endif var = ((FDIMT_ *) it_code->second)->get_size(); if (T) - mxFree(T); - T = (double *) mxMalloc(var*(periods+y_kmin+y_kmax)*sizeof(double)); + mxFree(T); + T = (double *) mxMalloc(var*(periods+y_kmin+y_kmax)*sizeof(double)); test_mxMalloc(T, __LINE__, __FILE__, __func__, var*(periods+y_kmin+y_kmax)*sizeof(double)); if (block >= 0) { @@ -788,13 +783,12 @@ Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int blo GlobalTemporaryTerms = mxCreateDoubleMatrix(var, 1, mxREAL); T = mxGetPr(GlobalTemporaryTerms); } - else - { - T = (double *) mxMalloc(var*sizeof(double)); - test_mxMalloc(T, __LINE__, __FILE__, __func__, var*sizeof(double)); + else + { + T = (double *) mxMalloc(var*sizeof(double)); + test_mxMalloc(T, __LINE__, __FILE__, __func__, var*sizeof(double)); } - if (block >= 0) it_code = code_liste.begin() + code.get_begin_block(block); else @@ -806,7 +800,7 @@ Interpreter::MainLoop(string bin_basename, CodeLoad code, bool evaluate, int blo throw FatalExceptionHandling(tmp.str()); } } - max_res = max_res_local ; + max_res = max_res_local; max_res_idx = max_res_idx_local; Close_SaveCode(); return true; @@ -825,13 +819,13 @@ Interpreter::elastic(string str, unsigned int len, bool left) if (left) { //mexPrintf("(1) diff=%d\n",diff); - str.insert(str.end(),diff-1,' '); - str.insert(str.begin(),1,' '); + str.insert(str.end(), diff-1, ' '); + str.insert(str.begin(), 1, ' '); } else { - str.insert(str.end(),diff/2,' '); - str.insert(str.begin(),diff/2,' '); + str.insert(str.end(), diff/2, ' '); + str.insert(str.begin(), diff/2, ' '); } } else @@ -839,13 +833,13 @@ Interpreter::elastic(string str, unsigned int len, bool left) if (left) { //mexPrintf("(2) diff=%d\n",diff); - str.insert(str.end(),diff-1,' '); - str.insert(str.begin(),1,' '); + str.insert(str.end(), diff-1, ' '); + str.insert(str.begin(), 1, ' '); } else { - str.insert(str.end(),ceil(diff/2),' '); - str.insert(str.begin(),ceil(diff/2+1),' '); + str.insert(str.end(), ceil(diff/2), ' '); + str.insert(str.begin(), ceil(diff/2+1), ' '); } } return str; @@ -855,14 +849,14 @@ Interpreter::elastic(string str, unsigned int len, bool left) bool Interpreter::extended_path(string file_name, string bin_basename, bool evaluate, int block, int &nb_blocks, int nb_periods, vector<s_plan> sextended_path, vector<s_plan> sconstrained_extended_path, vector<string> dates, table_conditional_global_type table_conditional_global) { - CodeLoad code; + CodeLoad code; ReadCodeFile(file_name, code); it_code = code_liste.begin(); it_code_type Init_Code = code_liste.begin(); /*size_t size_of_direction = y_size*(periods + y_kmax + y_kmin)*sizeof(double); - double *y_save = (double *) mxMalloc(size_of_direction); - double *x_save = (double *) mxMalloc((periods + y_kmax + y_kmin) * col_x *sizeof(double));*/ + double *y_save = (double *) mxMalloc(size_of_direction); + double *x_save = (double *) mxMalloc((periods + y_kmax + y_kmin) * col_x *sizeof(double));*/ size_t size_of_direction = y_size*col_y*sizeof(double); double *y_save = (double *) mxMalloc(size_of_direction); test_mxMalloc(y_save, __LINE__, __FILE__, __func__, size_of_direction); @@ -872,7 +866,7 @@ Interpreter::extended_path(string file_name, string bin_basename, bool evaluate, vector_table_conditional_local_type vector_table_conditional_local; vector_table_conditional_local.clear(); - int endo_name_length_l = endo_name_length; + int endo_name_length_l = endo_name_length; for (int j = 0; j < col_x* nb_row_x; j++) { x_save[j] = x[j]; @@ -892,16 +886,16 @@ Interpreter::extended_path(string file_name, string bin_basename, bool evaluate, int date_length = dates[0].length(); int table_length = 2 + date_length + 3 + endo_name_length_l + 3 + real_max_length + 3 + 3 + 2 + 6 + 2; string line; - line.insert(line.begin(),table_length,'-'); - line.insert(line.length(),"\n"); + line.insert(line.begin(), table_length, '-'); + line.insert(line.length(), "\n"); if (old_print_it) { - mexPrintf("\nExtended Path simulation:\n"); - mexPrintf("-------------------------\n"); - mexPrintf(line.c_str()); - string title = "|" + elastic("date",date_length+2, false) + "|" + elastic("variable",endo_name_length_l+2, false) + "|" + elastic("max. value",real_max_length+2, false) + "| iter. |" + elastic("cvg",5, false) + "|\n"; - mexPrintf(title.c_str()); - mexPrintf(line.c_str()); + mexPrintf("\nExtended Path simulation:\n"); + mexPrintf("-------------------------\n"); + mexPrintf(line.c_str()); + string title = "|" + elastic("date", date_length+2, false) + "|" + elastic("variable", endo_name_length_l+2, false) + "|" + elastic("max. value", real_max_length+2, false) + "| iter. |" + elastic("cvg", 5, false) + "|\n"; + mexPrintf(title.c_str()); + mexPrintf(line.c_str()); } for (int t = 0; t < nb_periods; t++) { @@ -909,7 +903,7 @@ Interpreter::extended_path(string file_name, string bin_basename, bool evaluate, previous_block_exogenous.clear(); if (old_print_it) { - mexPrintf("|%s|",elastic(dates[t], date_length+2, false).c_str()); + mexPrintf("|%s|", elastic(dates[t], date_length+2, false).c_str()); mexEvalString("drawnow;"); } for (vector<s_plan>::const_iterator it = sextended_path.begin(); it != sextended_path.end(); it++) @@ -932,8 +926,8 @@ Interpreter::extended_path(string file_name, string bin_basename, bool evaluate, y[j ] = y[ j + (y_kmin) * y_size]; } for (int j = 0; j < col_x; j++) - { - x_save[t + y_kmin + j * nb_row_x] = x[y_kmin + j * nb_row_x]; + { + x_save[t + y_kmin + j * nb_row_x] = x[y_kmin + j * nb_row_x]; if (t < nb_periods) x[y_kmin + j * nb_row_x] = x_save[t + 1 + y_kmin + j * nb_row_x]; } @@ -945,30 +939,30 @@ Interpreter::extended_path(string file_name, string bin_basename, bool evaluate, if (P_endo_names[CHAR_LENGTH*(max_res_idx+i*y_size)] != ' ') res << P_endo_names[CHAR_LENGTH*(max_res_idx+i*y_size)]; res1 << std::scientific << max_res; - mexPrintf("%s|%s| %4d | x |\n",elastic(res.str(),endo_name_length_l+2, true).c_str(), elastic(res1.str(), real_max_length+2, false).c_str(), iter); + mexPrintf("%s|%s| %4d | x |\n", elastic(res.str(), endo_name_length_l+2, true).c_str(), elastic(res1.str(), real_max_length+2, false).c_str(), iter); mexPrintf(line.c_str()); mexEvalString("drawnow;"); } - } + } print_it = old_print_it; /*for (int j = 0; j < y_size; j++) { - for(int k = nb_periods; k < periods; k++) - y_save[j + (k + y_kmin) * y_size] = y[ j + ( k - (nb_periods-1) + y_kmin) * y_size]; + for(int k = nb_periods; k < periods; k++) + y_save[j + (k + y_kmin) * y_size] = y[ j + ( k - (nb_periods-1) + y_kmin) * y_size]; }*/ - for (int i = 0; i < y_size * col_y; i++) - y[i] = y_save[i]; + for (int i = 0; i < y_size * col_y; i++) + y[i] = y_save[i]; for (int j = 0; j < col_x * nb_row_x; j++) - x[j] = x_save[j]; + x[j] = x_save[j]; if (Init_Code->second) - mxFree(Init_Code->second); + mxFree(Init_Code->second); if (y_save) - mxFree(y_save); + mxFree(y_save); if (x_save) - mxFree(x_save); + mxFree(x_save); nb_blocks = Block_Count+1; if (T && !global_temporary_terms) - mxFree(T); + mxFree(T); return true; } @@ -986,7 +980,6 @@ Interpreter::compute_blocks(string file_name, string bin_basename, bool evaluate MainLoop(bin_basename, code, evaluate, block, true, false, s_plan_junk, vector_table_conditional_local_junk); - mxFree(Init_Code->second); nb_blocks = Block_Count+1; if (T && !global_temporary_terms) diff --git a/mex/sources/bytecode/Interpreter.hh b/mex/sources/bytecode/Interpreter.hh index d6fdec5b7eeebbe453ef7ddee22173d94f4da934..d41e0c8cdd4c75ff6ba79f5a0f0096a5c42e838b 100644 --- a/mex/sources/bytecode/Interpreter.hh +++ b/mex/sources/bytecode/Interpreter.hh @@ -27,7 +27,7 @@ #define BYTE_CODE #include "CodeInterpreter.hh" #include "SparseMatrix.hh" -#include "Evaluate.hh" +#include "Evaluate.hh" #ifdef LINBCG # include "linbcg.hh" #endif @@ -41,11 +41,10 @@ using namespace std; - class Interpreter : public dynSparseMatrix { private: -vector<int> previous_block_exogenous; + vector<int> previous_block_exogenous; protected: void evaluate_a_block(bool initialization); int simulate_a_block(vector_table_conditional_local_type vector_table_conditional_local); @@ -66,7 +65,7 @@ public: ); bool extended_path(string file_name, string bin_basename, bool evaluate, int block, int &nb_blocks, int nb_periods, vector<s_plan> sextended_path, vector<s_plan> sconstrained_extended_path, vector<string> dates, table_conditional_global_type table_conditional_global); bool compute_blocks(string file_name, string bin_basename, bool evaluate, int block, int &nb_blocks); - void check_for_controlled_exo_validity(FBEGINBLOCK_ *fb,vector<s_plan> sconstrained_extended_path); + void check_for_controlled_exo_validity(FBEGINBLOCK_ *fb, vector<s_plan> sconstrained_extended_path); bool MainLoop(string bin_basename, CodeLoad code, bool evaluate, int block, bool last_call, bool constrained, vector<s_plan> sconstrained_extended_path, vector_table_conditional_local_type vector_table_conditional_local); void ReadCodeFile(string file_name, CodeLoad &code); diff --git a/mex/sources/bytecode/Mem_Mngr.cc b/mex/sources/bytecode/Mem_Mngr.cc index 00bcc0564bfe5d3cfc67db5d914d3f32e68b13c1..52a2ab905e4fc056a0367f5d1c126d178d130e50 100644 --- a/mex/sources/bytecode/Mem_Mngr.cc +++ b/mex/sources/bytecode/Mem_Mngr.cc @@ -25,14 +25,14 @@ Mem_Mngr::Mem_Mngr() swp_f_b = 0; } /*void -Mem_Mngr::Print_heap() -{ + Mem_Mngr::Print_heap() + { unsigned int i; mexPrintf("i :"); for (i = 0; i < CHUNK_SIZE; i++) - mexPrintf("%3d ", i); + mexPrintf("%3d ", i); mexPrintf("\n"); -} + } */ void @@ -78,20 +78,20 @@ Mem_Mngr::mxMalloc_NZE() { CHUNK_SIZE += CHUNK_BLCK_SIZE; Nb_CHUNK++; - NZE_Mem = (NonZeroElem *) mxMalloc(CHUNK_BLCK_SIZE*sizeof(NonZeroElem)); /*The block of memory allocated*/ + NZE_Mem = (NonZeroElem *) mxMalloc(CHUNK_BLCK_SIZE*sizeof(NonZeroElem)); /*The block of memory allocated*/ error_msg.test_mxMalloc(NZE_Mem, __LINE__, __FILE__, __func__, CHUNK_BLCK_SIZE*sizeof(NonZeroElem)); NZE_Mem_Allocated.push_back(NZE_Mem); if (!NZE_Mem) mexPrintf("Not enough memory available\n"); - 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*/ - error_msg.test_mxMalloc(NZE_Mem_add , __LINE__, __FILE__, __func__, CHUNK_SIZE*sizeof(NonZeroElem *)); + 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*/ + error_msg.test_mxMalloc(NZE_Mem_add, __LINE__, __FILE__, __func__, CHUNK_SIZE*sizeof(NonZeroElem *)); } - else - { - NZE_Mem_add = (NonZeroElem **) mxMalloc(CHUNK_SIZE*sizeof(NonZeroElem *)); /*We have to define the size of pointer on the memory*/ - error_msg.test_mxMalloc(NZE_Mem_add , __LINE__, __FILE__, __func__, CHUNK_SIZE*sizeof(NonZeroElem *)); + else + { + NZE_Mem_add = (NonZeroElem **) mxMalloc(CHUNK_SIZE*sizeof(NonZeroElem *)); /*We have to define the size of pointer on the memory*/ + error_msg.test_mxMalloc(NZE_Mem_add, __LINE__, __FILE__, __func__, CHUNK_SIZE*sizeof(NonZeroElem *)); } if (!NZE_Mem_add) diff --git a/mex/sources/bytecode/Mem_Mngr.hh b/mex/sources/bytecode/Mem_Mngr.hh index 6d53199dfe7f04e885be13f4ca29bcb23bf7ef57..4bde597a04fc7c2c3f203fbb3db95cc8bc9b234e 100644 --- a/mex/sources/bytecode/Mem_Mngr.hh +++ b/mex/sources/bytecode/Mem_Mngr.hh @@ -19,7 +19,7 @@ #ifndef MEM_MNGR_HH_INCLUDED #define MEM_MNGR_HH_INCLUDED - + #include "ErrorHandling.hh" #include <vector> #include <fstream> @@ -27,7 +27,7 @@ # include <dynmex.h> #else # include "mex_interface.hh" -#endif +#endif //using namespace std; struct NonZeroElem @@ -50,7 +50,7 @@ public: void Free_All(); Mem_Mngr(); void fixe_file_name(string filename_arg); - bool swp_f; + bool swp_f; ErrorMsg error_msg; private: v_NonZeroElem Chunk_Stack; diff --git a/mex/sources/bytecode/SparseMatrix.cc b/mex/sources/bytecode/SparseMatrix.cc index d6b60885d13a7d39867e0d2c1f8736a8c3bdb6f6..7526bbf4ee0032aef7495aa5382de04ebd91b937 100644 --- a/mex/sources/bytecode/SparseMatrix.cc +++ b/mex/sources/bytecode/SparseMatrix.cc @@ -28,67 +28,64 @@ #include "SparseMatrix.hh" #ifdef CUDA -#include "SparseMatrix_kernel.cu" +# include "SparseMatrix_kernel.cu" #endif using namespace std; #ifdef _MSC_VER -#include <windows.h> +# include <windows.h> HINSTANCE hinstLib; -#define UMFPACK_INFO 90 -#define UMFPACK_CONTROL 20 +# define UMFPACK_INFO 90 +# define UMFPACK_CONTROL 20 /* used in all UMFPACK_report_* routines: */ -#define UMFPACK_PRL 0 /* print level */ +# define UMFPACK_PRL 0 /* print level */ /* returned by all routines that use Info: */ -#define UMFPACK_OK (0) -#define UMFPACK_STATUS 0 /* UMFPACK_OK, or other result */ +# define UMFPACK_OK (0) +# define UMFPACK_STATUS 0 /* UMFPACK_OK, or other result */ typedef void (*t_umfpack_dl_free_numeric)(void **Numeric); t_umfpack_dl_free_numeric umfpack_dl_free_numeric; typedef void (*t_umfpack_dl_free_symbolic)(void **Symbolic); t_umfpack_dl_free_symbolic umfpack_dl_free_symbolic; typedef int64_t (*t_umfpack_dl_solve)(int64_t sys, - const int64_t Ap [ ], - const int64_t Ai [ ], - const double Ax [ ], - double X [ ], - const double B [ ], + const int64_t Ap [], + const int64_t Ai [], + const double Ax [], + double X [], + const double B [], void *Numeric, const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]); t_umfpack_dl_solve umfpack_dl_solve; -typedef int64_t (*t_umfpack_dl_numeric)(const int64_t Ap [ ], - const int64_t Ai [ ], - const double Ax [ ], +typedef int64_t (*t_umfpack_dl_numeric)(const int64_t Ap [], + const int64_t Ai [], + const double Ax [], void *Symbolic, void **Numeric, const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]); t_umfpack_dl_numeric umfpack_dl_numeric; typedef int64_t (*t_umfpack_dl_symbolic)(int64_t n_row, - int64_t n_col, - const int64_t Ap [ ], - const int64_t Ai [ ], - const double Ax [ ], - void **Symbolic, - const double Control [UMFPACK_CONTROL], - double Info [UMFPACK_INFO]); + int64_t n_col, + const int64_t Ap [], + const int64_t Ai [], + const double Ax [], + void **Symbolic, + const double Control [UMFPACK_CONTROL], + double Info [UMFPACK_INFO]); t_umfpack_dl_symbolic umfpack_dl_symbolic; typedef void (*t_umfpack_dl_report_info)(const double Control [UMFPACK_CONTROL], - const double Info [UMFPACK_INFO]); + const double Info [UMFPACK_INFO]); t_umfpack_dl_report_info umfpack_dl_report_info; typedef void (*t_umfpack_dl_report_status)(const double Control [UMFPACK_CONTROL], - int64_t status); + int64_t status); t_umfpack_dl_report_status umfpack_dl_report_status; typedef void (*t_umfpack_dl_defaults)(double Control [UMFPACK_CONTROL]); t_umfpack_dl_defaults umfpack_dl_defaults; #endif - - - dynSparseMatrix::dynSparseMatrix() { pivotva = NULL; @@ -183,11 +180,11 @@ dynSparseMatrix::dynSparseMatrix() } dynSparseMatrix::dynSparseMatrix(const int y_size_arg, const int y_kmin_arg, const int y_kmax_arg, const bool print_it_arg, const bool steady_state_arg, const int periods_arg, - const int minimal_solving_periods_arg, const double slowc_arg + const int minimal_solving_periods_arg, const double slowc_arg #ifdef CUDA - , const int CUDA_device_arg, cublasHandle_t cublas_handle_arg, cusparseHandle_t cusparse_handle_arg, cusparseMatDescr_t descr_arg + , const int CUDA_device_arg, cublasHandle_t cublas_handle_arg, cusparseHandle_t cusparse_handle_arg, cusparseMatDescr_t descr_arg #endif - ): + ) : Evaluate(y_size_arg, y_kmin_arg, y_kmax_arg, print_it_arg, steady_state_arg, periods_arg, minimal_solving_periods_arg, slowc_arg) { pivotva = NULL; @@ -206,7 +203,7 @@ dynSparseMatrix::dynSparseMatrix(const int y_size_arg, const int y_kmin_arg, con IM_i.clear(); lu_inc_tol = 1e-10; Symbolic = NULL; - Numeric = NULL; + Numeric = NULL; #ifdef CUDA CUDA_device = CUDA_device_arg; cublas_handle = cublas_handle_arg; @@ -286,7 +283,6 @@ dynSparseMatrix::dynSparseMatrix(const int y_size_arg, const int y_kmin_arg, con #endif } - int dynSparseMatrix::NRow(int r) { @@ -531,7 +527,7 @@ dynSparseMatrix::Read_SparseMatrix(string file_name, const int Size, int periods filename = file_name; mem_mngr.fixe_file_name(file_name); /*mexPrintf("steady_state=%d, size=%d, solve_algo=%d, stack_solve_algo=%d, two_boundaries=%d\n",steady_state, Size, solve_algo, stack_solve_algo, two_boundaries); - mexEvalString("drawnow;");*/ + mexEvalString("drawnow;");*/ if (!SaveCode.is_open()) { if (steady_state) @@ -621,7 +617,7 @@ dynSparseMatrix::Read_SparseMatrix(string file_name, const int Size, int periods } } } - index_vara = (int *) mxMalloc(Size*(periods+y_kmin+y_kmax)*sizeof(int)); + index_vara = (int *) mxMalloc(Size*(periods+y_kmin+y_kmax)*sizeof(int)); test_mxMalloc(index_vara, __LINE__, __FILE__, __func__, Size*(periods+y_kmin+y_kmax)*sizeof(int)); for (int j = 0; j < Size; j++) SaveCode.read(reinterpret_cast<char *>(&index_vara[j]), sizeof(*index_vara)); @@ -631,7 +627,7 @@ dynSparseMatrix::Read_SparseMatrix(string file_name, const int Size, int periods for (int j = 0; j < Size; j++) index_vara[j+Size*i] = index_vara[j+Size*(i-1)] + y_size; } - index_equa = (int *) mxMalloc(Size*sizeof(int)); + index_equa = (int *) mxMalloc(Size*sizeof(int)); test_mxMalloc(index_equa, __LINE__, __FILE__, __func__, Size*sizeof(int)); for (int j = 0; j < Size; j++) SaveCode.read(reinterpret_cast<char *>(&index_equa[j]), sizeof(*index_equa)); @@ -643,37 +639,37 @@ dynSparseMatrix::Simple_Init(int Size, map<pair<pair<int, int>, int>, int> &IM, int i, eq, var, lag; map<pair<pair<int, int>, int>, int>::iterator it4; NonZeroElem *first; - pivot = (int *) mxMalloc(Size*sizeof(int)); + pivot = (int *) mxMalloc(Size*sizeof(int)); test_mxMalloc(pivot, __LINE__, __FILE__, __func__, Size*sizeof(int)); - pivot_save = (int *) mxMalloc(Size*sizeof(int)); + pivot_save = (int *) mxMalloc(Size*sizeof(int)); test_mxMalloc(pivot_save, __LINE__, __FILE__, __func__, Size*sizeof(int)); - pivotk = (int *) mxMalloc(Size*sizeof(int)); + pivotk = (int *) mxMalloc(Size*sizeof(int)); test_mxMalloc(pivotk, __LINE__, __FILE__, __func__, Size*sizeof(int)); - pivotv = (double *) mxMalloc(Size*sizeof(double)); + pivotv = (double *) mxMalloc(Size*sizeof(double)); test_mxMalloc(pivotv, __LINE__, __FILE__, __func__, Size*sizeof(double)); - pivotva = (double *) mxMalloc(Size*sizeof(double)); + pivotva = (double *) mxMalloc(Size*sizeof(double)); test_mxMalloc(pivotva, __LINE__, __FILE__, __func__, Size*sizeof(double)); - b = (int *) mxMalloc(Size*sizeof(int)); + b = (int *) mxMalloc(Size*sizeof(int)); test_mxMalloc(b, __LINE__, __FILE__, __func__, Size*sizeof(int)); line_done = (bool *) mxMalloc(Size*sizeof(bool)); - test_mxMalloc(line_done, __LINE__, __FILE__, __func__, Size*sizeof(bool)); + test_mxMalloc(line_done, __LINE__, __FILE__, __func__, Size*sizeof(bool)); mem_mngr.init_CHUNK_BLCK_SIZE(u_count); g_save_op = NULL; g_nop_all = 0; i = Size*sizeof(NonZeroElem *); - FNZE_R = (NonZeroElem **) mxMalloc(i); + FNZE_R = (NonZeroElem **) mxMalloc(i); test_mxMalloc(FNZE_R, __LINE__, __FILE__, __func__, i); - FNZE_C = (NonZeroElem **) mxMalloc(i); + FNZE_C = (NonZeroElem **) mxMalloc(i); test_mxMalloc(FNZE_C, __LINE__, __FILE__, __func__, i); - NonZeroElem **temp_NZE_R = (NonZeroElem **) mxMalloc(i); + NonZeroElem **temp_NZE_R = (NonZeroElem **) mxMalloc(i); test_mxMalloc(*temp_NZE_R, __LINE__, __FILE__, __func__, i); - NonZeroElem **temp_NZE_C = (NonZeroElem **) mxMalloc(i); + NonZeroElem **temp_NZE_C = (NonZeroElem **) mxMalloc(i); test_mxMalloc(*temp_NZE_C, __LINE__, __FILE__, __func__, i); i = Size*sizeof(int); - NbNZRow = (int *) mxMalloc(i); + NbNZRow = (int *) mxMalloc(i); test_mxMalloc(NbNZRow, __LINE__, __FILE__, __func__, i); - NbNZCol = (int *) mxMalloc(i); + NbNZCol = (int *) mxMalloc(i); test_mxMalloc(NbNZCol, __LINE__, __FILE__, __func__, i); it4 = IM.begin(); eq = -1; @@ -848,12 +844,11 @@ dynSparseMatrix::Init_Matlab_Sparse_Simple(int Size, map<pair<pair<int, int>, in Aj[Size] = NZE; } - void dynSparseMatrix::Init_UMFPACK_Sparse_Simple(int Size, map<pair<pair<int, int>, int>, int> &IM, SuiteSparse_long **Ap, SuiteSparse_long **Ai, double **Ax, double **b, bool &zero_solution, mxArray *x0_m) { int eq, var; - *b = (double*)mxMalloc(Size * sizeof(double)); + *b = (double *) mxMalloc(Size * sizeof(double)); test_mxMalloc(*b, __LINE__, __FILE__, __func__, Size * sizeof(double)); if (!(*b)) { @@ -868,7 +863,7 @@ dynSparseMatrix::Init_UMFPACK_Sparse_Simple(int Size, map<pair<pair<int, int>, i tmp << " in Init_UMFPACK_Sparse_Simple, can't retrieve x0 vector\n"; throw FatalExceptionHandling(tmp.str()); } - *Ap = (SuiteSparse_long*)mxMalloc((Size+1) * sizeof(SuiteSparse_long)); + *Ap = (SuiteSparse_long *) mxMalloc((Size+1) * sizeof(SuiteSparse_long)); test_mxMalloc(*Ap, __LINE__, __FILE__, __func__, (Size+1) * sizeof(SuiteSparse_long)); if (!(*Ap)) { @@ -877,7 +872,7 @@ dynSparseMatrix::Init_UMFPACK_Sparse_Simple(int Size, map<pair<pair<int, int>, i throw FatalExceptionHandling(tmp.str()); } size_t prior_nz = IM.size(); - *Ai = (SuiteSparse_long*)mxMalloc(prior_nz * sizeof(SuiteSparse_long)); + *Ai = (SuiteSparse_long *) mxMalloc(prior_nz * sizeof(SuiteSparse_long)); test_mxMalloc(*Ai, __LINE__, __FILE__, __func__, prior_nz * sizeof(SuiteSparse_long)); if (!(*Ai)) { @@ -885,7 +880,7 @@ dynSparseMatrix::Init_UMFPACK_Sparse_Simple(int Size, map<pair<pair<int, int>, i tmp << " in Init_UMFPACK_Sparse, can't allocate Ai index vector\n"; throw FatalExceptionHandling(tmp.str()); } - *Ax = (double*)mxMalloc(prior_nz * sizeof(double)); + *Ax = (double *) mxMalloc(prior_nz * sizeof(double)); test_mxMalloc(*Ax, __LINE__, __FILE__, __func__, prior_nz * sizeof(double)); if (!(*Ax)) { @@ -1003,13 +998,13 @@ void dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Size, map<pair<pair<int, int>, int>, int> &IM, SuiteSparse_long **Ap, SuiteSparse_long **Ai, double **Ax, double **b, mxArray *x0_m, vector_table_conditional_local_type vector_table_conditional_local, int block_num) { int t, eq, var, lag, ti_y_kmin, ti_y_kmax; - double* jacob_exo ; - int row_x = 0; + double *jacob_exo; + int row_x = 0; #ifdef DEBUG int col_x; -#endif +#endif int n = periods * Size; - *b = (double*)mxMalloc(n * sizeof(double)); + *b = (double *) mxMalloc(n * sizeof(double)); if (!(*b)) { ostringstream tmp; @@ -1023,16 +1018,16 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si tmp << " in Init_UMFPACK_Sparse_Simple, can't retrieve x0 vector\n"; throw FatalExceptionHandling(tmp.str()); } - *Ap = (SuiteSparse_long*)mxMalloc((n+1) * sizeof(SuiteSparse_long)); + *Ap = (SuiteSparse_long *) mxMalloc((n+1) * sizeof(SuiteSparse_long)); test_mxMalloc(*Ap, __LINE__, __FILE__, __func__, (n+1) * sizeof(SuiteSparse_long)); if (!(*Ap)) { ostringstream tmp; tmp << " in Init_UMFPACK_Sparse, can't allocate Ap index vector\n"; throw FatalExceptionHandling(tmp.str()); - } + } size_t prior_nz = IM.size() * periods; - *Ai = (SuiteSparse_long*)mxMalloc(prior_nz * sizeof(SuiteSparse_long)); + *Ai = (SuiteSparse_long *) mxMalloc(prior_nz * sizeof(SuiteSparse_long)); test_mxMalloc(*Ai, __LINE__, __FILE__, __func__, prior_nz * sizeof(SuiteSparse_long)); if (!(*Ai)) { @@ -1040,7 +1035,7 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si tmp << " in Init_UMFPACK_Sparse, can't allocate Ai index vector\n"; throw FatalExceptionHandling(tmp.str()); } - *Ax = (double*)mxMalloc(prior_nz * sizeof(double)); + *Ax = (double *) mxMalloc(prior_nz * sizeof(double)); test_mxMalloc(*Ax, __LINE__, __FILE__, __func__, prior_nz * sizeof(double)); if (!(*Ax)) { @@ -1068,10 +1063,10 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si #ifdef DEBUG col_x = mxGetN(jacobian_exo_block[block_num]); #endif - } - else - { - jacob_exo = NULL; + } + else + { + jacob_exo = NULL; } #ifdef DEBUG int local_index; @@ -1087,26 +1082,26 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si it4 = IM.begin(); var = 0; while (it4 != IM.end()) - { + { var = it4->first.first.first; #ifdef DEBUG - if (var < 0 || var >= Size) - { - ostringstream tmp; - tmp << " in Init_UMFPACK_Sparse, var (" << var << ") out of range\n"; - throw FatalExceptionHandling(tmp.str()); - } -#endif + if (var < 0 || var >= Size) + { + ostringstream tmp; + tmp << " in Init_UMFPACK_Sparse, var (" << var << ") out of range\n"; + throw FatalExceptionHandling(tmp.str()); + } +#endif eq = it4->first.second+Size*t; #ifdef DEBUG - if (eq < 0 || eq >= Size) - { - ostringstream tmp; - tmp << " in Init_UMFPACK_Sparse, eq (" << eq << ") out of range\n"; - throw FatalExceptionHandling(tmp.str()); - } + if (eq < 0 || eq >= Size) + { + ostringstream tmp; + tmp << " in Init_UMFPACK_Sparse, eq (" << eq << ") out of range\n"; + throw FatalExceptionHandling(tmp.str()); + } #endif - lag = - it4->first.first.second; + lag = -it4->first.first.second; int index = it4->second+ (t-lag) * u_count_init; if (var != last_var) { @@ -1129,7 +1124,7 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si { if ((t == 0) && (var < (periods+y_kmax)*Size) && (lag == 0) && (vector_table_conditional_local.size())) { - flip_exo = vector_table_conditional_local[var].var_exo; + flip_exo = vector_table_conditional_local[var].var_exo; #ifdef DEBUG local_index = eq; #endif @@ -1146,23 +1141,23 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si #ifdef DEBUG if (local_index < 0 || local_index >= Size * periods) - { - ostringstream tmp; - tmp << " in Init_UMFPACK_Sparse, index (" << local_index << ") out of range for b vector\n"; - throw FatalExceptionHandling(tmp.str()); - } - if (k + row_x*flip_exo < 0 || k + row_x*flip_exo >= row_x * col_x) - { - ostringstream tmp; - tmp << " in Init_UMFPACK_Sparse, index (" << var+Size*(y_kmin+t+lag) << ") out of range for jacob_exo vector\n"; - throw FatalExceptionHandling(tmp.str()); - } - if (t+y_kmin+flip_exo*nb_row_x < 0 || t+y_kmin+flip_exo*nb_row_x >= nb_row_x * this->col_x) - { - ostringstream tmp; - tmp << " in Init_UMFPACK_Sparse, index (" << index_vara[var+Size*(y_kmin+t+lag)] << ") out of range for x vector max=" << nb_row_x * this->col_x << "\n"; - throw FatalExceptionHandling(tmp.str()); - } + { + ostringstream tmp; + tmp << " in Init_UMFPACK_Sparse, index (" << local_index << ") out of range for b vector\n"; + throw FatalExceptionHandling(tmp.str()); + } + if (k + row_x*flip_exo < 0 || k + row_x*flip_exo >= row_x * col_x) + { + ostringstream tmp; + tmp << " in Init_UMFPACK_Sparse, index (" << var+Size*(y_kmin+t+lag) << ") out of range for jacob_exo vector\n"; + throw FatalExceptionHandling(tmp.str()); + } + if (t+y_kmin+flip_exo*nb_row_x < 0 || t+y_kmin+flip_exo*nb_row_x >= nb_row_x * this->col_x) + { + ostringstream tmp; + tmp << " in Init_UMFPACK_Sparse, index (" << index_vara[var+Size*(y_kmin+t+lag)] << ") out of range for x vector max=" << nb_row_x * this->col_x << "\n"; + throw FatalExceptionHandling(tmp.str()); + } #endif u[k] -= jacob_exo[k + row_x*flip_exo] * x[t+y_kmin+flip_exo*nb_row_x]; } @@ -1172,10 +1167,10 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si } /*if (t==0) { - if (min_lag > lag) - min_lag = lag; - if (max_lag < lag) - max_lag = lag; + if (min_lag > lag) + min_lag = lag; + if (max_lag < lag) + max_lag = lag; }*/ if (var < (periods+y_kmax)*Size) @@ -1221,14 +1216,14 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si tmp << " in Init_UMFPACK_Sparse, index (" << var+Size*(y_kmin+t) << ") out of range for index_vara vector\n"; throw FatalExceptionHandling(tmp.str()); } - if (index_vara[var+Size*(y_kmin+t/*+lag*/)] < 0 || index_vara[var+Size*(y_kmin+t/*+lag*/)] >= y_size*(periods+y_kmin+y_kmax)) + if (index_vara[var+Size*(y_kmin+t /*+lag*/)] < 0 || index_vara[var+Size*(y_kmin+t /*+lag*/)] >= y_size*(periods+y_kmin+y_kmax)) { ostringstream tmp; - tmp << " in Init_UMFPACK_Sparse, index (" << index_vara[var+Size*(y_kmin+t/*+lag*/)] << ") out of range for y vector max=" << y_size*(periods+y_kmin+y_kmax) << "\n"; + tmp << " in Init_UMFPACK_Sparse, index (" << index_vara[var+Size*(y_kmin+t /*+lag*/)] << ") out of range for y vector max=" << y_size*(periods+y_kmin+y_kmax) << "\n"; throw FatalExceptionHandling(tmp.str()); - } + } #endif - (*b)[eq - lag * Size] += u[index] * y[index_vara[var+Size*(y_kmin+t/*+lag*/)]]; + (*b)[eq - lag * Size] += u[index] * y[index_vara[var+Size*(y_kmin+t /*+lag*/)]]; } } @@ -1282,17 +1277,17 @@ dynSparseMatrix::Init_UMFPACK_Sparse(int periods, int y_kmin, int y_kmax, int Si #ifdef DEBUG mexPrintf("*Ax = ["); for (int i = 0; i < NZE; i++) - mexPrintf("%f ",(*Ax)[i]); + mexPrintf("%f ", (*Ax)[i]); mexPrintf("]\n"); mexPrintf("*Ap = ["); for (int i = 0; i < n+1; i++) - mexPrintf("%d ",(*Ap)[i]); + mexPrintf("%d ", (*Ap)[i]); mexPrintf("]\n"); mexPrintf("*Ai = ["); for (int i = 0; i < NZE; i++) - mexPrintf("%d ",(*Ai)[i]); + mexPrintf("%d ", (*Ai)[i]); mexPrintf("]\n"); #endif } @@ -1302,8 +1297,8 @@ dynSparseMatrix::Init_CUDA_Sparse_Simple(int Size, map<pair<pair<int, int>, int> { int eq, var; - *b = (double*)mxMalloc(Size * sizeof(double)); - test_mxMalloc(*b, __LINE__, __FILE__, __func__, Size * sizeof(double)); + *b = (double *) mxMalloc(Size * sizeof(double)); + test_mxMalloc(*b, __LINE__, __FILE__, __func__, Size * sizeof(double)); if (!(*b)) { ostringstream tmp; @@ -1317,7 +1312,7 @@ dynSparseMatrix::Init_CUDA_Sparse_Simple(int Size, map<pair<pair<int, int>, int> tmp << " in Init_CUDA_Sparse_Simple, can't retrieve x0 vector\n"; throw FatalExceptionHandling(tmp.str()); } - *Ap = (SuiteSparse_long*)mxMalloc((Size+1) * sizeof(SuiteSparse_long)); + *Ap = (SuiteSparse_long *) mxMalloc((Size+1) * sizeof(SuiteSparse_long)); test_mxMalloc(*Ap, __LINE__, __FILE__, __func__, (Size+1) * sizeof(SuiteSparse_long)); if (!(*Ap)) { @@ -1326,7 +1321,7 @@ dynSparseMatrix::Init_CUDA_Sparse_Simple(int Size, map<pair<pair<int, int>, int> throw FatalExceptionHandling(tmp.str()); } size_t prior_nz = IM.size(); - *Ai = (SuiteSparse_long*)mxMalloc(prior_nz * sizeof(SuiteSparse_long)); + *Ai = (SuiteSparse_long *) mxMalloc(prior_nz * sizeof(SuiteSparse_long)); test_mxMalloc(*Ai, __LINE__, __FILE__, __func__, prior_nz * sizeof(SuiteSparse_long)); if (!(*Ai)) { @@ -1334,7 +1329,7 @@ dynSparseMatrix::Init_CUDA_Sparse_Simple(int Size, map<pair<pair<int, int>, int> tmp << " in Init_CUDA_Sparse, can't allocate Ai index vector\n"; throw FatalExceptionHandling(tmp.str()); } - *Ax = (double*)mxMalloc(prior_nz * sizeof(double)); + *Ax = (double *) mxMalloc(prior_nz * sizeof(double)); test_mxMalloc(*Ax, __LINE__, __FILE__, __func__, prior_nz * sizeof(double)); if (!(*Ax)) { @@ -1439,10 +1434,9 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, cudaSetDevice(CUDA_device); - - double *Host_b = (double*)mxMalloc(n * sizeof(double)); + double *Host_b = (double *) mxMalloc(n * sizeof(double)); test_mxMalloc(Host_b, __LINE__, __FILE__, __func__, n * sizeof(double)); - cudaChk(cudaMalloc((void**)b, n * sizeof(double)), " in Init_Cuda_Sparse, not enought memory to allocate b vector on the graphic card\n"); + cudaChk(cudaMalloc((void **) b, n * sizeof(double)), " in Init_Cuda_Sparse, not enought memory to allocate b vector on the graphic card\n"); double *Host_x0 = mxGetPr(x0_m); if (!Host_x0) @@ -1451,45 +1445,41 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, tmp << " in Init_Cuda_Sparse, can't retrieve x0 vector\n"; throw FatalExceptionHandling(tmp.str()); } - cudaChk(cudaMalloc((void**)x0, n * sizeof(double)), " in Init_Cuda_Sparse, not enought memory to allocate x0 vector on the graphic card\n"); + cudaChk(cudaMalloc((void **) x0, n * sizeof(double)), " in Init_Cuda_Sparse, not enought memory to allocate x0 vector on the graphic card\n"); - int* Host_Ap = (int*)mxMalloc((n+1) * sizeof(int)); + int *Host_Ap = (int *) mxMalloc((n+1) * sizeof(int)); test_mxMalloc(Host_Ap, __LINE__, __FILE__, __func__, (n+1) * sizeof(int)); - - int* Host_Ai = (int*)mxMalloc(prior_nz * sizeof(int)); + int *Host_Ai = (int *) mxMalloc(prior_nz * sizeof(int)); test_mxMalloc(Host_Ai, __LINE__, __FILE__, __func__, prior_nz * sizeof(int)); - - double* Host_Ax = (double*)mxMalloc(prior_nz * sizeof(double)); + double *Host_Ax = (double *) mxMalloc(prior_nz * sizeof(double)); test_mxMalloc(Host_Ax, __LINE__, __FILE__, __func__, prior_nz * sizeof(double)); - int* Host_Ai_tild, * Host_Ap_tild; + int *Host_Ai_tild, *Host_Ap_tild; if (preconditioner == 3) { - Host_Ap_tild = (int*) mxMalloc((n+1)*sizeof(int)); - test_mxMalloc(Host_Ap_tild, __LINE__, __FILE__, __func__, (n+1)*sizeof(int)); - Host_Ai_tild = (int*) mxMalloc(prior_nz*sizeof(int)); - test_mxMalloc(Host_Ai_tild, __LINE__, __FILE__, __func__, prior_nz*sizeof(int)); + Host_Ap_tild = (int *) mxMalloc((n+1)*sizeof(int)); + test_mxMalloc(Host_Ap_tild, __LINE__, __FILE__, __func__, (n+1)*sizeof(int)); + Host_Ai_tild = (int *) mxMalloc(prior_nz*sizeof(int)); + test_mxMalloc(Host_Ai_tild, __LINE__, __FILE__, __func__, prior_nz*sizeof(int)); Host_Ap_tild[0] = 0; } - if (preconditioner == 0) preconditioner_size = n; else if (preconditioner == 1 || preconditioner == 2 || preconditioner == 3) preconditioner_size = prior_nz; - double *Host_A_tild = (double*)mxMalloc(preconditioner_size * sizeof(double)); + double *Host_A_tild = (double *) mxMalloc(preconditioner_size * sizeof(double)); test_mxMalloc(Host_A_tild, __LINE__, __FILE__, __func__, preconditioner_size * sizeof(double)); - map<pair<pair<int, int>, int>, int>::iterator it4; for (int i = 0; i < y_size*(periods+y_kmin); i++) ya[i] = y[i]; -#ifdef DEBUG +# ifdef DEBUG unsigned int max_nze = mxGetNzmax(A_m); -#endif +# endif unsigned int NZE = 0, NZE_tild = 0; int last_eq = 0; for (int i = 0; i < periods*Size; i++) @@ -1510,17 +1500,17 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, eq = it4->first.first.first; if (eq != last_eq) { -#ifdef DEBUG +# ifdef DEBUG if (1+last_eq + t * Size > (n + 1)) { ostringstream tmp; tmp << " in Init_CUDA_Sparse, 1+last_eq + t * Size (" << 1+last_eq + t * Size << ") out of range for Host_Ap vector\n"; throw FatalExceptionHandling(tmp.str()); } -#endif +# endif Host_Ap[1+last_eq + t * Size] = NZE; if (preconditioner == 3 && t == 0) - Host_Ap_tild[1+last_eq ] = NZE_tild; + Host_Ap_tild[1+last_eq ] = NZE_tild; last_eq = eq; } var = it4->first.second+Size*t; @@ -1532,7 +1522,7 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, ti_y_kmax = min(periods-(t + 1), y_kmax); if ((lag <= ti_y_kmax && lag >= ti_y_kmin) || preconditioner == 3) /*Build the index for sparse matrix containing the jacobian : u*/ { -#ifdef DEBUG +# ifdef DEBUG if (index < 0 || index >= u_count_alloc || index > (periods-1)* IM.size() + Size * Size + periods * Size) { ostringstream tmp; @@ -1545,7 +1535,7 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, tmp << " in Init_CUDA_Sparse, exceeds the capacity of A_i or A_x sparse matrix\n"; throw FatalExceptionHandling(tmp.str()); } -#endif +# endif bool to_store = true; if (preconditioner == 0) { @@ -1563,10 +1553,10 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, } if (t == 0) { - map<pair<int, int>, int>::const_iterator it = jacob_struct.find(make_pair(eq + t * Size, var)); - if (it != jacob_struct.end()) - Host_A_tild[it->second] += u[index]; - else + map<pair<int, int>, int>::const_iterator it = jacob_struct.find(make_pair(eq + t * Size, var)); + if (it != jacob_struct.end()) + Host_A_tild[it->second] += u[index]; + else { jacob_struct[make_pair(eq, var)] = NZE_tild; Host_A_tild[NZE_tild] = u[index]; @@ -1584,7 +1574,7 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, } else { -#ifdef DEBUG +# ifdef DEBUG if (var < 0 || var >= Size * periods) { ostringstream tmp; @@ -1603,13 +1593,13 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, tmp << " in Init_CUDA_Sparse, index (" << index_vara[var+Size*(y_kmin+lag)] << ") out of range for y vector max=" << y_size*(periods+y_kmin+y_kmax) << "\n"; throw FatalExceptionHandling(tmp.str()); } -#endif +# endif Host_b[eq + t * Size] += u[index]*y[index_vara[var+Size*(y_kmin+lag)]]; } } else // ...and store it in the u vector { -#ifdef DEBUG +# ifdef DEBUG if (index < 0 || index >= u_count_alloc) { ostringstream tmp; @@ -1622,7 +1612,7 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, tmp << " in Init_CUDA_Sparse, index (" << var << ") out of range for b vector\n"; throw FatalExceptionHandling(tmp.str()); } -#endif +# endif Host_b[var] += u[index]; } it4++; @@ -1631,12 +1621,12 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, Host_Ap[Size*periods] = NZE; if (preconditioner == 3) { - int* tmp_Ap_tild = (int*) mxMalloc((Size + 1) * sizeof(int) ); - test_mxMalloc(tmp_Ap_tild, __LINE__, __FILE__, __func__, (Size + 1) * sizeof(int)) ; - int* tmp_Ai_tild = (int*) mxMalloc(NZE_tild * sizeof(int) ); - test_mxMalloc(tmp_Ai_tild, __LINE__, __FILE__, __func__, NZE_tild * sizeof(int)); - double* tmp_A_tild = (double*) mxMalloc(NZE_tild * sizeof(double)); - test_mxMalloc(tmp_A_tild, __LINE__, __FILE__, __func__, NZE_tild * sizeof(double)); + int *tmp_Ap_tild = (int *) mxMalloc((Size + 1) * sizeof(int)); + test_mxMalloc(tmp_Ap_tild, __LINE__, __FILE__, __func__, (Size + 1) * sizeof(int)); + int *tmp_Ai_tild = (int *) mxMalloc(NZE_tild * sizeof(int)); + test_mxMalloc(tmp_Ai_tild, __LINE__, __FILE__, __func__, NZE_tild * sizeof(int)); + double *tmp_A_tild = (double *) mxMalloc(NZE_tild * sizeof(double)); + test_mxMalloc(tmp_A_tild, __LINE__, __FILE__, __func__, NZE_tild * sizeof(double)); memcpy(tmp_Ap_tild, Host_Ap_tild, (Size + 1) * sizeof(int)); memcpy(tmp_Ai_tild, Host_Ai_tild, NZE_tild * sizeof(int)); memcpy(tmp_A_tild, Host_A_tild, NZE_tild * sizeof(double)); @@ -1646,8 +1636,8 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, for (int i = 0; i < Size; i++) { - for(int j = tmp_Ap_tild[i]; j < tmp_Ap_tild[i+1]; j++) - if (abs(tmp_A_tild[j]) > 1.0e-20 ) + for (int j = tmp_Ap_tild[i]; j < tmp_Ap_tild[i+1]; j++) + if (abs(tmp_A_tild[j]) > 1.0e-20) { Host_A_tild[NZE_tild] = tmp_A_tild[j]; Host_Ai_tild[NZE_tild] = tmp_Ai_tild[j]; @@ -1665,32 +1655,31 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, if (preconditioner == 1 || preconditioner == 2 || preconditioner == 3) preconditioner_size = NZE; - -#ifdef DEBUG +# ifdef DEBUG mexPrintf("Host_Ax = ["); for (int i = 0; i < NZE; i++) - mexPrintf("%f ",Host_Ax[i]); + mexPrintf("%f ", Host_Ax[i]); mexPrintf("]\n"); mexPrintf("Host_Ap = ["); for (int i = 0; i < n+1; i++) - mexPrintf("%d ",Host_Ap[i]); + mexPrintf("%d ", Host_Ap[i]); mexPrintf("]\n"); mexPrintf("Host_Ai = ["); for (int i = 0; i < NZE; i++) - mexPrintf("%d ",Host_Ai[i]); + mexPrintf("%d ", Host_Ai[i]); mexPrintf("]\n"); -#endif - cudaChk(cudaMalloc((void**)Ai, NZE * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ai index vector on the graphic card\n"); - cudaChk(cudaMalloc((void**)Ax, NZE * sizeof(double)), " in Init_Cuda_Sparse, can't allocate Ax on the graphic card\n"); - cudaChk(cudaMalloc((void**)Ap, (n+1) * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ap index vector on the graphic card\n"); +# endif + cudaChk(cudaMalloc((void **) Ai, NZE * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ai index vector on the graphic card\n"); + cudaChk(cudaMalloc((void **) Ax, NZE * sizeof(double)), " in Init_Cuda_Sparse, can't allocate Ax on the graphic card\n"); + cudaChk(cudaMalloc((void **) Ap, (n+1) * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ap index vector on the graphic card\n"); if (preconditioner == 3) { - cudaChk(cudaMalloc((void**)Ai_tild, NZE_tild * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ai_tild index vector on the graphic card\n"); - cudaChk(cudaMalloc((void**)Ap_tild, (n+1) * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ap_tild index vector on the graphic card\n"); + cudaChk(cudaMalloc((void **) Ai_tild, NZE_tild * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ai_tild index vector on the graphic card\n"); + cudaChk(cudaMalloc((void **) Ap_tild, (n+1) * sizeof(int)), " in Init_Cuda_Sparse, can't allocate Ap_tild index vector on the graphic card\n"); } - cudaChk(cudaMalloc((void**)A_tild, preconditioner_size * sizeof(double)), " in Init_Cuda_Sparse, can't allocate A_tild on the graphic card\n"); + cudaChk(cudaMalloc((void **) A_tild, preconditioner_size * sizeof(double)), " in Init_Cuda_Sparse, can't allocate A_tild on the graphic card\n"); cudaChk(cudaMemcpy(*x0, Host_x0, n * sizeof(double), cudaMemcpyHostToDevice), " in Init_CUDA_Sparse, cudaMemcpy x0 = Host_x0 failed"); cudaChk(cudaMemcpy(*b, Host_b, n * sizeof(double), cudaMemcpyHostToDevice), " in Init_CUDA_Sparse, cudaMemcpy b = Host_b failed"); @@ -1706,16 +1695,15 @@ dynSparseMatrix::Init_CUDA_Sparse(int periods, int y_kmin, int y_kmax, int Size, } #endif - void -dynSparseMatrix::PrintM(int n, double* Ax, mwIndex *Ap, mwIndex *Ai) +dynSparseMatrix::PrintM(int n, double *Ax, mwIndex *Ap, mwIndex *Ai) { int nnz = Ap[n]; - double *A = (double*)mxMalloc(n * n * sizeof(double)); + double *A = (double *) mxMalloc(n * n * sizeof(double)); test_mxMalloc(A, __LINE__, __FILE__, __func__, n * n * sizeof(double)); - memset(A,0,n * n * sizeof(double)); + memset(A, 0, n * n * sizeof(double)); int k = 0; - for (int i = 0; i< n; i++) + for (int i = 0; i < n; i++) { for (int j = Ap[i]; j < (int) Ap[i + 1]; j++) { @@ -1728,10 +1716,10 @@ dynSparseMatrix::PrintM(int n, double* Ax, mwIndex *Ap, mwIndex *Ai) mexPrintf("Problem nnz(%d) != number of elements(%d)\n", nnz, k); mexPrintf("----------------------\n"); //mexEvalString("drawnow;"); - for (int i = 0; i < n ; i++) + for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) - mexPrintf("%-6.3f ",A[i * n + j]); + mexPrintf("%-6.3f ", A[i * n + j]); mexPrintf("\n"); } mxFree(A); @@ -1890,35 +1878,35 @@ dynSparseMatrix::Init_GE(int periods, int y_kmin, int y_kmax, int Size, map<pair map<pair<pair<int, int>, int>, int>::iterator it4; NonZeroElem *first; pivot = (int *) mxMalloc(Size*periods*sizeof(int)); - test_mxMalloc(pivot, __LINE__, __FILE__, __func__, Size*periods*sizeof(int)); - pivot_save = (int *) mxMalloc(Size*periods*sizeof(int)); + test_mxMalloc(pivot, __LINE__, __FILE__, __func__, Size*periods*sizeof(int)); + pivot_save = (int *) mxMalloc(Size*periods*sizeof(int)); test_mxMalloc(pivot_save, __LINE__, __FILE__, __func__, Size*periods*sizeof(int)); - pivotk = (int *) mxMalloc(Size*periods*sizeof(int)); + pivotk = (int *) mxMalloc(Size*periods*sizeof(int)); test_mxMalloc(pivotk, __LINE__, __FILE__, __func__, Size*periods*sizeof(int)); - pivotv = (double *) mxMalloc(Size*periods*sizeof(double)); + pivotv = (double *) mxMalloc(Size*periods*sizeof(double)); test_mxMalloc(pivotv, __LINE__, __FILE__, __func__, Size*periods*sizeof(double)); - pivotva = (double *) mxMalloc(Size*periods*sizeof(double)); + pivotva = (double *) mxMalloc(Size*periods*sizeof(double)); test_mxMalloc(pivotva, __LINE__, __FILE__, __func__, Size*periods*sizeof(double)); - b = (int *) mxMalloc(Size*periods*sizeof(int)); + b = (int *) mxMalloc(Size*periods*sizeof(int)); test_mxMalloc(b, __LINE__, __FILE__, __func__, Size*periods*sizeof(int)); - line_done = (bool *) mxMalloc(Size*periods*sizeof(bool)); + line_done = (bool *) mxMalloc(Size*periods*sizeof(bool)); test_mxMalloc(line_done, __LINE__, __FILE__, __func__, Size*periods*sizeof(bool)); mem_mngr.init_CHUNK_BLCK_SIZE(u_count); g_save_op = NULL; g_nop_all = 0; i = (periods+y_kmax+1)*Size*sizeof(NonZeroElem *); - FNZE_R = (NonZeroElem **) mxMalloc(i); + FNZE_R = (NonZeroElem **) mxMalloc(i); test_mxMalloc(FNZE_R, __LINE__, __FILE__, __func__, i); - FNZE_C = (NonZeroElem **) mxMalloc(i); + FNZE_C = (NonZeroElem **) mxMalloc(i); test_mxMalloc(FNZE_C, __LINE__, __FILE__, __func__, i); - NonZeroElem **temp_NZE_R = (NonZeroElem **) mxMalloc(i); + NonZeroElem **temp_NZE_R = (NonZeroElem **) mxMalloc(i); test_mxMalloc(*temp_NZE_R, __LINE__, __FILE__, __func__, i); - NonZeroElem **temp_NZE_C = (NonZeroElem **) mxMalloc(i); + NonZeroElem **temp_NZE_C = (NonZeroElem **) mxMalloc(i); test_mxMalloc(*temp_NZE_C, __LINE__, __FILE__, __func__, i); i = (periods+y_kmax+1)*Size*sizeof(int); - NbNZRow = (int *) mxMalloc(i); + NbNZRow = (int *) mxMalloc(i); test_mxMalloc(NbNZRow, __LINE__, __FILE__, __func__, i); - NbNZCol = (int *) mxMalloc(i); + NbNZCol = (int *) mxMalloc(i); test_mxMalloc(NbNZCol, __LINE__, __FILE__, __func__, i); for (int i = 0; i < periods*Size; i++) @@ -2687,7 +2675,7 @@ dynSparseMatrix::mult_SAT_B(mxArray *A_m, mxArray *B_m) double *B_d = mxGetPr(B_m); mxArray *C_m = mxCreateDoubleMatrix(m_A, n_B, mxREAL); double *C_d = mxGetPr(C_m); - for (int j = 0; j < (int)n_B; j++) + for (int j = 0; j < (int) n_B; j++) { for (unsigned int i = 0; i < n_A; i++) { @@ -2839,19 +2827,18 @@ dynSparseMatrix::Sparse_transpose(mxArray *A_m) return C_m; } - -#define sign(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a)) +#define sign(a, b) ((b) >= 0.0 ? fabs(a) : -fabs(a)) bool dynSparseMatrix::mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc) { - const double GOLD=1.618034; - const double GLIMIT=100.0; - const double TINY=1.0e-20; + const double GOLD = 1.618034; + const double GLIMIT = 100.0; + const double TINY = 1.0e-20; double tmp; - mexPrintf("bracketing *ax=%f, *bx=%f\n",*ax, *bx); + mexPrintf("bracketing *ax=%f, *bx=%f\n", *ax, *bx); //mexEvalString("drawnow;"); - double ulim,u,r,q,fu; + double ulim, u, r, q, fu; if (!compute_complete(*ax, fa)) return false; if (!compute_complete(*bx, fb)) @@ -2866,35 +2853,35 @@ dynSparseMatrix::mnbrak(double *ax, double *bx, double *cx, double *fa, double * *fa = *fb; *fb = tmp; } - *cx=(*bx)+GOLD*(*bx-*ax); + *cx = (*bx)+GOLD*(*bx-*ax); if (!compute_complete(*cx, fc)) return false; while (*fb > *fc) { - r=(*bx-*ax)*(*fb-*fc); - q=(*bx-*cx)*(*fb-*fa); - u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ - (2.0*sign(fmax(fabs(q-r),TINY),q-r)); - ulim=(*bx)+GLIMIT*(*cx-*bx); + r = (*bx-*ax)*(*fb-*fc); + q = (*bx-*cx)*(*fb-*fa); + u = (*bx)-((*bx-*cx)*q-(*bx-*ax)*r) + /(2.0*sign(fmax(fabs(q-r), TINY), q-r)); + ulim = (*bx)+GLIMIT*(*cx-*bx); if ((*bx-u)*(u-*cx) > 0.0) { if (!compute_complete(u, &fu)) return false; if (fu < *fc) { - *ax=(*bx); - *bx=u; - *fa=(*fb); - *fb=fu; + *ax = (*bx); + *bx = u; + *fa = (*fb); + *fb = fu; return true; } else if (fu > *fb) { - *cx=u; - *fc=fu; + *cx = u; + *fc = fu; return true; } - u=(*cx)+GOLD*(*cx-*bx); + u = (*cx)+GOLD*(*cx-*bx); if (!compute_complete(u, &fu)) return false; } @@ -2915,13 +2902,13 @@ dynSparseMatrix::mnbrak(double *ax, double *bx, double *cx, double *fa, double * } else if ((u-ulim)*(ulim-*cx) >= 0.0) { - u=ulim; + u = ulim; if (!compute_complete(u, &fu)) return false; } else { - u=(*cx)+GOLD*(*cx-*bx); + u = (*cx)+GOLD*(*cx-*bx); if (!compute_complete(u, &fu)) return false; } @@ -2938,23 +2925,23 @@ dynSparseMatrix::mnbrak(double *ax, double *bx, double *cx, double *fa, double * bool dynSparseMatrix::golden(double ax, double bx, double cx, double tol, double solve_tolf, double *xmin) { - const double R=0.61803399; - const double C=(1.0-R); + const double R = 0.61803399; + const double C = (1.0-R); mexPrintf("golden\n"); //mexEvalString("drawnow;"); - double f1,f2,x0,x1,x2,x3; - int iter= 0, max_iter= 100; - x0=ax; - x3=cx; + double f1, f2, x0, x1, x2, x3; + int iter = 0, max_iter = 100; + x0 = ax; + x3 = cx; if (fabs(cx-bx) > fabs(bx-ax)) { - x1=bx; - x2=bx+C*(cx-bx); + x1 = bx; + x2 = bx+C*(cx-bx); } else { - x2=bx; - x1=bx-C*(bx-ax); + x2 = bx; + x1 = bx-C*(bx-ax); } if (!compute_complete(x1, &f1)) return false; @@ -2984,12 +2971,12 @@ dynSparseMatrix::golden(double ax, double bx, double cx, double tol, double solv } if (f1 < f2) { - *xmin=x1; + *xmin = x1; return true; } else { - *xmin=x2; + *xmin = x2; return true; } } @@ -3303,12 +3290,11 @@ void dynSparseMatrix::End_Matlab_LU_UMFPack() { if (Symbolic) - umfpack_dl_free_symbolic (&Symbolic) ; + umfpack_dl_free_symbolic(&Symbolic); if (Numeric) - umfpack_dl_free_numeric (&Numeric) ; + umfpack_dl_free_numeric(&Numeric); } - void dynSparseMatrix::End_Solver() { @@ -3320,17 +3306,17 @@ void dynSparseMatrix::Printfull_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b, int n) { double A[n*n]; - for (int i = 0 ; i < n*n ; i++) + for (int i = 0; i < n*n; i++) A[i] = 0; int k = 0; for (int i = 0; i < n; i++) - for (int j = Ap[i]; j < Ap[i+1]; j++) - A[Ai[j] * n + i] = Ax[k++]; + for (int j = Ap[i]; j < Ap[i+1]; j++) + A[Ai[j] * n + i] = Ax[k++]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) - mexPrintf("%4.1f ",A[i*n+j]); - mexPrintf(" %6.3f\n",b[i]); + mexPrintf("%4.1f ", A[i*n+j]); + mexPrintf(" %6.3f\n", b[i]); } } @@ -3339,8 +3325,8 @@ dynSparseMatrix::Print_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, doubl { int k = 0; for (int i = 0; i < n; i++) - for (int j = Ap[i]; j < Ap[i+1]; j++) - mexPrintf("(%d, %d) %f\n", Ai[j]+1, i+1, Ax[k++]); + for (int j = Ap[i]; j < Ap[i+1]; j++) + mexPrintf("(%d, %d) %f\n", Ai[j]+1, i+1, Ax[k++]); } void @@ -3351,11 +3337,11 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do double Control [UMFPACK_CONTROL], Info [UMFPACK_INFO], res [n]; #else double *Control, *Info, *res; - Control = (double*)mxMalloc(UMFPACK_CONTROL * sizeof(double)); + Control = (double *) mxMalloc(UMFPACK_CONTROL * sizeof(double)); test_mxMalloc(Control, __LINE__, __FILE__, __func__, UMFPACK_CONTROL * sizeof(double)); - Info = (double*)mxMalloc(UMFPACK_INFO * sizeof(double)); + Info = (double *) mxMalloc(UMFPACK_INFO * sizeof(double)); test_mxMalloc(Info, __LINE__, __FILE__, __func__, UMFPACK_INFO * sizeof(double)); - res = (double*)mxMalloc(n * sizeof(double)); + res = (double *) mxMalloc(n * sizeof(double)); test_mxMalloc(res, __LINE__, __FILE__, __func__, n * sizeof(double)); #endif @@ -3375,8 +3361,8 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do } } if (iter > 0) - umfpack_dl_free_numeric(&Numeric) ; - status = umfpack_dl_numeric (Ap, Ai, Ax, Symbolic, &Numeric, Control, Info); + umfpack_dl_free_numeric(&Numeric); + status = umfpack_dl_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info); if (status < 0) { umfpack_dl_report_info(Control, Info); @@ -3458,7 +3444,7 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do direction[eq] = yy; y[eq+it_*y_size] += slowc_l * yy; } - } + } mxFree(Ap); mxFree(Ai); @@ -3471,7 +3457,6 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do #endif } - void dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b, int n, int Size, double slowc_l, bool is_two_boundaries, int it_) { @@ -3480,11 +3465,11 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do double Control [UMFPACK_CONTROL], Info [UMFPACK_INFO], res [n]; #else double *Control, *Info, *res; - Control = (double*)mxMalloc(UMFPACK_CONTROL * sizeof(double)); + Control = (double *) mxMalloc(UMFPACK_CONTROL * sizeof(double)); test_mxMalloc(Control, __LINE__, __FILE__, __func__, UMFPACK_CONTROL * sizeof(double)); - Info = (double*)mxMalloc(UMFPACK_INFO * sizeof(double)); + Info = (double *) mxMalloc(UMFPACK_INFO * sizeof(double)); test_mxMalloc(Info, __LINE__, __FILE__, __func__, UMFPACK_INFO * sizeof(double)); - res = (double*)mxMalloc(n * sizeof(double)); + res = (double *) mxMalloc(n * sizeof(double)); test_mxMalloc(res, __LINE__, __FILE__, __func__, n * sizeof(double)); #endif @@ -3504,8 +3489,8 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do } } if (iter > 0) - umfpack_dl_free_numeric(&Numeric) ; - status = umfpack_dl_numeric (Ap, Ai, Ax, Symbolic, &Numeric, Control, Info); + umfpack_dl_free_numeric(&Numeric); + status = umfpack_dl_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info); if (status < 0) { umfpack_dl_report_info(Control, Info); @@ -3551,43 +3536,42 @@ dynSparseMatrix::Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, do #endif } - void dynSparseMatrix::Solve_LU_UMFPack(mxArray *A_m, mxArray *b_m, int Size, double slowc_l, bool is_two_boundaries, int it_) { SuiteSparse_long n = mxGetM(A_m); - SuiteSparse_long *Ap = (SuiteSparse_long*)mxGetJc (A_m); + SuiteSparse_long *Ap = (SuiteSparse_long *) mxGetJc(A_m); - SuiteSparse_long *Ai = (SuiteSparse_long*)mxGetIr(A_m); - double* Ax = mxGetPr(A_m); - double* B = mxGetPr(b_m); + SuiteSparse_long *Ai = (SuiteSparse_long *) mxGetIr(A_m); + double *Ax = mxGetPr(A_m); + double *B = mxGetPr(b_m); SuiteSparse_long status, sys = 0; #ifndef _MSC_VER double Control [UMFPACK_CONTROL], Info [UMFPACK_INFO], res [n]; #else double *Control, *Info, *res; - Control = (double*)mxMalloc(UMFPACK_CONTROL * sizeof(double)); + Control = (double *) mxMalloc(UMFPACK_CONTROL * sizeof(double)); test_mxMalloc(Control, __LINE__, __FILE__, __func__, UMFPACK_CONTROL * sizeof(double)); - Info = (double*)mxMalloc(UMFPACK_INFO * sizeof(double)); + Info = (double *) mxMalloc(UMFPACK_INFO * sizeof(double)); test_mxMalloc(Info, __LINE__, __FILE__, __func__, UMFPACK_INFO * sizeof(double)); - res = (double*)mxMalloc(n * sizeof(double)); + res = (double *) mxMalloc(n * sizeof(double)); test_mxMalloc(res, __LINE__, __FILE__, __func__, n * sizeof(double)); #endif - void *Symbolic, *Numeric ; - umfpack_dl_defaults (Control) ; + void *Symbolic, *Numeric; + umfpack_dl_defaults(Control); - status = umfpack_dl_symbolic (n, n, Ap, Ai, Ax, &Symbolic, Control, Info) ; + status = umfpack_dl_symbolic(n, n, Ap, Ai, Ax, &Symbolic, Control, Info); if (status != UMFPACK_OK) - umfpack_dl_report_info ((double*) NULL, Info) ; + umfpack_dl_report_info((double *) NULL, Info); - status = umfpack_dl_numeric (Ap, Ai, Ax, Symbolic, &Numeric, Control, Info) ; + status = umfpack_dl_numeric(Ap, Ai, Ax, Symbolic, &Numeric, Control, Info); if (status != UMFPACK_OK) - umfpack_dl_report_info ((double*) NULL, Info) ; + umfpack_dl_report_info((double *) NULL, Info); - status = umfpack_dl_solve (sys, Ap, Ai, Ax, res, B, Numeric, Control, Info) ; + status = umfpack_dl_solve(sys, Ap, Ai, Ax, res, B, Numeric, Control, Info); if (status != UMFPACK_OK) - umfpack_dl_report_info ((double*) NULL, Info) ; + umfpack_dl_report_info((double *) NULL, Info); //double *res = mxGetPr(z); if (is_two_boundaries) for (int i = 0; i < n; i++) @@ -3615,42 +3599,38 @@ dynSparseMatrix::Solve_LU_UMFPack(mxArray *A_m, mxArray *b_m, int Size, double s } - #ifdef CUDA void -printM(int n,double *Ax, int* Ap, int* Ai, cusparseMatDescr_t descrA, cusparseHandle_t cusparse_handle) +printM(int n, double *Ax, int *Ap, int *Ai, cusparseMatDescr_t descrA, cusparseHandle_t cusparse_handle) { //cudaError_t cuda_error; //cusparseStatus_t cusparse_status; - double * A_dense; - cudaChk(cudaMalloc((void**) &A_dense, n * n *sizeof(double)), "A_dense cudaMalloc has failed\n"); - + double *A_dense; + cudaChk(cudaMalloc((void **) &A_dense, n * n *sizeof(double)), "A_dense cudaMalloc has failed\n"); cusparseChk(cusparseDcsr2dense(cusparse_handle, n, n, descrA, - Ax, Ap,Ai, A_dense, n), "cusparseDcsr2dense has failed\n"); - double *A_dense_hoste = (double*)mxMalloc(n * n * sizeof(double)); + Ax, Ap, Ai, A_dense, n), "cusparseDcsr2dense has failed\n"); + double *A_dense_hoste = (double *) mxMalloc(n * n * sizeof(double)); test_mxMalloc(A_dense_hoste, __LINE__, __FILE__, __func__, n * n * sizeof(double)); - cudaChk(cudaMemcpy(A_dense_hoste, A_dense, n * n * sizeof(double),cudaMemcpyDeviceToHost), " cudaMemcpy(A_dense_hoste, A_dense) has failed\n"); + cudaChk(cudaMemcpy(A_dense_hoste, A_dense, n * n * sizeof(double), cudaMemcpyDeviceToHost), " cudaMemcpy(A_dense_hoste, A_dense) has failed\n"); mexPrintf("----------------------\n"); - mexPrintf("FillMode=%d, IndexBase=%d, MatType=%d, DiagType=%d\n",cusparseGetMatFillMode(descrA), cusparseGetMatIndexBase(descrA), cusparseGetMatType(descrA), cusparseGetMatDiagType(descrA)); + mexPrintf("FillMode=%d, IndexBase=%d, MatType=%d, DiagType=%d\n", cusparseGetMatFillMode(descrA), cusparseGetMatIndexBase(descrA), cusparseGetMatType(descrA), cusparseGetMatDiagType(descrA)); //mexEvalString("drawnow;"); - for (int i = 0; i < n ; i++) + for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) - mexPrintf("%-6.3f ",A_dense_hoste[i + j * n]); + mexPrintf("%-6.3f ", A_dense_hoste[i + j * n]); mexPrintf("\n"); } mxFree(A_dense_hoste); cudaChk(cudaFree(A_dense), "cudaFree(A_dense) has failed\n"); } - - void -dynSparseMatrix::Solve_CUDA_BiCGStab_Free(double* tmp_vect_host, double* p, double* r, double* v, double* s, double* t, double* y_, double* z, double* tmp_, - int* Ai, double* Ax, int* Ap, double* x0, double* b, double* A_tild, int* A_tild_i, int* A_tild_p/*, double* Lx, int* Li, int* Lp, - double* Ux, int* Ui, int* Up, int* device_n*/, cusparseSolveAnalysisInfo_t infoL, cusparseSolveAnalysisInfo_t infoU, - cusparseMatDescr_t descrL, cusparseMatDescr_t descrU, int preconditioner) +dynSparseMatrix::Solve_CUDA_BiCGStab_Free(double *tmp_vect_host, double *p, double *r, double *v, double *s, double *t, double *y_, double *z, double *tmp_, + int *Ai, double *Ax, int *Ap, double *x0, double *b, double *A_tild, int *A_tild_i, int *A_tild_p/*, double* Lx, int* Li, int* Lp, + double* Ux, int* Ui, int* Up, int* device_n*/, cusparseSolveAnalysisInfo_t infoL, cusparseSolveAnalysisInfo_t infoU, + cusparseMatDescr_t descrL, cusparseMatDescr_t descrU, int preconditioner) { //cudaError_t cuda_error; //cusparseStatus_t cusparse_status; @@ -3670,18 +3650,18 @@ dynSparseMatrix::Solve_CUDA_BiCGStab_Free(double* tmp_vect_host, double* p, doub cudaChk(cudaFree(b), " in Solve_Cuda_BiCGStab, can't free b\n"); /*if (preconditioner == 0) {*/ - cudaChk(cudaFree(A_tild), " in Solve_Cuda_BiCGStab, can't free A_tild (1)\n"); - cudaChk(cudaFree(A_tild_i), " in Solve_Cuda_BiCGStab, can't free A_tild_i (1)\n"); - cudaChk(cudaFree(A_tild_p), " in Solve_Cuda_BiCGStab, can't free A_tild_p (1)\n"); - /*} - else - { - cudaChk(cudaFree(Lx), " in Solve_Cuda_BiCGStab, can't free Lx\n"); - cudaChk(cudaFree(Li), " in Solve_Cuda_BiCGStab, can't free Li\n"); - cudaChk(cudaFree(Lp), " in Solve_Cuda_BiCGStab, can't free Lp\n"); - cudaChk(cudaFree(Ux), " in Solve_Cuda_BiCGStab, can't free Ux\n"); - cudaChk(cudaFree(Ui), " in Solve_Cuda_BiCGStab, can't free Ui\n"); - cudaChk(cudaFree(Up), " in Solve_Cuda_BiCGStab, can't free Up\n"); + cudaChk(cudaFree(A_tild), " in Solve_Cuda_BiCGStab, can't free A_tild (1)\n"); + cudaChk(cudaFree(A_tild_i), " in Solve_Cuda_BiCGStab, can't free A_tild_i (1)\n"); + cudaChk(cudaFree(A_tild_p), " in Solve_Cuda_BiCGStab, can't free A_tild_p (1)\n"); + /*} + else + { + cudaChk(cudaFree(Lx), " in Solve_Cuda_BiCGStab, can't free Lx\n"); + cudaChk(cudaFree(Li), " in Solve_Cuda_BiCGStab, can't free Li\n"); + cudaChk(cudaFree(Lp), " in Solve_Cuda_BiCGStab, can't free Lp\n"); + cudaChk(cudaFree(Ux), " in Solve_Cuda_BiCGStab, can't free Ux\n"); + cudaChk(cudaFree(Ui), " in Solve_Cuda_BiCGStab, can't free Ui\n"); + cudaChk(cudaFree(Up), " in Solve_Cuda_BiCGStab, can't free Up\n"); }*/ //cudaChk(cudaFree(device_n), " in Solve_Cuda_BiCGStab, can't free device_n\n"); if (preconditioner == 1 || preconditioner == 2 || preconditioner == 3) @@ -3699,14 +3679,14 @@ dynSparseMatrix::Solve_CUDA_BiCGStab_Free(double* tmp_vect_host, double* p, doub #endif void -Solve(double* Ax, int* Ap, int* Ai, double *b, int n, bool Lower, double *x) +Solve(double *Ax, int *Ap, int *Ai, double *b, int n, bool Lower, double *x) { if (Lower) { for (int i = 0; i < n; i++) { double sum = 0; - for(int j = Ap[i]; j < Ap[i+1]; j++) + for (int j = Ap[i]; j < Ap[i+1]; j++) { int k = Ai[j]; if (k < i) @@ -3717,10 +3697,10 @@ Solve(double* Ax, int* Ap, int* Ai, double *b, int n, bool Lower, double *x) } else { - for (int i = n-1 ; i >= 0; i--) + for (int i = n-1; i >= 0; i--) { double sum = 0, mul = 1; - for(int j = Ap[i]; j < Ap[i+1]; j++) + for (int j = Ap[i]; j < Ap[i+1]; j++) { int k = Ai[j]; if (k > i) @@ -3734,14 +3714,14 @@ Solve(double* Ax, int* Ap, int* Ai, double *b, int n, bool Lower, double *x) } void -Check(int n, double* Ax, int* Ap, int* Ai, double* b, double *x, bool Lower) +Check(int n, double *Ax, int *Ap, int *Ai, double *b, double *x, bool Lower) { if (Lower) { for (int i = 0; i < n; i++) { double sum = 0; - for(int j = Ap[i]; j < Ap[i+1]; j++) + for (int j = Ap[i]; j < Ap[i+1]; j++) { int k = Ai[j]; if (k < i) @@ -3749,15 +3729,15 @@ Check(int n, double* Ax, int* Ap, int* Ai, double* b, double *x, bool Lower) } double err = b[i] - sum - x[i]; if (abs(err) > 1e-10) - mexPrintf("error at i=%d\n",i); + mexPrintf("error at i=%d\n", i); } } else { - for (int i = n-1 ; i >= 0; i--) + for (int i = n-1; i >= 0; i--) { double sum = 0; - for(int j = Ap[i]; j < Ap[i+1]; j++) + for (int j = Ap[i]; j < Ap[i+1]; j++) { int k = Ai[j]; if (k >= i) @@ -3765,7 +3745,7 @@ Check(int n, double* Ax, int* Ap, int* Ai, double* b, double *x, bool Lower) } double err = b[i] - sum; if (abs(err) > 1e-10) - mexPrintf("error at i=%d\n",i); + mexPrintf("error at i=%d\n", i); } } } @@ -3773,7 +3753,7 @@ Check(int n, double* Ax, int* Ap, int* Ai, double* b, double *x, bool Lower) #ifdef CUDA int dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, int *Ai_tild, double *A_tild, double *b, double *x0, int n, int Size, double slowc_l, bool is_two_boundaries, - int it_, int nnz, int nnz_tild, int preconditioner, int max_iterations, int block) + int it_, int nnz, int nnz_tild, int preconditioner, int max_iterations, int block) { cusparseSolveAnalysisInfo_t info, infoL, infoU; cusparseMatDescr_t descrL, descrU; @@ -3790,8 +3770,8 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, double bnorm; double tmp1, tmp2; int refinement_needed = 0, stagnation = 0; - int max_refinement = min(min(int(floor(double(n)/50)),10),n-max_iterations), max_stagnation = 3; - int nblocks = ceil(double(n) / double(1024)); + int max_refinement = min(min(int (floor(double (n)/50)), 10), n-max_iterations), max_stagnation = 3; + int nblocks = ceil(double (n) / double (1024)); int n_threads; if (nblocks == 0) n_threads = n; @@ -3799,10 +3779,10 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, n_threads = 1024; int periods = n / Size; - double * tmp_vect_host = (double*)mxMalloc(n * sizeof(double)); + double *tmp_vect_host = (double *) mxMalloc(n * sizeof(double)); test_mxMalloc(tmp_vect_host, __LINE__, __FILE__, __func__, n * sizeof(double)); - cublasChk(cublasDnrm2(cublas_handle, n,b, 1, &bnorm), + cublasChk(cublasDnrm2(cublas_handle, n, b, 1, &bnorm), " in Solve_Cuda_BiCGStab, cublasDnrm2(b) has failed\n"); double tolb = tol * bnorm; @@ -3844,26 +3824,26 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, bool convergence = false; double zeros = 0.0, one = 1.0, m_one = -1.0; - cudaChk(cudaMalloc((void**)&tmp_, n * sizeof(double)), " in Solve_Cuda_Sparse, can't allocate tmp_ on the graphic card\n"); + cudaChk(cudaMalloc((void **) &tmp_, n * sizeof(double)), " in Solve_Cuda_Sparse, can't allocate tmp_ on the graphic card\n"); - cudaChk(cudaMalloc((void**)&r, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate r on the graphic card\n"); + cudaChk(cudaMalloc((void **) &r, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate r on the graphic card\n"); cudaChk(cudaMemcpy(r, b, n * sizeof(double), cudaMemcpyDeviceToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy r = b has failed\n"); //r = b - A * x0 cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, - n, nnz, &m_one, - CUDA_descr, Ax, - Ap, Ai, - x0, &one, - r), "in Solve_Cuda_BiCGStab, cusparseDcsrmv A * x0 has failed"); + n, nnz, &m_one, + CUDA_descr, Ax, + Ap, Ai, + x0, &one, + r), "in Solve_Cuda_BiCGStab, cusparseDcsrmv A * x0 has failed"); cudaChk(cudaMemcpy(tmp_vect_host, r, n*sizeof(double), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = p_tild has failed\n"); /*mexPrintf("r\n"); - for (int i = 0; i < n; i++) + for (int i = 0; i < n; i++) mexPrintf("%f\n",tmp_vect_host[i]);*/ - cudaChk(cudaMalloc((void**)&r0, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate r0 on the graphic card\n"); + cudaChk(cudaMalloc((void **) &r0, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate r0 on the graphic card\n"); cudaChk(cudaMemcpy(r0, r, n * sizeof(double), cudaMemcpyDeviceToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy r0 = r has failed\n"); cublasChk(cublasDnrm2(cublas_handle, n, // numerator @@ -3890,12 +3870,11 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, return 0; } - if (preconditioner == 0) { //Apply the Jacobi preconditioner /*VecDiv<<<nblocks, n_threads>>>(r_, A_tild, z_, n); - cuda_error = cudaMemcpy(zz_, z_, n * sizeof(double), cudaMemcpyDeviceToDevice);*/ + cuda_error = cudaMemcpy(zz_, z_, n * sizeof(double), cudaMemcpyDeviceToDevice);*/ } else if (preconditioner == 1) { @@ -3915,26 +3894,26 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, " in Solve_Cuda_BiCGStab, cusparseDcsrilu0 has failed\n"); //Make a copy of the indexes in A_tild_i and A_tild_p to use it the Bicgstab algorithm - cudaChk(cudaMalloc((void**)&A_tild_i, nnz * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate A_tild_i on the graphic card\n"); + cudaChk(cudaMalloc((void **) &A_tild_i, nnz * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate A_tild_i on the graphic card\n"); cudaChk(cudaMemcpy(A_tild_i, Ai, nnz * sizeof(int), cudaMemcpyDeviceToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_i = Ai has failed\n"); - cudaChk(cudaMalloc((void**)&A_tild_p, (n + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate A_tild_p on the graphic card\n"); + cudaChk(cudaMalloc((void **) &A_tild_p, (n + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate A_tild_p on the graphic card\n"); cudaChk(cudaMemcpy(A_tild_p, Ap, (n + 1) * sizeof(int), cudaMemcpyDeviceToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_p = Ap has failed\n"); } else if (preconditioner == 2) { //Because the Jacobian matrix A is store in CSC format in matlab // we have to transpose it to get a CSR format used by CUDA - mwIndex* Awi, *Awp; - double* A_tild_host = (double*)mxMalloc(nnz*sizeof(double)); - test_mxMalloc(A_tild_host, __LINE__, __FILE__, __func__, nnz*sizeof(double)); - Awi = (mwIndex*)mxMalloc(nnz * sizeof(mwIndex)); - test_mxMalloc(Awi, __LINE__, __FILE__, __func__, nnz * sizeof(mwIndex)); - Awp = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex)); - test_mxMalloc(Awp, __LINE__, __FILE__, __func__, (n + 1) * sizeof(mwIndex)); - int* Aii = (int*)mxMalloc(nnz * sizeof(int)); - test_mxMalloc(Aii, __LINE__, __FILE__, __func__, nnz * sizeof(int)); - int* Aip = (int*)mxMalloc((n + 1) * sizeof(int)); - test_mxMalloc(Aip, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int)); + mwIndex *Awi, *Awp; + double *A_tild_host = (double *) mxMalloc(nnz*sizeof(double)); + test_mxMalloc(A_tild_host, __LINE__, __FILE__, __func__, nnz*sizeof(double)); + Awi = (mwIndex *) mxMalloc(nnz * sizeof(mwIndex)); + test_mxMalloc(Awi, __LINE__, __FILE__, __func__, nnz * sizeof(mwIndex)); + Awp = (mwIndex *) mxMalloc((n + 1) * sizeof(mwIndex)); + test_mxMalloc(Awp, __LINE__, __FILE__, __func__, (n + 1) * sizeof(mwIndex)); + int *Aii = (int *) mxMalloc(nnz * sizeof(int)); + test_mxMalloc(Aii, __LINE__, __FILE__, __func__, nnz * sizeof(int)); + int *Aip = (int *) mxMalloc((n + 1) * sizeof(int)); + test_mxMalloc(Aip, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int)); cudaChk(cudaMemcpy(A_tild_host, A_tild, nnz*sizeof(double), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_host = A_tild has failed\n"); cudaChk(cudaMemcpy(Aii, Ai, nnz*sizeof(int), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy Aii = Ai has failed\n"); cudaChk(cudaMemcpy(Aip, Ap, (n+1)*sizeof(int), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy Aip = Ai has failed\n"); @@ -3944,7 +3923,7 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, Awp[i] = Aip[i]; mxFree(Aii); mxFree(Aip); - mxArray * At_m = mxCreateSparse(n,n,nnz,mxREAL); + mxArray *At_m = mxCreateSparse(n, n, nnz, mxREAL); mxSetIr(At_m, Awi); mxSetJc(At_m, Awp); mxSetPr(At_m, A_tild_host); @@ -3953,9 +3932,9 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, mxDestroyArray(At_m); /*mexPrintf("A_m\n"); - mexCallMATLAB(0, NULL, 1, &A_m, "disp_dense");*/ + mexCallMATLAB(0, NULL, 1, &A_m, "disp_dense");*/ /*mxFree(Awi); - mxFree(Awp);*/ + mxFree(Awp);*/ /*[L1, U1] = ilu(g1a=;*/ const char *field_names[] = {"type", "droptol", "milu", "udiag", "thresh"}; @@ -3964,7 +3943,7 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, const int milu = 2; const int udiag = 3; const int thresh = 4; - mwSize dims[1] = {(mwSize)1 }; + mwSize dims[1] = {(mwSize) 1 }; mxArray *Setup = mxCreateStructArray(1, dims, 5, field_names); mxSetFieldByNumber(Setup, 0, type, mxCreateString("ilutp")); //mxSetFieldByNumber(Setup, 0, type, mxCreateString("nofill")); @@ -3985,40 +3964,39 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, } mxDestroyArray(Setup); - - /* //ILUT preconditionner computed by Matlab (todo: in futur version of cuda replace it by a new equivalent cuda function) - const char *field_names[] = {"type", "droptol", "milu", "udiag", "thresh"}; - const int type = 0; - const int droptol = 1; - const int milu = 2; - const int udiag = 3; - const int thresh = 4; - mwSize dims[1] = {(mwSize)1 }; - mxArray *Setup = mxCreateStructArray(1, dims, 5, field_names); - mxSetFieldByNumber(Setup, 0, type, mxCreateString("ilutp")); - mxSetFieldByNumber(Setup, 0, droptol, mxCreateDoubleScalar(lu_inc_tol)); - mxSetFieldByNumber(Setup, 0, milu, mxCreateString("off")); - mxSetFieldByNumber(Setup, 0, udiag, mxCreateDoubleScalar(0)); - mxSetFieldByNumber(Setup, 0, thresh, mxCreateDoubleScalar(0)); - mxArray *lhs0[2], *rhs0[2]; - rhs0[0] = A_m; - rhs0[1] = Setup; - mexCallMATLAB(1, lhs0, 2, rhs0, "ilu"); -*/ + /* //ILUT preconditionner computed by Matlab (todo: in futur version of cuda replace it by a new equivalent cuda function) + const char *field_names[] = {"type", "droptol", "milu", "udiag", "thresh"}; + const int type = 0; + const int droptol = 1; + const int milu = 2; + const int udiag = 3; + const int thresh = 4; + mwSize dims[1] = {(mwSize)1 }; + mxArray *Setup = mxCreateStructArray(1, dims, 5, field_names); + mxSetFieldByNumber(Setup, 0, type, mxCreateString("ilutp")); + mxSetFieldByNumber(Setup, 0, droptol, mxCreateDoubleScalar(lu_inc_tol)); + mxSetFieldByNumber(Setup, 0, milu, mxCreateString("off")); + mxSetFieldByNumber(Setup, 0, udiag, mxCreateDoubleScalar(0)); + mxSetFieldByNumber(Setup, 0, thresh, mxCreateDoubleScalar(0)); + mxArray *lhs0[2], *rhs0[2]; + rhs0[0] = A_m; + rhs0[1] = Setup; + mexCallMATLAB(1, lhs0, 2, rhs0, "ilu"); + */ // To store the resultng matrix in a CSR format we have to transpose it mxArray *Wt = lhs0[0]; - mwIndex* Wtj = mxGetJc(Wt); + mwIndex *Wtj = mxGetJc(Wt); nnz = Wtj[n]; - mxArray* W; + mxArray *W; mexCallMATLAB(1, &W, 1, &Wt, "transpose"); mxDestroyArray(Wt); - double* pW = mxGetPr(W); - mwIndex* Wi = mxGetIr(W); - mwIndex* Wp = mxGetJc(W); - int *Wii = (int*)mxMalloc(nnz * sizeof(int)); - test_mxMalloc(Wii, __LINE__, __FILE__, __func__, nnz * sizeof(int)); - int *Wip = (int*)mxMalloc((n + 1) * sizeof(int)); - test_mxMalloc(Wip, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int)); + double *pW = mxGetPr(W); + mwIndex *Wi = mxGetIr(W); + mwIndex *Wp = mxGetJc(W); + int *Wii = (int *) mxMalloc(nnz * sizeof(int)); + test_mxMalloc(Wii, __LINE__, __FILE__, __func__, nnz * sizeof(int)); + int *Wip = (int *) mxMalloc((n + 1) * sizeof(int)); + test_mxMalloc(Wip, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int)); for (int i = 0; i < nnz; i++) Wii[i] = Wi[i]; for (int i = 0; i < n + 1; i++) @@ -4028,32 +4006,32 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, cudaChk(cudaFree(A_tild), "cudaFree(A_tild) has failed\n"); - cudaChk(cudaMalloc((void**)&A_tild, nnz * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate A_tild on the graphic card\n"); + cudaChk(cudaMalloc((void **) &A_tild, nnz * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate A_tild on the graphic card\n"); cudaChk(cudaMemcpy(A_tild, pW, nnz * sizeof(double), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild = pW has failed\n"); - cudaChk(cudaMalloc((void**)&A_tild_i, nnz * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Ai on the graphic card\n"); + cudaChk(cudaMalloc((void **) &A_tild_i, nnz * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Ai on the graphic card\n"); cudaChk(cudaMemcpy(A_tild_i, Wii, nnz * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_i = A_tild_i_host has failed\n"); - cudaChk(cudaMalloc((void**)&A_tild_p, (n + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate A_tild_p on the graphic card\n"); + cudaChk(cudaMalloc((void **) &A_tild_p, (n + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate A_tild_p on the graphic card\n"); cudaChk(cudaMemcpy(A_tild_p, Wip, (n + 1) * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_p = A_tild_j_host has failed\n"); /*mxFree(pW); - mxFree(Wi); - mxFree(Wj);*/ + mxFree(Wi); + mxFree(Wj);*/ mxDestroyArray(W); mxFree(Wii); mxFree(Wip); } else if (preconditioner == 3) { - mwIndex* Aowi, *Aowp; - double* A_host = (double*)mxMalloc(nnz*sizeof(double)); - test_mxMalloc(A_host, __LINE__, __FILE__, __func__, nnz*sizeof(double)); - Aowi = (mwIndex*)mxMalloc(nnz * sizeof(mwIndex)); - test_mxMalloc(Aowi, __LINE__, __FILE__, __func__, nnz * sizeof(mwIndex)); - Aowp = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex)); - test_mxMalloc(Aowp, __LINE__, __FILE__, __func__, (n + 1) * sizeof(mwIndex)); - int* Aoii = (int*)mxMalloc(nnz * sizeof(int)); - test_mxMalloc(Aoii, __LINE__, __FILE__, __func__, nnz * sizeof(int)); - int* Aoip = (int*)mxMalloc((n + 1) * sizeof(int)); - test_mxMalloc(Aoip, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int)); + mwIndex *Aowi, *Aowp; + double *A_host = (double *) mxMalloc(nnz*sizeof(double)); + test_mxMalloc(A_host, __LINE__, __FILE__, __func__, nnz*sizeof(double)); + Aowi = (mwIndex *) mxMalloc(nnz * sizeof(mwIndex)); + test_mxMalloc(Aowi, __LINE__, __FILE__, __func__, nnz * sizeof(mwIndex)); + Aowp = (mwIndex *) mxMalloc((n + 1) * sizeof(mwIndex)); + test_mxMalloc(Aowp, __LINE__, __FILE__, __func__, (n + 1) * sizeof(mwIndex)); + int *Aoii = (int *) mxMalloc(nnz * sizeof(int)); + test_mxMalloc(Aoii, __LINE__, __FILE__, __func__, nnz * sizeof(int)); + int *Aoip = (int *) mxMalloc((n + 1) * sizeof(int)); + test_mxMalloc(Aoip, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int)); cudaChk(cudaMemcpy(A_host, Ax, nnz*sizeof(double), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_host = A_tild has failed\n"); cudaChk(cudaMemcpy(Aoii, Ai, nnz*sizeof(int), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy Aii = Ai_tild has failed\n"); cudaChk(cudaMemcpy(Aoip, Ap, (n+1)*sizeof(int), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy Aip = Ap_tild has failed\n"); @@ -4063,30 +4041,30 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, Aowp[i] = Aoip[i]; mxFree(Aoii); mxFree(Aoip); - mxArray * Ao_m = mxCreateSparse(n,n,nnz,mxREAL); + mxArray *Ao_m = mxCreateSparse(n, n, nnz, mxREAL); mxSetIr(Ao_m, Aowi); mxSetJc(Ao_m, Aowp); mxSetPr(Ao_m, A_host); /*mexPrintf("A_m\n"); - mxArray *Aoo; - mexCallMATLAB(1, &Aoo, 1, &Ao_m, "transpose"); - mexCallMATLAB(0, NULL, 1, &Aoo, "disp_dense"); - mxDestroyArray(Ao_m); - mxDestroyArray(Aoo);*/ + mxArray *Aoo; + mexCallMATLAB(1, &Aoo, 1, &Ao_m, "transpose"); + mexCallMATLAB(0, NULL, 1, &Aoo, "disp_dense"); + mxDestroyArray(Ao_m); + mxDestroyArray(Aoo);*/ //Because the Jacobian matrix A is store in CSC format in matlab // we have to transpose it to get a CSR format used by CUDA - mwIndex* Awi, *Awp; - double* A_tild_host = (double*)mxMalloc(nnz_tild*sizeof(double)); - test_mxMalloc(A_tild_host, __LINE__, __FILE__, __func__, nnz_tild*sizeof(double)); - Awi = (mwIndex*)mxMalloc(nnz_tild * sizeof(mwIndex)); - test_mxMalloc(Awi, __LINE__, __FILE__, __func__, nnz_tild * sizeof(mwIndex)); - Awp = (mwIndex*)mxMalloc((Size + 1) * sizeof(mwIndex)); - test_mxMalloc(Awp, __LINE__, __FILE__, __func__, (Size + 1) * sizeof(mwIndex)); - int* Aii = (int*)mxMalloc(nnz_tild * sizeof(int)); - test_mxMalloc(Aii, __LINE__, __FILE__, __func__, nnz_tild * sizeof(int)); - int* Aip = (int*)mxMalloc((Size + 1) * sizeof(int)); - test_mxMalloc(Aip, __LINE__, __FILE__, __func__, (Size + 1) * sizeof(int)); + mwIndex *Awi, *Awp; + double *A_tild_host = (double *) mxMalloc(nnz_tild*sizeof(double)); + test_mxMalloc(A_tild_host, __LINE__, __FILE__, __func__, nnz_tild*sizeof(double)); + Awi = (mwIndex *) mxMalloc(nnz_tild * sizeof(mwIndex)); + test_mxMalloc(Awi, __LINE__, __FILE__, __func__, nnz_tild * sizeof(mwIndex)); + Awp = (mwIndex *) mxMalloc((Size + 1) * sizeof(mwIndex)); + test_mxMalloc(Awp, __LINE__, __FILE__, __func__, (Size + 1) * sizeof(mwIndex)); + int *Aii = (int *) mxMalloc(nnz_tild * sizeof(int)); + test_mxMalloc(Aii, __LINE__, __FILE__, __func__, nnz_tild * sizeof(int)); + int *Aip = (int *) mxMalloc((Size + 1) * sizeof(int)); + test_mxMalloc(Aip, __LINE__, __FILE__, __func__, (Size + 1) * sizeof(int)); cudaChk(cudaMemcpy(A_tild_host, A_tild, nnz_tild*sizeof(double), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_host = A_tild has failed\n"); cudaChk(cudaMemcpy(Aii, Ai_tild, nnz_tild*sizeof(int), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy Aii = Ai_tild has failed\n"); cudaChk(cudaMemcpy(Aip, Ap_tild, (Size+1)*sizeof(int), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy Aip = Ap_tild has failed\n"); @@ -4098,14 +4076,14 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, mexPrintf("%20.17f\n",A_tild_host[i]);*/ mxFree(Aii); mxFree(Aip); - mxArray * At_m = mxCreateSparse(Size,Size,nnz_tild,mxREAL); + mxArray *At_m = mxCreateSparse(Size, Size, nnz_tild, mxREAL); mxSetIr(At_m, Awi); mxSetJc(At_m, Awp); mxSetPr(At_m, A_tild_host); mxArray *A_m; mexCallMATLAB(1, &A_m, 1, &At_m, "transpose"); /*mexPrintf("A_tild_m\n"); - mexCallMATLAB(0, NULL, 1, &A_m, "disp_dense");*/ + mexCallMATLAB(0, NULL, 1, &A_m, "disp_dense");*/ mxDestroyArray(At_m); mxArray *P, *Q, *L, *U; mxArray *lhs0[4]; @@ -4125,33 +4103,33 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, mxDestroyArray(L0); mxDestroyArray(U0); /*L = lhs0[0]; - U = lhs0[1]; - P = lhs0[2]; - Q = lhs0[3];*/ + U = lhs0[1]; + P = lhs0[2]; + Q = lhs0[3];*/ /*mexPrintf("L\n"); - mexCallMATLAB(0, NULL, 1, &L, "disp_dense"); + mexCallMATLAB(0, NULL, 1, &L, "disp_dense"); - mexPrintf("U\n"); - mexCallMATLAB(0, NULL, 1, &U, "disp_dense"); + mexPrintf("U\n"); + mexCallMATLAB(0, NULL, 1, &U, "disp_dense"); - mexPrintf("P\n"); - mexCallMATLAB(0, NULL, 1, &P, "disp_dense"); + mexPrintf("P\n"); + mexCallMATLAB(0, NULL, 1, &P, "disp_dense"); - mexPrintf("Q\n"); - mexCallMATLAB(0, NULL, 1, &Q, "disp_dense");*/ + mexPrintf("Q\n"); + mexCallMATLAB(0, NULL, 1, &Q, "disp_dense");*/ - mwIndex* Qiw_host = mxGetIr(Q); - mwIndex* Qjw_host = mxGetJc(Q); - double* Qx_host = mxGetPr(Q); + mwIndex *Qiw_host = mxGetIr(Q); + mwIndex *Qjw_host = mxGetJc(Q); + double *Qx_host = mxGetPr(Q); Q_nnz = Qjw_host[Size]; - mexPrintf("Q_nnz=%d\n",Q_nnz); - int *Qi_host = (int*)mxMalloc(Q_nnz * periods * sizeof(int)); - test_mxMalloc(Qi_host, __LINE__, __FILE__, __func__, Q_nnz * periods * sizeof(int)); - double *Q_x_host = (double*)mxMalloc(Q_nnz * periods * sizeof(double)); - test_mxMalloc(Q_x_host, __LINE__, __FILE__, __func__, Q_nnz * periods * sizeof(double)); - int *Qj_host = (int*)mxMalloc((n + 1) * sizeof(int)); - test_mxMalloc(Qj_host, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int)); + mexPrintf("Q_nnz=%d\n", Q_nnz); + int *Qi_host = (int *) mxMalloc(Q_nnz * periods * sizeof(int)); + test_mxMalloc(Qi_host, __LINE__, __FILE__, __func__, Q_nnz * periods * sizeof(int)); + double *Q_x_host = (double *) mxMalloc(Q_nnz * periods * sizeof(double)); + test_mxMalloc(Q_x_host, __LINE__, __FILE__, __func__, Q_nnz * periods * sizeof(double)); + int *Qj_host = (int *) mxMalloc((n + 1) * sizeof(int)); + test_mxMalloc(Qj_host, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int)); for (int t = 0; t < periods; t++) { for (int i = 0; i < Q_nnz; i++) @@ -4166,55 +4144,51 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, } Qj_host[periods * Size] = periods * Q_nnz; - /*mwIndex *Qtiw_host = (mwIndex*) mxMalloc(Q_nnz * periods * sizeof(mwIndex)); - double *Qt_x_host = (double*)mxMalloc(Q_nnz * periods * sizeof(double)); - mwIndex *Qtjw_host = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex)); - mexPrintf("n = %d\n",n); - for (int i = 0; i < n + 1; i++) + double *Qt_x_host = (double*)mxMalloc(Q_nnz * periods * sizeof(double)); + mwIndex *Qtjw_host = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex)); + mexPrintf("n = %d\n",n); + for (int i = 0; i < n + 1; i++) Qtjw_host[i] = Qj_host[i]; - for (int i = 0; i < Q_nnz * periods; i++) + for (int i = 0; i < Q_nnz * periods; i++) { - Qtiw_host[i] = Qi_host[i]; - Qt_x_host[i] = Q_x_host[i]; + Qtiw_host[i] = Qi_host[i]; + Qt_x_host[i] = Q_x_host[i]; } - mxArray* Qt_m = mxCreateSparse(n,n,Q_nnz * periods,mxREAL); - mxSetIr(Qt_m, Qtiw_host); - mxSetJc(Qt_m, Qtjw_host); - mxSetPr(Qt_m, Qt_x_host); - mexPrintf("Qt_m\n"); - mexCallMATLAB(0, NULL, 1, &Qt_m, "disp_dense");*/ - + mxArray* Qt_m = mxCreateSparse(n,n,Q_nnz * periods,mxREAL); + mxSetIr(Qt_m, Qtiw_host); + mxSetJc(Qt_m, Qtjw_host); + mxSetPr(Qt_m, Qt_x_host); + mexPrintf("Qt_m\n"); + mexCallMATLAB(0, NULL, 1, &Qt_m, "disp_dense");*/ /*mexPrintf("Qtjw_host[periods * Size=%d]=%d\n", periods * Size, Qtjw_host[periods * Size]); - for (int i = 0; i < n; i++) + for (int i = 0; i < n; i++) for (int j = Qtjw_host[i]; j < Qtjw_host[i+1]; j++) - mexPrintf("(i=%d, j=%d) = %f\n", i, Qtiw_host[j], Qt_x_host[j]);*/ + mexPrintf("(i=%d, j=%d) = %f\n", i, Qtiw_host[j], Qt_x_host[j]);*/ //mxDestroyArray(Qt_m); - - cudaChk(cudaMalloc((void**)&Qx, Q_nnz * periods * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate Qx on the graphic card\n"); + cudaChk(cudaMalloc((void **) &Qx, Q_nnz * periods * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate Qx on the graphic card\n"); cudaChk(cudaMemcpy(Qx, Q_x_host, Q_nnz * periods * sizeof(double), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy Qx = Qx_host has failed\n"); - cudaChk(cudaMalloc((void**)&Qi, Q_nnz * periods * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Qi on the graphic card\n"); + cudaChk(cudaMalloc((void **) &Qi, Q_nnz * periods * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Qi on the graphic card\n"); cudaChk(cudaMemcpy(Qi, Qi_host, Q_nnz * periods * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy Qi = Qi_host has failed\n"); - cudaChk(cudaMalloc((void**)&Qj, (Size * periods + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Qj on the graphic card\n"); + cudaChk(cudaMalloc((void **) &Qj, (Size * periods + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Qj on the graphic card\n"); cudaChk(cudaMemcpy(Qj, Qj_host, (Size * periods + 1) * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy Qj = Qj_host has failed\n"); mxFree(Qi_host); mxFree(Qj_host); mxFree(Q_x_host); mxDestroyArray(Q); - - mwIndex* Piw_host = mxGetIr(P); - mwIndex* Pjw_host = mxGetJc(P); - double* Px_host = mxGetPr(P); + mwIndex *Piw_host = mxGetIr(P); + mwIndex *Pjw_host = mxGetJc(P); + double *Px_host = mxGetPr(P); P_nnz = Pjw_host[Size]; - int *Pi_host = (int*)mxMalloc(P_nnz * periods * sizeof(int)); - test_mxMalloc(Pi_host, __LINE__, __FILE__, __func__, P_nnz * periods * sizeof(int)); - double *P_x_host = (double*)mxMalloc(P_nnz * periods * sizeof(double)); - test_mxMalloc(P_x_host, __LINE__, __FILE__, __func__, P_nnz * periods * sizeof(double)); - int *Pj_host = (int*)mxMalloc((n + 1) * sizeof(int)); - test_mxMalloc(Pj_host, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int)); + int *Pi_host = (int *) mxMalloc(P_nnz * periods * sizeof(int)); + test_mxMalloc(Pi_host, __LINE__, __FILE__, __func__, P_nnz * periods * sizeof(int)); + double *P_x_host = (double *) mxMalloc(P_nnz * periods * sizeof(double)); + test_mxMalloc(P_x_host, __LINE__, __FILE__, __func__, P_nnz * periods * sizeof(double)); + int *Pj_host = (int *) mxMalloc((n + 1) * sizeof(int)); + test_mxMalloc(Pj_host, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int)); for (int t = 0; t < periods; t++) { for (int i = 0; i < P_nnz; i++) @@ -4228,29 +4202,28 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, Pj_host[periods * Size] = periods * P_nnz; /*mwIndex *Ptiw_host = (mwIndex*) mxMalloc(P_nnz * periods * sizeof(mwIndex)); - double *Pt_x_host = (double*)mxMalloc(P_nnz * periods * sizeof(double)); - mwIndex *Ptjw_host = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex)); - for (int i = 0; i < n + 1; i++) + double *Pt_x_host = (double*)mxMalloc(P_nnz * periods * sizeof(double)); + mwIndex *Ptjw_host = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex)); + for (int i = 0; i < n + 1; i++) Ptjw_host[i] = Pj_host[i]; - for (int i = 0; i < P_nnz * periods; i++) + for (int i = 0; i < P_nnz * periods; i++) { - Ptiw_host[i] = Pi_host[i]; - Pt_x_host[i] = P_x_host[i]; + Ptiw_host[i] = Pi_host[i]; + Pt_x_host[i] = P_x_host[i]; } - mxArray* Pt_m = mxCreateSparse(n,n,P_nnz * periods,mxREAL); - mxSetIr(Pt_m, Ptiw_host); - mxSetJc(Pt_m, Ptjw_host); - mxSetPr(Pt_m, Pt_x_host); - mexPrintf("Pt_m\n"); - mexCallMATLAB(0, NULL, 1, &Pt_m, "disp_dense"); - mxDestroyArray(Pt_m);*/ - + mxArray* Pt_m = mxCreateSparse(n,n,P_nnz * periods,mxREAL); + mxSetIr(Pt_m, Ptiw_host); + mxSetJc(Pt_m, Ptjw_host); + mxSetPr(Pt_m, Pt_x_host); + mexPrintf("Pt_m\n"); + mexCallMATLAB(0, NULL, 1, &Pt_m, "disp_dense"); + mxDestroyArray(Pt_m);*/ - cudaChk(cudaMalloc((void**)&Px, P_nnz * periods * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate Px on the graphic card\n"); + cudaChk(cudaMalloc((void **) &Px, P_nnz * periods * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate Px on the graphic card\n"); cudaChk(cudaMemcpy(Px, P_x_host, P_nnz * periods * sizeof(double), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy Px = Px_host has failed\n"); - cudaChk(cudaMalloc((void**)&Pi, P_nnz * periods * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Pi on the graphic card\n"); + cudaChk(cudaMalloc((void **) &Pi, P_nnz * periods * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Pi on the graphic card\n"); cudaChk(cudaMemcpy(Pi, Pi_host, P_nnz * periods * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy Pi = Pi_host has failed\n"); - cudaChk(cudaMalloc((void**)&Pj, (Size * periods + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Pj on the graphic card\n"); + cudaChk(cudaMalloc((void **) &Pj, (Size * periods + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Pj on the graphic card\n"); cudaChk(cudaMemcpy(Pj, Pj_host, (Size * periods + 1) * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy Pj = Pj_host has failed\n"); mxFree(Pi_host); mxFree(Pj_host); @@ -4258,52 +4231,52 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, mxDestroyArray(P); /*mwIndex* Piw_host = mxGetIr(P); - mwIndex* Pjw_host = mxGetJc(P); - double* Px_host = mxGetPr(P); - P_nnz = Pjw_host[Size]; - int *Pi_host = (int*)mxMalloc(P_nnz * sizeof(int)); - int *Pj_host = (int*)mxMalloc((Size + 1) * sizeof(int)); - for (int i = 0; i < P_nnz; i++) + mwIndex* Pjw_host = mxGetJc(P); + double* Px_host = mxGetPr(P); + P_nnz = Pjw_host[Size]; + int *Pi_host = (int*)mxMalloc(P_nnz * sizeof(int)); + int *Pj_host = (int*)mxMalloc((Size + 1) * sizeof(int)); + for (int i = 0; i < P_nnz; i++) Pi_host[i] = Piw_host[i]; - for (int i = 0; i < Size + 1; i++) + for (int i = 0; i < Size + 1; i++) Pj_host[i] = Pjw_host[i]; - cudaChk(cudaMalloc((void**)&Px, P_nnz * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate Px on the graphic card\n"); - cudaChk(cudaMemcpy(Px, Px_host, P_nnz * sizeof(double), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy Px = Px_host has failed\n"); - cudaChk(cudaMalloc((void**)&Pi, P_nnz * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Pi on the graphic card\n"); - cudaChk(cudaMemcpy(Pi, Pi_host, P_nnz * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy Pi = Pi_host has failed\n"); - cudaChk(cudaMalloc((void**)&Pj, (Size + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Pj on the graphic card\n"); - cudaChk(cudaMemcpy(Pj, Pj_host, (Size + 1) * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy Pj = Pj_host has failed\n"); - mxFree(Pi_host); - mxFree(Pj_host); - mxDestroyArray(P);*/ + cudaChk(cudaMalloc((void**)&Px, P_nnz * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate Px on the graphic card\n"); + cudaChk(cudaMemcpy(Px, Px_host, P_nnz * sizeof(double), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy Px = Px_host has failed\n"); + cudaChk(cudaMalloc((void**)&Pi, P_nnz * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Pi on the graphic card\n"); + cudaChk(cudaMemcpy(Pi, Pi_host, P_nnz * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy Pi = Pi_host has failed\n"); + cudaChk(cudaMalloc((void**)&Pj, (Size + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Pj on the graphic card\n"); + cudaChk(cudaMemcpy(Pj, Pj_host, (Size + 1) * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy Pj = Pj_host has failed\n"); + mxFree(Pi_host); + mxFree(Pj_host); + mxDestroyArray(P);*/ /*mexPrintf("L\n"); - mexCallMATLAB(0, NULL, 1, &L, "disp_dense"); + mexCallMATLAB(0, NULL, 1, &L, "disp_dense"); - mexPrintf("U\n"); - mexCallMATLAB(0, NULL, 1, &U, "disp_dense");*/ + mexPrintf("U\n"); + mexCallMATLAB(0, NULL, 1, &U, "disp_dense");*/ - mwIndex* Liw_host = mxGetIr(L); - mwIndex* Ljw_host = mxGetJc(L); - double* Lx_host = mxGetPr(L); + mwIndex *Liw_host = mxGetIr(L); + mwIndex *Ljw_host = mxGetJc(L); + double *Lx_host = mxGetPr(L); int L_nnz = Ljw_host[Size]; - mwIndex* Uiw_host = mxGetIr(U); - mwIndex* Ujw_host = mxGetJc(U); - double* Ux_host = mxGetPr(U); + mwIndex *Uiw_host = mxGetIr(U); + mwIndex *Ujw_host = mxGetJc(U); + double *Ux_host = mxGetPr(U); int U_nnz = Ujw_host[Size]; - double *pW = (double*)mxMalloc((L_nnz + U_nnz - Size) * periods * sizeof(double)); - test_mxMalloc(pW, __LINE__, __FILE__, __func__, (L_nnz + U_nnz - Size) * periods * sizeof(double)); - int *Wi = (int*)mxMalloc((L_nnz + U_nnz - Size) * periods * sizeof(int)); - test_mxMalloc(Wi, __LINE__, __FILE__, __func__, (L_nnz + U_nnz - Size) * periods * sizeof(int)); - int *Wj = (int*)mxMalloc((n + 1) * sizeof(int)); - test_mxMalloc(Wj, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int)); + double *pW = (double *) mxMalloc((L_nnz + U_nnz - Size) * periods * sizeof(double)); + test_mxMalloc(pW, __LINE__, __FILE__, __func__, (L_nnz + U_nnz - Size) * periods * sizeof(double)); + int *Wi = (int *) mxMalloc((L_nnz + U_nnz - Size) * periods * sizeof(int)); + test_mxMalloc(Wi, __LINE__, __FILE__, __func__, (L_nnz + U_nnz - Size) * periods * sizeof(int)); + int *Wj = (int *) mxMalloc((n + 1) * sizeof(int)); + test_mxMalloc(Wj, __LINE__, __FILE__, __func__, (n + 1) * sizeof(int)); Wj[0] = 0; W_nnz = 0; for (int t = 0; t < periods; t++) - for (int i = 0; i < Size ; i++) + for (int i = 0; i < Size; i++) { for (mwIndex l = Ujw_host[i]; l < Ujw_host[i+1]; l++) { @@ -4325,89 +4298,88 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, Wj[i + 1 + t * Size] = W_nnz; } //mexPrintf("Wj[%d] = %d, n=%d\n", periods * Size, Wj[periods * Size], n); - cudaChk(cudaMalloc((void**)&A_tild, W_nnz * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate Px on the graphic card\n"); + cudaChk(cudaMalloc((void **) &A_tild, W_nnz * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate Px on the graphic card\n"); cudaChk(cudaMemcpy(A_tild, pW, W_nnz * sizeof(double), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild = pW has failed\n"); - cudaChk(cudaMalloc((void**)&A_tild_i, W_nnz * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Pi on the graphic card\n"); + cudaChk(cudaMalloc((void **) &A_tild_i, W_nnz * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Pi on the graphic card\n"); cudaChk(cudaMemcpy(A_tild_i, Wi, W_nnz * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_i = Wi has failed\n"); - cudaChk(cudaMalloc((void**)&A_tild_p, (n + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Pj on the graphic card\n"); + cudaChk(cudaMalloc((void **) &A_tild_p, (n + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Pj on the graphic card\n"); cudaChk(cudaMemcpy(A_tild_p, Wj, (n + 1) * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_p = Wj has failed\n"); /*mwIndex *Wwi = (mwIndex*)mxMalloc(W_nnz * sizeof(mwIndex)); - mwIndex *Wwj = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex)); - for (int i = 0; i < W_nnz; i++) + mwIndex *Wwj = (mwIndex*)mxMalloc((n + 1) * sizeof(mwIndex)); + for (int i = 0; i < W_nnz; i++) Wwi[i] = Wi[i]; - for (int i = 0; i < n + 1; i++) + for (int i = 0; i < n + 1; i++) Wwj[i] = Wj[i]; - mxFree(Wi); - mxFree(Wj); - mxArray* Ao_tild = mxCreateSparse(n,n,W_nnz,mxREAL); - mxSetIr(Ao_tild, Wwi); - mxSetJc(Ao_tild, Wwj); - mxSetPr(Ao_tild, pW); - mexPrintf("Ao_tild\n"); - mexCallMATLAB(0, NULL, 1, &Ao_tild, "disp_dense"); - mxDestroyArray(Ao_tild);*/ - + mxFree(Wi); + mxFree(Wj); + mxArray* Ao_tild = mxCreateSparse(n,n,W_nnz,mxREAL); + mxSetIr(Ao_tild, Wwi); + mxSetJc(Ao_tild, Wwj); + mxSetPr(Ao_tild, pW); + mexPrintf("Ao_tild\n"); + mexCallMATLAB(0, NULL, 1, &Ao_tild, "disp_dense"); + mxDestroyArray(Ao_tild);*/ /*ostringstream tmp; - tmp << "debugging"; - mexWarnMsgTxt(tmp.str().c_str()); - return 4;*/ + tmp << "debugging"; + mexWarnMsgTxt(tmp.str().c_str()); + return 4;*/ /* Apply the permutation matrices (P and Q) to the b vector of system to solve : - b_tild = P-1 . b = P' . b */ + b_tild = P-1 . b = P' . b */ /*cudaChk(cudaMalloc((void**)&b_tild, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n"); - cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_TRANSPOSE, - n, n, nnz, &one, CUDA_descr, - Px, Pj, Pi, - b, &zeros, - b_tild), - " in Solve_Cuda_BiCGStab, b_tild = cusparseDcsrmv(P', b) has failed\n"); - - cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_TRANSPOSE, - n, n, nnz, &one, CUDA_descr, - Px, Pj, Pi, - b, &zeros, - b), - " in Solve_Cuda_BiCGStab, b = cusparseDcsrmv(P', b) has failed\n"); + cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_TRANSPOSE, + n, n, nnz, &one, CUDA_descr, + Px, Pj, Pi, + b, &zeros, + b_tild), + " in Solve_Cuda_BiCGStab, b_tild = cusparseDcsrmv(P', b) has failed\n"); + + cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_TRANSPOSE, + n, n, nnz, &one, CUDA_descr, + Px, Pj, Pi, + b, &zeros, + b), + " in Solve_Cuda_BiCGStab, b = cusparseDcsrmv(P', b) has failed\n"); */ /*mexPrintf("Wt = lu(A_m)\n"); - mexCallMATLAB(0, NULL, 1, &Wt, "disp_dense");*/ + mexCallMATLAB(0, NULL, 1, &Wt, "disp_dense");*/ /*ostringstream tmp; - tmp << "debugging"; - mexWarnMsgTxt(tmp.str().c_str()); - return 4;*/ + tmp << "debugging"; + mexWarnMsgTxt(tmp.str().c_str()); + return 4;*/ // To store the resultng matrix in a CSR format we have to transpose it /*mwIndex* Wtj = mxGetJc(Wt); - nnz = Wtj[n]; - mxArray* W; - mexCallMATLAB(1, &W, 1, &Wt, "transpose"); - mxDestroyArray(Wt); - pW = mxGetPr(W); - Wwi = mxGetIr(W); - mwIndex* Wp = mxGetJc(W); - int *Wii = (int*)mxMalloc(nnz * sizeof(int)); - int *Wip = (int*)mxMalloc((n + 1) * sizeof(int)); - for (int i = 0; i < nnz; i++) + nnz = Wtj[n]; + mxArray* W; + mexCallMATLAB(1, &W, 1, &Wt, "transpose"); + mxDestroyArray(Wt); + pW = mxGetPr(W); + Wwi = mxGetIr(W); + mwIndex* Wp = mxGetJc(W); + int *Wii = (int*)mxMalloc(nnz * sizeof(int)); + int *Wip = (int*)mxMalloc((n + 1) * sizeof(int)); + for (int i = 0; i < nnz; i++) Wii[i] = Wi[i]; - for (int i = 0; i < n + 1; i++) + for (int i = 0; i < n + 1; i++) Wip[i] = Wp[i]; - //mxFree(A_tild_host); + //mxFree(A_tild_host); - cudaChk(cudaFree(Ai_tild), " in Solve_Cuda_BiCGStab, cudaFree(Ai_tild) has failed\n"); - cudaChk(cudaFree(Ap_tild), " in Solve_Cuda_BiCGStab, cudaFree(Ap_tild) has failed\n"); - cudaChk(cudaFree(A_tild), " in Solve_Cuda_BiCGStab, cudaFree(A_tild) has failed\n"); + cudaChk(cudaFree(Ai_tild), " in Solve_Cuda_BiCGStab, cudaFree(Ai_tild) has failed\n"); + cudaChk(cudaFree(Ap_tild), " in Solve_Cuda_BiCGStab, cudaFree(Ap_tild) has failed\n"); + cudaChk(cudaFree(A_tild), " in Solve_Cuda_BiCGStab, cudaFree(A_tild) has failed\n"); - cudaChk(cudaMalloc((void**)&A_tild, nnz * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate A_tild on the graphic card\n"); - cudaChk(cudaMemcpy(A_tild, pW, nnz * sizeof(double), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild = pW has failed\n"); - cudaChk(cudaMalloc((void**)&A_tild_i, nnz * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Ai on the graphic card\n"); - cudaChk(cudaMemcpy(A_tild_i, Wii, nnz * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_i = A_tild_i_host has failed\n"); - cudaChk(cudaMalloc((void**)&A_tild_p, (n + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate A_tild_p on the graphic card\n"); - cudaChk(cudaMemcpy(A_tild_p, Wip, (n + 1) * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_p = A_tild_j_host has failed\n"); - mxDestroyArray(W); - mxFree(Wii); - mxFree(Wip);*/ + cudaChk(cudaMalloc((void**)&A_tild, nnz * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate A_tild on the graphic card\n"); + cudaChk(cudaMemcpy(A_tild, pW, nnz * sizeof(double), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild = pW has failed\n"); + cudaChk(cudaMalloc((void**)&A_tild_i, nnz * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate Ai on the graphic card\n"); + cudaChk(cudaMemcpy(A_tild_i, Wii, nnz * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_i = A_tild_i_host has failed\n"); + cudaChk(cudaMalloc((void**)&A_tild_p, (n + 1) * sizeof(int)), " in Solve_Cuda_BiCGStab, can't allocate A_tild_p on the graphic card\n"); + cudaChk(cudaMemcpy(A_tild_p, Wip, (n + 1) * sizeof(int), cudaMemcpyHostToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy A_tild_p = A_tild_j_host has failed\n"); + mxDestroyArray(W); + mxFree(Wii); + mxFree(Wip);*/ } if (preconditioner == 1 || preconditioner == 2 || preconditioner == 3) { @@ -4460,22 +4432,20 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, " in Solve_Cuda_BiCGStab, cusparseDcsrsm_analysis for infoU has failed\n"); } - cudaChk(cudaMalloc((void**)&v, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate v on the graphic card\n"); - cudaChk(cudaMalloc((void**)&p, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate p on the graphic card\n"); + cudaChk(cudaMalloc((void **) &v, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate v on the graphic card\n"); + cudaChk(cudaMalloc((void **) &p, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate p on the graphic card\n"); //cudaChk(cudaMemset(p, 0, n * sizeof(double)), " in Solve_Cuda_BiCGStab, cudaMemset p = 0 has failed\n"); - cudaChk(cudaMalloc((void**)&s, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate s on the graphic card\n"); - cudaChk(cudaMalloc((void**)&t, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate t on the graphic card\n"); - cudaChk(cudaMalloc((void**)&y_, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate y_ on the graphic card\n"); - cudaChk(cudaMalloc((void**)&z, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate z on the graphic card\n"); + cudaChk(cudaMalloc((void **) &s, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate s on the graphic card\n"); + cudaChk(cudaMalloc((void **) &t, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate t on the graphic card\n"); + cudaChk(cudaMalloc((void **) &y_, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate y_ on the graphic card\n"); + cudaChk(cudaMalloc((void **) &z, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate z on the graphic card\n"); double rho = 1.0, alpha = 1.0, omega = 1.0; - //residual = P*B*Q - L*U; //norm(Z,1) should be close to 0 - - while (iteration < 50/*max_iterations*/ && !convergence) + while (iteration < 50 /*max_iterations*/ && !convergence) { double rho_prev = rho; /**store in s previous value of r*/ @@ -4488,7 +4458,7 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, &rho), " in Solve_Cuda_BiCGStab, rho = cublasDdot(r0, r) has failed\n"); - mexPrintf("rho=%f\n",rho); + mexPrintf("rho=%f\n", rho); double beta; @@ -4503,9 +4473,9 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, /**p = r + beta * (p - omega * v)*/ // tmp_ = p - omega * v - VecAdd<<<nblocks, n_threads>>>(tmp_, p, -omega, v, n); + VecAdd<<< nblocks, n_threads>>> (tmp_, p, -omega, v, n); //p = r + beta * tmp_ - VecAdd<<<nblocks, n_threads>>>(p, r, beta, tmp_, n); + VecAdd<<< nblocks, n_threads>>> (p, r, beta, tmp_, n); } /**y_ solution of A_tild * y_ = p <=> L . U . y_ = p*/ @@ -4517,10 +4487,10 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, cudaChk(cudaMemcpy(tmp_vect_host, p, n*sizeof(double), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = p has failed\n"); /*mexPrintf("p\n"); - for (int i = 0; i < n; i++) - mexPrintf("%f\n",tmp_vect_host[i]);*/ + for (int i = 0; i < n; i++) + mexPrintf("%f\n",tmp_vect_host[i]);*/ - cudaChk(cudaMalloc((void**)&p_tild, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n"); + cudaChk(cudaMalloc((void **) &p_tild, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n"); cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, n, P_nnz * periods, &one, CUDA_descr, Px, Pj, Pi, @@ -4529,12 +4499,12 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, " in Solve_Cuda_BiCGStab, p_tild = cusparseDcsrmv(P', p) has failed\n"); /*mexPrintf("P\n"); - printM(n, Px, Pj, Pi, CUDA_descr, cusparse_handle);*/ + printM(n, Px, Pj, Pi, CUDA_descr, cusparse_handle);*/ cudaChk(cudaMemcpy(tmp_vect_host, p_tild, n*sizeof(double), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = p_tild has failed\n"); /*mexPrintf("p_tild\n"); - for (int i = 0; i < n; i++) - mexPrintf("%f\n",tmp_vect_host[i]);*/ + for (int i = 0; i < n; i++) + mexPrintf("%f\n",tmp_vect_host[i]);*/ cusparseChk(cusparseDcsrsv_solve(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, &one, @@ -4547,8 +4517,8 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, cudaChk(cudaMemcpy(tmp_vect_host, tmp_, n*sizeof(double), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = v has failed\n"); /*mexPrintf("tmp_\n"); - for (int i = 0; i < n; i++) - mexPrintf("%f\n",tmp_vect_host[i]);*/ + for (int i = 0; i < n; i++) + mexPrintf("%f\n",tmp_vect_host[i]);*/ } else cusparseChk(cusparseDcsrsv_solve(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE, @@ -4569,14 +4539,14 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, " in Solve_Cuda_BiCGStab, cusparseDcsrsv_solve for U . y_ = tmp_ has failed\n"); /*cudaChk(cudaMemcpy(tmp_vect_host, y_, n*sizeof(double), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = v has failed\n"); - mexPrintf("y_\n"); - for (int i = 0; i < n; i++) + mexPrintf("y_\n"); + for (int i = 0; i < n; i++) mexPrintf("%f\n",tmp_vect_host[i]);*/ if (preconditioner == 3) { double *y_tild; - cudaChk(cudaMalloc((void**)&y_tild, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n"); + cudaChk(cudaMalloc((void **) &y_tild, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n"); cudaChk(cudaMemcpy(y_tild, y_, n * sizeof(double), cudaMemcpyDeviceToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy y_tild = y_ has failed\n"); cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, n, Q_nnz * periods, &one, CUDA_descr, @@ -4587,8 +4557,8 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, cudaChk(cudaFree(y_tild), " in Solve_Cuda_BiCGStab, can't free y_tild\n"); } /*cudaChk(cudaMemcpy(tmp_vect_host, y_, n*sizeof(double), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = v has failed\n"); - mexPrintf("y_\n"); - for (int i = 0; i < n; i++) + mexPrintf("y_\n"); + for (int i = 0; i < n; i++) mexPrintf("%f\n",tmp_vect_host[i]);*/ /**v = A*y_*/ cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE, @@ -4599,11 +4569,9 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, " in Solve_Cuda_BiCGStab, v = cusparseDcsrmv(A, y_) has failed\n"); cudaChk(cudaMemcpy(tmp_vect_host, v, n*sizeof(double), cudaMemcpyDeviceToHost), " in Solve_Cuda_BiCGStab, cudaMemcpy tmp_vect_host = v has failed\n"); /*mexPrintf("v\n"); - for (int i = 0; i < n; i++) + for (int i = 0; i < n; i++) mexPrintf("%f\n",tmp_vect_host[i]);*/ - - /**alpha = rho / (rr0 . v) with rr0 = r0*/ cublasChk(cublasDdot(cublas_handle, n, // numerator r0, 1, @@ -4633,17 +4601,17 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, x0, 1, &tmp2), " in Solve_Cuda_BiCGStab, cublasDnrm2(y_) has failed\n"); - mexPrintf("abs(alpha)*tmp1 = %f, alpha = %f, tmp1 = %f, tmp2 = %f, eps = %f\n",abs(alpha)*tmp1 , alpha, tmp1, tmp2, eps); + mexPrintf("abs(alpha)*tmp1 = %f, alpha = %f, tmp1 = %f, tmp2 = %f, eps = %f\n", abs(alpha)*tmp1, alpha, tmp1, tmp2, eps); if (abs(alpha)*tmp1 < eps * tmp2) stagnation++; else stagnation = 0; /**x = x + alpha * y_*/ - VecInc<<<nblocks, n_threads>>>(x0, alpha, y_, n); + VecInc<<< nblocks, n_threads>>> (x0, alpha, y_, n); /**s = r_prev - alpha *v with r_prev = s*/ - VecInc<<<nblocks, n_threads>>>(s, -alpha, v, n); + VecInc<<< nblocks, n_threads>>> (s, -alpha, v, n); /**Has BiCGStab converged?*/ cublasChk(cublasDnrm2(cublas_handle, n, // numerator @@ -4695,7 +4663,7 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, if (preconditioner == 3) { double *s_tild; - cudaChk(cudaMalloc((void**)&s_tild, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n"); + cudaChk(cudaMalloc((void **) &s_tild, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate b_tild on the graphic card\n"); cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, n, P_nnz * periods, &one, CUDA_descr, Px, Pj, Pi, @@ -4732,7 +4700,7 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, if (preconditioner == 3) { double *z_tild; - cudaChk(cudaMalloc((void**)&z_tild, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate z_tild on the graphic card\n"); + cudaChk(cudaMalloc((void **) &z_tild, n * sizeof(double)), " in Solve_Cuda_BiCGStab, can't allocate z_tild on the graphic card\n"); cudaChk(cudaMemcpy(z_tild, z, n * sizeof(double), cudaMemcpyDeviceToDevice), " in Solve_Cuda_BiCGStab, cudaMemcpy z_tild = z has failed\n"); cusparseChk(cusparseDcsrmv(cusparse_handle, CUSPARSE_OPERATION_NON_TRANSPOSE, n, n, Q_nnz * periods, &one, CUDA_descr, @@ -4776,10 +4744,10 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, } /**x = x + omega * z*/ - VecInc<<<nblocks, n_threads>>>(x0, omega, z, n); + VecInc<<< nblocks, n_threads>>> (x0, omega, z, n); /**r = s - omega * t*/ - VecAdd<<<nblocks, n_threads>>>(r, s, -omega, t, n); + VecAdd<<< nblocks, n_threads>>> (r, s, -omega, t, n); /**Has BiCGStab converged?*/ cublasChk(cublasDnrm2(cublas_handle, n, // numerator @@ -4818,7 +4786,7 @@ dynSparseMatrix::Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, refinement_needed++; if (refinement_needed > max_refinement) { - Solve_CUDA_BiCGStab_Free(tmp_vect_host, p, r, v, s, t, y_, z, tmp_, Ai, Ax, Ap, x0, b, A_tild, A_tild_i, A_tild_p, /*Lx, Li, Lp, Ux, Ui, Up, device_n, */infoL, infoU, descrL, descrU, preconditioner); + Solve_CUDA_BiCGStab_Free(tmp_vect_host, p, r, v, s, t, y_, z, tmp_, Ai, Ax, Ap, x0, b, A_tild, A_tild_i, A_tild_p, /*Lx, Li, Lp, Ux, Ui, Up, device_n, */ infoL, infoU, descrL, descrU, preconditioner); ostringstream tmp; mexEvalString("diary off;"); tmp << "Error in bytecode: BiCGStab stagnated (Two consecutive iterates were the same.), in block " << block+1; @@ -4894,7 +4862,7 @@ dynSparseMatrix::Solve_Matlab_GMRES(mxArray *A_m, mxArray *b_m, int Size, double rhs[1] = b_m; rhs[2] = mxCreateDoubleScalar(Size); rhs[3] = mxCreateDoubleScalar(1e-6); - rhs[4] = mxCreateDoubleScalar((double)n); + rhs[4] = mxCreateDoubleScalar((double) n); rhs[5] = L1; rhs[6] = U1; rhs[7] = x0_m; @@ -4961,9 +4929,9 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou /* precond = 0 => Jacobi precond = 1 => Incomplet LU decomposition*/ size_t n = mxGetM(A_m); - mxArray *L1, *U1, *Diag; - L1 = NULL; - U1 = NULL; + mxArray *L1, *U1, *Diag; + L1 = NULL; + U1 = NULL; Diag = NULL; mxArray *rhs0[4]; @@ -4973,8 +4941,8 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou rhs0[0] = A_m; rhs0[1] = mxCreateDoubleScalar(0); mexCallMATLAB(1, lhs0, 2, rhs0, "spdiags"); - mxArray* tmp = lhs0[0]; - double* tmp_val = mxGetPr(tmp); + mxArray *tmp = lhs0[0]; + double *tmp_val = mxGetPr(tmp); Diag = mxCreateSparse(n, n, n, mxREAL); mwIndex *Diag_i = mxGetIr(Diag); mwIndex *Diag_j = mxGetJc(Diag); @@ -4996,7 +4964,7 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou const int milu = 2; const int udiag = 3; const int thresh = 4; - mwSize dims[1] = {(mwSize)1 }; + mwSize dims[1] = {(mwSize) 1 }; mxArray *Setup = mxCreateStructArray(1, dims, 5, field_names); mxSetFieldByNumber(Setup, 0, type, mxCreateString("ilutp")); mxSetFieldByNumber(Setup, 0, droptol, mxCreateDoubleScalar(lu_inc_tol)); @@ -5010,7 +4978,7 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou if (mexCallMATLAB(2, lhs0, 2, rhs0, "ilu")) { ostringstream tmp; - tmp << " In BiCGStab, the incomplet LU decomposition (ilu) ahs failed.\n"; + tmp << " In BiCGStab, the incomplet LU decomposition (ilu) ahs failed.\n"; throw FatalExceptionHandling(tmp.str()); } L1 = lhs0[0]; @@ -5018,14 +4986,14 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou mxDestroyArray(Setup); } double flags = 2; - mxArray *z; + mxArray *z; z = NULL; 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); double *resid = mxGetPr(res); double *b = mxGetPr(b_m); - for (int i = 0; i < (int)n; i++) + for (int i = 0; i < (int) n; i++) resid[i] = b[i] - resid[i]; mxArray *rhs[2]; mxArray *lhs[1]; @@ -5038,14 +5006,14 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou z = lhs[0]; double *phat = mxGetPr(z); double *x0 = mxGetPr(x0_m); - for (int i = 0; i < (int)n; i++) + for (int i = 0; i < (int) n; i++) phat[i] = x0[i] + phat[i]; /*Check the solution*/ res = mult_SAT_B(Sparse_transpose(A_m), z); resid = mxGetPr(res); double cum_abs = 0; - for (int i = 0; i < (int)n; i++) + for (int i = 0; i < (int) n; i++) { resid[i] = b[i] - resid[i]; cum_abs += fabs(resid[i]); @@ -5067,7 +5035,7 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou rhs[0] = A_m; rhs[1] = b_m; rhs[2] = mxCreateDoubleScalar(1e-6); - rhs[3] = mxCreateDoubleScalar((double)n); + rhs[3] = mxCreateDoubleScalar((double) n); rhs[4] = Diag; //rhs[5] = x0_m; mxArray *lhs[2]; @@ -5088,7 +5056,7 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou rhs[0] = A_m; rhs[1] = b_m; rhs[2] = mxCreateDoubleScalar(1e-6); - rhs[3] = mxCreateDoubleScalar((double)n); + rhs[3] = mxCreateDoubleScalar((double) n); rhs[4] = L1; rhs[5] = U1; rhs[6] = x0_m; @@ -5106,7 +5074,6 @@ dynSparseMatrix::Solve_Matlab_BiCGStab(mxArray *A_m, mxArray *b_m, int Size, dou } } - if (flags > 0) { ostringstream tmp; @@ -5177,8 +5144,8 @@ dynSparseMatrix::Singular_display(int block, int Size) } mxArray *lhs[3]; mexCallMATLAB(3, lhs, 1, rhs, "svd"); - mxArray* SVD_u = lhs[0]; - mxArray* SVD_s = lhs[1]; + mxArray *SVD_u = lhs[0]; + mxArray *SVD_s = lhs[1]; //mxArray* SVD_v = lhs[2]; double *SVD_ps = mxGetPr(SVD_s); double *SVD_pu = mxGetPr(SVD_u); @@ -5195,35 +5162,35 @@ dynSparseMatrix::Singular_display(int block, int Size) for (int j = 0; j < Size; j++) { double rr = SVD_pu[j + i * Size] / max_u; - if ( rr < -1e-10) + if (rr < -1e-10) { equ_list.push_back(j); if (rr != -1) - mexPrintf(" - %3.2f*Dequ_%d_dy",abs(rr),j+1); + mexPrintf(" - %3.2f*Dequ_%d_dy", abs(rr), j+1); else - mexPrintf(" - Dequ_%d_dy",j+1); + mexPrintf(" - Dequ_%d_dy", j+1); } else if (rr > 1e-10) { equ_list.push_back(j); if (j > 0) if (rr != 1) - mexPrintf(" + %3.2f*Dequ_%d_dy",rr,j+1); + mexPrintf(" + %3.2f*Dequ_%d_dy", rr, j+1); else - mexPrintf(" + Dequ_%d_dy",j+1); + mexPrintf(" + Dequ_%d_dy", j+1); else if (rr != 1) - mexPrintf(" %3.2f*Dequ_%d_dy",rr,j+1); + mexPrintf(" %3.2f*Dequ_%d_dy", rr, j+1); else - mexPrintf(" Dequ_%d_dy",j+1); + mexPrintf(" Dequ_%d_dy", j+1); } } mexPrintf(" = 0\n"); /*mexPrintf(" with:\n"); - it_code = get_begin_block(block); - for (int j=0; j < Size; j++) + it_code = get_begin_block(block); + for (int j=0; j < Size; j++) { - if (find(equ_list.begin(), equ_list.end(), j) != equ_list.end()) - mexPrintf(" equ_%d: %s\n",j, print_expression(it_code_expr, false, Size, block, steady_state, 0, 0, it_code, true).c_str()); + if (find(equ_list.begin(), equ_list.end(), j) != equ_list.end()) + mexPrintf(" equ_%d: %s\n",j, print_expression(it_code_expr, false, Size, block, steady_state, 0, 0, it_code, true).c_str()); }*/ } } @@ -5238,7 +5205,6 @@ dynSparseMatrix::Singular_display(int block, int Size) throw FatalExceptionHandling(tmp.str()); } - bool dynSparseMatrix::Solve_ByteCode_Sparse_GaussianElimination(int Size, int blck, int it_) { @@ -5539,21 +5505,21 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo for (int t = 0; t < periods; t++) { /*clock_t time11 = clock(); - mexPrintf("t=%d, record = %d\n",t, record);*/ + mexPrintf("t=%d, record = %d\n",t, record);*/ #ifdef MATLAB_MEX_FILE - if ( utIsInterruptPending() ) - throw UserExceptionHandling(); + if (utIsInterruptPending()) + throw UserExceptionHandling(); #endif if (record && symbolic) { /*if (save_op) { - mxFree(save_op); - save_op = NULL; + mxFree(save_op); + save_op = NULL; }*/ save_op = (int *) mxMalloc(nop*sizeof(int)); - test_mxMalloc(save_op, __LINE__, __FILE__, __func__, nop*sizeof(int)); + test_mxMalloc(save_op, __LINE__, __FILE__, __func__, nop*sizeof(int)); nopa = nop; } nop = 0; @@ -5747,7 +5713,7 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo bc[nb_eq_todo++] = first; first = first->NZE_C_N; } -//#pragma omp parallel for num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) shared(nb_var_piva, first_piva, nopa, save_op) reduction(+:nop) + //#pragma omp parallel for num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) shared(nb_var_piva, first_piva, nopa, save_op) reduction(+:nop) for (int j = 0; j < nb_eq_todo; j++) { t_save_op_s *save_op_s_l; @@ -5774,7 +5740,7 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo int sub_c_index = first_sub->c_index; int piv_c_index = first_piv->c_index; int tmp_lag = first_sub->lag_index; - while (l_sub < (nb_var_sub/*=NRow(row)*/) || l_piv < nb_var_piv) + while (l_sub < (nb_var_sub /*=NRow(row)*/) || l_piv < nb_var_piv) { if (l_sub < nb_var_sub && (sub_c_index < piv_c_index || l_piv >= nb_var_piv)) { @@ -5792,9 +5758,9 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo tmp_u_count = Get_u(); lag = first_piv->c_index/Size-row/Size; //#pragma omp critical - { - Insert(row, first_piv->c_index, tmp_u_count, lag); - } + { + Insert(row, first_piv->c_index, tmp_u_count, lag); + } u[tmp_u_count] = -u[first_piv->u_index]*first_elem; if (nop+2 >= nopa) { @@ -5821,9 +5787,9 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo NonZeroElem *firsta = first; NonZeroElem *first_suba = first_sub->NZE_R_N; //#pragma omp critical - { - Delete(first_sub->r_index, first_sub->c_index); - } + { + Delete(first_sub->r_index, first_sub->c_index); + } first = firsta->NZE_C_N; first_sub = first_suba; if (first_sub) @@ -5882,7 +5848,7 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo nop += 3; } } - else if(symbolic) + else if (symbolic) { nop += 2; if (piv_abs < eps) @@ -5916,7 +5882,7 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo bc[nb_eq_todo++] = first; first = first->NZE_C_N; } -//#pragma omp parallel for num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) shared(nb_var_piva, first_piva, nopa, save_op) reduction(+:nop) + //#pragma omp parallel for num_threads(atoi(getenv("DYNARE_NUM_THREADS"))) shared(nb_var_piva, first_piva, nopa, save_op) reduction(+:nop) for (int j = 0; j < nb_eq_todo; j++) { NonZeroElem *first = bc[j]; @@ -5949,9 +5915,9 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo tmp_u_count = Get_u(); lag = first_piv->c_index/Size-row/Size; //#pragma omp critical - { - Insert(row, first_piv->c_index, tmp_u_count, lag); - } + { + Insert(row, first_piv->c_index, tmp_u_count, lag); + } u[tmp_u_count] = -u[first_piv->u_index]*first_elem; nop += 3; first_piv = first_piv->NZE_R_N; @@ -5968,9 +5934,9 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo NonZeroElem *firsta = first; NonZeroElem *first_suba = first_sub->NZE_R_N; //#pragma omp critical - { - Delete(first_sub->r_index, first_sub->c_index); - } + { + Delete(first_sub->r_index, first_sub->c_index); + } first = firsta->NZE_C_N; first_sub = first_suba; if (first_sub) @@ -6011,7 +5977,7 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo } if (symbolic) { - if (t > int(periods*0.35)) + if (t > int (periods*0.35)) { symbolic = false; mxFree(save_opaa); @@ -6020,7 +5986,7 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo } else if (record && (nop == nop1)) { - if (t > int(periods*0.35)) + if (t > int (periods*0.35)) { symbolic = false; if (save_opaa) @@ -6090,8 +6056,8 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo mxFree(pivk_v); mxFree(NR); /*mexPrintf("tbreak=%d, periods=%d time required=%f\n",tbreak,periods, (1000.0*(double (clock())-double (time00)))/double (CLOCKS_PER_SEC)); - mexEvalString("drawnow;"); - time00 = clock();*/ + mexEvalString("drawnow;"); + time00 = clock();*/ nop_all += nop; if (symbolic) { @@ -6110,13 +6076,12 @@ dynSparseMatrix::Solve_ByteCode_Symbolic_Sparse_GaussianElimination(int Size, bo slowc_save = slowc; bksub(tbreak, last_period, Size, slowc_lbx); /*mexPrintf("remaining operations and bksub time required=%f\n",tbreak,periods, (1000.0*(double (clock())-double (time00)))/double (CLOCKS_PER_SEC)); - mexEvalString("drawnow;");*/ + mexEvalString("drawnow;");*/ End_GE(Size); } - void -dynSparseMatrix::Grad_f_product(int n, mxArray *b_m, double* vectr, mxArray *A_m, SuiteSparse_long *Ap, SuiteSparse_long *Ai, double* Ax, double* b_) +dynSparseMatrix::Grad_f_product(int n, mxArray *b_m, double *vectr, mxArray *A_m, SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b_) { if ((solve_algo == 5 && steady_state) || (stack_solve_algo == 5 && !steady_state)) { @@ -6191,9 +6156,9 @@ dynSparseMatrix::Check_and_Correct_Previous_Iteration(int block_num, int y_size, y[eq+it_*y_size] = ya[eq+it_*y_size] + slowc_save * direction[eq+it_*y_size]; } /*mexPrintf("reducing solwc_save = %e, it_=%d, y_size=%d, size=%d, y[%d]=%e, ya[%d]=%e,\n y[%d]=%e, ya[%d]=%e\n",slowc_save, it_, y_size, size-1, index_vara[0]+it_*y_size, y[index_vara[0]+it_*y_size], index_vara[0]+it_*y_size, ya[index_vara[0]+it_*y_size] - , index_vara[size-1]+it_*y_size, y[index_vara[size-1]+it_*y_size], index_vara[size-1]+it_*y_size, ya[index_vara[size-1]+it_*y_size]);*/ - //mexPrintf("->slowc_save=%f\n",slowc_save); - compute_complete(true, res1, res2, max_res, max_res_idx); + , index_vara[size-1]+it_*y_size, y[index_vara[size-1]+it_*y_size], index_vara[size-1]+it_*y_size, ya[index_vara[size-1]+it_*y_size]);*/ + //mexPrintf("->slowc_save=%f\n",slowc_save); + compute_complete(true, res1, res2, max_res, max_res_idx); } while (res2 > g0 && slowc_save > 1e-1) @@ -6210,7 +6175,7 @@ dynSparseMatrix::Check_and_Correct_Previous_Iteration(int block_num, int y_size, compute_complete(true, res1, res2, max_res, max_res_idx); } double ax = slowc_save-0.001, bx = slowc_save+0.001, cx = slowc_save, fa, fb, fc, xmin; - if (false/*slowc_save > 2e-1*/) + if (false /*slowc_save > 2e-1*/) if (mnbrak(&ax, &bx, &cx, &fa, &fb, &fc)) if (golden(ax, bx, cx, 1e-1, solve_tolf, &xmin)) slowc_save = xmin; @@ -6221,73 +6186,73 @@ dynSparseMatrix::Check_and_Correct_Previous_Iteration(int block_num, int y_size, if (false) { - double *p = (double*)mxMalloc(size * sizeof(double)); - test_mxMalloc(p, __LINE__, __FILE__, __func__, size * sizeof(double)); + double *p = (double *) mxMalloc(size * sizeof(double)); + test_mxMalloc(p, __LINE__, __FILE__, __func__, size * sizeof(double)); Grad_f_product(size, b_m_save, p, A_m_save, Ap_save, Ai_save, Ax_save, b_save); - double slope=0.0; + double slope = 0.0; for (int i = 1; i < size; i++) - slope += - direction[i] * p[i]; + slope += -direction[i] * p[i]; /*if (slope > 0) mexPrintf("Roundoff in lnsearch\n"); - else*/ - { - prev_slowc_save = 1; - double crit_opt = res2/2; - double max_try_iteration = 100; - double small_ = 1.0e-4; - bool try_at_cvg = false; - while ((try_at_iteration < max_try_iteration) && (!try_at_cvg) && (abs(prev_slowc_save - slowc_save) > 1e-10)) - { - crit_opt = res2 / 2; - if (slowc_save < 1e-7) - { - try_at_cvg = true; - continue; - } - else if ((crit_opt <= crit_opt_old + small_ * slowc_save * slope) && !(isnan(res1) || isinf(res1))) - { - try_at_cvg = true; - continue; - } - else if (try_at_iteration == 0) - { - prev_slowc_save = slowc_save; - //slowc_save = max(- top * slope / ( (crit_opt - crit_opt_old - slope)), bottom); - slowc_save /= 1.2; - } - else - { - double t1 = crit_opt - slope * slowc_save - crit_opt_old; - double t2 = glambda2 - slope * prev_slowc_save - crit_opt_old; - 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); - if (a == 0) - slowc_save = max(min( - slope/(2 * b) , top * slowc_save), bottom * slowc_save); - else - { - double delta = b*b - 3 * a * slope; - if (delta <= 0) - slowc_save = top * slowc_save; - else if (b <= 0) - slowc_save = max(min(-b + sqrt(delta) / (3 * a), top * slowc_save), bottom * slowc_save); - else - slowc_save = max(min(- slope / (b + sqrt(delta)), top * slowc_save), bottom * slowc_save); - } - } - if (abs(prev_slowc_save - slowc_save) < 1e-10) - slowc_save /= 1.1; - //mexPrintf("=>slowc_save=%f, prev_slowc_save=%f\n",slowc_save, prev_slowc_save); - prev_slowc_save = slowc_save; - glambda2 = crit_opt; - try_at_iteration++; - for (int i = 0; i < size; i++) - { - int eq = index_vara[i]; - y[eq+it_*y_size] = ya[eq+it_*y_size] + slowc_save * direction[eq+it_*y_size]; - } - compute_complete(true, res1, res2, max_res, max_res_idx); - } - } + else*/ + { + prev_slowc_save = 1; + double crit_opt = res2/2; + double max_try_iteration = 100; + double small_ = 1.0e-4; + bool try_at_cvg = false; + while ((try_at_iteration < max_try_iteration) && (!try_at_cvg) && (abs(prev_slowc_save - slowc_save) > 1e-10)) + { + crit_opt = res2 / 2; + if (slowc_save < 1e-7) + { + try_at_cvg = true; + continue; + } + else if ((crit_opt <= crit_opt_old + small_ * slowc_save * slope) && !(isnan(res1) || isinf(res1))) + { + try_at_cvg = true; + continue; + } + else if (try_at_iteration == 0) + { + prev_slowc_save = slowc_save; + //slowc_save = max(- top * slope / ( (crit_opt - crit_opt_old - slope)), bottom); + slowc_save /= 1.2; + } + else + { + double t1 = crit_opt - slope * slowc_save - crit_opt_old; + double t2 = glambda2 - slope * prev_slowc_save - crit_opt_old; + 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); + if (a == 0) + slowc_save = max(min(-slope/(2 * b), top * slowc_save), bottom * slowc_save); + else + { + double delta = b*b - 3 * a * slope; + if (delta <= 0) + slowc_save = top * slowc_save; + else if (b <= 0) + slowc_save = max(min(-b + sqrt(delta) / (3 * a), top * slowc_save), bottom * slowc_save); + else + slowc_save = max(min(-slope / (b + sqrt(delta)), top * slowc_save), bottom * slowc_save); + } + } + if (abs(prev_slowc_save - slowc_save) < 1e-10) + slowc_save /= 1.1; + //mexPrintf("=>slowc_save=%f, prev_slowc_save=%f\n",slowc_save, prev_slowc_save); + prev_slowc_save = slowc_save; + glambda2 = crit_opt; + try_at_iteration++; + for (int i = 0; i < size; i++) + { + int eq = index_vara[i]; + y[eq+it_*y_size] = ya[eq+it_*y_size] + slowc_save * direction[eq+it_*y_size]; + } + compute_complete(true, res1, res2, max_res, max_res_idx); + } + } mxFree(p); } //if (print_it) @@ -6320,7 +6285,6 @@ dynSparseMatrix::Simulate_One_Boundary(int block_num, int y_size, int y_kmin, in double *Ax = NULL, *b = NULL; int preconditioner = 1; - try_at_iteration = 0; Clear_u(); bool singular_system = false; @@ -6389,8 +6353,8 @@ dynSparseMatrix::Simulate_One_Boundary(int block_num, int y_size, int y_kmin, in mexPrintf("MODEL STEADY STATE: Sparse LU\n"); break; case 7: - mexPrintf(preconditioner_print_out("MODEL STEADY STATE: (method=GMRES)\n", preconditioner, true).c_str()); - //mexPrintf("MODEL STEADY STATE: (method=GMRES)\n"); + mexPrintf(preconditioner_print_out("MODEL STEADY STATE: (method=GMRES)\n", preconditioner, true).c_str()); + //mexPrintf("MODEL STEADY STATE: (method=GMRES)\n"); break; case 8: mexPrintf(preconditioner_print_out("MODEL STEADY STATE: (method=BiCGStab)\n", preconditioner, true).c_str()); @@ -6448,10 +6412,10 @@ dynSparseMatrix::Simulate_One_Boundary(int block_num, int y_size, int y_kmin, in { mxFree(Ai_save); mxFree(Ax_save); - Ai_save = (SuiteSparse_long*)mxMalloc(Ap[size] * sizeof(SuiteSparse_long)); - test_mxMalloc(Ai_save, __LINE__, __FILE__, __func__, Ap[size] * sizeof(SuiteSparse_long)); - Ax_save = (double*)mxMalloc(Ap[size] * sizeof(double)); - test_mxMalloc(Ax_save, __LINE__, __FILE__, __func__, Ap[size] * sizeof(double)); + Ai_save = (SuiteSparse_long *) mxMalloc(Ap[size] * sizeof(SuiteSparse_long)); + test_mxMalloc(Ai_save, __LINE__, __FILE__, __func__, Ap[size] * sizeof(SuiteSparse_long)); + Ax_save = (double *) mxMalloc(Ap[size] * sizeof(double)); + test_mxMalloc(Ax_save, __LINE__, __FILE__, __func__, Ap[size] * sizeof(double)); } memcpy(Ap_save, Ap, (size + 1) * sizeof(SuiteSparse_long)); memcpy(Ai_save, Ai, Ap[size] * sizeof(SuiteSparse_long)); @@ -6483,9 +6447,6 @@ dynSparseMatrix::Simulate_One_Boundary(int block_num, int y_size, int y_kmin, in return singular_system; } - - - bool dynSparseMatrix::solve_linear(const int block_num, const int y_size, const int y_kmin, const int y_kmax, const int size, const int iter) { @@ -6540,15 +6501,15 @@ dynSparseMatrix::Simulate_Newton_One_Boundary(const bool forward) iter = 0; if ((solve_algo == 6 && steady_state) || ((stack_solve_algo == 0 || stack_solve_algo == 1 || stack_solve_algo == 4) && !steady_state)) { - Ap_save = (SuiteSparse_long*)mxMalloc((size + 1) * sizeof(SuiteSparse_long)); - test_mxMalloc(Ap_save, __LINE__, __FILE__, __func__, (size + 1) * sizeof(SuiteSparse_long)); + Ap_save = (SuiteSparse_long *) mxMalloc((size + 1) * sizeof(SuiteSparse_long)); + test_mxMalloc(Ap_save, __LINE__, __FILE__, __func__, (size + 1) * sizeof(SuiteSparse_long)); Ap_save[size] = 0; - Ai_save = (SuiteSparse_long*)mxMalloc(1 * sizeof(SuiteSparse_long)); - test_mxMalloc(Ai_save, __LINE__, __FILE__, __func__, 1 * sizeof(SuiteSparse_long)); - Ax_save = (double*)mxMalloc(1 * sizeof(double)); - test_mxMalloc(Ax_save, __LINE__, __FILE__, __func__, 1 * sizeof(double)); - b_save = (double*)mxMalloc((size) * sizeof(SuiteSparse_long)); - test_mxMalloc(b_save, __LINE__, __FILE__, __func__, (size) * sizeof(SuiteSparse_long)); + Ai_save = (SuiteSparse_long *) mxMalloc(1 * sizeof(SuiteSparse_long)); + test_mxMalloc(Ai_save, __LINE__, __FILE__, __func__, 1 * sizeof(SuiteSparse_long)); + Ax_save = (double *) mxMalloc(1 * sizeof(double)); + test_mxMalloc(Ax_save, __LINE__, __FILE__, __func__, 1 * sizeof(double)); + b_save = (double *) mxMalloc((size) * sizeof(SuiteSparse_long)); + test_mxMalloc(b_save, __LINE__, __FILE__, __func__, (size) * sizeof(SuiteSparse_long)); } if (steady_state) { @@ -6600,7 +6561,7 @@ dynSparseMatrix::preconditioner_print_out(string s, int preconditioner, bool ss) { int n = s.length(); string tmp = ", preconditioner="; - switch(preconditioner) + switch (preconditioner) { case 0: if (ss) @@ -6647,7 +6608,6 @@ dynSparseMatrix::Simulate_Newton_Two_Boundaries(int blck, int y_size, int y_kmin double *Ax = NULL, *b; SuiteSparse_long *Ap = NULL, *Ai = NULL; - if (iter > 0) { if (print_it) @@ -6660,7 +6620,7 @@ dynSparseMatrix::Simulate_Newton_Two_Boundaries(int blck, int y_size, int y_kmin if (isnan(res1) || isinf(res1) || (res2 > 12*g0 && iter > 0)) { if (iter == 0 || fabs(slowc_save) < 1e-8) - { + { mexPrintf("res1 = %f, res2 = %f g0 = %f iter = %d\n", res1, res2, g0, iter); for (int j = 0; j < y_size; j++) { @@ -6872,7 +6832,7 @@ dynSparseMatrix::Simulate_Newton_Two_Boundaries(int blck, int y_size, int y_kmin mexPrintf("(** %f milliseconds **)\n", 1000.0*(double (t2) - double (t1))/double (CLOCKS_PER_SEC)); mexEvalString("drawnow;"); } - if ((!steady_state && (stack_solve_algo == 4 /*|| stack_solve_algo == 0*/))/* || steady_state*/) + if ((!steady_state && (stack_solve_algo == 4 /*|| stack_solve_algo == 0*/)) /* || steady_state*/) { clock_t t2 = clock(); double ax = -0.1, bx = 1.1, cx = 0.5, fa, fb, fc, xmin; @@ -6909,4 +6869,3 @@ dynSparseMatrix::fixe_u(double **u, int u_count_int, int max_lag_plus_max_lead_p 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 441569bb7004bc5fbd971c036d8ca578c817dea7..08785375503a98fb25b56561663233f12bfe9697 100644 --- a/mex/sources/bytecode/SparseMatrix.hh +++ b/mex/sources/bytecode/SparseMatrix.hh @@ -27,14 +27,14 @@ #include <ctime> #include "dynblas.h" #if !(defined _MSC_VER) -#include "dynumfpack.h" +# include "dynumfpack.h" #endif #ifdef CUDA -#include "cuda.h" -#include "cuda_runtime_api.h" -#include "cublas_v2.h" -#include "cusparse_v2.h" +# include "cuda.h" +# include "cuda_runtime_api.h" +# include "cublas_v2.h" +# include "cusparse_v2.h" #endif #include "Mem_Mngr.hh" @@ -42,38 +42,38 @@ //#include "Interpreter.hh" #include "Evaluate.hh" -#define cudaChk(x, y) \ - { \ - cudaError_t cuda_error = x; \ - if (cuda_error != cudaSuccess) \ - { \ - ostringstream tmp; \ - tmp << y; \ - throw FatalExceptionHandling(tmp.str()); \ - } \ - }; +#define cudaChk(x, y) \ + { \ + cudaError_t cuda_error = x; \ + if (cuda_error != cudaSuccess) \ + { \ + ostringstream tmp; \ + tmp << y; \ + throw FatalExceptionHandling(tmp.str()); \ + } \ + }; -#define cusparseChk(x, y) \ - { \ - cusparseStatus_t cusparse_status = x; \ - if (cusparse_status != CUSPARSE_STATUS_SUCCESS) \ - { \ - ostringstream tmp; \ - tmp << y; \ - throw FatalExceptionHandling(tmp.str()); \ - } \ - }; +#define cusparseChk(x, y) \ + { \ + cusparseStatus_t cusparse_status = x; \ + if (cusparse_status != CUSPARSE_STATUS_SUCCESS) \ + { \ + ostringstream tmp; \ + tmp << y; \ + throw FatalExceptionHandling(tmp.str()); \ + } \ + }; -#define cublasChk(x, y) \ - { \ - cublasStatus_t cublas_status = x; \ - if (cublas_status != CUBLAS_STATUS_SUCCESS) \ - { \ - ostringstream tmp; \ - tmp << y; \ - throw FatalExceptionHandling(tmp.str()); \ - } \ - }; +#define cublasChk(x, y) \ + { \ + cublasStatus_t cublas_status = x; \ + if (cublas_status != CUBLAS_STATUS_SUCCESS) \ + { \ + ostringstream tmp; \ + tmp << y; \ + throw FatalExceptionHandling(tmp.str()); \ + } \ + }; #define NEW_ALLOC #define MARKOVITZ @@ -99,20 +99,18 @@ const double very_big = 1e24; const int alt_symbolic_count_max = 1; const double mem_increasing_factor = 1.1; - - class dynSparseMatrix : public Evaluate { public: - #if (defined _MSC_VER) +#if (defined _MSC_VER) typedef int64_t SuiteSparse_long; - #endif +#endif dynSparseMatrix(); dynSparseMatrix(const int y_size_arg, const int y_kmin_arg, const int y_kmax_arg, const bool print_it_arg, const bool steady_state_arg, const int periods_arg, const int minimal_solving_periods_arg, const double slowc_arg #ifdef CUDA - ,const int CUDA_device_arg, cublasHandle_t cublas_handle_arg, cusparseHandle_t cusparse_handle_arg, cusparseMatDescr_t descr_arg + , const int CUDA_device_arg, cublasHandle_t cublas_handle_arg, cusparseHandle_t cusparse_handle_arg, cusparseMatDescr_t descr_arg #endif - ); + ); void Simulate_Newton_Two_Boundaries(int blck, int y_size, int y_kmin, int y_kmax, int Size, int periods, bool cvg, int minimal_solving_periods, int stack_solve_algo, unsigned int endo_name_length, char *P_endo_names, vector_table_conditional_local_type vector_table_conditional_local); void Simulate_Newton_One_Boundary(bool forward); void fixe_u(double **u, int u_count_int, int max_lag_plus_max_lead_plus_1); @@ -146,17 +144,17 @@ private: void Solve_Matlab_LU_UMFPack(mxArray *A_m, mxArray *b_m, int Size, double slowc_l, bool is_two_boundaries, int it_); void Print_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, int n); void Printfull_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b, int n); - void PrintM(int n, double* Ax, mwIndex *Ap, mwIndex *Ai); + void PrintM(int n, double *Ax, mwIndex *Ap, mwIndex *Ai); void Solve_LU_UMFPack(mxArray *A_m, mxArray *b_m, int Size, double slowc_l, bool is_two_boundaries, int it_); void Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b, int n, int Size, double slowc_l, bool is_two_boundaries, int it_, vector_table_conditional_local_type vector_table_conditional_local); void Solve_LU_UMFPack(SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b, int n, int Size, double slowc_l, bool is_two_boundaries, int it_); void End_Matlab_LU_UMFPack(); #ifdef CUDA - void Solve_CUDA_BiCGStab_Free(double* tmp_vect_host, double* p, double* r, double* v, double* s, double* t, double* y_, double* z, double* tmp_, - int* Ai, double* Ax, int* Ap, double* x0, double* b, double* A_tild, int* A_tild_i, int* A_tild_p, - cusparseSolveAnalysisInfo_t infoL, cusparseSolveAnalysisInfo_t infoU, - cusparseMatDescr_t descrL, cusparseMatDescr_t descrU, int preconditioner); + void Solve_CUDA_BiCGStab_Free(double *tmp_vect_host, double *p, double *r, double *v, double *s, double *t, double *y_, double *z, double *tmp_, + int *Ai, double *Ax, int *Ap, double *x0, double *b, double *A_tild, int *A_tild_i, int *A_tild_p, + cusparseSolveAnalysisInfo_t infoL, cusparseSolveAnalysisInfo_t infoU, + cusparseMatDescr_t descrL, cusparseMatDescr_t descrU, int preconditioner); int Solve_CUDA_BiCGStab(int *Ap, int *Ai, double *Ax, int *Ap_tild, int *Ai_tild, double *A_tild, double *b, double *x0, int n, int Size, double slowc_l, bool is_two_boundaries, int it_, int nnz, int nnz_tild, int preconditioner, int max_iterations, int block); #endif void Solve_Matlab_GMRES(mxArray *A_m, mxArray *b_m, int Size, double slowc, int block, bool is_two_boundaries, int it_, mxArray *x0_m); @@ -171,7 +169,7 @@ private: , long int *ndiv, long int *nsub #endif ); - void Grad_f_product(int n, mxArray *b_m, double* vectr, mxArray *A_m, SuiteSparse_long *Ap, SuiteSparse_long *Ai, double* Ax, double *b); + void Grad_f_product(int n, mxArray *b_m, double *vectr, mxArray *A_m, SuiteSparse_long *Ap, SuiteSparse_long *Ai, double *Ax, double *b); void Insert(const int r, const int c, const int u_index, const int lag_index); void Delete(const int r, const int c); int At_Row(int r, NonZeroElem **first); @@ -186,15 +184,15 @@ private: void Delete_u(int pos); void Clear_u(); void Print_u(); - void *Symbolic, *Numeric ; + void *Symbolic, *Numeric; void CheckIt(int y_size, int y_kmin, int y_kmax, int Size, int periods); void Check_the_Solution(int periods, int y_kmin, int y_kmax, int Size, double *u, int *pivot, int *b); int complete(int beg_t, int Size, int periods, int *b); void bksub(int tbreak, int last_period, int Size, double slowc_l #ifdef PROFILER - , long int *nmul + , long int *nmul #endif - ); + ); void 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); @@ -245,7 +243,7 @@ protected: int u_count_alloc, u_count_alloc_save; vector<double *> jac; double *jcb; - double slowc_save, prev_slowc_save, markowitz_c; + double slowc_save, prev_slowc_save, markowitz_c; int y_decal; int *index_equa; int u_count, tbreak_g; @@ -254,7 +252,7 @@ protected: int restart; double g_lambda1, g_lambda2, gp_0; double lu_inc_tol; -//private: + //private: SuiteSparse_long *Ap_save, *Ai_save; double *Ax_save, *b_save; mxArray *A_m_save, *b_m_save; diff --git a/mex/sources/bytecode/bytecode.cc b/mex/sources/bytecode/bytecode.cc index 8ec42982d6c1a78fc67b038182d6aa4ad55346f8..80ba1b4509344876c93df587e0257029d5a89b6a 100644 --- a/mex/sources/bytecode/bytecode.cc +++ b/mex/sources/bytecode/bytecode.cc @@ -22,46 +22,42 @@ #include <ctime> #include <math.h> #ifdef DYN_MEX_FUNC_ERR_MSG_TXT - #undef DYN_MEX_FUNC_ERR_MSG_TXT +# undef DYN_MEX_FUNC_ERR_MSG_TXT #endif // DYN_MEX_FUNC_ERR_MSG_TXT -#define DYN_MEX_FUNC_ERR_MSG_TXT(str) \ - do { \ - mexPrintf("%s\n", str); \ - if (nlhs > 0) \ - { \ - plhs[0] = mxCreateDoubleScalar(1); \ - if (nlhs > 1) \ - { \ - double *pind; \ - plhs[1] = mxCreateDoubleMatrix(int(row_y), int(col_y), mxREAL); \ - pind = mxGetPr(plhs[1]); \ - if (evaluate ) \ - { \ - for (unsigned int i = 0; i < row_y*col_y; i++) \ - pind[i] = 0; \ - } \ - else \ - { \ - for (unsigned int i = 0; i < row_y*col_y; i++) \ - pind[i] = yd[i]; \ - } \ - for (int i = 2; i < nlhs; i++) \ - plhs[i] = mxCreateDoubleScalar(1); \ - } \ - } \ - return; \ +#define DYN_MEX_FUNC_ERR_MSG_TXT(str) \ + do { \ + mexPrintf("%s\n", str); \ + if (nlhs > 0) \ + { \ + plhs[0] = mxCreateDoubleScalar(1); \ + if (nlhs > 1) \ + { \ + double *pind; \ + plhs[1] = mxCreateDoubleMatrix(int (row_y), int (col_y), mxREAL); \ + pind = mxGetPr(plhs[1]); \ + if (evaluate) \ + { \ + for (unsigned int i = 0; i < row_y*col_y; i++) \ + pind[i] = 0; \ + } \ + else \ + { \ + for (unsigned int i = 0; i < row_y*col_y; i++) \ + pind[i] = yd[i]; \ + } \ + for (int i = 2; i < nlhs; i++) \ + plhs[i] = mxCreateDoubleScalar(1); \ + } \ + } \ + return; \ } while (0) - #ifdef DEBUG_EX using namespace std; # include <sstream> - - - string Get_Argument(const char *argv) { @@ -73,7 +69,6 @@ Get_Argument(const char *argv) void (*prev_fn)(int); - string Get_Argument(const mxArray *prhs) { @@ -90,11 +85,9 @@ Get_Argument(const mxArray *prhs) } #endif - //#include <windows.h> #include <stdio.h> - #ifdef CUDA int GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_handle, cusparseMatDescr_t *descr) @@ -103,7 +96,7 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand int device_count, device, version, version_max = 0; cublasStatus_t cublas_status; cudaError_t cuda_error; - *descr=0; + *descr = 0; /* ask cuda how many devices it can find */ cudaGetDeviceCount(&device_count); @@ -124,9 +117,9 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand cuda_error = cudaGetDeviceProperties(&deviceProp, i); if (cuda_error != cudaSuccess) { - ostringstream tmp; - tmp << " bytecode cudaGetDeviceProperties failed\n"; - throw FatalExceptionHandling(tmp.str()); + ostringstream tmp; + tmp << " bytecode cudaGetDeviceProperties failed\n"; + throw FatalExceptionHandling(tmp.str()); } mexPrintf("> GPU device %d: \"%s\" has:\n - %d Multi-Processors,\n - %d threads per multiprocessor,\n", i, deviceProp.name, deviceProp.multiProcessorCount, deviceProp.maxThreadsPerMultiProcessor); mexEvalString("drawnow;"); @@ -136,7 +129,7 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand device = i; version_max = version; } - mexPrintf(" - %4.2fMhz clock rate,\n - %2.0fMb of memory,\n - %d.%d compute capabilities.\n", double(deviceProp.clockRate) / (1024 * 1024), double(deviceProp.totalGlobalMem) / (1024 * 1024), deviceProp.major, deviceProp.minor); + mexPrintf(" - %4.2fMhz clock rate,\n - %2.0fMb of memory,\n - %d.%d compute capabilities.\n", double (deviceProp.clockRate) / (1024 * 1024), double (deviceProp.totalGlobalMem) / (1024 * 1024), deviceProp.major, deviceProp.minor); mexEvalString("drawnow;"); } } @@ -146,17 +139,17 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand cuda_error = cudaSetDevice(device); if (cuda_error != cudaSuccess) { - ostringstream tmp; - tmp << " bytecode cudaSetDevice failed\n"; - throw FatalExceptionHandling(tmp.str()); + ostringstream tmp; + tmp << " bytecode cudaSetDevice failed\n"; + throw FatalExceptionHandling(tmp.str()); } - if(version_max < 0x11) + if (version_max < 0x11) { - ostringstream tmp; - tmp << " bytecode requires a minimum CUDA compute 1.1 capability\n"; - cudaDeviceReset(); - throw FatalExceptionHandling(tmp.str()); + ostringstream tmp; + tmp << " bytecode requires a minimum CUDA compute 1.1 capability\n"; + cudaDeviceReset(); + throw FatalExceptionHandling(tmp.str()); } // Initialize CuBlas library @@ -164,16 +157,16 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand if (cublas_status != CUBLAS_STATUS_SUCCESS) { ostringstream tmp; - switch(cublas_status) + switch (cublas_status) { - case CUBLAS_STATUS_NOT_INITIALIZED: - tmp << " the CUBLAS initialization failed.\n"; - break; - case CUBLAS_STATUS_ALLOC_FAILED: - tmp << " the resources could not be allocated.\n"; - break; - default: - tmp << " unknown error during the initialization of cusparse library.\n"; + case CUBLAS_STATUS_NOT_INITIALIZED: + tmp << " the CUBLAS initialization failed.\n"; + break; + case CUBLAS_STATUS_ALLOC_FAILED: + tmp << " the resources could not be allocated.\n"; + break; + default: + tmp << " unknown error during the initialization of cusparse library.\n"; } throw FatalExceptionHandling(tmp.str()); } @@ -184,19 +177,19 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand if (cusparse_status != CUSPARSE_STATUS_SUCCESS) { ostringstream tmp; - switch(cusparse_status) + switch (cusparse_status) { - case CUSPARSE_STATUS_NOT_INITIALIZED: - tmp << " the CUDA Runtime initialization failed.\n"; - break; - case CUSPARSE_STATUS_ALLOC_FAILED: - tmp << " the resources could not be allocated.\n"; - break; - case CUSPARSE_STATUS_ARCH_MISMATCH: - tmp << " the device compute capability (CC) is less than 1.1. The CC of at least 1.1 is required.\n"; - break; - default: - tmp << " unknown error during the initialization of cusparse library.\n"; + case CUSPARSE_STATUS_NOT_INITIALIZED: + tmp << " the CUDA Runtime initialization failed.\n"; + break; + case CUSPARSE_STATUS_ALLOC_FAILED: + tmp << " the resources could not be allocated.\n"; + break; + case CUSPARSE_STATUS_ARCH_MISMATCH: + tmp << " the device compute capability (CC) is less than 1.1. The CC of at least 1.1 is required.\n"; + break; + default: + tmp << " unknown error during the initialization of cusparse library.\n"; } throw FatalExceptionHandling(tmp.str()); } @@ -221,7 +214,7 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand tmp << " cudaGetVersion has failed\n"; throw FatalExceptionHandling(tmp.str()); } - mexPrintf(" - CUDA version %5.3f\n", double(cuda_version) / 1000); + mexPrintf(" - CUDA version %5.3f\n", double (cuda_version) / 1000); int cublas_version; cublas_status = cublasGetVersion(*cublas_handle, &cublas_version); if (cublas_status != CUBLAS_STATUS_SUCCESS) @@ -230,7 +223,7 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand tmp << " cublasGetVersion has failed\n"; throw FatalExceptionHandling(tmp.str()); } - mexPrintf(" - CUBLAS version %5.3f\n", double(cublas_version) / 1000); + mexPrintf(" - CUBLAS version %5.3f\n", double (cublas_version) / 1000); int cusparse_version; cusparse_status = cusparseGetVersion(*cusparse_handle, &cusparse_version); if (cusparse_status != CUSPARSE_STATUS_SUCCESS) @@ -239,7 +232,7 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand tmp << " cusparseGetVersion has failed\n"; throw FatalExceptionHandling(tmp.str()); } - mexPrintf(" - CUSPARSE version %5.3f\n", double(cusparse_version) / 1000); + mexPrintf(" - CUSPARSE version %5.3f\n", double (cusparse_version) / 1000); mexPrintf("-----------------------------------------\n"); return device; } @@ -247,16 +240,16 @@ GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_hand void GPU_close(cublasHandle_t cublas_handle, cusparseHandle_t cusparse_handle, cusparseMatDescr_t descr) { - cublasChk(cublasDestroy(cublas_handle),"in bytecode cublasDestroy failed\n"); + cublasChk(cublasDestroy(cublas_handle), "in bytecode cublasDestroy failed\n"); cusparseChk(cusparseDestroyMatDescr(descr), "in bytecode cusparseDestroyMatDescr failed\n"); - cusparseChk(cusparseDestroy(cusparse_handle),"in bytecode cusparseDestroy failed\n"); + cusparseChk(cusparseDestroy(cusparse_handle), "in bytecode cusparseDestroy failed\n"); } #endif string deblank(string x) { - for(int i = 0; i < (int) x.length(); i++) + for (int i = 0; i < (int) x.length(); i++) if (x[i] == ' ') x.erase(i--, 1); return x; @@ -317,7 +310,7 @@ Get_Arguments_and_global_variables(int nrhs, steady_col_y = mxGetN(prhs[i]); break; case 4: - periods = int(mxGetScalar(prhs[i])); + periods = int (mxGetScalar(prhs[i])); break; case 5: *block_structur = mxDuplicateArray(prhs[i]); @@ -327,7 +320,7 @@ Get_Arguments_and_global_variables(int nrhs, *GlobalTemporaryTerms = mxDuplicateArray(prhs[i]); break; default: - mexPrintf("Unknown argument count_array_argument=%d\n",count_array_argument); + mexPrintf("Unknown argument count_array_argument=%d\n", count_array_argument); break; } count_array_argument++; @@ -358,7 +351,7 @@ Get_Arguments_and_global_variables(int nrhs, pos += 5; block = atoi(Get_Argument(prhs[i]).substr(pos, string::npos).c_str())-1; } - else if (Get_Argument(prhs[i]).substr(0,13) == "extended_path") + else if (Get_Argument(prhs[i]).substr(0, 13) == "extended_path") { *extended_path = true; if ((i+1) >= nrhs) @@ -430,7 +423,6 @@ Get_Arguments_and_global_variables(int nrhs, } } - #ifdef DEBUG_EX int main(int nrhs, const char *prhs[]) @@ -449,7 +441,7 @@ main(int nrhs, const char *prhs[]) char *plhs[1]; load_global((char *) prhs[1]); #endif - mxArray *pfplan_struct = NULL; + mxArray *pfplan_struct = NULL; ErrorMsg error_msg; size_t i, row_y = 0, col_y = 0, row_x = 0, col_x = 0, nb_row_xd = 0; size_t steady_row_y, steady_col_y; @@ -467,7 +459,7 @@ main(int nrhs, const char *prhs[]) double *steady_yd = NULL, *steady_xd = NULL; string plan, pfplan; bool extended_path; - mxArray* extended_path_struct; + mxArray *extended_path_struct; table_conditional_local_type conditional_local; vector<s_plan> splan, spfplan, sextended_path, sconditional_extended_path; @@ -520,76 +512,76 @@ main(int nrhs, const char *prhs[]) string tmp = "The 'extended_path' option must be followed by the extended_path descriptor"; DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } - mxArray* date_str = mxGetField(extended_path_struct, 0, "date_str"); + mxArray *date_str = mxGetField(extended_path_struct, 0, "date_str"); if (date_str == NULL) { string tmp = "date_str"; - tmp.insert(0,"The extended_path description structure does not contain the member: "); + tmp.insert(0, "The extended_path description structure does not contain the member: "); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } int nb_periods = mxGetM(date_str) * mxGetN(date_str); - mxArray* constrained_vars_ = mxGetField(extended_path_struct, 0, "constrained_vars_"); + mxArray *constrained_vars_ = mxGetField(extended_path_struct, 0, "constrained_vars_"); if (constrained_vars_ == NULL) { string tmp = "constrained_vars_"; - tmp.insert(0,"The extended_path description structure does not contain the member: "); + tmp.insert(0, "The extended_path description structure does not contain the member: "); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } - mxArray* constrained_paths_ = mxGetField(extended_path_struct, 0, "constrained_paths_"); + mxArray *constrained_paths_ = mxGetField(extended_path_struct, 0, "constrained_paths_"); if (constrained_paths_ == NULL) { string tmp = "constrained_paths_"; - tmp.insert(0,"The extended_path description structure does not contain the member: "); + tmp.insert(0, "The extended_path description structure does not contain the member: "); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } - mxArray* constrained_int_date_ = mxGetField(extended_path_struct, 0, "constrained_int_date_"); + mxArray *constrained_int_date_ = mxGetField(extended_path_struct, 0, "constrained_int_date_"); if (constrained_int_date_ == NULL) { string tmp = "constrained_int_date_"; - tmp.insert(0,"The extended_path description structure does not contain the member: "); + tmp.insert(0, "The extended_path description structure does not contain the member: "); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } - mxArray* constrained_perfect_foresight_ = mxGetField(extended_path_struct, 0, "constrained_perfect_foresight_"); + mxArray *constrained_perfect_foresight_ = mxGetField(extended_path_struct, 0, "constrained_perfect_foresight_"); if (constrained_perfect_foresight_ == NULL) { string tmp = "constrained_perfect_foresight_"; - tmp.insert(0,"The extended_path description structure does not contain the member: "); + tmp.insert(0, "The extended_path description structure does not contain the member: "); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } - mxArray* shock_var_ = mxGetField(extended_path_struct, 0, "shock_vars_"); + mxArray *shock_var_ = mxGetField(extended_path_struct, 0, "shock_vars_"); if (shock_var_ == NULL) { string tmp = "shock_vars_"; - tmp.insert(0,"The extended_path description structure does not contain the member: "); + tmp.insert(0, "The extended_path description structure does not contain the member: "); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } - mxArray* shock_paths_ = mxGetField(extended_path_struct, 0, "shock_paths_"); + mxArray *shock_paths_ = mxGetField(extended_path_struct, 0, "shock_paths_"); if (shock_paths_ == NULL) { string tmp = "shock_paths_"; - tmp.insert(0,"The extended_path description structure does not contain the member: "); + tmp.insert(0, "The extended_path description structure does not contain the member: "); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } - mxArray* shock_int_date_ = mxGetField(extended_path_struct, 0, "shock_int_date_"); + mxArray *shock_int_date_ = mxGetField(extended_path_struct, 0, "shock_int_date_"); if (shock_int_date_ == NULL) { string tmp = "shock_int_date_"; - tmp.insert(0,"The extended_path description structure does not contain the member: "); + tmp.insert(0, "The extended_path description structure does not contain the member: "); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } - mxArray* shock_str_date_ = mxGetField(extended_path_struct, 0, "shock_str_date_"); + mxArray *shock_str_date_ = mxGetField(extended_path_struct, 0, "shock_str_date_"); if (shock_str_date_ == NULL) { string tmp = "shock_str_date_"; - tmp.insert(0,"The extended_path description structure does not contain the member: "); + tmp.insert(0, "The extended_path description structure does not contain the member: "); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } int nb_constrained = mxGetM(constrained_vars_) * mxGetN(constrained_vars_); int nb_controlled = 0; - mxArray* options_cond_fcst_ = mxGetField(extended_path_struct, 0, "options_cond_fcst_"); - mxArray* controlled_varexo = NULL; + mxArray *options_cond_fcst_ = mxGetField(extended_path_struct, 0, "options_cond_fcst_"); + mxArray *controlled_varexo = NULL; if (options_cond_fcst_ != NULL) { controlled_varexo = mxGetField(options_cond_fcst_, 0, "controlled_varexo"); @@ -599,13 +591,13 @@ main(int nrhs, const char *prhs[]) DYN_MEX_FUNC_ERR_MSG_TXT("The number of exogenized variables and the number of exogenous controlled variables should be equal."); } } - double * controlled_varexo_value = NULL; + double *controlled_varexo_value = NULL; if (controlled_varexo != NULL) controlled_varexo_value = mxGetPr(controlled_varexo); - double * constrained_var_value = mxGetPr(constrained_vars_); + double *constrained_var_value = mxGetPr(constrained_vars_); sconditional_extended_path.resize(nb_constrained); max_periods = 0; - if ( nb_constrained) + if (nb_constrained) { conditional_local.is_cond = false; conditional_local.var_exo = 0; @@ -628,18 +620,18 @@ main(int nrhs, const char *prhs[]) { sconditional_extended_path[i].exo_num = ceil(constrained_var_value[i]); sconditional_extended_path[i].var_num = ceil(controlled_varexo_value[i]); - mxArray* Array_constrained_paths_ = mxGetCell(constrained_paths_, i); + mxArray *Array_constrained_paths_ = mxGetCell(constrained_paths_, i); double *specific_constrained_paths_ = mxGetPr(Array_constrained_paths_); double *specific_constrained_int_date_ = mxGetPr(mxGetCell(constrained_int_date_, i)); int nb_local_periods = mxGetM(Array_constrained_paths_) * mxGetN(Array_constrained_paths_); - int* constrained_int_date = (int*)mxMalloc(nb_local_periods * sizeof(int)); - error_msg.test_mxMalloc(constrained_int_date, __LINE__, __FILE__, __func__, nb_local_periods * sizeof(int)); + int *constrained_int_date = (int *) mxMalloc(nb_local_periods * sizeof(int)); + error_msg.test_mxMalloc(constrained_int_date, __LINE__, __FILE__, __func__, nb_local_periods * sizeof(int)); if (nb_periods < nb_local_periods) { ostringstream oss; oss << nb_periods; string tmp = oss.str(); - tmp.insert(0,"The total number of simulation periods ("); + tmp.insert(0, "The total number of simulation periods ("); tmp.append(") is lesser than the number of periods in the shock definitions ("); oss << nb_local_periods; string tmp1 = oss.str(); @@ -653,27 +645,27 @@ main(int nrhs, const char *prhs[]) sconditional_extended_path[i].value[j] = 0; for (int j = 0; j < nb_local_periods; j++) { - constrained_int_date[j] = int(specific_constrained_int_date_[j]) - 1; + constrained_int_date[j] = int (specific_constrained_int_date_[j]) - 1; conditional_local.is_cond = true; conditional_local.var_exo = sconditional_extended_path[i].var_num - 1; conditional_local.var_endo = sconditional_extended_path[i].exo_num - 1; conditional_local.constrained_value = specific_constrained_paths_[j]; table_conditional_global[constrained_int_date[j]][sconditional_extended_path[i].exo_num - 1] = conditional_local; sconditional_extended_path[i].per_value[j] = make_pair(constrained_int_date[j], specific_constrained_paths_[j]); - sconditional_extended_path[i].value[constrained_int_date[j]] = specific_constrained_paths_[j]; + sconditional_extended_path[i].value[constrained_int_date[j]] = specific_constrained_paths_[j]; if (max_periods < constrained_int_date[j] + 1) - max_periods = constrained_int_date[j] + 1; + max_periods = constrained_int_date[j] + 1; } mxFree(constrained_int_date); } vector_table_conditional_local_type vv = table_conditional_global[0]; - double * shock_var_value = mxGetPr(shock_var_); + double *shock_var_value = mxGetPr(shock_var_); int nb_shocks = mxGetM(shock_var_) * mxGetN(shock_var_); sextended_path.resize(nb_shocks); for (int i = 0; i < nb_shocks; i++) { sextended_path[i].exo_num = ceil(shock_var_value[i]); - mxArray* Array_shock_paths_ = mxGetCell(shock_paths_, i); + mxArray *Array_shock_paths_ = mxGetCell(shock_paths_, i); double *specific_shock_paths_ = mxGetPr(Array_shock_paths_); double *specific_shock_int_date_ = mxGetPr(mxGetCell(shock_int_date_, i)); int nb_local_periods = mxGetM(Array_shock_paths_) * mxGetN(Array_shock_paths_); @@ -682,7 +674,7 @@ main(int nrhs, const char *prhs[]) ostringstream oss; oss << nb_periods; string tmp = oss.str(); - tmp.insert(0,"The total number of simulation periods ("); + tmp.insert(0, "The total number of simulation periods ("); tmp.append(") is lesser than the number of periods in the shock definitions ("); oss << nb_local_periods; string tmp1 = oss.str(); @@ -696,16 +688,16 @@ main(int nrhs, const char *prhs[]) sextended_path[i].value[j] = 0; for (int j = 0; j < nb_local_periods; j++) { - sextended_path[i].per_value[j] = make_pair(int(specific_shock_int_date_[j]), specific_shock_paths_[j]); - sextended_path[i].value[int(specific_shock_int_date_[j]-1)] = specific_shock_paths_[j]; - if (max_periods < int(specific_shock_int_date_[j]) ) - max_periods = int(specific_shock_int_date_[j]); + sextended_path[i].per_value[j] = make_pair(int (specific_shock_int_date_[j]), specific_shock_paths_[j]); + sextended_path[i].value[int (specific_shock_int_date_[j]-1)] = specific_shock_paths_[j]; + if (max_periods < int (specific_shock_int_date_[j])) + max_periods = int (specific_shock_int_date_[j]); } } - for (int i=0; i < nb_periods; i++) + for (int i = 0; i < nb_periods; i++) { int buflen = mxGetNumberOfElements(mxGetCell(date_str, i)) + 1; - char* buf = (char*)mxCalloc(buflen, sizeof(char)); + char *buf = (char *) mxCalloc(buflen, sizeof(char)); int info = mxGetString(mxGetCell(date_str, i), buf, buflen); if (info) { @@ -715,14 +707,14 @@ main(int nrhs, const char *prhs[]) dates.push_back(string(buf));//string(Dates[i]); mxFree(buf); } - } - if (plan.length()>0) + } + if (plan.length() > 0) { - mxArray* plan_struct = mexGetVariable("base", plan.c_str()); + mxArray *plan_struct = mexGetVariable("base", plan.c_str()); if (plan_struct == NULL) { string tmp = plan; - tmp.insert(0,"Can't find the plan: "); + tmp.insert(0, "Can't find the plan: "); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } size_t n_plan = mxGetN(plan_struct); @@ -731,7 +723,7 @@ main(int nrhs, const char *prhs[]) { splan[i].var = ""; splan[i].exo = ""; - mxArray* tmp = mxGetField(plan_struct, i, "exo"); + mxArray *tmp = mxGetField(plan_struct, i, "exo"); if (tmp) { char name [100]; @@ -744,7 +736,7 @@ main(int nrhs, const char *prhs[]) else { string tmp = name; - tmp.insert(0,"the variable '"); + tmp.insert(0, "the variable '"); tmp.append("' defined as var in plan is not an exogenous or a deterministic exogenous\n"); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } @@ -762,7 +754,7 @@ main(int nrhs, const char *prhs[]) else { string tmp = name; - tmp.insert(0,"the variable '"); + tmp.insert(0, "the variable '"); tmp.append("' defined as exo in plan is not an endogenous variable\n"); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } @@ -772,7 +764,7 @@ main(int nrhs, const char *prhs[]) { size_t num_shocks = mxGetM(tmp); (splan[i]).per_value.resize(num_shocks); - double * per_value = mxGetPr(tmp); + double *per_value = mxGetPr(tmp); for (int j = 0; j < (int) num_shocks; j++) (splan[i]).per_value[j] = make_pair(ceil(per_value[j]), per_value[j + num_shocks]); } @@ -788,19 +780,19 @@ main(int nrhs, const char *prhs[]) mexPrintf(" plan shocks on var=%s for the following periods and with the following values:\n", it->var.c_str()); for (vector<pair<int, double> >::iterator it1 = it->per_value.begin(); it1 != it->per_value.end(); it1++) { - mexPrintf(" %3d %10.5f\n",it1->first, it1->second); + mexPrintf(" %3d %10.5f\n", it1->first, it1->second); } i++; } } - if (pfplan.length()>0) + if (pfplan.length() > 0) { pfplan_struct = mexGetVariable("base", pfplan.c_str()); if (!pfplan_struct) { string tmp = pfplan; - tmp.insert(0,"Can't find the pfplan: "); + tmp.insert(0, "Can't find the pfplan: "); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } size_t n_plan = mxGetN(pfplan_struct); @@ -809,7 +801,7 @@ main(int nrhs, const char *prhs[]) { spfplan[i].var = ""; spfplan[i].exo = ""; - mxArray* tmp = mxGetField(pfplan_struct, i, "var"); + mxArray *tmp = mxGetField(pfplan_struct, i, "var"); if (tmp) { char name [100]; @@ -822,7 +814,7 @@ main(int nrhs, const char *prhs[]) else { string tmp = name; - tmp.insert(0,"the variable '"); + tmp.insert(0, "the variable '"); tmp.append("' defined as var in pfplan is not an exogenous or a deterministic exogenous\n"); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } @@ -840,7 +832,7 @@ main(int nrhs, const char *prhs[]) else { string tmp = name; - tmp.insert(0,"the variable '"); + tmp.insert(0, "the variable '"); tmp.append("' defined as exo in pfplan is not an endogenous variable\n"); DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str()); } @@ -849,7 +841,7 @@ main(int nrhs, const char *prhs[]) if (tmp) { size_t num_shocks = mxGetM(tmp); - double * per_value = mxGetPr(tmp); + double *per_value = mxGetPr(tmp); (spfplan[i]).per_value.resize(num_shocks); for (int j = 0; j < (int) num_shocks; j++) spfplan[i].per_value[j] = make_pair(ceil(per_value[j]), per_value[j+ num_shocks]); @@ -866,14 +858,12 @@ main(int nrhs, const char *prhs[]) mexPrintf(" plan shocks on var=%s (%d) for the following periods and with the following values:\n", it->var.c_str(), it->var_num); for (vector<pair<int, double> >::iterator it1 = it->per_value.begin(); it1 != it->per_value.end(); it1++) { - mexPrintf(" %3d %10.5f\n",it1->first, it1->second); + mexPrintf(" %3d %10.5f\n", it1->first, it1->second); } i++; } } - - int field_steady_state = mxGetFieldNumber(oo_, "steady_state"); if (field_steady_state < 0) DYN_MEX_FUNC_ERR_MSG_TXT("steady_state is not a field of oo_"); @@ -893,11 +883,11 @@ main(int nrhs, const char *prhs[]) if (!count_array_argument) { - mxArray* endo_sim_arr = mxGetFieldByNumber(oo_, 0, field_endo_simul); + mxArray *endo_sim_arr = mxGetFieldByNumber(oo_, 0, field_endo_simul); yd = mxGetPr(endo_sim_arr); row_y = mxGetM(endo_sim_arr); col_y = mxGetN(endo_sim_arr); - mxArray* exo_sim_arr = mxGetFieldByNumber(oo_, 0, field_exo_simul); + mxArray *exo_sim_arr = mxGetFieldByNumber(oo_, 0, field_exo_simul); xd = mxGetPr(exo_sim_arr); row_x = mxGetM(exo_sim_arr); col_x = mxGetN(exo_sim_arr); @@ -928,9 +918,9 @@ main(int nrhs, const char *prhs[]) DYN_MEX_FUNC_ERR_MSG_TXT("options_ is not a field of options_"); } - if (!steady_yd ) + if (!steady_yd) { - mxArray* steady_state_arr = mxGetFieldByNumber(oo_, 0, field_steady_state); + mxArray *steady_state_arr = mxGetFieldByNumber(oo_, 0, field_steady_state); steady_yd = mxGetPr(steady_state_arr); steady_row_y = mxGetM(steady_state_arr); steady_col_y = mxGetN(steady_state_arr); @@ -941,12 +931,12 @@ main(int nrhs, const char *prhs[]) { if (!count_array_argument) { - mxArray* steady_state_arr = mxGetFieldByNumber(oo_, 0, field_steady_state); + mxArray *steady_state_arr = mxGetFieldByNumber(oo_, 0, field_steady_state); yd = mxGetPr(steady_state_arr); row_y = mxGetM(steady_state_arr); col_y = mxGetN(steady_state_arr); - mxArray* exo_steady_state_arr = mxGetFieldByNumber(oo_, 0, field_exo_steady_state); + mxArray *exo_steady_state_arr = mxGetFieldByNumber(oo_, 0, field_exo_steady_state); xd = mxGetPr(exo_steady_state_arr); row_x = mxGetM(exo_steady_state_arr); col_x = mxGetN(exo_steady_state_arr); @@ -956,7 +946,7 @@ main(int nrhs, const char *prhs[]) int field = mxGetFieldNumber(options_, "verbosity"); int verbose = 0; if (field >= 0) - verbose = int(*mxGetPr((mxGetFieldByNumber(options_, 0, field)))); + verbose = int (*mxGetPr((mxGetFieldByNumber(options_, 0, field)))); else DYN_MEX_FUNC_ERR_MSG_TXT("verbosity is not a field of options_"); if (verbose) @@ -976,7 +966,7 @@ main(int nrhs, const char *prhs[]) DYN_MEX_FUNC_ERR_MSG_TXT("steady is not a field of options_"); } field = mxGetFieldNumber(temporaryfield, "maxit"); - if (field<0) + if (field < 0) { if (!steady_state) DYN_MEX_FUNC_ERR_MSG_TXT("maxit is not a field of options_.simul"); @@ -1027,7 +1017,7 @@ main(int nrhs, const char *prhs[]) DYN_MEX_FUNC_ERR_MSG_TXT("dynatol is not a field of options_"); field = mxGetFieldNumber(dynatol, "f"); if (field >= 0) - solve_tolf= *mxGetPr((mxGetFieldByNumber(dynatol, 0, field))); + solve_tolf = *mxGetPr((mxGetFieldByNumber(dynatol, 0, field))); else DYN_MEX_FUNC_ERR_MSG_TXT("f is not a field of options_.dynatol"); } @@ -1040,7 +1030,7 @@ main(int nrhs, const char *prhs[]) size_t buflen = mxGetM(mxa) * mxGetN(mxa) + 1; char *fname; fname = (char *) mxCalloc(buflen+1, sizeof(char)); - size_t status = mxGetString(mxa, fname, int(buflen)); + size_t status = mxGetString(mxa, fname, int (buflen)); fname[buflen] = ' '; if (status != 0) mexWarnMsgTxt("Not enough space. Filename is truncated."); @@ -1059,7 +1049,7 @@ main(int nrhs, const char *prhs[]) #else if (stack_solve_algo == 7 && !steady_state) DYN_MEX_FUNC_ERR_MSG_TXT("bytecode has not been compiled with CUDA option. Bytecode Can't use options_.stack_solve_algo=7\n"); -#endif +#endif size_t size_of_direction = col_y*row_y*sizeof(double); double *y = (double *) mxMalloc(size_of_direction); error_msg.test_mxMalloc(y, __LINE__, __FILE__, __func__, size_of_direction); @@ -1067,8 +1057,8 @@ main(int nrhs, const char *prhs[]) error_msg.test_mxMalloc(ya, __LINE__, __FILE__, __func__, size_of_direction); direction = (double *) mxMalloc(size_of_direction); error_msg.test_mxMalloc(direction, __LINE__, __FILE__, __func__, size_of_direction); - memset(direction, 0, size_of_direction); - /*mexPrintf("col_x : %d, row_x : %d\n",col_x, row_x);*/ + memset(direction, 0, size_of_direction); + /*mexPrintf("col_x : %d, row_x : %d\n",col_x, row_x);*/ double *x = (double *) mxMalloc(col_x*row_x*sizeof(double)); error_msg.test_mxMalloc(x, __LINE__, __FILE__, __func__, col_x*row_x*sizeof(double)); for (i = 0; i < row_x*col_x; i++) @@ -1079,10 +1069,10 @@ main(int nrhs, const char *prhs[]) { y[i] = double (yd[i]); ya[i] = double (yd[i]); - } - size_t y_size = row_y; - size_t nb_row_x = row_x; - + } + size_t y_size = row_y; + size_t nb_row_x = row_x; + clock_t t0 = clock(); Interpreter interprete(params, y, ya, x, steady_yd, steady_xd, direction, y_size, nb_row_x, nb_row_xd, periods, y_kmin, y_kmax, maxit_, solve_tolf, size_of_direction, slowc, y_decal, markowitz_c, file_name, minimal_solving_periods, stack_solve_algo, solve_algo, global_temporary_terms, print, print_error, GlobalTemporaryTerms, steady_state, @@ -1096,28 +1086,28 @@ main(int nrhs, const char *prhs[]) int nb_blocks = 0; double *pind; bool no_error = true; - + if (extended_path) - { - try - { - interprete.extended_path(f, f, evaluate, block, nb_blocks, max_periods, sextended_path, sconditional_extended_path, dates, table_conditional_global); - } - catch (GeneralExceptionHandling &feh) - { - DYN_MEX_FUNC_ERR_MSG_TXT(feh.GetErrorMsg().c_str()); - } + { + try + { + interprete.extended_path(f, f, evaluate, block, nb_blocks, max_periods, sextended_path, sconditional_extended_path, dates, table_conditional_global); + } + catch (GeneralExceptionHandling &feh) + { + DYN_MEX_FUNC_ERR_MSG_TXT(feh.GetErrorMsg().c_str()); + } } else { - try - { - interprete.compute_blocks(f, f, evaluate, block, nb_blocks); - } - catch (GeneralExceptionHandling &feh) - { - DYN_MEX_FUNC_ERR_MSG_TXT(feh.GetErrorMsg().c_str()); - } + try + { + interprete.compute_blocks(f, f, evaluate, block, nb_blocks); + } + catch (GeneralExceptionHandling &feh) + { + DYN_MEX_FUNC_ERR_MSG_TXT(feh.GetErrorMsg().c_str()); + } } #ifdef CUDA @@ -1145,7 +1135,7 @@ main(int nrhs, const char *prhs[]) if (evaluate) { vector<double> residual = interprete.get_residual(); - plhs[1] = mxCreateDoubleMatrix(int(residual.size()/double(col_y)), int(col_y), mxREAL); + plhs[1] = mxCreateDoubleMatrix(int (residual.size()/double (col_y)), int (col_y), mxREAL); pind = mxGetPr(plhs[1]); for (i = 0; i < residual.size(); i++) pind[i] = residual[i]; @@ -1157,20 +1147,20 @@ main(int nrhs, const char *prhs[]) out_periods = max_periods + y_kmin; else out_periods = row_y; - plhs[1] = mxCreateDoubleMatrix(out_periods, int(col_y), mxREAL); + plhs[1] = mxCreateDoubleMatrix(out_periods, int (col_y), mxREAL); pind = mxGetPr(plhs[1]); for (i = 0; i < out_periods*col_y; i++) pind[i] = y[i]; } } else - { + { int out_periods; if (extended_path) out_periods = max_periods + y_kmin; else out_periods = col_y; - plhs[1] = mxCreateDoubleMatrix(int(row_y), out_periods, mxREAL); + plhs[1] = mxCreateDoubleMatrix(int (row_y), out_periods, mxREAL); pind = mxGetPr(plhs[1]); if (evaluate) { @@ -1180,7 +1170,7 @@ main(int nrhs, const char *prhs[]) } else for (i = 0; i < row_y*out_periods; i++) - pind[i] = y[i]; + pind[i] = y[i]; } if (nlhs > 2) { @@ -1194,7 +1184,7 @@ main(int nrhs, const char *prhs[]) jacob_exo_field_number = 1; jacob_exo_det_field_number = 2; jacob_other_endo_field_number = 3; - mwSize dims[1] = {(mwSize)nb_blocks }; + mwSize dims[1] = {(mwSize) nb_blocks }; plhs[2] = mxCreateStructArray(1, dims, 4, field_names); } else if (!mxIsStruct(block_structur)) @@ -1234,18 +1224,18 @@ main(int nrhs, const char *prhs[]) } } else - { - plhs[2] = mxCreateDoubleMatrix(int(row_x), int(col_x), mxREAL); + { + plhs[2] = mxCreateDoubleMatrix(int (row_x), int (col_x), mxREAL); pind = mxGetPr(plhs[2]); - for (i = 0; i < row_x*col_x; i++) - { - pind[i] = x[i]; + for (i = 0; i < row_x*col_x; i++) + { + pind[i] = x[i]; } - + } if (nlhs > 3) { - plhs[3] = mxCreateDoubleMatrix(int(row_y), int(col_y), mxREAL); + plhs[3] = mxCreateDoubleMatrix(int (row_y), int (col_y), mxREAL); pind = mxGetPr(plhs[3]); for (i = 0; i < row_y*col_y; i++) pind[i] = y[i]; @@ -1253,7 +1243,7 @@ main(int nrhs, const char *prhs[]) { mxArray *GlobalTemporaryTerms = interprete.get_Temporary_Terms(); size_t nb_temp_terms = mxGetM(GlobalTemporaryTerms); - plhs[4] = mxCreateDoubleMatrix(int(nb_temp_terms), 1, mxREAL); + plhs[4] = mxCreateDoubleMatrix(int (nb_temp_terms), 1, mxREAL); pind = mxGetPr(plhs[4]); double *tt = mxGetPr(GlobalTemporaryTerms); for (i = 0; i < nb_temp_terms; i++) @@ -1266,15 +1256,15 @@ main(int nrhs, const char *prhs[]) } #else Free_global(); -#endif +#endif if (x) - mxFree(x); + mxFree(x); if (y) - mxFree(y); + mxFree(y); if (ya) - mxFree(ya); + mxFree(ya); if (direction) - mxFree(direction); + mxFree(direction); #ifdef _MSC_VER_ /*fFreeResult =*/ FreeLibrary(hinstLib); #endif diff --git a/mex/sources/bytecode/testing/mex_interface.hh b/mex/sources/bytecode/testing/mex_interface.hh index 9ae11800e90cf2842261349d4cb529d30e3ddd4a..d734c8366579ea63bb958055c04f80fbf55f266a 100644 --- a/mex/sources/bytecode/testing/mex_interface.hh +++ b/mex/sources/bytecode/testing/mex_interface.hh @@ -142,7 +142,7 @@ mxCreateStructArray(unsigned int rows, mwSize *cols, int nfields, const string & 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 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); diff --git a/mex/sources/dynumfpack.h b/mex/sources/dynumfpack.h index 60182c47106453f543b98f456a07b45e709fb14b..d21ed7954748e484382fae05e6f74764cff5d91e 100644 --- a/mex/sources/dynumfpack.h +++ b/mex/sources/dynumfpack.h @@ -28,60 +28,60 @@ extern "C" { #endif -/* -------------------------------------------------------------------------- */ -/* size of Info and Control arrays */ -/* -------------------------------------------------------------------------- */ + /* -------------------------------------------------------------------------- */ + /* size of Info and Control arrays */ + /* -------------------------------------------------------------------------- */ -/* These might be larger in future versions, since there are only 3 unused - * entries in Info, and no unused entries in Control. */ + /* These might be larger in future versions, since there are only 3 unused + * entries in Info, and no unused entries in Control. */ #define UMFPACK_INFO 90 #define UMFPACK_CONTROL 20 -/* used in all UMFPACK_report_* routines: */ -#define UMFPACK_PRL 0 /* print level */ -/* returned by all routines that use Info: */ + /* used in all UMFPACK_report_* routines: */ +#define UMFPACK_PRL 0 /* print level */ + /* returned by all routines that use Info: */ #define UMFPACK_OK (0) -#define UMFPACK_STATUS 0 /* UMFPACK_OK, or other result */ +#define UMFPACK_STATUS 0 /* UMFPACK_OK, or other result */ #ifdef _WIN64 -typedef long long int SuiteSparse_long; + typedef long long int SuiteSparse_long; #else -typedef long SuiteSparse_long; + typedef long SuiteSparse_long; #endif -void umfpack_dl_defaults(double Control[UMFPACK_CONTROL]); + void umfpack_dl_defaults(double Control[UMFPACK_CONTROL]); -SuiteSparse_long umfpack_dl_symbolic(SuiteSparse_long n_row, SuiteSparse_long n_col, - const SuiteSparse_long Ap [ ], const SuiteSparse_long Ai [ ], - const double Ax [ ], void **Symbolic, - const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]); + SuiteSparse_long umfpack_dl_symbolic(SuiteSparse_long n_row, SuiteSparse_long n_col, + const SuiteSparse_long Ap [], const SuiteSparse_long Ai [], + const double Ax [], void **Symbolic, + const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]); -SuiteSparse_long umfpack_dl_numeric(const SuiteSparse_long Ap [ ], const SuiteSparse_long Ai [ ], - const double Ax [ ], void *Symbolic, void **Numeric, - const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]); + SuiteSparse_long umfpack_dl_numeric(const SuiteSparse_long Ap [], const SuiteSparse_long Ai [], + const double Ax [], void *Symbolic, void **Numeric, + const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]); -SuiteSparse_long umfpack_dl_solve(SuiteSparse_long sys, const SuiteSparse_long Ap [ ], - const SuiteSparse_long Ai [ ], const double Ax [ ], - double X [ ], const double B [ ], void *Numeric, - const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]); + SuiteSparse_long umfpack_dl_solve(SuiteSparse_long sys, const SuiteSparse_long Ap [], + const SuiteSparse_long Ai [], const double Ax [], + double X [], const double B [], void *Numeric, + const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO]); -void umfpack_dl_report_info(const double Control [UMFPACK_CONTROL], - const double Info [UMFPACK_INFO]); + void umfpack_dl_report_info(const double Control [UMFPACK_CONTROL], + const double Info [UMFPACK_INFO]); -void umfpack_dl_report_status(const double Control [UMFPACK_CONTROL], - SuiteSparse_long status); + void umfpack_dl_report_status(const double Control [UMFPACK_CONTROL], + SuiteSparse_long status); -void umfpack_dl_free_symbolic(void **Symbolic); + void umfpack_dl_free_symbolic(void **Symbolic); -void umfpack_dl_free_numeric(void **Numeric); + void umfpack_dl_free_numeric(void **Numeric); -SuiteSparse_long umfpack_dl_load_symbolic (void **Symbolic, char *filename) ; + SuiteSparse_long umfpack_dl_load_symbolic(void **Symbolic, char *filename); -SuiteSparse_long umfpack_dl_load_numeric (void **Numeric, char *filename) ; + SuiteSparse_long umfpack_dl_load_numeric(void **Numeric, char *filename); -SuiteSparse_long umfpack_dl_save_symbolic (void *Symbolic, char *filename) ; + SuiteSparse_long umfpack_dl_save_symbolic(void *Symbolic, char *filename); -SuiteSparse_long umfpack_dl_save_numeric (void *Numeric, char *filename) ; + SuiteSparse_long umfpack_dl_save_numeric(void *Numeric, char *filename); #ifdef __cplusplus } /* extern "C" */ diff --git a/mex/sources/estimation/DecisionRules.cc b/mex/sources/estimation/DecisionRules.cc index 48f5c236c13d5f15620e8c6a6f65a725c6c16d1d..d8e38960f641b9337da78deff6375f82c8680d10 100644 --- a/mex/sources/estimation/DecisionRules.cc +++ b/mex/sources/estimation/DecisionRules.cc @@ -213,4 +213,3 @@ operator<<(std::ostream &out, const DecisionRules::BlanchardKahnException &e) out << "The Blanchard Kahn rank condition is not satisfied"; return out; } - diff --git a/mex/sources/estimation/DecisionRules.hh b/mex/sources/estimation/DecisionRules.hh index 22e30bdf11967609f930fc0da3f0c60d13ca84cc..069536e8f4762e404f73e02ac393002b4939c514 100644 --- a/mex/sources/estimation/DecisionRules.hh +++ b/mex/sources/estimation/DecisionRules.hh @@ -49,7 +49,9 @@ public: //! True if the model fails the order condition. False if it fails the rank condition. const bool order; const int n_fwrd_vars, n_explosive_eigenvals; - BlanchardKahnException(bool order_arg, int n_fwrd_vars_arg, int n_explosive_eigenvals_arg) : order(order_arg), n_fwrd_vars(n_fwrd_vars_arg), n_explosive_eigenvals(n_explosive_eigenvals_arg) {}; + BlanchardKahnException(bool order_arg, int n_fwrd_vars_arg, int n_explosive_eigenvals_arg) : order(order_arg), n_fwrd_vars(n_fwrd_vars_arg), n_explosive_eigenvals(n_explosive_eigenvals_arg) + { + }; }; /*! The zetas are supposed to follow C convention (first vector index is zero). @@ -57,7 +59,9 @@ public: DecisionRules(size_t n_arg, size_t p_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 qz_criterium); - virtual ~DecisionRules(){}; + virtual ~DecisionRules() + { + }; /*! \param jacobian First columns are backetermined vars at t-1 (in the order of zeta_back_mixed), then all vars at t (in the orig order), then forward vars at t+1 (in the order of zeta_fwrd_mixed), then exogenous vars. diff --git a/mex/sources/estimation/DetrendData.cc b/mex/sources/estimation/DetrendData.cc index 6349932c9de29dcd7fdff0ec40f665d0b312020e..7a24c89e571965d938bccf527fce767e9275bfbf 100644 --- a/mex/sources/estimation/DetrendData.cc +++ b/mex/sources/estimation/DetrendData.cc @@ -44,4 +44,3 @@ DetrendData::detrend(const VectorView &SteadyState, const MatrixConstView &dataV detrendedDataView(i, j) = dataView(i, j) - SteadyState(varobs[i]); } }; - diff --git a/mex/sources/estimation/DetrendData.hh b/mex/sources/estimation/DetrendData.hh index 59cfc3d0f2174ab913d6a6907917e32ac887760f..ce4d185cc8c1c13773f77dedace6513f6e32e72e 100644 --- a/mex/sources/estimation/DetrendData.hh +++ b/mex/sources/estimation/DetrendData.hh @@ -31,7 +31,9 @@ class DetrendData { public: - virtual ~DetrendData(){}; + virtual ~DetrendData() + { + }; DetrendData(const std::vector<size_t> &varobs_arg, bool noconstant_arg); void detrend(const VectorView &SteadyState, const MatrixConstView &dataView, MatrixView &detrendedDataView); diff --git a/mex/sources/estimation/EstimatedParameter.cc b/mex/sources/estimation/EstimatedParameter.cc index bf59ae15601f2612dd21f7844266b3f49a15cdc2..a6810ceb1d9d71e5183d3dc82e5ecb1ccbb860e3 100644 --- a/mex/sources/estimation/EstimatedParameter.cc +++ b/mex/sources/estimation/EstimatedParameter.cc @@ -37,4 +37,3 @@ EstimatedParameter::EstimatedParameter(const EstimatedParameter::pType type_arg, EstimatedParameter::~EstimatedParameter() { } - diff --git a/mex/sources/estimation/EstimatedParameter.hh b/mex/sources/estimation/EstimatedParameter.hh index e323b125bbf5178590f6348da93884709c047f42..69f2e3be815293eb2dd5d749f63ac60e36f92f1d 100644 --- a/mex/sources/estimation/EstimatedParameter.hh +++ b/mex/sources/estimation/EstimatedParameter.hh @@ -33,19 +33,20 @@ struct EstimatedParameter public: // parameter types enum pType - { - shock_SD = 1, // standard deviation of a structural shock - measureErr_SD = 2, // standard deviation of a measurement error - shock_Corr = 3, // correlation betwwen two structural shocks - measureErr_Corr = 4, // correlation between two measurement errors - deepPar = 5 // deep parameter - }; + { + shock_SD = 1, // standard deviation of a structural shock + measureErr_SD = 2, // standard deviation of a measurement error + shock_Corr = 3, // correlation betwwen two structural shocks + measureErr_Corr = 4, // correlation between two measurement errors + deepPar = 5 // deep parameter + }; 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 ); - virtual ~EstimatedParameter(); + virtual + ~EstimatedParameter(); enum pType ptype; size_t ID1; diff --git a/mex/sources/estimation/EstimatedParametersDescription.hh b/mex/sources/estimation/EstimatedParametersDescription.hh index 0e4a14fac672406ae228f6660ff1d17d23466ad2..24a210d1c3d6d69e5982a0a0a8b584fa4e2f6ff6 100644 --- a/mex/sources/estimation/EstimatedParametersDescription.hh +++ b/mex/sources/estimation/EstimatedParametersDescription.hh @@ -45,7 +45,8 @@ class EstimatedParametersDescription { public: - virtual ~EstimatedParametersDescription(); + virtual + ~EstimatedParametersDescription(); EstimatedParametersDescription(std::vector<EstimationSubsample> &estSubsamples, std::vector<EstimatedParameter> &estParams); std::vector<EstimationSubsample> estSubsamples; std::vector<EstimatedParameter> estParams; diff --git a/mex/sources/estimation/EstimationSubsample.cc b/mex/sources/estimation/EstimationSubsample.cc index f8e937377e84c305c3246a89a88c7981e0767aac..51d6c556d70f1fc6a1db772cf3469c4fa849d537 100644 --- a/mex/sources/estimation/EstimationSubsample.cc +++ b/mex/sources/estimation/EstimationSubsample.cc @@ -33,4 +33,3 @@ EstimationSubsample::EstimationSubsample(size_t INstartPeriod, size_t INendPerio EstimationSubsample::~EstimationSubsample() { } - diff --git a/mex/sources/estimation/EstimationSubsample.hh b/mex/sources/estimation/EstimationSubsample.hh index 5d76e1293e5e3bd896970721106ab1c2c0914ca6..b4e6ad4595125fd150a6195d4bae1c686487f4ad 100644 --- a/mex/sources/estimation/EstimationSubsample.hh +++ b/mex/sources/estimation/EstimationSubsample.hh @@ -59,7 +59,8 @@ class EstimationSubsample { public: EstimationSubsample(size_t startPeriod, size_t endPeriod); - virtual ~EstimationSubsample(); + virtual + ~EstimationSubsample(); size_t startPeriod; size_t endPeriod; diff --git a/mex/sources/estimation/InitializeKalmanFilter.cc b/mex/sources/estimation/InitializeKalmanFilter.cc index 53ea5df6c7339cea9285fb0b08bafe8df76b6613..adbd7565d7bb4c993b58b3e80f8865a558fa18fc 100644 --- a/mex/sources/estimation/InitializeKalmanFilter.cc +++ b/mex/sources/estimation/InitializeKalmanFilter.cc @@ -74,4 +74,3 @@ InitializeKalmanFilter::setPstar(Matrix &Pstar, Matrix &Pinf, const Matrix &T, c Pinf.setAll(0.0); } - diff --git a/mex/sources/estimation/InitializeKalmanFilter.hh b/mex/sources/estimation/InitializeKalmanFilter.hh index 83e25a19fcd3f2fb940aae260df088701aab583e..7a49f7ad1c33aa2eee894d4677047279df7d74a7 100644 --- a/mex/sources/estimation/InitializeKalmanFilter.hh +++ b/mex/sources/estimation/InitializeKalmanFilter.hh @@ -49,13 +49,15 @@ public: const std::vector<size_t> &varobs_arg, double qz_criterium_arg, double lyapunov_tol_arg, bool noconstant_arg); - virtual ~InitializeKalmanFilter(); + virtual + ~InitializeKalmanFilter(); // initialise parameter dependent KF matrices only but not Ps template <class Vec1, class Vec2, class Mat1, class Mat2> - void initialize(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &R, - const Mat2 &Q, Matrix &RQRt, Matrix &T, - const MatrixConstView &dataView, - MatrixView &detrendedDataView) + void + initialize(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &R, + const Mat2 &Q, Matrix &RQRt, Matrix &T, + const MatrixConstView &dataView, + MatrixView &detrendedDataView) { modelSolution.compute(steadyState, deepParams, g_x, g_u); detrendData.detrend(steadyState, dataView, detrendedDataView); @@ -66,10 +68,11 @@ public: // initialise all KF matrices template <class Vec1, class Vec2, class Mat1, class Mat2> - void initialize(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &R, - const Mat2 &Q, Matrix &RQRt, Matrix &T, Matrix &Pstar, Matrix &Pinf, - const MatrixConstView &dataView, - MatrixView &detrendedDataView) + void + initialize(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &R, + const Mat2 &Q, Matrix &RQRt, Matrix &T, Matrix &Pstar, Matrix &Pinf, + const MatrixConstView &dataView, + MatrixView &detrendedDataView) { initialize(steadyState, deepParams, R, Q, RQRt, T, dataView, detrendedDataView); setPstar(Pstar, Pinf, T, RQRt); @@ -90,7 +93,8 @@ private: void setT(Matrix &T); template <class Mat1, class Mat2> - void setRQR(Mat1 &R, const Mat2 &Q, Matrix &RQRt) + void + setRQR(Mat1 &R, const Mat2 &Q, Matrix &RQRt) { mat::assignByVectors(R, mat::nullVec, mat::nullVec, g_u, zeta_varobs_back_mixed, mat::nullVec); diff --git a/mex/sources/estimation/KalmanFilter.cc b/mex/sources/estimation/KalmanFilter.cc index 32f121899caba3bd746056d1b281c60b8902cda4..a97a7110b040e33bedc0bea0dff88be722b45b60 100644 --- a/mex/sources/estimation/KalmanFilter.cc +++ b/mex/sources/estimation/KalmanFilter.cc @@ -74,7 +74,6 @@ KalmanFilter::compute_zeta_varobs_back_mixed(const std::vector<size_t> &zeta_bac return zeta_varobs_back_mixed; } - /** * Multi-variate standard Kalman Filter */ @@ -86,7 +85,7 @@ KalmanFilter::filter(const MatrixView &detrendedDataView, const Matrix &H, Vect bool nonstationary = true; a_init.setAll(0.0); int info; - + for (size_t t = 0; t < detrendedDataView.getCols(); ++t) { if (nonstationary) @@ -192,4 +191,3 @@ KalmanFilter::filter(const MatrixView &detrendedDataView, const Matrix &H, Vect return loglik; } - diff --git a/mex/sources/estimation/KalmanFilter.hh b/mex/sources/estimation/KalmanFilter.hh index 25a4699faf3db72a8e8e11cca04afd25fc4703ad..f199ec87bb25342d7d5929e26a14335319791896 100644 --- a/mex/sources/estimation/KalmanFilter.hh +++ b/mex/sources/estimation/KalmanFilter.hh @@ -48,7 +48,8 @@ class KalmanFilter { public: - virtual ~KalmanFilter(); + virtual + ~KalmanFilter(); KalmanFilter(const std::string &basename, 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_arg, const std::vector<size_t> &varobs_arg, @@ -56,18 +57,19 @@ public: bool noconstant_arg); template <class Vec1, class Vec2, class Mat1> - double compute(const MatrixConstView &dataView, Vec1 &steadyState, - const Mat1 &Q, const Matrix &H, const Vec2 &deepParams, - VectorView &vll, MatrixView &detrendedDataView, size_t start, size_t period) + double + compute(const MatrixConstView &dataView, Vec1 &steadyState, + const Mat1 &Q, const Matrix &H, const Vec2 &deepParams, + VectorView &vll, MatrixView &detrendedDataView, size_t start, size_t period) { - if (period == 0) // initialise all KF matrices - initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T, Pstar, Pinf, - dataView, detrendedDataView); - else // initialise parameter dependent KF matrices only but not Ps - initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T, - dataView, detrendedDataView); + if (period == 0) // initialise all KF matrices + initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T, Pstar, Pinf, + dataView, detrendedDataView); + else // initialise parameter dependent KF matrices only but not Ps + initKalmanFilter.initialize(steadyState, deepParams, R, Q, RQRt, T, + dataView, detrendedDataView); - return filter(detrendedDataView, H, vll, start); + return filter(detrendedDataView, H, vll, start); } private: diff --git a/mex/sources/estimation/LogLikelihoodMain.cc b/mex/sources/estimation/LogLikelihoodMain.cc index 8109ad99a74f55e49ab8e2275b6ce8500ad6ed4d..42ebd789bbee69fc33cc5303ea56a053edd8c557 100644 --- a/mex/sources/estimation/LogLikelihoodMain.cc +++ b/mex/sources/estimation/LogLikelihoodMain.cc @@ -31,11 +31,11 @@ LogLikelihoodMain::LogLikelihoodMain(const std::string &basename, EstimatedParam const std::vector<size_t> &varobs, double riccati_tol, double lyapunov_tol, bool noconstant_arg) - : estSubsamples(estiParDesc.estSubsamples), - logLikelihoodSubSample(basename, estiParDesc, n_endo, n_exo, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium, - varobs, riccati_tol, lyapunov_tol, noconstant_arg), - vll(estiParDesc.getNumberOfPeriods()), // time dimension size of data - detrendedData(varobs.size(), estiParDesc.getNumberOfPeriods()) +: estSubsamples(estiParDesc.estSubsamples), + logLikelihoodSubSample(basename, estiParDesc, n_endo, n_exo, zeta_fwrd_arg, zeta_back_arg, zeta_mixed_arg, zeta_static_arg, qz_criterium, + varobs, riccati_tol, lyapunov_tol, noconstant_arg), + vll(estiParDesc.getNumberOfPeriods()), // time dimension size of data + detrendedData(varobs.size(), estiParDesc.getNumberOfPeriods()) { } @@ -44,5 +44,3 @@ LogLikelihoodMain::~LogLikelihoodMain() { } - - diff --git a/mex/sources/estimation/LogLikelihoodMain.hh b/mex/sources/estimation/LogLikelihoodMain.hh index 731336a25baadc61daa747496fbcee80dd28ec35..e18c84cb2c331b89fb60a10c7851e4b391377d43 100644 --- a/mex/sources/estimation/LogLikelihoodMain.hh +++ b/mex/sources/estimation/LogLikelihoodMain.hh @@ -36,7 +36,8 @@ private: Matrix detrendedData; public: - virtual ~LogLikelihoodMain(); + virtual + ~LogLikelihoodMain(); LogLikelihoodMain(const std::string &basename, 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, @@ -53,25 +54,30 @@ public: */ template <class VEC1, class VEC2> - double compute(VEC1 &steadyState, VEC2 &estParams, VectorView &deepParams, const MatrixConstView &data, - MatrixView &Q, Matrix &H, size_t start) + double + compute(VEC1 &steadyState, VEC2 &estParams, VectorView &deepParams, const MatrixConstView &data, + MatrixView &Q, Matrix &H, size_t start) { double logLikelihood = 0; for (size_t i = 0; i < estSubsamples.size(); ++i) { - MatrixConstView dataView(data, 0, estSubsamples[i].startPeriod, - data.getRows(), estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1); - MatrixView detrendedDataView(detrendedData, 0, estSubsamples[i].startPeriod, - data.getRows(), estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1); + MatrixConstView dataView(data, 0, estSubsamples[i].startPeriod, + data.getRows(), estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1); + MatrixView detrendedDataView(detrendedData, 0, estSubsamples[i].startPeriod, + data.getRows(), estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1); - VectorView vllView(vll, estSubsamples[i].startPeriod, estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1); - logLikelihood += logLikelihoodSubSample.compute(steadyState, dataView, estParams, deepParams, - Q, H, vllView, detrendedDataView, start, i); + VectorView vllView(vll, estSubsamples[i].startPeriod, estSubsamples[i].endPeriod-estSubsamples[i].startPeriod+1); + logLikelihood += logLikelihoodSubSample.compute(steadyState, dataView, estParams, deepParams, + Q, H, vllView, detrendedDataView, start, i); } return logLikelihood; }; - Vector &getVll() { return vll; }; + Vector & + getVll() + { + return vll; + }; }; #endif // !defined(E126AEF5_AC28_400a_821A_3BCFD1BC4C22__INCLUDED_) diff --git a/mex/sources/estimation/LogLikelihoodSubSample.cc b/mex/sources/estimation/LogLikelihoodSubSample.cc index 9a3aabf80ee70fb113c4d6bca468cd52df8ce44b..7d53b67fbcbfde3a1d77d0f3b7191467d4972a03 100644 --- a/mex/sources/estimation/LogLikelihoodSubSample.cc +++ b/mex/sources/estimation/LogLikelihoodSubSample.cc @@ -38,4 +38,3 @@ LogLikelihoodSubSample::LogLikelihoodSubSample(const std::string &basename, Esti varobs, riccati_tol, lyapunov_tol, noconstant_arg), eigQ(n_exo), eigH(varobs.size()) { }; - diff --git a/mex/sources/estimation/LogLikelihoodSubSample.hh b/mex/sources/estimation/LogLikelihoodSubSample.hh index 4e0fa509f3ee496e8444ba61e0a3a9708a44ca52..e87071ffa652077a9b9e27f1116c0016a8a244b5 100644 --- a/mex/sources/estimation/LogLikelihoodSubSample.hh +++ b/mex/sources/estimation/LogLikelihoodSubSample.hh @@ -42,15 +42,17 @@ public: const std::vector<size_t> &varobs_arg, double riccati_tol_in, double lyapunov_tol, bool noconstant_arg); template <class VEC1, class VEC2> - double compute(VEC1 &steadyState, const MatrixConstView &dataView, VEC2 &estParams, VectorView &deepParams, - MatrixView &Q, Matrix &H, VectorView &vll, MatrixView &detrendedDataView, size_t start, size_t period) + double + compute(VEC1 &steadyState, const MatrixConstView &dataView, VEC2 &estParams, VectorView &deepParams, + MatrixView &Q, Matrix &H, VectorView &vll, MatrixView &detrendedDataView, size_t start, size_t period) { updateParams(estParams, deepParams, Q, H, period); return kalmanFilter.compute(dataView, steadyState, Q, H, deepParams, vll, detrendedDataView, start, period); } - virtual ~LogLikelihoodSubSample(); + virtual + ~LogLikelihoodSubSample(); class UpdateParamsException { @@ -69,8 +71,9 @@ private: // methods template <class VEC> - void updateParams(VEC &estParams, VectorView &deepParams, - MatrixView &Q, Matrix &H, size_t period) + void + updateParams(VEC &estParams, VectorView &deepParams, + MatrixView &Q, Matrix &H, size_t period) { size_t i, k, k1, k2; int test; @@ -79,97 +82,96 @@ private: for (i = 0; i < estParams.getSize(); ++i) { - found = false; - it = find(estiParDesc.estParams[i].subSampleIDs.begin(), - estiParDesc.estParams[i].subSampleIDs.end(), period); - if (it != estiParDesc.estParams[i].subSampleIDs.end()) - found = true; - if (found) - { - switch (estiParDesc.estParams[i].ptype) - { - case EstimatedParameter::shock_SD: - k = estiParDesc.estParams[i].ID1; - Q(k, k) = estParams(i)*estParams(i); - break; - - case EstimatedParameter::measureErr_SD: - k = estiParDesc.estParams[i].ID1; - H(k, k) = estParams(i)*estParams(i); - break; - - case EstimatedParameter::shock_Corr: - k1 = estiParDesc.estParams[i].ID1; - k2 = estiParDesc.estParams[i].ID2; - Q(k1, k2) = estParams(i)*sqrt(Q(k1, k1)*Q(k2, k2)); - Q(k2, k1) = Q(k1, k2); - // [CholQ,testQ] = chol(Q); - test = lapack::choleskyDecomp(Q, "L"); + found = false; + it = find(estiParDesc.estParams[i].subSampleIDs.begin(), + estiParDesc.estParams[i].subSampleIDs.end(), period); + if (it != estiParDesc.estParams[i].subSampleIDs.end()) + found = true; + if (found) + { + switch (estiParDesc.estParams[i].ptype) + { + case EstimatedParameter::shock_SD: + k = estiParDesc.estParams[i].ID1; + Q(k, k) = estParams(i)*estParams(i); + break; + + case EstimatedParameter::measureErr_SD: + k = estiParDesc.estParams[i].ID1; + H(k, k) = estParams(i)*estParams(i); + break; + + case EstimatedParameter::shock_Corr: + k1 = estiParDesc.estParams[i].ID1; + k2 = estiParDesc.estParams[i].ID2; + Q(k1, k2) = estParams(i)*sqrt(Q(k1, k1)*Q(k2, k2)); + Q(k2, k1) = Q(k1, k2); + // [CholQ,testQ] = chol(Q); + test = lapack::choleskyDecomp(Q, "L"); assert(test >= 0); - - if (test > 0) - { - // The variance-covariance matrix of the structural innovations is not definite positive. - // We have to compute the eigenvalues of this matrix in order to build the penalty. - double delta = 0; - eigQ.calculate(Q); // get eigenvalues - //k = find(a < 0); - if (eigQ.hasConverged()) - { - const Vector &evQ = eigQ.getD(); - for (i = 0; i < evQ.getSize(); ++i) - if (evQ(i) < 0) - delta -= evQ(i); - } - - throw UpdateParamsException(delta); - } // if - break; - - case EstimatedParameter::measureErr_Corr: - k1 = estiParDesc.estParams[i].ID1; - k2 = estiParDesc.estParams[i].ID2; - // H(k1,k2) = xparam1(i)*sqrt(H(k1,k1)*H(k2,k2)); - // H(k2,k1) = H(k1,k2); - H(k1, k2) = estParams(i)*sqrt(H(k1, k1)*H(k2, k2)); - H(k2, k1) = H(k1, k2); - - //[CholH,testH] = chol(H); - test = lapack::choleskyDecomp(H, "L"); - assert(test >= 0); - - if (test > 0) - { - // The variance-covariance matrix of the measurement errors is not definite positive. - // We have to compute the eigenvalues of this matrix in order to build the penalty. - //a = diag(eig(H)); - double delta = 0; - eigH.calculate(H); // get eigenvalues - //k = find(a < 0); - if (eigH.hasConverged()) - { - const Vector &evH = eigH.getD(); - for (i = 0; i < evH.getSize(); ++i) - if (evH(i) < 0) - delta -= evH(i); - } - throw UpdateParamsException(delta); - } // end if - break; - - //if estim_params_.np > 0 // i.e. num of deep parameters >0 - case EstimatedParameter::deepPar: - k = estiParDesc.estParams[i].ID1; - deepParams(k) = estParams(i); - break; - default: + + if (test > 0) + { + // The variance-covariance matrix of the structural innovations is not definite positive. + // We have to compute the eigenvalues of this matrix in order to build the penalty. + double delta = 0; + eigQ.calculate(Q); // get eigenvalues + //k = find(a < 0); + if (eigQ.hasConverged()) + { + const Vector &evQ = eigQ.getD(); + for (i = 0; i < evQ.getSize(); ++i) + if (evQ(i) < 0) + delta -= evQ(i); + } + + throw UpdateParamsException(delta); + } // if + break; + + case EstimatedParameter::measureErr_Corr: + k1 = estiParDesc.estParams[i].ID1; + k2 = estiParDesc.estParams[i].ID2; + // H(k1,k2) = xparam1(i)*sqrt(H(k1,k1)*H(k2,k2)); + // H(k2,k1) = H(k1,k2); + H(k1, k2) = estParams(i)*sqrt(H(k1, k1)*H(k2, k2)); + H(k2, k1) = H(k1, k2); + + //[CholH,testH] = chol(H); + test = lapack::choleskyDecomp(H, "L"); + assert(test >= 0); + + if (test > 0) + { + // The variance-covariance matrix of the measurement errors is not definite positive. + // We have to compute the eigenvalues of this matrix in order to build the penalty. + //a = diag(eig(H)); + double delta = 0; + eigH.calculate(H); // get eigenvalues + //k = find(a < 0); + if (eigH.hasConverged()) + { + const Vector &evH = eigH.getD(); + for (i = 0; i < evH.getSize(); ++i) + if (evH(i) < 0) + delta -= evH(i); + } + throw UpdateParamsException(delta); + } // end if + break; + + //if estim_params_.np > 0 // i.e. num of deep parameters >0 + case EstimatedParameter::deepPar: + k = estiParDesc.estParams[i].ID1; + deepParams(k) = estParams(i); + break; + default: assert(false); - } // end switch - } // end found + } // end switch + } // end found } //end for }; - }; #endif // !defined(DF8B7AF5_8169_4587_9037_2CD2C82E2DDF__INCLUDED_) diff --git a/mex/sources/estimation/LogPosteriorDensity.cc b/mex/sources/estimation/LogPosteriorDensity.cc index a9da75fc11d3ce6d24cb2d001fee2b6b4d603d1d..b7b94dbbd30f306fa4fc87186b4a74024578c5ec 100644 --- a/mex/sources/estimation/LogPosteriorDensity.cc +++ b/mex/sources/estimation/LogPosteriorDensity.cc @@ -41,7 +41,6 @@ LogPosteriorDensity::LogPosteriorDensity(const std::string &modName, EstimatedPa } - /** * vector of log likelihoods for each Kalman step */ @@ -50,4 +49,3 @@ LogPosteriorDensity::getLikVector() { return logLikelihoodMain.getVll(); } - diff --git a/mex/sources/estimation/LogPosteriorDensity.hh b/mex/sources/estimation/LogPosteriorDensity.hh index 820f2a575380275441603ef64341a7d15074d967..c8088bcb7d1ec2707eacc66c07e8f5aa1f81f6df 100644 --- a/mex/sources/estimation/LogPosteriorDensity.hh +++ b/mex/sources/estimation/LogPosteriorDensity.hh @@ -42,7 +42,8 @@ private: LogLikelihoodMain logLikelihoodMain; public: - virtual ~LogPosteriorDensity(); + virtual + ~LogPosteriorDensity(); LogPosteriorDensity(const std::string &modName, EstimatedParametersDescription &estParamsDesc, 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, diff --git a/mex/sources/estimation/LogPriorDensity.hh b/mex/sources/estimation/LogPriorDensity.hh index 5a07402be09a93de0b3cbba76da30ddbde03477f..b1f424810e129205620b9c537d4f8811c168bb7c 100644 --- a/mex/sources/estimation/LogPriorDensity.hh +++ b/mex/sources/estimation/LogPriorDensity.hh @@ -35,18 +35,20 @@ class LogPriorDensity public: LogPriorDensity(EstimatedParametersDescription &estParsDesc); - virtual ~LogPriorDensity(); + virtual + ~LogPriorDensity(); template<class VEC> - double compute(VEC &ep) + double + compute(VEC &ep) { assert(estParsDesc.estParams.size() == ep.getSize()); double logPriorDensity = 0; for (size_t i = 0; i < ep.getSize(); ++i) { - logPriorDensity += log(((*(estParsDesc.estParams[i]).prior)).pdf(ep(i))); - if (std::isinf(fabs(logPriorDensity))) - return logPriorDensity; + logPriorDensity += log(((*(estParsDesc.estParams[i]).prior)).pdf(ep(i))); + if (std::isinf(fabs(logPriorDensity))) + return logPriorDensity; } return logPriorDensity; }; diff --git a/mex/sources/estimation/ModelSolution.cc b/mex/sources/estimation/ModelSolution.cc index 64543bf09d3a78cd0ded0e0044dd5a69fd98c449..3a8478dd88177be9e872af1043f397741af22a3f 100644 --- a/mex/sources/estimation/ModelSolution.cc +++ b/mex/sources/estimation/ModelSolution.cc @@ -51,5 +51,3 @@ ModelSolution::ModelSolution(const std::string &basename, size_t n_endo_arg, si zeta_mixed_arg.begin(), zeta_mixed_arg.end(), back_inserter(zeta_back_mixed)); } - - diff --git a/mex/sources/estimation/ModelSolution.hh b/mex/sources/estimation/ModelSolution.hh index 92e03a5446c428772c77a5b118c3fa98a62fd4b7..88f3120569fef11f0a1ae032d5028806af0d10ba 100644 --- a/mex/sources/estimation/ModelSolution.hh +++ b/mex/sources/estimation/ModelSolution.hh @@ -42,9 +42,12 @@ public: ModelSolution(const std::string &basename, 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() {}; + virtual ~ModelSolution() + { + }; template <class Vec1, class Vec2, class Mat1, class Mat2> - void compute(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &ghx, Mat2 &ghu) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException, SteadyStateSolver::SteadyStateException) + void + compute(Vec1 &steadyState, const Vec2 &deepParams, Mat1 &ghx, Mat2 &ghu) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException, SteadyStateSolver::SteadyStateException) { // compute Steady State steadyStateSolver.compute(steadyState, Mx, deepParams); @@ -69,8 +72,9 @@ private: Vector llXsteadyState; //Matrix jacobian; template <class Vec1, class Vec2, class Mat1, class Mat2> - void ComputeModelSolution(Vec1 &steadyState, const Vec2 &deepParams, - Mat1 &ghx, Mat2 &ghu) + void + ComputeModelSolution(Vec1 &steadyState, const Vec2 &deepParams, + Mat1 &ghx, Mat2 &ghu) throw (DecisionRules::BlanchardKahnException, GeneralizedSchurDecomposition::GSDException) { // set extended Steady State diff --git a/mex/sources/estimation/Prior.hh b/mex/sources/estimation/Prior.hh index de29bf7898716075fb0b4b3d2593e74a9ea57c62..c3d0ce3e187cd0a55d556c0e4f27e86e0cb74043 100644 --- a/mex/sources/estimation/Prior.hh +++ b/mex/sources/estimation/Prior.hh @@ -47,17 +47,18 @@ struct Prior public: //! probablity density functions enum pShape - { - Beta = 1, - Gamma = 2, - Gaussian = 3, // i.e. Normal density - Inv_gamma_1 = 4, // Inverse gamma (type 1) density - Uniform = 5, - Inv_gamma_2 = 6 //Inverse gamma (type 2) density - }; + { + Beta = 1, + Gamma = 2, + Gaussian = 3, // i.e. Normal density + Inv_gamma_1 = 4, // Inverse gamma (type 1) density + Uniform = 5, + Inv_gamma_2 = 6 //Inverse gamma (type 2) density + }; Prior(double mean, double standard, double lower_bound, double upper_bound, double fhp, double shp); - virtual ~Prior(); + virtual + ~Prior(); const double mean; const double standard; @@ -100,7 +101,9 @@ public: distribution(fhp, shp) { }; - virtual ~BetaPrior(){}; + virtual ~BetaPrior() + { + }; virtual pShape getShape() { @@ -134,7 +137,9 @@ public: distribution(fhp, shp) { }; - virtual ~GammaPrior(){}; + virtual ~GammaPrior() + { + }; virtual pShape getShape() { @@ -164,7 +169,9 @@ public: distribution(shp/2, 2/fhp) { }; - virtual ~InvGamma1_Prior(){}; + virtual ~InvGamma1_Prior() + { + }; virtual pShape getShape() { @@ -199,7 +206,9 @@ public: distribution(shp/2, 2/fhp) { }; - virtual ~InvGamma2_Prior(){}; + virtual ~InvGamma2_Prior() + { + }; virtual pShape getShape() { @@ -239,7 +248,9 @@ public: distribution(fhp, shp) //pdf distribution(mean, standard) { }; - virtual ~GaussianPrior(){}; + virtual ~GaussianPrior() + { + }; virtual pShape getShape() { @@ -277,7 +288,9 @@ public: distribution(fhp, shp) //pdf distribution(lower_bound, upper_bound) { }; - virtual ~UniformPrior(){}; + virtual ~UniformPrior() + { + }; virtual pShape getShape() { diff --git a/mex/sources/estimation/Proposal.cc b/mex/sources/estimation/Proposal.cc index 7e7b633d85d38d923ef4eb7bc27072df7aeb2fab..f632ab2c4ffbda69e70ec8201760ff4671ee270d 100644 --- a/mex/sources/estimation/Proposal.cc +++ b/mex/sources/estimation/Proposal.cc @@ -88,4 +88,3 @@ Proposal::selectionTestDraw() { return uniformVrng(); } - diff --git a/mex/sources/estimation/Proposal.hh b/mex/sources/estimation/Proposal.hh index 13be358fb11703860839072d7bbf85b40a8f6b3b..7d1386cc8762607b0b6cb5336897f953b08c3578 100644 --- a/mex/sources/estimation/Proposal.hh +++ b/mex/sources/estimation/Proposal.hh @@ -63,7 +63,9 @@ 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.hh b/mex/sources/estimation/RandomWalkMetropolisHastings.hh index f281939bac044a69958cda72e1264a2a03078c8d..0a28dbb4ebc45fcfa47872bb2733510a9145aef0 100644 --- a/mex/sources/estimation/RandomWalkMetropolisHastings.hh +++ b/mex/sources/estimation/RandomWalkMetropolisHastings.hh @@ -42,13 +42,16 @@ public: parDraw(size), newParDraw(size) { }; - virtual ~RandomWalkMetropolisHastings() {}; + virtual ~RandomWalkMetropolisHastings() + { + }; template<class VEC1> - double compute(VectorView &mhLogPostDens, MatrixView &mhParams, VEC1 &steadyState, - Vector &estParams, VectorView &deepParams, const MatrixConstView &data, MatrixView &Q, Matrix &H, - const size_t presampleStart, const size_t startDraw, size_t nMHruns, - LogPosteriorDensity &lpd, Proposal &pDD, EstimatedParametersDescription &epd) + double + compute(VectorView &mhLogPostDens, MatrixView &mhParams, VEC1 &steadyState, + Vector &estParams, VectorView &deepParams, const MatrixConstView &data, MatrixView &Q, Matrix &H, + const size_t presampleStart, const size_t startDraw, size_t nMHruns, + LogPosteriorDensity &lpd, Proposal &pDD, EstimatedParametersDescription &epd) { //streambuf *likbuf, *drawbuf *backup; std::ofstream urandfilestr, drawfilestr; @@ -64,46 +67,46 @@ public: for (size_t run = startDraw - 1; run < nMHruns; ++run) { - overbound = false; - pDD.draw(parDraw, newParDraw); - for (count = 0; count < parDraw.getSize(); ++count) - { - overbound = (newParDraw(count) < epd.estParams[count].lower_bound || newParDraw(count) > epd.estParams[count].upper_bound); - if (overbound) - { - newLogpost = -INFINITY; - break; - } - } - if (!overbound) - { - try - { - newLogpost = -lpd.compute(steadyState, newParDraw, deepParams, data, Q, H, presampleStart); - } - catch (const std::exception &e) - { - throw; // for now handle the system and other errors higher-up - } - catch (...) - { - newLogpost = -INFINITY; - } - } - urand = pDD.selectionTestDraw(); - if ((newLogpost > -INFINITY) && log(urand) < newLogpost-logpost) - { - parDraw = newParDraw; - logpost = newLogpost; - accepted++; - } - mat::get_row(mhParams, run) = parDraw; - mhLogPostDens(run) = logpost; + overbound = false; + pDD.draw(parDraw, newParDraw); + for (count = 0; count < parDraw.getSize(); ++count) + { + overbound = (newParDraw(count) < epd.estParams[count].lower_bound || newParDraw(count) > epd.estParams[count].upper_bound); + if (overbound) + { + newLogpost = -INFINITY; + break; + } + } + if (!overbound) + { + try + { + newLogpost = -lpd.compute(steadyState, newParDraw, deepParams, data, Q, H, presampleStart); + } + catch (const std::exception &e) + { + throw; // for now handle the system and other errors higher-up + } + catch (...) + { + newLogpost = -INFINITY; + } + } + urand = pDD.selectionTestDraw(); + if ((newLogpost > -INFINITY) && log(urand) < newLogpost-logpost) + { + parDraw = newParDraw; + logpost = newLogpost; + accepted++; + } + mat::get_row(mhParams, run) = parDraw; + mhLogPostDens(run) = logpost; - urandfilestr << urand << "\n"; //"," - for (size_t c = 0; c < newParDraw.getSize()-1; ++c) - drawfilestr << newParDraw(c) << ","; - drawfilestr << newParDraw(newParDraw.getSize()-1) << "\n"; + urandfilestr << urand << "\n"; //"," + for (size_t c = 0; c < newParDraw.getSize()-1; ++c) + drawfilestr << newParDraw(c) << ","; + drawfilestr << newParDraw(newParDraw.getSize()-1) << "\n"; } urandfilestr.close(); diff --git a/mex/sources/estimation/SteadyStateSolver.cc b/mex/sources/estimation/SteadyStateSolver.cc index e2e9980aebf6b29c6185e1daf6aaba0c8b12b665..03361cda2e0e2e9ff4364fb69a86fbc5b5788be9 100644 --- a/mex/sources/estimation/SteadyStateSolver.cc +++ b/mex/sources/estimation/SteadyStateSolver.cc @@ -33,12 +33,12 @@ SteadyStateSolver::static_f(const gsl_vector *yy, void *p, gsl_vector *F) params *pp = (params *) p; VectorConstView deepParams(pp->deepParams, pp->n_params, 1); MatrixConstView x(pp->x, 1, pp->n_exo, 1); - + VectorView y(yy->data, yy->size, yy->stride); VectorView residual(F->data, F->size, F->stride); pp->static_dll->eval(y, x, deepParams, residual, NULL, NULL); - + return GSL_SUCCESS; } @@ -48,11 +48,11 @@ SteadyStateSolver::static_df(const gsl_vector *yy, void *p, gsl_matrix *J) params *pp = (params *) p; VectorConstView deepParams(pp->deepParams, pp->n_params, 1); MatrixConstView x(pp->x, 1, pp->n_exo, 1); - + VectorView y(yy->data, yy->size, yy->stride); pp->static_dll->eval(y, x, deepParams, *pp->residual, pp->g1, NULL); - + assert(J->size1 == J->size2 && J->size1 == J->tda); MatrixView g1t(J->data, J->size1, J->size2, J->tda); mat::transpose(g1t, *pp->g1); // GSL wants row-major order @@ -66,16 +66,15 @@ SteadyStateSolver::static_fdf(const gsl_vector *yy, void *p, gsl_vector *F, gsl_ params *pp = (params *) p; VectorConstView deepParams(pp->deepParams, pp->n_params, 1); MatrixConstView x(pp->x, 1, pp->n_exo, 1); - + VectorView y(yy->data, yy->size, yy->stride); VectorView residual(F->data, F->size, F->stride); pp->static_dll->eval(y, x, deepParams, residual, pp->g1, NULL); - + assert(J->size1 == J->size2 && J->size1 == J->tda); MatrixView g1t(J->data, J->size1, J->size2, J->tda); mat::transpose(g1t, *pp->g1); // GSL wants row-major order return GSL_SUCCESS; } - diff --git a/mex/sources/estimation/SteadyStateSolver.hh b/mex/sources/estimation/SteadyStateSolver.hh index e52f5f433cf7f3d00746c39dbe831c90167d8dbc..846543c7d95d6ec0de34101f9fe2f3a58f1d5d35 100644 --- a/mex/sources/estimation/SteadyStateSolver.hh +++ b/mex/sources/estimation/SteadyStateSolver.hh @@ -55,7 +55,7 @@ public: { public: std::string message; - SteadyStateException(const std::string &message_arg) : message(message_arg) + SteadyStateException(const std::string &message_arg) : message(message_arg) { } }; @@ -63,7 +63,8 @@ public: SteadyStateSolver(const std::string &basename, size_t n_endo_arg); template <class Vec1, class Mat, class Vec2> - void compute(Vec1 &steadyState, const Mat &Mx, const Vec2 &deepParams) throw (SteadyStateException) + void + compute(Vec1 &steadyState, const Mat &Mx, const Vec2 &deepParams) throw (SteadyStateException) { assert(steadyState.getStride() == 1); assert(deepParams.getStride() == 1); @@ -97,7 +98,7 @@ public: status = gsl_multiroot_test_residual(s->f, tolerance); } - while(status == GSL_CONTINUE && iter < max_iterations); + while (status == GSL_CONTINUE && iter < max_iterations); if (status != GSL_SUCCESS) throw SteadyStateException(std::string(gsl_strerror(status))); @@ -107,5 +108,3 @@ public: gsl_multiroot_fdfsolver_free(s); } }; - - diff --git a/mex/sources/estimation/libmat/DiscLyapFast.hh b/mex/sources/estimation/libmat/DiscLyapFast.hh index cd0b014c0c34d81f5abd7097a53aa044049662c5..1acef6dadd07b35bca643ea429553ea52559ff01 100644 --- a/mex/sources/estimation/libmat/DiscLyapFast.hh +++ b/mex/sources/estimation/libmat/DiscLyapFast.hh @@ -60,7 +60,9 @@ 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 = 1e-16, size_t flag_ch = 0) throw (DLPException); diff --git a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc index 0b9e5d01b1cbd83f59cf08f453139aacddef6d6e..ca6fde75a1439b22d749cd20efb500819f4f2007 100644 --- a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc +++ b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.cc @@ -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/GeneralizedSchurDecomposition.hh b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh index f776ba3330a7f86d4eda22326c23cde261412515..3d2898f8402ba3da272b039de43a41b059725bbd 100644 --- a/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh +++ b/mex/sources/estimation/libmat/GeneralizedSchurDecomposition.hh @@ -37,11 +37,14 @@ public: { public: const lapack_int info, n; - GSDException(lapack_int info_arg, lapack_int n_arg) : info(info_arg), n(n_arg) {}; + GSDException(lapack_int info_arg, lapack_int n_arg) : info(info_arg), n(n_arg) + { + }; }; //! \todo Replace heuristic choice for workspace size by a query to determine the optimal size GeneralizedSchurDecomposition(size_t n_arg, double criterium_arg); - virtual ~GeneralizedSchurDecomposition(); + virtual + ~GeneralizedSchurDecomposition(); //! \todo Add a lock around the modification of criterium_static for making it thread-safe template<class Mat1, class Mat2, class Mat3> void compute(Mat1 &S, Mat2 &T, Mat3 &Z, size_t &sdim) throw (GSDException); diff --git a/mex/sources/estimation/libmat/LUSolver.hh b/mex/sources/estimation/libmat/LUSolver.hh index e78c18c74327799b5a370a34e36a062e06824198..1c0af58c1d373c1e8569084eb3730332469df7df 100644 --- a/mex/sources/estimation/libmat/LUSolver.hh +++ b/mex/sources/estimation/libmat/LUSolver.hh @@ -32,10 +32,13 @@ public: { public: const lapack_int info; - LUException(lapack_int info_arg) : info(info_arg) {}; + LUException(lapack_int info_arg) : info(info_arg) + { + }; }; LUSolver(size_t dim_arg); - virtual ~LUSolver(); + virtual + ~LUSolver(); /*! Computes A^(-1)*B (possibly transposing A). The output is stored in B. diff --git a/mex/sources/estimation/libmat/Matrix.hh b/mex/sources/estimation/libmat/Matrix.hh index 860af9507e9d916e193ae8a62eb6aee0b65519ba..774811f5d2114e909dc5c21263d54c4350788e64 100644 --- a/mex/sources/estimation/libmat/Matrix.hh +++ b/mex/sources/estimation/libmat/Matrix.hh @@ -69,19 +69,52 @@ public: Matrix(size_t rows_arg, size_t cols_arg); Matrix(size_t size_arg); Matrix(const Matrix &arg); - virtual ~Matrix(); - inline size_t getRows() const { return rows; } - inline size_t getCols() const { return cols; } - inline size_t getLd() const { return rows; } - inline double *getData() { return data; } - inline const double *getData() const { return data; } - inline void setAll(double val) { std::fill_n(data, rows*cols, val); } - inline double &operator() (size_t i, size_t j) { return data[i+j*rows]; } - inline const double &operator() (size_t i, size_t j) const { return data[i+j*rows]; } + virtual + ~Matrix(); + inline size_t + getRows() const + { + return rows; + } + inline size_t + getCols() const + { + return cols; + } + inline size_t + getLd() const + { + return rows; + } + inline double * + getData() + { + return data; + } + inline const double * + getData() const + { + return data; + } + inline void + setAll(double val) + { + std::fill_n(data, rows*cols, val); + } + inline double & + operator()(size_t i, size_t j) + { + return data[i+j*rows]; + } + inline const double & + operator()(size_t i, size_t j) const + { + return data[i+j*rows]; + } //! Assignment operator, only works for matrices of same dimension template<class Mat> Matrix & - operator= (const Mat &arg) + operator=(const Mat &arg) { assert(rows == arg.getRows() && cols == arg.getCols()); for (size_t j = 0; j < cols; j++) @@ -112,23 +145,54 @@ public: && col_offset < arg.getCols() && col_offset + cols_arg <= arg.getCols()); } - virtual ~MatrixView(){}; - inline size_t getRows() const { return rows; } - inline size_t getCols() const { return cols; } - inline size_t getLd() const { return ld; } - inline double *getData() { return data; } - inline const double *getData() const { return data; } - inline void setAll(double val) + virtual ~MatrixView() + { + }; + inline size_t + getRows() const + { + return rows; + } + inline size_t + getCols() const + { + return cols; + } + inline size_t + getLd() const + { + return ld; + } + inline double * + getData() + { + return data; + } + inline const double * + getData() const + { + return data; + } + inline void + setAll(double val) { for (double *p = data; p < data + cols*ld; p += ld) std::fill_n(p, rows, val); } - inline double &operator() (size_t i, size_t j) { return data[i+j*ld]; } - inline const double &operator() (size_t i, size_t j) const { return data[i+j*ld]; } + inline double & + operator()(size_t i, size_t j) + { + return data[i+j*ld]; + } + inline const double & + operator()(size_t i, size_t j) const + { + return data[i+j*ld]; + } //! Assignment operator, only works for matrices of same dimension template<class Mat> MatrixView & - operator= (const Mat &arg) + operator=(const Mat &arg) { assert(rows == arg.getRows() && cols == arg.getCols()); for (size_t j = 0; j < cols; j++) @@ -158,12 +222,34 @@ public: && col_offset < arg.getCols() && col_offset + cols_arg <= arg.getCols()); } - virtual ~MatrixConstView(){}; - inline size_t getRows() const { return rows; } - inline size_t getCols() const { return cols; } - inline size_t getLd() const { return ld; } - inline const double *getData() const { return data; } - inline const double &operator() (size_t i, size_t j) const { return data[i+j*ld]; } + virtual ~MatrixConstView() + { + }; + inline size_t + getRows() const + { + return rows; + } + inline size_t + getCols() const + { + return cols; + } + inline size_t + getLd() const + { + return ld; + } + inline const double * + getData() const + { + return data; + } + inline const double & + operator()(size_t i, size_t j) const + { + return data[i+j*ld]; + } }; std::ostream &operator<<(std::ostream &out, const Matrix &M); @@ -561,9 +647,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 d8022a7e5cc66d60fd971f9865a3345b6021081f..0d1f900dca59de15545f265465c786aeda864630 100644 --- a/mex/sources/estimation/libmat/QRDecomposition.hh +++ b/mex/sources/estimation/libmat/QRDecomposition.hh @@ -41,7 +41,8 @@ public: \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(); + virtual + ~QRDecomposition(); //! Performs the QR decomposition of a matrix, and left-multiplies another matrix by Q /*! \param[in,out] A On input, the matrix to be decomposed. On output, equals to the output of dgeqrf diff --git a/mex/sources/estimation/libmat/Vector.hh b/mex/sources/estimation/libmat/Vector.hh index d020beaf4664698f0cbeca6aa158ca56921be9fd..5deaa4deb81993d98bb9d2d1069b87b065077859 100644 --- a/mex/sources/estimation/libmat/Vector.hh +++ b/mex/sources/estimation/libmat/Vector.hh @@ -63,17 +63,47 @@ private: public: Vector(size_t size_arg); Vector(const Vector &arg); - virtual ~Vector(); - inline size_t getSize() const { return size; } - inline size_t getStride() const { return 1; } - inline double *getData() { return data; } - inline const double *getData() const { return data; } - inline void setAll(double val) { std::fill_n(data, size, val); } - inline double &operator() (size_t i) { return data[i]; } - inline const double &operator() (size_t i) const { return data[i]; } + virtual + ~Vector(); + inline size_t + getSize() const + { + return size; + } + inline size_t + getStride() const + { + return 1; + } + inline double * + getData() + { + return data; + } + inline const double * + getData() const + { + return data; + } + inline void + setAll(double val) + { + std::fill_n(data, size, val); + } + inline double & + operator()(size_t i) + { + return data[i]; + } + 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(); @@ -99,25 +129,52 @@ private: public: VectorView(double *data_arg, size_t size_arg, size_t stride_arg); /* Can't use a template for the 2 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 */ VectorView(Vector &arg, size_t offset, size_t size_arg); VectorView(VectorView &arg, size_t offset, size_t size_arg); - virtual ~VectorView(){}; - inline size_t getSize() const { return size; } - inline size_t getStride() const { return stride; } - inline double *getData() { return data; } - inline const double *getData() const { return data; } - inline void setAll(double val) + virtual ~VectorView() + { + }; + inline size_t + getSize() const + { + return size; + } + inline size_t + getStride() const + { + return stride; + } + inline double * + getData() + { + return data; + } + inline const double * + getData() const + { + return data; + } + inline void + setAll(double val) { for (double *p = data; p < data + size*stride; p += stride) *p = val; } - inline double &operator() (size_t i) { return data[i*stride]; } - inline const double &operator() (size_t i) const { return data[i*stride]; } + inline double & + operator()(size_t i) + { + return data[i*stride]; + } + inline const double & + operator()(size_t i) const + { + return data[i*stride]; + } //! Assignment operator, only works for vectors of same size template<class Vec> VectorView & - operator= (const Vec &arg) + operator=(const Vec &arg) { assert(size == arg.getSize()); double *p1; @@ -145,11 +202,29 @@ public: VectorConstView(const VectorView &arg, size_t offset, size_t size_arg); VectorConstView(const VectorConstView &arg, size_t offset, size_t size_arg); - virtual ~VectorConstView() {}; - inline size_t getSize() const { return size; } - inline size_t getStride() const { return stride; } - inline const double *getData() const { return data; } - inline const double &operator() (size_t i) const { return data[i*stride]; } + virtual ~VectorConstView() + { + }; + inline size_t + getSize() const + { + return size; + } + inline size_t + getStride() const + { + return stride; + } + inline const double * + getData() const + { + return data; + } + inline const double & + operator()(size_t i) const + { + return data[i*stride]; + } }; std::ostream &operator<<(std::ostream &out, const Vector &V); diff --git a/mex/sources/estimation/logMHMCMCposterior.cc b/mex/sources/estimation/logMHMCMCposterior.cc index 5fd7faaae7a8b7ea5eb512e4e13cc1160ac0d844..ee9dd2f6410dabaeb7b0e2ff2099b4ec756bcbe8 100644 --- a/mex/sources/estimation/logMHMCMCposterior.cc +++ b/mex/sources/estimation/logMHMCMCposterior.cc @@ -47,7 +47,11 @@ public: LogMHMCMCposteriorMexErrMsgTxtException(const std::string &msg) : errMsg(msg) { } - inline const char *getErrMsg() { return errMsg.c_str(); } + inline const char * + getErrMsg() + { + return errMsg.c_str(); + } }; void @@ -279,7 +283,7 @@ 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) { @@ -287,7 +291,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, return (-1); } if (mxMhParamDrawsPtr) - mxDestroyArray(mxMhParamDrawsPtr); // accepted MCMC MH draws + mxDestroyArray(mxMhParamDrawsPtr); // accepted MCMC MH draws mxMhParamDrawsPtr = mxCreateDoubleMatrix(currInitSizeArray, npar, mxREAL); if (mxMhParamDrawsPtr == NULL) { @@ -375,7 +379,7 @@ 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) { @@ -383,7 +387,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, return (-1); } if (mxMhParamDrawsPtr) - mxDestroyArray(mxMhParamDrawsPtr); // accepted MCMC MH draws + mxDestroyArray(mxMhParamDrawsPtr); // accepted MCMC MH draws mxMhParamDrawsPtr = mxCreateDoubleMatrix(currInitSizeArray, npar, mxREAL); if (mxMhParamDrawsPtr == NULL) { @@ -603,9 +607,9 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, 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 @@ -631,7 +635,7 @@ sampleMHMC(LogPosteriorDensity &lpd, RandomWalkMetropolisHastings &rwmh, int logMCMCposterior(VectorConstView &estParams, const MatrixConstView &data, const size_t fblock, const size_t nBlocks, const VectorConstView &nMHruns, const MatrixConstView &D, - VectorView &steadyState, VectorView &deepParams, MatrixView &Q, Matrix &H) + VectorView &steadyState, VectorView &deepParams, MatrixView &Q, Matrix &H) { // Retrieve pointers to global variables const mxArray *M_ = mexGetVariablePtr("global", "M_"); @@ -712,7 +716,6 @@ logMCMCposterior(VectorConstView &estParams, const MatrixConstView &data, estParamsInfo); EstimatedParametersDescription epd(estSubsamples, estParamsInfo); - bool noconstant = (bool) *mxGetPr(mxGetField(options_, 0, "noconstant")); // Allocate LogPosteriorDensity object @@ -771,20 +774,20 @@ mexFunction(int nlhs, mxArray *plhs[], assert(nMHruns.getSize() == nBlocks); - mxArray *dataset_data = mxGetField(dataset,0,"data"); + mxArray *dataset_data = mxGetField(dataset, 0, "data"); MatrixConstView data(mxGetPr(dataset_data), mxGetM(dataset_data), mxGetN(dataset_data), mxGetM(dataset_data)); - int endo_nbr = *(int*)mxGetPr(mxGetField(M_, 0, "endo_nbr")); - int exo_nbr = *(int*)mxGetPr(mxGetField(M_, 0, "exo_nbr")); - int param_nbr = *(int*)mxGetPr(mxGetField(M_, 0, "param_nbr")); + int endo_nbr = *(int *) mxGetPr(mxGetField(M_, 0, "endo_nbr")); + int exo_nbr = *(int *) mxGetPr(mxGetField(M_, 0, "exo_nbr")); + int param_nbr = *(int *) mxGetPr(mxGetField(M_, 0, "param_nbr")); int varobs_nbr = mxGetN(mxGetField(options_, 0, "varobs")); - VectorView steadyState(mxGetPr(mxGetField(oo_,0,"steady_state")),endo_nbr, 1); - VectorView deepParams(mxGetPr(mxGetField(M_, 0, "params")),param_nbr,1); + VectorView steadyState(mxGetPr(mxGetField(oo_, 0, "steady_state")), endo_nbr, 1); + VectorView deepParams(mxGetPr(mxGetField(M_, 0, "params")), param_nbr, 1); MatrixView Q(mxGetPr(mxGetField(M_, 0, "Sigma_e")), exo_nbr, exo_nbr, exo_nbr); - Matrix H(varobs_nbr,varobs_nbr); + Matrix H(varobs_nbr, varobs_nbr); const mxArray *H_mx = mxGetField(M_, 0, "H"); if (mxGetM(H_mx) == 1 && mxGetN(H_mx) == 1 && *mxGetPr(H_mx) == 0) H.setAll(0.0); diff --git a/mex/sources/estimation/logposterior.cc b/mex/sources/estimation/logposterior.cc index 641244ce490b517039a253040824c8e1d0723a0b..319d5e51760469819e7d66ee88bc6323c6698a6c 100644 --- a/mex/sources/estimation/logposterior.cc +++ b/mex/sources/estimation/logposterior.cc @@ -36,7 +36,11 @@ public: LogposteriorMexErrMsgTxtException(const std::string &msg) : errMsg(msg) { } - inline const char *getErrMsg() { return errMsg.c_str(); } + inline const char * + getErrMsg() + { + return errMsg.c_str(); + } }; void @@ -103,8 +107,8 @@ template <class VEC1, class VEC2> double logposterior(VEC1 &estParams, const MatrixConstView &data, const mxArray *options_, const mxArray *M_, const mxArray *estim_params_, - const mxArray *bayestopt_, const mxArray *oo_, VEC2 &steadyState, double *trend_coeff, - VectorView &deepParams, Matrix &H, MatrixView &Q) + const mxArray *bayestopt_, const mxArray *oo_, VEC2 &steadyState, double *trend_coeff, + VectorView &deepParams, Matrix &H, MatrixView &Q) { double loglinear = *mxGetPr(mxGetField(options_, 0, "loglinear")); if (loglinear == 1) @@ -203,10 +207,10 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { - if (nrhs != 7 ) + if (nrhs != 7) DYN_MEX_FUNC_ERR_MSG_TXT("logposterior: exactly 7 input arguments are required."); - if (nlhs > 9 ) + if (nlhs > 9) DYN_MEX_FUNC_ERR_MSG_TXT("logposterior returns 8 output arguments at the most."); // Check and retrieve the RHS arguments @@ -219,9 +223,9 @@ mexFunction(int nlhs, mxArray *plhs[], for (int i = 1; i < 7; ++i) if (!mxIsStruct(prhs[i])) { - std::stringstream msg; - msg << "logposterior: argument " << i+1 << " must be a Matlab structure"; - DYN_MEX_FUNC_ERR_MSG_TXT(msg.str().c_str()); + std::stringstream msg; + msg << "logposterior: argument " << i+1 << " must be a Matlab structure"; + DYN_MEX_FUNC_ERR_MSG_TXT(msg.str().c_str()); } const mxArray *dataset = prhs[1]; @@ -231,7 +235,7 @@ mexFunction(int nlhs, mxArray *plhs[], const mxArray *bayestopt_ = prhs[5]; const mxArray *oo_ = prhs[6]; - const mxArray *dataset_data = mxGetField(dataset,0,"data"); + const mxArray *dataset_data = mxGetField(dataset, 0, "data"); MatrixConstView data(mxGetPr(dataset_data), mxGetM(dataset_data), mxGetN(dataset_data), mxGetM(dataset_data)); // Creaete LHS arguments @@ -251,12 +255,12 @@ mexFunction(int nlhs, mxArray *plhs[], double *lik = mxGetPr(plhs[0]); double *exit_flag = mxGetPr(plhs[1]); - VectorView steadyState(mxGetPr(mxGetField(oo_,0,"steady_state")),endo_nbr, 1); - VectorView deepParams(mxGetPr(mxGetField(M_, 0, "params")),param_nbr,1); + VectorView steadyState(mxGetPr(mxGetField(oo_, 0, "steady_state")), endo_nbr, 1); + VectorView deepParams(mxGetPr(mxGetField(M_, 0, "params")), param_nbr, 1); MatrixView Q(mxGetPr(mxGetField(M_, 0, "Sigma_e")), exo_nbr, exo_nbr, exo_nbr); - Matrix H(varobs_nbr,varobs_nbr); + Matrix H(varobs_nbr, varobs_nbr); const mxArray *H_mx = mxGetField(M_, 0, "H"); if (mxGetM(H_mx) == 1 && mxGetN(H_mx) == 1 && *mxGetPr(H_mx) == 0) H.setAll(0.0); @@ -270,7 +274,7 @@ mexFunction(int nlhs, mxArray *plhs[], try { *lik = logposterior(estParams, data, options_, M_, estim_params_, bayestopt_, oo_, - steadyState, trend_coeff, deepParams, H, Q); + steadyState, trend_coeff, deepParams, H, Q); *info_mx = 0; *exit_flag = 0; } diff --git a/mex/sources/estimation/tests/testInitKalman.cc b/mex/sources/estimation/tests/testInitKalman.cc index 37884a6cc39317a5ca416c7fed1e61a8ab852e03..21bd129547c3cec6ac27d73ab0765f9a33cc4c9f 100644 --- a/mex/sources/estimation/tests/testInitKalman.cc +++ b/mex/sources/estimation/tests/testInitKalman.cc @@ -147,4 +147,3 @@ main(int argc, char **argv) std::cout << "Matrix Pinf: " << std::endl << Pinf << std::endl; } - diff --git a/mex/sources/estimation/tests/testKalman.cc b/mex/sources/estimation/tests/testKalman.cc index cd1401c6959e5531fd06d9dfd2fa927d25be296c..29e85c600acd6cf07fd52f9adb0d86c292cfd5c0 100644 --- a/mex/sources/estimation/tests/testKalman.cc +++ b/mex/sources/estimation/tests/testKalman.cc @@ -130,4 +130,3 @@ main(int argc, char **argv) std::cout << "ll: " << std::endl << ll << std::endl; } - diff --git a/mex/sources/estimation/utils/dynamic_dll.cc b/mex/sources/estimation/utils/dynamic_dll.cc index b50d67c414773eda997937b0a6e03d2972935167..c4eeecc6815876620a3c57e0edc1ba65c59b6d3d 100644 --- a/mex/sources/estimation/utils/dynamic_dll.cc +++ b/mex/sources/estimation/utils/dynamic_dll.cc @@ -88,4 +88,3 @@ DynamicModelDLL::~DynamicModelDLL() dlclose(dynamicHinstance); #endif } - diff --git a/mex/sources/estimation/utils/dynamic_dll.hh b/mex/sources/estimation/utils/dynamic_dll.hh index 36f5b9ec30eb7306737e331584584149b4bfff98..ce346d08a09a2cdcdc2a404db4a7c5ad96dc54d4 100644 --- a/mex/sources/estimation/utils/dynamic_dll.hh +++ b/mex/sources/estimation/utils/dynamic_dll.hh @@ -32,9 +32,8 @@ #include "ts_exception.h" // <model>_Dynamic DLL pointer -typedef void (*DynamicFn) -(const double *y, const double *x, int nb_row_x, const double *params, const double *steady_state, - int it_, double *residual, double *g1, double *g2, double *g3); +typedef void (*DynamicFn)(const double *y, const double *x, int nb_row_x, const double *params, const double *steady_state, + int it_, double *residual, double *g1, double *g2, double *g3); /** * creates pointer to Dynamic function inside <model>_dynamic.dll @@ -53,12 +52,14 @@ private: public: // construct and load Dynamic model DLL DynamicModelDLL(const std::string &basename) throw (TSException); - virtual ~DynamicModelDLL(); + virtual + ~DynamicModelDLL(); //! evaluate Dynamic model DLL template<class Vec1, class Vec2, class Vec3, class Vec4, class Mat1> - void eval(const Vec1 &y, const Mat1 &x, const Vec2 &modParams, const Vec3 &ySteady, - Vec4 &residual, Matrix *g1, Matrix *g2, Matrix *g3) throw (TSException) + void + eval(const Vec1 &y, const Mat1 &x, const Vec2 &modParams, const Vec3 &ySteady, + Vec4 &residual, Matrix *g1, Matrix *g2, Matrix *g3) throw (TSException) { assert(y.getStride() == 1); assert(x.getLd() == x.getRows()); @@ -70,6 +71,6 @@ public: assert(g3->getLd() == g3->getRows()); Dynamic(y.getData(), x.getData(), 1, modParams.getData(), ySteady.getData(), 0, residual.getData(), - g1 == NULL ? NULL : g1->getData(), g2 == NULL ? NULL : g2->getData(), g3 == NULL ? NULL : g3->getData()); + g1 == NULL ? NULL : g1->getData(), g2 == NULL ? NULL : g2->getData(), g3 == NULL ? NULL : g3->getData()); }; }; diff --git a/mex/sources/estimation/utils/static_dll.hh b/mex/sources/estimation/utils/static_dll.hh index 77f183890aa45f5399ed7df406c7e48dbf187cf9..3ca5febc3fae76da9977a5dae956efe9722478d6 100644 --- a/mex/sources/estimation/utils/static_dll.hh +++ b/mex/sources/estimation/utils/static_dll.hh @@ -32,8 +32,7 @@ #include "ts_exception.h" // Pointer to the Static function in the MEX -typedef void (*StaticFn) -(const double *y, const double *x, int nb_row_x, const double *params, double *residual, double *g1, double *v2); +typedef void (*StaticFn)(const double *y, const double *x, int nb_row_x, const double *params, double *residual, double *g1, double *v2); /** * creates pointer to Dynamic function inside <model>_static.dll @@ -52,12 +51,14 @@ private: public: // construct and load Static model DLL StaticModelDLL(const std::string &basename) throw (TSException); - virtual ~StaticModelDLL(); + virtual + ~StaticModelDLL(); //! evaluate Static model DLL template<class Vec1, class Vec2, class Vec3, class Mat1> - void eval(const Vec1 &y, const Mat1 &x, const Vec2 &modParams, - Vec3 &residual, Matrix *g1, Matrix *v2) throw (TSException) + void + eval(const Vec1 &y, const Mat1 &x, const Vec2 &modParams, + Vec3 &residual, Matrix *g1, Matrix *v2) throw (TSException) { assert(y.getStride() == 1); assert(x.getLd() == x.getRows()); @@ -67,6 +68,6 @@ public: assert(v2->getLd() == v2->getRows()); Static(y.getData(), x.getData(), 1, modParams.getData(), residual.getData(), - g1 == NULL ? NULL : g1->getData(), v2 == NULL ? NULL : v2->getData()); + g1 == NULL ? NULL : g1->getData(), v2 == NULL ? NULL : v2->getData()); }; }; diff --git a/mex/sources/estimation/utils/ts_exception.h b/mex/sources/estimation/utils/ts_exception.h index b0f8ca71a0c49e0f243765ad7deb8e323fa0c34e..ba0bfb3245653acae361c43756f88b74c3846b98 100644 --- a/mex/sources/estimation/utils/ts_exception.h +++ b/mex/sources/estimation/utils/ts_exception.h @@ -70,4 +70,3 @@ public: ; #endif - diff --git a/mex/sources/k_order_perturbation/dynamic_dll.hh b/mex/sources/k_order_perturbation/dynamic_dll.hh index cf3755058e005ee2d83dcca74dc4694dd76062a7..922f1d12d522f167529a169cd79cf1eaed7a8c37 100644 --- a/mex/sources/k_order_perturbation/dynamic_dll.hh +++ b/mex/sources/k_order_perturbation/dynamic_dll.hh @@ -35,9 +35,8 @@ #include "dynare_exception.h" // <model>_Dynamic DLL pointer -typedef void (*DynamicDLLFn) -(const double *y, const double *x, int nb_row_x, const double *params, const double *steady_state, - int it_, double *residual, double *g1, double *g2, double *g3); +typedef void (*DynamicDLLFn)(const double *y, const double *x, int nb_row_x, const double *params, const double *steady_state, + int it_, double *residual, double *g1, double *g2, double *g3); /** * creates pointer to Dynamic function inside <model>_dynamic.dll @@ -56,7 +55,8 @@ private: public: // construct and load Dynamic model DLL DynamicModelDLL(const string &fname) throw (DynareException); - virtual ~DynamicModelDLL(); + virtual + ~DynamicModelDLL(); void eval(const Vector &y, const Vector &x, const Vector ¶ms, const Vector &ySteady, Vector &residual, TwoDMatrix *g1, TwoDMatrix *g2, TwoDMatrix *g3) throw (DynareException); diff --git a/mex/sources/k_order_perturbation/dynamic_m.hh b/mex/sources/k_order_perturbation/dynamic_m.hh index 632dcdd7acd157585748e3cb9cde434bf49ebdc3..746acdedcac7bff58764745ba5e8d81f806e8899 100644 --- a/mex/sources/k_order_perturbation/dynamic_m.hh +++ b/mex/sources/k_order_perturbation/dynamic_m.hh @@ -37,7 +37,8 @@ private: const static int nrhs_dynamic = 5; public: DynamicModelMFile(const string &modName) throw (DynareException); - virtual ~DynamicModelMFile(); + virtual + ~DynamicModelMFile(); void eval(const Vector &y, const Vector &x, const Vector ¶ms, const Vector &ySteady, Vector &residual, TwoDMatrix *g1, TwoDMatrix *g2, TwoDMatrix *g3) throw (DynareException); }; diff --git a/mex/sources/k_order_perturbation/k_ord_dynare.cc b/mex/sources/k_order_perturbation/k_ord_dynare.cc index 87697f0cd187e5f294795f9e911db46931323657..1fd09c4805d71283a8b956437aaa19ded92c9b08 100644 --- a/mex/sources/k_order_perturbation/k_ord_dynare.cc +++ b/mex/sources/k_order_perturbation/k_ord_dynare.cc @@ -63,7 +63,7 @@ KordpDynare::KordpDynare(const vector<string> &endo, int num_endo, const int nsteps, int norder, Journal &jr, DynamicModelAC *dynamicModelFile_arg, double sstol, const vector<int> &var_order, const TwoDMatrix &llincidence, double criterium, - TwoDMatrix *g1_arg, TwoDMatrix *g2_arg, TwoDMatrix *g3_arg) throw (TLException) : + TwoDMatrix *g1_arg, TwoDMatrix *g2_arg, TwoDMatrix *g3_arg) throw (TLException) : nStat(nstat), nBoth(nboth), nPred(npred), nForw(nforw), nExog(nexog), nPar(npar), nYs(npred + nboth), nYss(nboth + nforw), nY(num_endo), nJcols(jcols), NNZD(nnzd), nSteps(nsteps), nOrder(norder), journal(jr), ySteady(ysteady), params(inParams), vCov(vcov), @@ -116,30 +116,30 @@ KordpDynare::calcDerivativesAtSteady() { g1p = new TwoDMatrix(nY, nJcols); g1p->zeros(); - + if (nOrder > 1) - { - // allocate space for sparse Hessian - g2p = new TwoDMatrix((int) NNZD[1], 3); - g2p->zeros(); - } - + { + // allocate space for sparse Hessian + g2p = new TwoDMatrix((int) NNZD[1], 3); + g2p->zeros(); + } + if (nOrder > 2) - { - g3p = new TwoDMatrix((int) NNZD[2], 3); - g3p->zeros(); - } + { + g3p = new TwoDMatrix((int) NNZD[2], 3); + g3p->zeros(); + } Vector xx(nexog()); xx.zeros(); - + Vector out(nY); out.zeros(); Vector llxSteady(nJcols-nExog); LLxSteady(ySteady, llxSteady); - + dynamicModelFile->eval(llxSteady, xx, params, ySteady, out, g1p, g2p, g3p); - + } populateDerivativesContainer(*g1p, 1, JacobianIndices); diff --git a/mex/sources/k_order_perturbation/k_ord_dynare.hh b/mex/sources/k_order_perturbation/k_ord_dynare.hh index 869bb9660d2097a961745754d9e88d7f2a9a859b..f24cf668e6c2a6a12aad058b0b90527933e8a5a8 100644 --- a/mex/sources/k_order_perturbation/k_ord_dynare.hh +++ b/mex/sources/k_order_perturbation/k_ord_dynare.hh @@ -135,7 +135,8 @@ public: const vector<int> &varOrder, const TwoDMatrix &ll_Incidence, double qz_criterium, TwoDMatrix *g1_arg, TwoDMatrix *g2_arg, TwoDMatrix *g3_arg) throw (TLException); - virtual ~KordpDynare(); + virtual + ~KordpDynare(); int nstat() const { diff --git a/mex/sources/k_order_perturbation/k_order_perturbation.cc b/mex/sources/k_order_perturbation/k_order_perturbation.cc index f2eb3f80daeea3aef18ecb0bdd65fa950430071b..4be824595ed359a75f52465807a78a46b708fbc2 100644 --- a/mex/sources/k_order_perturbation/k_order_perturbation.cc +++ b/mex/sources/k_order_perturbation/k_order_perturbation.cc @@ -62,14 +62,15 @@ DynareMxArrayToString(const mxArray *mxFldp, const int len, const int width, vec out[j] += cNamesCharStr[j+i*len]; } -void copy_derivatives(mxArray *destin,const Symmetry &sym,const FGSContainer *derivs,const std::string &fieldname) +void +copy_derivatives(mxArray *destin, const Symmetry &sym, const FGSContainer *derivs, const std::string &fieldname) { - const TwoDMatrix* x = derivs->get(sym); + const TwoDMatrix *x = derivs->get(sym); int n = x->numRows(); int m = x->numCols(); mxArray *tmp = mxCreateDoubleMatrix(n, m, mxREAL); - memcpy(mxGetPr(tmp),x->getData().base(),n*m*sizeof(double)); - mxSetField(destin,0,fieldname.c_str(),tmp); + memcpy(mxGetPr(tmp), x->getData().base(), n*m*sizeof(double)); + mxSetField(destin, 0, fieldname.c_str(), tmp); } extern "C" { @@ -176,7 +177,7 @@ extern "C" { //get NNZH =NNZD(2) = the total number of non-zero Hessian elements mxFldp = mxGetField(M_, 0, "NNZDerivatives"); dparams = mxGetPr(mxFldp); - Vector NNZD(dparams, (int) mxGetM(mxFldp)); + Vector NNZD(dparams, (int)mxGetM(mxFldp)); if (NNZD[kOrder-1] == -1) DYN_MEX_FUNC_ERR_MSG_TXT("The derivatives were not computed for the required order. Make sure that you used the right order option inside the stoch_simul command"); @@ -197,32 +198,31 @@ extern "C" { if ((nEndo != nendo) || (nExog != nexo)) DYN_MEX_FUNC_ERR_MSG_TXT("Incorrect number of input parameters."); - TwoDMatrix *g1m=NULL; - TwoDMatrix *g2m=NULL; - TwoDMatrix *g3m=NULL; + TwoDMatrix *g1m = NULL; + TwoDMatrix *g2m = NULL; + TwoDMatrix *g3m = NULL; // derivatives passed as arguments */ - if (nrhs > 3) + if (nrhs > 3) { - const mxArray *g1 = prhs[3]; - int m = (int) mxGetM(g1); - int n = (int) mxGetN(g1); - g1m = new TwoDMatrix(m, n, mxGetPr(g1)); - if (nrhs > 4) - { - const mxArray *g2 = prhs[4]; - int m = (int) mxGetM(g2); - int n = (int) mxGetN(g2); - g2m = new TwoDMatrix(m, n, mxGetPr(g2)); - if (nrhs > 5) - { - const mxArray *g3 = prhs[5]; - int m = (int) mxGetM(g3); - int n = (int) mxGetN(g3); - g3m = new TwoDMatrix(m, n, mxGetPr(g3)); - } - } + const mxArray *g1 = prhs[3]; + int m = (int) mxGetM(g1); + int n = (int) mxGetN(g1); + g1m = new TwoDMatrix(m, n, mxGetPr(g1)); + if (nrhs > 4) + { + const mxArray *g2 = prhs[4]; + int m = (int) mxGetM(g2); + int n = (int) mxGetN(g2); + g2m = new TwoDMatrix(m, n, mxGetPr(g2)); + if (nrhs > 5) + { + const mxArray *g3 = prhs[5]; + int m = (int) mxGetM(g3); + int n = (int) mxGetN(g3); + g3m = new TwoDMatrix(m, n, mxGetPr(g3)); + } + } } - const int nSteps = 0; // Dynare++ solving steps, for time being default to 0 = deterministic steady state const double sstol = 1.e-13; //NL solver tolerance from @@ -250,7 +250,7 @@ extern "C" { ySteady, vCov, modParams, nStat, nPred, nForw, nBoth, jcols, NNZD, nSteps, kOrder, journal, dynamicModelFile, sstol, var_order_vp, llincidence, qz_criterium, - g1m, g2m, g3m); + g1m, g2m, g3m); // construct main K-order approximation class @@ -283,40 +283,40 @@ extern "C" { for (map<string, ConstTwoDMatrix>::const_iterator cit = mm.begin(); ((cit != mm.end()) && (ii < nlhs)); ++cit) { - plhs[ii] = mxCreateDoubleMatrix((*cit).second.numRows(), (*cit).second.numCols(), mxREAL); - - // Copy Dynare++ matrix into MATLAB matrix - const ConstVector &vec = (*cit).second.getData(); - assert(vec.skip() == 1); - memcpy(mxGetPr(plhs[ii]), vec.base(), vec.length() * sizeof(double)); - - ++ii; - + plhs[ii] = mxCreateDoubleMatrix((*cit).second.numRows(), (*cit).second.numCols(), mxREAL); + + // Copy Dynare++ matrix into MATLAB matrix + const ConstVector &vec = (*cit).second.getData(); + assert(vec.skip() == 1); + memcpy(mxGetPr(plhs[ii]), vec.base(), vec.length() * sizeof(double)); + + ++ii; + } - if (kOrder == 3 && nlhs > 4) - { - const FGSContainer *derivs = app.get_rule_ders(); - const std::string fieldnames[] = {"gy", "gu", "gyy", "gyu", "guu", "gss", - "gyyy", "gyyu", "gyuu", "guuu", "gyss", "guss"}; - // creates the char** expected by mxCreateStructMatrix() - const char* c_fieldnames[12]; - for (int i=0; i < 12;++i) - c_fieldnames[i] = fieldnames[i].c_str(); - plhs[ii] = mxCreateStructMatrix(1,1,12,c_fieldnames); - copy_derivatives(plhs[ii],Symmetry(1,0,0,0),derivs,"gy"); - copy_derivatives(plhs[ii],Symmetry(0,1,0,0),derivs,"gu"); - copy_derivatives(plhs[ii],Symmetry(2,0,0,0),derivs,"gyy"); - copy_derivatives(plhs[ii],Symmetry(0,2,0,0),derivs,"guu"); - copy_derivatives(plhs[ii],Symmetry(1,1,0,0),derivs,"gyu"); - copy_derivatives(plhs[ii],Symmetry(0,0,0,2),derivs,"gss"); - copy_derivatives(plhs[ii],Symmetry(3,0,0,0),derivs,"gyyy"); - copy_derivatives(plhs[ii],Symmetry(0,3,0,0),derivs,"guuu"); - copy_derivatives(plhs[ii],Symmetry(2,1,0,0),derivs,"gyyu"); - copy_derivatives(plhs[ii],Symmetry(1,2,0,0),derivs,"gyuu"); - copy_derivatives(plhs[ii],Symmetry(1,0,0,2),derivs,"gyss"); - copy_derivatives(plhs[ii],Symmetry(0,1,0,2),derivs,"guss"); - } - } + if (kOrder == 3 && nlhs > 4) + { + const FGSContainer *derivs = app.get_rule_ders(); + const std::string fieldnames[] = {"gy", "gu", "gyy", "gyu", "guu", "gss", + "gyyy", "gyyu", "gyuu", "guuu", "gyss", "guss"}; + // creates the char** expected by mxCreateStructMatrix() + const char *c_fieldnames[12]; + for (int i = 0; i < 12; ++i) + c_fieldnames[i] = fieldnames[i].c_str(); + plhs[ii] = mxCreateStructMatrix(1, 1, 12, c_fieldnames); + copy_derivatives(plhs[ii], Symmetry(1, 0, 0, 0), derivs, "gy"); + copy_derivatives(plhs[ii], Symmetry(0, 1, 0, 0), derivs, "gu"); + copy_derivatives(plhs[ii], Symmetry(2, 0, 0, 0), derivs, "gyy"); + copy_derivatives(plhs[ii], Symmetry(0, 2, 0, 0), derivs, "guu"); + copy_derivatives(plhs[ii], Symmetry(1, 1, 0, 0), derivs, "gyu"); + copy_derivatives(plhs[ii], Symmetry(0, 0, 0, 2), derivs, "gss"); + copy_derivatives(plhs[ii], Symmetry(3, 0, 0, 0), derivs, "gyyy"); + copy_derivatives(plhs[ii], Symmetry(0, 3, 0, 0), derivs, "guuu"); + copy_derivatives(plhs[ii], Symmetry(2, 1, 0, 0), derivs, "gyyu"); + copy_derivatives(plhs[ii], Symmetry(1, 2, 0, 0), derivs, "gyuu"); + copy_derivatives(plhs[ii], Symmetry(1, 0, 0, 2), derivs, "gyss"); + copy_derivatives(plhs[ii], Symmetry(0, 1, 0, 2), derivs, "guss"); + } + } } catch (const KordException &e) { 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 d4f50cc57d6096d4fb42bf4045cdc57cc5a5a84e..be71632d69c20ca901537b0ead46ce7fe271f7e6 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) ) + if ((nrhs > 4) || (nrhs < 3)) DYN_MEX_FUNC_ERR_MSG_TXT("sparse_hessian_times_B_kronecker_C takes 3 or 4 input arguments and provides 2 output arguments."); if (!mxIsSparse(prhs[0])) diff --git a/mex/sources/linsolve/linsolve.cc b/mex/sources/linsolve/linsolve.cc index b33cf2f4564496715f367757e8539c03dfd24291..daec3999fc38aea07d56bc8154a15a88ef60d082 100644 --- a/mex/sources/linsolve/linsolve.cc +++ b/mex/sources/linsolve/linsolve.cc @@ -28,7 +28,6 @@ * along with Dynare. If not, see <http://www.gnu.org/licenses/>. */ - #include <octave/oct.h> #include <octave/ov-struct.h> @@ -81,10 +80,9 @@ If requested, @var{r} will contain the reciprocal condition number.\n\ return retval; } - MatrixType typA; typA.mark_as_full(); - + bool transa = false; if (nargin == 3) { diff --git a/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc b/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc index de78ff2e4503de2933df1229008fd812a8b96a96..19cc5739e9b29fde76c45c3a893407e8db605f98 100644 --- a/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc +++ b/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc @@ -29,23 +29,24 @@ #include <dynblas.h> #ifdef USE_OMP -#include <omp.h> +# include <omp.h> #endif using namespace std; #define FIRST_ORDER_LOOP 1// Comment out this line to use mkl-blas instead of loops when computing ghx*yhat and ghu*epsilon -void set_vector_of_indices(const int n, const int r, vector<int> &v1, vector<int> &v2, vector<int> &v3) +void +set_vector_of_indices(const int n, const int r, vector<int> &v1, vector<int> &v2, vector<int> &v3) { const int m = n*(n+1)/2; - v1.resize(m,0); - v2.resize(m,0); - v3.resize(m,0); - for(int i=0, index=0, jndex=0;i<n; i++) + v1.resize(m, 0); + v2.resize(m, 0); + v3.resize(m, 0); + for (int i = 0, index = 0, jndex = 0; i < n; i++) { - jndex+=i; - for(int j=i; j<n; j++, index++, jndex++) + jndex += i; + for (int j = i; j < n; j++, index++, jndex++) { v1[index] = i; v2[index] = j; @@ -54,191 +55,191 @@ void set_vector_of_indices(const int n, const int r, vector<int> &v1, vector<int } } -void ss2Iteration_pruning(double* y2, double* y1, const double* yhat2, const double* yhat1, const double *epsilon, - double* ghx, double* ghu, - const double* constant, const double* ghxx, const double* ghuu, const double* ghxu, const double* ss, - const blas_int m, const blas_int n, const blas_int q, const blas_int s, const int number_of_threads) +void +ss2Iteration_pruning(double *y2, double *y1, const double *yhat2, const double *yhat1, const double *epsilon, + double *ghx, double *ghu, + const double *constant, const double *ghxx, const double *ghuu, const double *ghxu, const double *ss, + const blas_int m, const blas_int n, const blas_int q, const blas_int s, const int number_of_threads) { - #ifndef FIRST_ORDER_LOOP - const char transpose[2] = "N"; - const double one = 1.0; - const blas_int ONE = 1; - #endif +#ifndef FIRST_ORDER_LOOP + const char transpose[2] = "N"; + const double one = 1.0; + const blas_int ONE = 1; +#endif vector<int> ii1, ii2, ii3;// vector indices for ghxx vector<int> jj1, jj2, jj3;// vector indices for ghuu set_vector_of_indices(n, m, ii1, ii2, ii3); set_vector_of_indices(q, m, jj1, jj2, jj3); - #ifdef USE_OMP - #pragma omp parallel for num_threads(number_of_threads) - #endif - for (int particle = 0; particle<s; particle++) - { - int particle_ = particle*m; - int particle__ = particle*n; - int particle___ = particle*q; - memcpy(&y2[particle_],&constant[0],m*sizeof(double)); - memcpy(&y1[particle_],&ss[0],m*sizeof(double)); - #ifndef FIRST_ORDER_LOOP - dgemv(transpose,&m,&n,&one,&ghx[0],&m,&yhat2[particle__],&ONE,&one,&y2[particle_],&ONE); - dgemv(transpose,&m,&q,&one,&ghu[0],&m,&epsilon[particle___],&ONE,&one,&y2[particle_],&ONE); - #endif - for (int variable = 0; variable<m; variable++) - { - int variable_ = variable + particle_; - // +ghx*yhat2+ghu*u - #ifdef FIRST_ORDER_LOOP - for (int column = 0, column_=0; column<q; column++, column_ += m) - { - int i1 = variable+column_; - int i2 = column+particle__; - int i3 = column+particle___; - y2[variable_] += ghx[i1]*yhat2[i2]; - y2[variable_] += ghu[i1]*epsilon[i3]; - } - for (int column = q, column_=q*m; column<n; column++, column_ += m) - { - y2[variable_] += ghx[variable+column_]*yhat2[column+particle__]; - } - #endif - // +ghxx*kron(yhat1,yhat1) - for(int i=0; i<n*(n+1)/2; i++) - { - int i1 = particle__+ii1[i]; - int i2 = particle__+ii2[i]; - if(i1==i2) - { - y2[variable_] += .5*ghxx[variable+ii3[i]]*yhat1[i1]*yhat1[i1]; - } - else - { - y2[variable_] += ghxx[variable+ii3[i]]*yhat1[i1]*yhat1[i2]; - } - } - // +ghuu*kron(u,u) - for(int j=0; j<q*(q+1)/2; j++) - { - int j1 = particle___+jj1[j]; - int j2 = particle___+jj2[j]; - if(j1==j2) - { - y2[variable_] += .5*ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j1]; - } - else - { - y2[variable_] += ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j2]; - } - } - // +ghxu*kron(yhat1,u) - for (int v = particle__, i = 0; v<particle__+n; v++) - for (int s = particle___; s<particle___+q; s++, i += m) - y2[variable_] += ghxu[variable+i]*epsilon[s]*yhat2[v]; - #ifdef FIRST_ORDER_LOOP - for (int column = 0, column_=0; column<q; column++, column_ += m) - { - int i1 = variable+column_; - int i2 = column+particle__; - int i3 = column+particle___; - y1[variable_] += ghx[i1]*yhat1[i2]; - y1[variable_] += ghu[i1]*epsilon[i3]; - } - for (int column = q, column_=q*m; column<n; column++, column_ += m) - { - y1[variable_] += ghx[variable+column_]*yhat1[column+particle__]; - } - #endif - } - #ifndef FIRST_ORDER_LOOP - dgemv(transpose,&m,&n,&one,&ghx[0],&m,&yhat1[particle__],&ONE,&one,&y1[particle_],&ONE); - dgemv(transpose,&m,&q,&one,&ghu[0],&m,&epsilon[particle___],&ONE,&one,&y1[particle_],&ONE); - #endif - } +#ifdef USE_OMP +# pragma omp parallel for num_threads(number_of_threads) +#endif + for (int particle = 0; particle < s; particle++) + { + int particle_ = particle*m; + int particle__ = particle*n; + int particle___ = particle*q; + memcpy(&y2[particle_], &constant[0], m*sizeof(double)); + memcpy(&y1[particle_], &ss[0], m*sizeof(double)); +#ifndef FIRST_ORDER_LOOP + dgemv(transpose, &m, &n, &one, &ghx[0], &m, &yhat2[particle__], &ONE, &one, &y2[particle_], &ONE); + dgemv(transpose, &m, &q, &one, &ghu[0], &m, &epsilon[particle___], &ONE, &one, &y2[particle_], &ONE); +#endif + for (int variable = 0; variable < m; variable++) + { + int variable_ = variable + particle_; + // +ghx*yhat2+ghu*u +#ifdef FIRST_ORDER_LOOP + for (int column = 0, column_ = 0; column < q; column++, column_ += m) + { + int i1 = variable+column_; + int i2 = column+particle__; + int i3 = column+particle___; + y2[variable_] += ghx[i1]*yhat2[i2]; + y2[variable_] += ghu[i1]*epsilon[i3]; + } + for (int column = q, column_ = q*m; column < n; column++, column_ += m) + { + y2[variable_] += ghx[variable+column_]*yhat2[column+particle__]; + } +#endif + // +ghxx*kron(yhat1,yhat1) + for (int i = 0; i < n*(n+1)/2; i++) + { + int i1 = particle__+ii1[i]; + int i2 = particle__+ii2[i]; + if (i1 == i2) + { + y2[variable_] += .5*ghxx[variable+ii3[i]]*yhat1[i1]*yhat1[i1]; + } + else + { + y2[variable_] += ghxx[variable+ii3[i]]*yhat1[i1]*yhat1[i2]; + } + } + // +ghuu*kron(u,u) + for (int j = 0; j < q*(q+1)/2; j++) + { + int j1 = particle___+jj1[j]; + int j2 = particle___+jj2[j]; + if (j1 == j2) + { + y2[variable_] += .5*ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j1]; + } + else + { + y2[variable_] += ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j2]; + } + } + // +ghxu*kron(yhat1,u) + for (int v = particle__, i = 0; v < particle__+n; v++) + for (int s = particle___; s < particle___+q; s++, i += m) + y2[variable_] += ghxu[variable+i]*epsilon[s]*yhat2[v]; +#ifdef FIRST_ORDER_LOOP + for (int column = 0, column_ = 0; column < q; column++, column_ += m) + { + int i1 = variable+column_; + int i2 = column+particle__; + int i3 = column+particle___; + y1[variable_] += ghx[i1]*yhat1[i2]; + y1[variable_] += ghu[i1]*epsilon[i3]; + } + for (int column = q, column_ = q*m; column < n; column++, column_ += m) + { + y1[variable_] += ghx[variable+column_]*yhat1[column+particle__]; + } +#endif + } +#ifndef FIRST_ORDER_LOOP + dgemv(transpose, &m, &n, &one, &ghx[0], &m, &yhat1[particle__], &ONE, &one, &y1[particle_], &ONE); + dgemv(transpose, &m, &q, &one, &ghu[0], &m, &epsilon[particle___], &ONE, &one, &y1[particle_], &ONE); +#endif + } } -void ss2Iteration(double* y, const double* yhat, const double *epsilon, - double* ghx, double* ghu, - const double* constant, const double* ghxx, const double* ghuu, const double* ghxu, - const blas_int m, const blas_int n, const blas_int q, const blas_int s, const int number_of_threads) +void +ss2Iteration(double *y, const double *yhat, const double *epsilon, + double *ghx, double *ghu, + const double *constant, const double *ghxx, const double *ghuu, const double *ghxu, + const blas_int m, const blas_int n, const blas_int q, const blas_int s, const int number_of_threads) { - #ifndef FIRST_ORDER_LOOP - const char transpose[2] = "N"; - const double one = 1.0; - const blas_int ONE = 1; - #endif +#ifndef FIRST_ORDER_LOOP + const char transpose[2] = "N"; + const double one = 1.0; + const blas_int ONE = 1; +#endif vector<int> ii1, ii2, ii3;// vector indices for ghxx vector<int> jj1, jj2, jj3;// vector indices for ghuu set_vector_of_indices(n, m, ii1, ii2, ii3); set_vector_of_indices(q, m, jj1, jj2, jj3); - #ifdef USE_OMP - #pragma omp parallel for num_threads(number_of_threads) - #endif - for (int particle = 0; particle<s; particle++) - { - int particle_ = particle*m; - int particle__ = particle*n; - int particle___ = particle*q; - memcpy(&y[particle_],&constant[0],m*sizeof(double)); - #ifndef FIRST_ORDER_LOOP - dgemv(transpose,&m,&n,&one,&ghx[0],&m,&yhat[particle__],&ONE,&one,&y[particle_],&ONE); - dgemv(transpose,&m,&q,&one,&ghu[0],&m,&epsilon[particle___],&ONE,&one,&y[particle_],&ONE); - #endif - for (int variable = 0; variable<m; variable++) - { - int variable_ = variable + particle_; - // +ghx*yhat+ghu*u - #ifdef FIRST_ORDER_LOOP - for (int column = 0, column_=0; column<q; column++, column_ += m) - { - int i1 = variable+column_; - int i2 = column+particle__; - int i3 = column+particle___; - y[variable_] += ghx[i1]*yhat[i2]; - y[variable_] += ghu[i1]*epsilon[i3]; - } - for (int column = q, column_=q*m; column<n; column++, column_ += m) - { - y[variable_] += ghx[variable+column_]*yhat[column+particle__]; - } - #endif - // +ghxx*kron(yhat,yhat) - for(int i=0; i<n*(n+1)/2; i++) - { - int i1 = particle__+ii1[i]; - int i2 = particle__+ii2[i]; - if(i1==i2) - { - y[variable_] += .5*ghxx[variable+ii3[i]]*yhat[i1]*yhat[i1]; - } - else - { - y[variable_] += ghxx[variable+ii3[i]]*yhat[i1]*yhat[i2]; - } - } - // +ghuu*kron(u,u) - for(int j=0; j<q*(q+1)/2; j++) - { - int j1 = particle___+jj1[j]; - int j2 = particle___+jj2[j]; - if(j1==j2) - { - y[variable_] += .5*ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j1]; - } - else - { - y[variable_] += ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j2]; - } - } - // +ghxu*kron(yhat,u) - for (int v = particle__, i = 0; v<particle__+n; v++) - for (int s = particle___; s<particle___+q; s++, i += m) - y[variable_] += ghxu[variable+i]*epsilon[s]*yhat[v]; - } - } +#ifdef USE_OMP +# pragma omp parallel for num_threads(number_of_threads) +#endif + for (int particle = 0; particle < s; particle++) + { + int particle_ = particle*m; + int particle__ = particle*n; + int particle___ = particle*q; + memcpy(&y[particle_], &constant[0], m*sizeof(double)); +#ifndef FIRST_ORDER_LOOP + dgemv(transpose, &m, &n, &one, &ghx[0], &m, &yhat[particle__], &ONE, &one, &y[particle_], &ONE); + dgemv(transpose, &m, &q, &one, &ghu[0], &m, &epsilon[particle___], &ONE, &one, &y[particle_], &ONE); +#endif + for (int variable = 0; variable < m; variable++) + { + int variable_ = variable + particle_; + // +ghx*yhat+ghu*u +#ifdef FIRST_ORDER_LOOP + for (int column = 0, column_ = 0; column < q; column++, column_ += m) + { + int i1 = variable+column_; + int i2 = column+particle__; + int i3 = column+particle___; + y[variable_] += ghx[i1]*yhat[i2]; + y[variable_] += ghu[i1]*epsilon[i3]; + } + for (int column = q, column_ = q*m; column < n; column++, column_ += m) + { + y[variable_] += ghx[variable+column_]*yhat[column+particle__]; + } +#endif + // +ghxx*kron(yhat,yhat) + for (int i = 0; i < n*(n+1)/2; i++) + { + int i1 = particle__+ii1[i]; + int i2 = particle__+ii2[i]; + if (i1 == i2) + { + y[variable_] += .5*ghxx[variable+ii3[i]]*yhat[i1]*yhat[i1]; + } + else + { + y[variable_] += ghxx[variable+ii3[i]]*yhat[i1]*yhat[i2]; + } + } + // +ghuu*kron(u,u) + for (int j = 0; j < q*(q+1)/2; j++) + { + int j1 = particle___+jj1[j]; + int j2 = particle___+jj2[j]; + if (j1 == j2) + { + y[variable_] += .5*ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j1]; + } + else + { + y[variable_] += ghuu[variable+jj3[j]]*epsilon[j1]*epsilon[j2]; + } + } + // +ghxu*kron(yhat,u) + for (int v = particle__, i = 0; v < particle__+n; v++) + for (int s = particle___; s < particle___+q; s++, i += m) + y[variable_] += ghxu[variable+i]*epsilon[s]*yhat[v]; + } + } } - - - -void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +void +mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* ** prhs[0] yhat [double] n*s array, time t particles. @@ -275,27 +276,27 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) //mexPrintf("\n The number of column of epsilon is %d.", mxGetN(prhs[1])); // Check the dimensions. if ( - (s != mxGetN(prhs[1])) || // Number of columns for epsilon - (n != mxGetN(prhs[2])) || // Number of columns for ghx - (m != mxGetM(prhs[3])) || // Number of rows for ghu - (q != mxGetN(prhs[3])) || // Number of columns for ghu - (m != mxGetM(prhs[4])) || // Number of rows for 2nd order constant correction + deterministic steady state - (m != mxGetM(prhs[5])) || // Number of rows for ghxx - (n*n != mxGetN(prhs[5])) || // Number of columns for ghxx - (m != mxGetM(prhs[6])) || // Number of rows for ghuu - (q*q != mxGetN(prhs[6])) || // Number of columns for ghuu - (m != mxGetM(prhs[7])) || // Number of rows for ghxu - (n*q != mxGetN(prhs[7])) // Number of rows for ghxu + (s != mxGetN(prhs[1])) // Number of columns for epsilon + || (n != mxGetN(prhs[2])) // Number of columns for ghx + || (m != mxGetM(prhs[3])) // Number of rows for ghu + || (q != mxGetN(prhs[3])) // Number of columns for ghu + || (m != mxGetM(prhs[4])) // Number of rows for 2nd order constant correction + deterministic steady state + || (m != mxGetM(prhs[5])) // Number of rows for ghxx + || (n*n != mxGetN(prhs[5])) // Number of columns for ghxx + || (m != mxGetM(prhs[6])) // Number of rows for ghuu + || (q*q != mxGetN(prhs[6])) // Number of columns for ghuu + || (m != mxGetM(prhs[7])) // Number of rows for ghxu + || (n*q != mxGetN(prhs[7])) // Number of rows for ghxu ) { mexErrMsgTxt("Input dimension mismatch!."); } - if (nrhs>9) + if (nrhs > 9) { if ( - (n != mxGetM(prhs[8])) || // Number of rows for yhat_ - (s != mxGetN(prhs[8])) || // Number of columns for yhat_ - (m != mxGetM(prhs[9])) // Number of rows for ss + (n != mxGetM(prhs[8])) // Number of rows for yhat_ + || (s != mxGetN(prhs[8])) // Number of columns for yhat_ + || (m != mxGetM(prhs[9])) // Number of rows for ss ) { mexErrMsgTxt("Input dimension mismatch!."); @@ -311,12 +312,12 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) double *ghuu = mxGetPr(prhs[6]); double *ghxu = mxGetPr(prhs[7]); double *yhat_ = NULL, *ss = NULL; - if (nrhs>9) + if (nrhs > 9) { yhat_ = mxGetPr(prhs[8]); ss = mxGetPr(prhs[9]); } - if (nrhs==9) + if (nrhs == 9) { int numthreads = (int) mxGetScalar(prhs[8]); double *y; diff --git a/mex/sources/mjdgges/mjdgges.c b/mex/sources/mjdgges/mjdgges.c index 700f769b8ef848ba57b153a5d852c9c42e756985..c73165d3509342b489580c4284572405ad200295 100644 --- a/mex/sources/mjdgges/mjdgges.c +++ b/mex/sources/mjdgges/mjdgges.c @@ -28,7 +28,7 @@ double criterium; lapack_int my_criteria(const double *alphar, const double *alphai, const double *beta) { - return ((*alphar * *alphar + *alphai * *alphai) < criterium * *beta * *beta); + return ((*alphar **alphar + *alphai **alphai) < criterium **beta **beta); } void @@ -60,15 +60,15 @@ mjdgges(double *a, double *b, double *z, double *n, double *sdim, double *eval_r pei = eval_i; for (per = eval_r; per <= &eval_r[i_n-1]; ++per) { - if ((fabs(*par) > zhreshold) || (fabs(*pb) > zhreshold)) - *per = *par / *pb; + if ((fabs(*par) > zhreshold) || (fabs(*pb) > zhreshold)) + *per = *par / *pb; else - { - /* the ratio is too close to 0/0; - returns specific error number only if no other error */ - if (i_info == 0) - *info = -30; - } + { + /* the ratio is too close to 0/0; + returns specific error number only if no other error */ + if (i_info == 0) + *info = -30; + } if (*pai == 0.0 && *pb == 0.0) *pei = 0.0; else @@ -147,7 +147,6 @@ mexFunction(int nlhs, mxArray *plhs[], zhreshold = 1e-6; } - /* keep a and b intact */ memcpy(s, a, sizeof(double)*n1*n1); memcpy(t, b, sizeof(double)*n1*n1); diff --git a/mex/sources/ms-sbvar/mex_top_level.cc b/mex/sources/ms-sbvar/mex_top_level.cc index f4aff318198b1ba44ecc62a26a2449c95f060b05..4ca78b408f8ed3eb633f5f222a9f528ae02e76d2 100644 --- a/mex/sources/ms-sbvar/mex_top_level.cc +++ b/mex/sources/ms-sbvar/mex_top_level.cc @@ -48,16 +48,16 @@ mexFunction(int nlhs, mxArray *plhs[], /* * Allocate memory */ - maxnargs = (int)(mxGetN(prhs[0])/2+1); - argument = (char *)mxCalloc(mxGetN(prhs[0])+1, sizeof(char)); - args = (char **)mxCalloc(maxnargs, sizeof(char *)); - if (argument==NULL || args==NULL) + maxnargs = (int) (mxGetN(prhs[0])/2+1); + argument = (char *) mxCalloc(mxGetN(prhs[0])+1, sizeof(char)); + args = (char **) mxCalloc(maxnargs, sizeof(char *)); + if (argument == NULL || args == NULL) DYN_MEX_FUNC_ERR_MSG_TXT("Error in MS-SBVAR MEX file: could not allocate memory. (1)"); /* * Create argument string from prhs and parse to create args / nargs */ - if (!(args[nargs] = (char *)mxCalloc(strlen(mainarg)+1, sizeof(char)))) + if (!(args[nargs] = (char *) mxCalloc(strlen(mainarg)+1, sizeof(char)))) DYN_MEX_FUNC_ERR_MSG_TXT("Error in MS-SBVAR MEX file: could not allocate memory. (2)"); strncpy(args[nargs++], mainarg, strlen(mainarg)); @@ -66,9 +66,9 @@ mexFunction(int nlhs, mxArray *plhs[], DYN_MEX_FUNC_ERR_MSG_TXT("Error in MS-SBVAR MEX file: error using mxGetString.\n"); beginarg = &argument[0]; - while((n=strcspn(beginarg, " "))) + while ((n = strcspn(beginarg, " "))) { - if (!(args[nargs] = (char *)mxCalloc(n+1, sizeof(char)))) + if (!(args[nargs] = (char *) mxCalloc(n+1, sizeof(char)))) DYN_MEX_FUNC_ERR_MSG_TXT("Error in MS-SBVAR MEX file: could not allocate memory. (3)"); strncpy(args[nargs++], beginarg, n); @@ -91,7 +91,7 @@ mexFunction(int nlhs, mxArray *plhs[], /* * free memory */ - for (n=0; n<nargs; n++) + for (n = 0; n < nargs; n++) mxFree(args[n]); mxFree(args); diff --git a/mex/sources/ms-sbvar/mex_write_to_matlab.c b/mex/sources/ms-sbvar/mex_write_to_matlab.c index 7f188786d278017b172d949736130441b2a21064..8f7a5c58042225d569bc3e482c2586f24b252272 100644 --- a/mex/sources/ms-sbvar/mex_write_to_matlab.c +++ b/mex/sources/ms-sbvar/mex_write_to_matlab.c @@ -31,9 +31,9 @@ mex_write_to_matlab_matfile(double *data, int rows, int cols, const char *varnam if (matfile == NULL) mexErrMsgTxt("Error encountered in mex when opening a .mat file"); - if (matPutVariable(matfile, varname, toWrite) != 0 || - ferror(matGetFp(matfile)) > 0 || - feof(matGetFp(matfile)) > 0) + if (matPutVariable(matfile, varname, toWrite) != 0 + || ferror(matGetFp(matfile)) > 0 + || feof(matGetFp(matfile)) > 0) mexErrMsgTxt("Error encountered in mex when writing a .mat file"); if (matClose(matfile) != 0) diff --git a/mex/sources/ms-sbvar/modify_for_mex.h b/mex/sources/ms-sbvar/modify_for_mex.h index b42f3f6c70f4c9ff4d3b632c7503b28407c3cd3f..1048d64cb38ceb620c005f9e59f4582efac5024b 100644 --- a/mex/sources/ms-sbvar/modify_for_mex.h +++ b/mex/sources/ms-sbvar/modify_for_mex.h @@ -22,29 +22,29 @@ #if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE) -#include <dynmex.h> -#include <dynblas.h> -#include <dynlapack.h> +# include <dynmex.h> +# include <dynblas.h> +# include <dynlapack.h> -#define dw_malloc mxMalloc -#define dw_calloc mxCalloc -#define dw_realloc mxRealloc -#define dw_free mxFree -#define dw_exit msExit +# define dw_malloc mxMalloc +# define dw_calloc mxCalloc +# define dw_realloc mxRealloc +# define dw_free mxFree +# define dw_exit msExit /* Handle Ctrl-C in Matlab/Octave */ -#ifdef MATLAB_MEX_FILE +# ifdef MATLAB_MEX_FILE extern bool utIsInterruptPending(); -#else -#include <octave/config.h> -#include <octave/quit.h> -#endif +# else +# include <octave/config.h> +# include <octave/quit.h> +# endif void msExit(int status); extern int constant_seed; -/* Write Matlab Output -mxArray *globalMatlabStruct;*/ +/* Write Matlab Output + mxArray *globalMatlabStruct;*/ void mex_write_to_matlab_matfile(double *, int, int, const char *, const char *); void mex_write_to_matlab_global_struct(double *, int, int, const char *); mxArray *getMxArray(double *, int, int); diff --git a/mex/sources/qzcomplex/qzcomplex.cc b/mex/sources/qzcomplex/qzcomplex.cc index 7b95ce76f463608881ebb7cab374a6dbd25110f8..92cf7f7aeaadd27445fbbf91e0c2e64bba9a54b6 100644 --- a/mex/sources/qzcomplex/qzcomplex.cc +++ b/mex/sources/qzcomplex/qzcomplex.cc @@ -25,15 +25,15 @@ */ #ifdef __MINGW32__ -#define __CROSS_COMPILATION__ +# define __CROSS_COMPILATION__ #endif #ifdef __MINGW64__ -#define __CROSS_COMPILATION__ +# define __CROSS_COMPILATION__ #endif #ifdef __CROSS_COMPILATION__ -#define M_PI 3.14159265358979323846 +# define M_PI 3.14159265358979323846 #endif #include <octave/oct.h> diff --git a/mex/sources/sobol/gaussian.hh b/mex/sources/sobol/gaussian.hh index 4506117731ff409b5ef26adc9ca2e34ef8ea8f73..8692814f4825665b11a7969dbbe66cfbbaf9410a 100644 --- a/mex/sources/sobol/gaussian.hh +++ b/mex/sources/sobol/gaussian.hh @@ -1,6 +1,6 @@ /* Generates gaussian random deviates from uniform random deviates. -** -** Pseudo code of the algorithm is given at http://home.online.no/~pjacklam/notes/invnorm +** +** Pseudo code of the algorithm is given at http://home.online.no/~pjacklam/notes/invnorm ** ** Copyright (C) 2010-2016 Dynare Team ** @@ -18,8 +18,8 @@ ** ** You should have received a copy of the GNU General Public License ** along with Dynare. If not, see <http://www.gnu.org/licenses/>. -** -** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr +** +** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr */ #include <cstdlib> @@ -41,58 +41,60 @@ using namespace std; #define DEBUG_OMP 0 #ifdef __MINGW32__ -#define __CROSS_COMPILATION__ +# define __CROSS_COMPILATION__ #endif #ifdef __MINGW64__ -#define __CROSS_COMPILATION__ +# define __CROSS_COMPILATION__ #endif #ifdef __CROSS_COMPILATION__ -#define M_PI 3.14159265358979323846 +# define M_PI 3.14159265358979323846 #endif -template<typename T> T icdf( const T uniform ) +template<typename T> +T +icdf(const T uniform) /* ** This function invert the gaussian cumulative distribution function. ** */ -{ - static T A[6] = +{ + static T A[6] = { -3.969683028665376e+01, - 2.209460984245205e+02, + 2.209460984245205e+02, -2.759285104469687e+02, - 1.383577518672690e+02, + 1.383577518672690e+02, -3.066479806614716e+01, - 2.506628277459239e+00 + 2.506628277459239e+00 }; - static T B[5] = + static T B[5] = { -5.447609879822406e+01, - 1.615858368580409e+02, + 1.615858368580409e+02, -1.556989798598866e+02, - 6.680131188771972e+01, + 6.680131188771972e+01, -1.328068155288572e+01 }; - static T C[6] = + static T C[6] = { -7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00, -2.549732539343734e+00, - 4.374664141464968e+00, - 2.938163982698783e+00 + 4.374664141464968e+00, + 2.938163982698783e+00 }; - static T D[4] = + static T D[4] = { 7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00, 3.754408661907416e+00 }; - T gaussian = (T)0.0; - if ( (0<uniform) && (uniform<lb) ) + T gaussian = (T) 0.0; + if ((0 < uniform) && (uniform < lb)) { T tmp; tmp = sqrt(-2*log(uniform)); @@ -117,65 +119,71 @@ template<typename T> T icdf( const T uniform ) } } } - if ( (0<uniform) && (uniform<1) ) + if ((0 < uniform) && (uniform < 1)) { T tmp, tmp_; tmp = .5*erfc(-gaussian/sqrt(2.0))-uniform; tmp_ = tmp*sqrt(2*M_PI)*exp(.5*gaussian*gaussian); gaussian = gaussian - tmp_/(1+.5*gaussian*tmp_); } - if ( uniform==0) + if (uniform == 0) { gaussian = -INFINITY; } - if ( uniform==1) + if (uniform == 1) { gaussian = INFINITY; } - return(gaussian); + return (gaussian); } -template<typename T> void icdfm( const int n, T *U) -{ - #if USE_OMP - #pragma omp parallel for num_threads(omp_get_num_threads()) - #endif - for(int i=0; i<n; i++) +template<typename T> +void +icdfm(const int n, T *U) +{ +#if USE_OMP +# pragma omp parallel for num_threads(omp_get_num_threads()) +#endif + for (int i = 0; i < n; i++) { U[i] = icdf(U[i]); } return; } -template<typename T> void icdfmSigma( const int d, const int n, T *U, const double *LowerCholSigma) -{ +template<typename T> +void +icdfmSigma(const int d, const int n, T *U, const double *LowerCholSigma) +{ double one = 1.0; double zero = 0.0; blas_int dd(d); blas_int nn(n); icdfm(n*d, U); double tmp[n*d]; - dgemm("N","N",&dd,&nn,&dd,&one,LowerCholSigma,&dd,U,&dd,&zero,tmp,&dd); - memcpy(U,tmp,d*n*sizeof(double)); + dgemm("N", "N", &dd, &nn, &dd, &one, LowerCholSigma, &dd, U, &dd, &zero, tmp, &dd); + memcpy(U, tmp, d*n*sizeof(double)); return; } -template<typename T> void usphere( const int d, const int n, T *U) -{ +template<typename T> +void +usphere(const int d, const int n, T *U) +{ icdfm(n*d, U); - #if USE_OMP - #pragma omp parallel for num_threads(omp_get_num_threads()) - #endif - for (int j=0; j<n; j++)// sequence index. +#if USE_OMP +# pragma omp parallel for num_threads(omp_get_num_threads()) +#endif + for (int j = 0; j < n; j++)// sequence index. { int k = j*d; double norm = 0.0; - for(int i=0; i<d; i++)// dimension index. + for (int i = 0; i < d; i++)// dimension index. { norm = norm + U[k+i]*U[k+i]; } norm = sqrt(norm); - for(int i=0; i<d; i++)// dimension index. + for (int i = 0; i < d; i++)// dimension index. { U[k+i] = U[k+i]/norm; } @@ -183,22 +191,24 @@ template<typename T> void usphere( const int d, const int n, T *U) return; } -template<typename T> void usphereRadius( const int d, const int n, double radius, T *U) -{ +template<typename T> +void +usphereRadius(const int d, const int n, double radius, T *U) +{ icdfm(n*d, U); - #if USE_OMP - #pragma omp parallel for num_threads(omp_get_num_threads()) - #endif - for (int j=0; j<n; j++)// sequence index. +#if USE_OMP +# pragma omp parallel for num_threads(omp_get_num_threads()) +#endif + for (int j = 0; j < n; j++)// sequence index. { int k = j*d; double norm = 0.0; - for(int i=0; i<d; i++)// dimension index. + for (int i = 0; i < d; i++)// dimension index. { norm = norm + U[k+i]*U[k+i]; } norm = sqrt(norm); - for(int i=0; i<d; i++)// dimension index. + for (int i = 0; i < d; i++)// dimension index. { U[k+i] = radius*U[k+i]/norm; } diff --git a/mex/sources/sobol/initialize_v_array.hh b/mex/sources/sobol/initialize_v_array.hh index ac6a09b6b495638337f752eec519f59e0329d101..c276701f4fafbd06b2bdecd0a5fd0c384d72d6a1 100644 --- a/mex/sources/sobol/initialize_v_array.hh +++ b/mex/sources/sobol/initialize_v_array.hh @@ -1,6 +1,8 @@ -template<typename T> int initialize_v_array (int dim_max, int log_max, T **v) +template<typename T> +int +initialize_v_array(int dim_max, int log_max, T **v) /* -** This function initializes the v array used in the sobol routine. +** This function initializes the v array used in the sobol routine. ** ** Original files downloaded from http://people.sc.fsu.edu/~burkardt/cpp_src/sobol/ (version 17-Feb-2009 09:46) ** @@ -23,6 +25,6 @@ template<typename T> int initialize_v_array (int dim_max, int log_max, T **v) ** AUTHOR(S): stephane DOT adjemian AT univ DASH lemans DOT fr */ { - #include "initialize_v_array.inc" +#include "initialize_v_array.inc" return 1; } diff --git a/mex/sources/sobol/qmc_sequence.cc b/mex/sources/sobol/qmc_sequence.cc index 72f530c61291f3ed4686b6e6dfdbbafb8a0d1b7f..76d2e0d166a0d06b3a2f98f873ce17b82ee9ace0 100644 --- a/mex/sources/sobol/qmc_sequence.cc +++ b/mex/sources/sobol/qmc_sequence.cc @@ -32,9 +32,10 @@ // the maximum dimension defined in sobol.ff (but undef at the end) #define DIM_MAX 1111 -void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +void +mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { - /* + /* ** INPUTS: ** prhs[0] [integer] scalar, dimension. ** prhs[1] [integer] scalar, seed. @@ -51,12 +52,12 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) ** plhs[0] [double] sequence_size*dimension array, the Sobol sequence. ** plhs[1] [integer] scalar, seed. ** plhs[2] [integer] zero in case of success, one in case of error - ** + ** */ /* ** Check the number of input and output arguments. */ - if ( !( (nrhs==5) | (nrhs==4) | (nrhs==3) ) ) + if (!((nrhs == 5) | (nrhs == 4) | (nrhs == 3))) { DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: Five, four or three input arguments are required!"); } @@ -67,40 +68,40 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) /* ** Test the first input argument and assign it to dimension. */ - if ( !( mxIsNumeric(prhs[0]) ) ) + if (!(mxIsNumeric(prhs[0]))) { DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: First input (dimension) has to be a positive integer!"); } - int dimension = ( int ) mxGetScalar(prhs[0]); + int dimension = (int) mxGetScalar(prhs[0]); /* ** Test the second input argument and assign it to seed. */ - if ( !( mxIsNumeric(prhs[1]) && mxIsClass(prhs[1],"int64") ) ) + if (!(mxIsNumeric(prhs[1]) && mxIsClass(prhs[1], "int64"))) { DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: Second input (seed) has to be an integer [int64]!"); } - int64_T seed = ( int64_T ) mxGetScalar( prhs[1] ); + int64_T seed = (int64_T) mxGetScalar(prhs[1]); /* ** Test the third input argument and assign it to type (kind of QMC sequence). */ int error_flag_3 = 0; - if ( !(mxIsNumeric(prhs[2])) ) + if (!(mxIsNumeric(prhs[2]))) { error_flag_3 = 1; } - int type = ( int ) mxGetScalar(prhs[2]); - if ( !(type==0 || type==1 || type==2) ) + int type = (int) mxGetScalar(prhs[2]); + if (!(type == 0 || type == 1 || type == 2)) { error_flag_3 = 1; } - if (error_flag_3==1) + if (error_flag_3 == 1) { DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: Third input (type of QMC sequence) has to be an integer equal to 0, 1 or 2!"); } /* ** Test dimension>=2 when type==2 */ - if ( (type==2) && (dimension<2) ) + if ((type == 2) && (dimension < 2)) { DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: First input (dimension) has to be greater than 1 for a uniform QMC on an hypershere!"); } @@ -114,14 +115,14 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) /* ** Test the optional fourth input argument and assign it to sequence_size. */ - if ( ( nrhs>3 ) && !mxIsNumeric(prhs[3]) ) + if ((nrhs > 3) && !mxIsNumeric(prhs[3])) { DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: Fourth input (qmc sequence size) has to be a positive integer!"); } int sequence_size; - if ( nrhs>3) + if (nrhs > 3) { - sequence_size = ( int ) mxGetScalar( prhs[3] ); + sequence_size = (int) mxGetScalar(prhs[3]); } else { @@ -130,53 +131,53 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) /* ** Test the optional fifth input argument and assign it to lower_and_upper_bounds. */ - if ( ( nrhs>4 ) && (type==0) && ( !( mxGetN(prhs[4])==2) ) )// Sequence of uniformly distributed numbers in an hypercube. + if ((nrhs > 4) && (type == 0) && (!(mxGetN(prhs[4]) == 2)))// Sequence of uniformly distributed numbers in an hypercube. { DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: The fifth input argument must be an array with two columns!"); } - if ( (nrhs>4) && (type==0) && ( !( (int)mxGetM(prhs[4])==dimension) ) ) + if ((nrhs > 4) && (type == 0) && (!((int) mxGetM(prhs[4]) == dimension))) { DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: The fourth input argument must be an array with a number of lines equal to dimension (first input argument)!"); } - if ( ( nrhs>4 ) && (type==1) && ( !( ((int)mxGetN(prhs[4])==dimension) && ((int)mxGetM(prhs[4])==dimension) ) ) )// Sequence of normally distributed numbers. + if ((nrhs > 4) && (type == 1) && (!(((int) mxGetN(prhs[4]) == dimension) && ((int) mxGetM(prhs[4]) == dimension))))// Sequence of normally distributed numbers. { DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: The fifth input argument must be a squared matrix (whose dimension is given by the first input argument)!"); } - if ( ( nrhs>4 ) && (type==2) && ( !( (mxGetN(prhs[4])==1) && (mxGetM(prhs[4])==1) ) ) )// Sequence of uniformly distributed numbers on an hypershere. + if ((nrhs > 4) && (type == 2) && (!((mxGetN(prhs[4]) == 1) && (mxGetM(prhs[4]) == 1))))// Sequence of uniformly distributed numbers on an hypershere. { DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: The fifth input argument must be a positive scalar!"); } double *lower_bounds = NULL, *upper_bounds = NULL; int unit_hypercube_flag = 1; - if ( (type==0) && (nrhs>4) ) + if ((type == 0) && (nrhs > 4)) { - lower_bounds = (double *) mxCalloc(dimension,sizeof(double)); - upper_bounds = (double *) mxCalloc(dimension,sizeof(double)); + lower_bounds = (double *) mxCalloc(dimension, sizeof(double)); + upper_bounds = (double *) mxCalloc(dimension, sizeof(double)); double *tmp; - tmp = (double *) mxCalloc(dimension*2,sizeof(double)); - memcpy(tmp,mxGetPr(prhs[4]),dimension*2*sizeof(double)); + tmp = (double *) mxCalloc(dimension*2, sizeof(double)); + memcpy(tmp, mxGetPr(prhs[4]), dimension*2*sizeof(double)); lower_bounds = &tmp[0]; upper_bounds = &tmp[dimension]; unit_hypercube_flag = 0; } double *cholcov; int identity_covariance_matrix = 1; - if ( (type==1) && (nrhs>4) ) + if ((type == 1) && (nrhs > 4)) { - cholcov = (double *) mxCalloc(dimension*dimension,sizeof(double)); + cholcov = (double *) mxCalloc(dimension*dimension, sizeof(double)); double *tmp; - tmp = (double *) mxCalloc(dimension*dimension,sizeof(double)); - memcpy(tmp,mxGetPr(prhs[4]),dimension*dimension*sizeof(double)); + tmp = (double *) mxCalloc(dimension*dimension, sizeof(double)); + memcpy(tmp, mxGetPr(prhs[4]), dimension*dimension*sizeof(double)); cholcov = &tmp[0]; identity_covariance_matrix = 0; } double radius = 1.0; int unit_radius = 1; - if ( (type==2) && (nrhs>4) ) + if ((type == 2) && (nrhs > 4)) { double *tmp; - tmp = (double *) mxCalloc(1,sizeof(double)); - memcpy(tmp,mxGetPr(prhs[4]),sizeof(double)); + tmp = (double *) mxCalloc(1, sizeof(double)); + memcpy(tmp, mxGetPr(prhs[4]), sizeof(double)); radius = tmp[0]; unit_radius = 0; } @@ -184,35 +185,35 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) ** Initialize outputs of the mex file. */ double *qmc_draws; - plhs[0] = mxCreateDoubleMatrix(dimension,sequence_size,mxREAL); + plhs[0] = mxCreateDoubleMatrix(dimension, sequence_size, mxREAL); qmc_draws = mxGetPr(plhs[0]); int64_T seed_out; - if (sequence_size==1) + if (sequence_size == 1) { - next_sobol ( dimension, &seed, qmc_draws ); + next_sobol(dimension, &seed, qmc_draws); seed_out = seed; } else - seed_out = sobol_block( dimension, sequence_size, seed, qmc_draws); + seed_out = sobol_block(dimension, sequence_size, seed, qmc_draws); - if (type==0 && unit_hypercube_flag==0)// Uniform QMC sequence in an hypercube. - expand_unit_hypercube( dimension, sequence_size, qmc_draws, lower_bounds, upper_bounds); - else if (type==1)// Normal QMC sequance in R^n. + if (type == 0 && unit_hypercube_flag == 0) // Uniform QMC sequence in an hypercube. + expand_unit_hypercube(dimension, sequence_size, qmc_draws, lower_bounds, upper_bounds); + else if (type == 1)// Normal QMC sequance in R^n. { - if (identity_covariance_matrix==1) + if (identity_covariance_matrix == 1) icdfm(dimension*sequence_size, qmc_draws); else - icdfmSigma(dimension,sequence_size, qmc_draws, cholcov); + icdfmSigma(dimension, sequence_size, qmc_draws, cholcov); } - else if (type==2)// Uniform QMC sequence on an hypershere. + else if (type == 2)// Uniform QMC sequence on an hypershere. { - if (unit_radius==1) + if (unit_radius == 1) usphere(dimension, sequence_size, qmc_draws); else usphereRadius(dimension, sequence_size, radius, qmc_draws); } - + if (nlhs >= 2) { plhs[1] = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL); diff --git a/mex/sources/sobol/sobol.hh b/mex/sources/sobol/sobol.hh index 8dbb987855a515c4a62aee20805bdbfcc2939827..37c589412e2a8551a17c5053b55ee5035b411281 100644 --- a/mex/sources/sobol/sobol.hh +++ b/mex/sources/sobol/sobol.hh @@ -1,5 +1,5 @@ /* Quasi Monte Carlo sequences (à la Sobol). -** +** ** Original files downloaded from http://people.sc.fsu.edu/~burkardt/cpp_src/sobol/ (version 17-Feb-2009 09:46) ** ** Copyright (C) 2009 John Burkardt @@ -33,8 +33,10 @@ using namespace std; #define DIM_MAX 1111 -template<typename T> int bit_hi1(T n) -/* +template<typename T> +int +bit_hi1(T n) +/* ** This function returns the position of the high 1 bit base 2 in an integer. ** ** Example: @@ -44,7 +46,7 @@ template<typename T> int bit_hi1(T n) ** 0 0 0 ** 1 1 1 ** 2 10 2 -** 3 11 2 +** 3 11 2 ** 4 100 3 ** 5 101 3 ** 6 110 3 @@ -63,7 +65,7 @@ template<typename T> int bit_hi1(T n) ** 1024 10000000000 11 ** 1025 10000000001 11 ** -** +** ** Original files downloaded from http://people.sc.fsu.edu/~burkardt/cpp_src/sobol/ (version 17-Feb-2009 09:46) ** ** Input, int or long long, the integer to be measured. @@ -72,16 +74,18 @@ template<typename T> int bit_hi1(T n) ** Output: the location of the high order bit. */ { - int bit = 0 ; - while ( n > 0 ) - { - bit++ ; - n = n/2 ; - } - return bit ; + int bit = 0; + while (n > 0) + { + bit++; + n = n/2; + } + return bit; } -template<typename T> int bit_lo0 ( T n ) +template<typename T> +int +bit_lo0(T n) /* ** This function returns the position of the low 0 bit base 2 in an integer. ** @@ -92,7 +96,7 @@ template<typename T> int bit_lo0 ( T n ) ** 0 0 1 ** 1 1 2 ** 2 10 1 -** 3 11 3 +** 3 11 3 ** 4 100 1 ** 5 101 2 ** 6 110 1 @@ -123,22 +127,23 @@ template<typename T> int bit_lo0 ( T n ) */ { int bit = 0; - while ( true ) - { - bit++; - T n2 = n/2; - if ( n == 2*n2 ) + while (true) { - break; + bit++; + T n2 = n/2; + if (n == 2*n2) + { + break; + } + n = n2; } - n = n2; - } return bit; } - -template<typename T> T ixor ( T i, T j ) -/* +template<typename T> +T +ixor(T i, T j) +/* ** This function calculates the exclusive OR of two integers. ** ** Original files downloaded from http://people.sc.fsu.edu/~burkardt/cpp_src/sobol/ (version 17-Feb-2009 09:46) @@ -150,25 +155,26 @@ template<typename T> T ixor ( T i, T j ) { T k = 0; T l = 1; - while ( i != 0 || j != 0 ) - { - T i2 = i / 2; - T j2 = j / 2; - if ( - ( ( i == 2 * i2 ) && ( j != 2 * j2 ) ) || - ( ( i != 2 * i2 ) && ( j == 2 * j2 ) ) ) - { - k = k + l; - } - i = i2; - j = j2; - l = 2 * l; - } + while (i != 0 || j != 0) + { + T i2 = i / 2; + T j2 = j / 2; + if ( + ((i == 2 * i2) && (j != 2 * j2)) + || ((i != 2 * i2) && (j == 2 * j2))) + { + k = k + l; + } + i = i2; + j = j2; + l = 2 * l; + } return k; } - -template<typename T1, typename T2> void next_sobol ( int dim_num, T1 *seed, T2 *quasi ) +template<typename T1, typename T2> +void +next_sobol(int dim_num, T1 *seed, T2 *quasi) /* ** This function generates a new quasirandom Sobol vector with each call. ** @@ -203,7 +209,7 @@ template<typename T1, typename T2> void next_sobol ( int dim_num, T1 *seed, T2 * ** ** Bennett Fox, ** Algorithm 647: -** Implementation and Relative Efficiency of Quasirandom +** Implementation and Relative Efficiency of Quasirandom ** Sequence Generators, ** ACM Transactions on Mathematical Software, ** Volume 12, Number 4, pages 362-376, 1986. @@ -218,10 +224,10 @@ template<typename T1, typename T2> void next_sobol ( int dim_num, T1 *seed, T2 * ** USSR Computational Mathematics and Mathematical Physics, ** Volume 16, pages 236-242, 1977. ** -** Ilya Sobol, YL Levitan, -** The Production of Points Uniformly Distributed in a Multidimensional +** Ilya Sobol, YL Levitan, +** The Production of Points Uniformly Distributed in a Multidimensional ** Cube (in Russian), -** Preprint IPM Akad. Nauk SSSR, +** Preprint IPM Akad. Nauk SSSR, ** Number 40, Moscow 1976. ** ** Parameters: @@ -238,287 +244,288 @@ template<typename T1, typename T2> void next_sobol ( int dim_num, T1 *seed, T2 * ** ** Output, double QUASI[DIM_NUM], the next quasirandom vector. */ -{ - static T1 atmost ; - static int dim_num_save = 0 ; - int LOG_MAX = sizeof(T1)*8-2 ; +{ + static T1 atmost; + static int dim_num_save = 0; + int LOG_MAX = sizeof(T1)*8-2; bool includ[LOG_MAX]; static bool initialized = false; static T1 lastq[DIM_MAX]; static T1 maxcol; T1 l = 0; static T1 poly[DIM_MAX] = - { - 1, 3, 7, 11, 13, 19, 25, 37, 59, 47, - 61, 55, 41, 67, 97, 91, 109, 103, 115, 131, + { + 1, 3, 7, 11, 13, 19, 25, 37, 59, 47, + 61, 55, 41, 67, 97, 91, 109, 103, 115, 131, 193, 137, 145, 143, 241, 157, 185, 167, 229, 171, 213, 191, 253, 203, 211, 239, 247, 285, 369, 299, 301, 333, 351, 355, 357, 361, 391, 397, 425, 451, 463, 487, 501, 529, 539, 545, 557, 563, 601, 607, - 617, 623, 631, 637, 647, 661, 675, 677, 687, 695, + 617, 623, 631, 637, 647, 661, 675, 677, 687, 695, 701, 719, 721, 731, 757, 761, 787, 789, 799, 803, 817, 827, 847, 859, 865, 875, 877, 883, 895, 901, 911, 949, 953, 967, 971, 973, 981, 985, 995, 1001, - 1019, 1033, 1051, 1063, 1069, 1125, 1135, 1153, 1163, 1221, - 1239, 1255, 1267, 1279, 1293, 1305, 1315, 1329, 1341, 1347, - 1367, 1387, 1413, 1423, 1431, 1441, 1479, 1509, 1527, 1531, - 1555, 1557, 1573, 1591, 1603, 1615, 1627, 1657, 1663, 1673, - 1717, 1729, 1747, 1759, 1789, 1815, 1821, 1825, 1849, 1863, - 1869, 1877, 1881, 1891, 1917, 1933, 1939, 1969, 2011, 2035, - 2041, 2053, 2071, 2091, 2093, 2119, 2147, 2149, 2161, 2171, - 2189, 2197, 2207, 2217, 2225, 2255, 2257, 2273, 2279, 2283, - 2293, 2317, 2323, 2341, 2345, 2363, 2365, 2373, 2377, 2385, - 2395, 2419, 2421, 2431, 2435, 2447, 2475, 2477, 2489, 2503, - 2521, 2533, 2551, 2561, 2567, 2579, 2581, 2601, 2633, 2657, - 2669, 2681, 2687, 2693, 2705, 2717, 2727, 2731, 2739, 2741, - 2773, 2783, 2793, 2799, 2801, 2811, 2819, 2825, 2833, 2867, - 2879, 2881, 2891, 2905, 2911, 2917, 2927, 2941, 2951, 2955, - 2963, 2965, 2991, 2999, 3005, 3017, 3035, 3037, 3047, 3053, - 3083, 3085, 3097, 3103, 3159, 3169, 3179, 3187, 3205, 3209, - 3223, 3227, 3229, 3251, 3263, 3271, 3277, 3283, 3285, 3299, - 3305, 3319, 3331, 3343, 3357, 3367, 3373, 3393, 3399, 3413, - 3417, 3427, 3439, 3441, 3475, 3487, 3497, 3515, 3517, 3529, - 3543, 3547, 3553, 3559, 3573, 3589, 3613, 3617, 3623, 3627, - 3635, 3641, 3655, 3659, 3669, 3679, 3697, 3707, 3709, 3713, - 3731, 3743, 3747, 3771, 3791, 3805, 3827, 3833, 3851, 3865, - 3889, 3895, 3933, 3947, 3949, 3957, 3971, 3985, 3991, 3995, - 4007, 4013, 4021, 4045, 4051, 4069, 4073, 4179, 4201, 4219, - 4221, 4249, 4305, 4331, 4359, 4383, 4387, 4411, 4431, 4439, - 4449, 4459, 4485, 4531, 4569, 4575, 4621, 4663, 4669, 4711, - 4723, 4735, 4793, 4801, 4811, 4879, 4893, 4897, 4921, 4927, - 4941, 4977, 5017, 5027, 5033, 5127, 5169, 5175, 5199, 5213, - 5223, 5237, 5287, 5293, 5331, 5391, 5405, 5453, 5523, 5573, - 5591, 5597, 5611, 5641, 5703, 5717, 5721, 5797, 5821, 5909, - 5913, 5955, 5957, 6005, 6025, 6061, 6067, 6079, 6081, 6231, - 6237, 6289, 6295, 6329, 6383, 6427, 6453, 6465, 6501, 6523, - 6539, 6577, 6589, 6601, 6607, 6631, 6683, 6699, 6707, 6761, - 6795, 6865, 6881, 6901, 6923, 6931, 6943, 6999, 7057, 7079, - 7103, 7105, 7123, 7173, 7185, 7191, 7207, 7245, 7303, 7327, - 7333, 7355, 7365, 7369, 7375, 7411, 7431, 7459, 7491, 7505, - 7515, 7541, 7557, 7561, 7701, 7705, 7727, 7749, 7761, 7783, - 7795, 7823, 7907, 7953, 7963, 7975, 8049, 8089, 8123, 8125, - 8137, 8219, 8231, 8245, 8275, 8293, 8303, 8331, 8333, 8351, - 8357, 8367, 8379, 8381, 8387, 8393, 8417, 8435, 8461, 8469, - 8489, 8495, 8507, 8515, 8551, 8555, 8569, 8585, 8599, 8605, - 8639, 8641, 8647, 8653, 8671, 8675, 8689, 8699, 8729, 8741, - 8759, 8765, 8771, 8795, 8797, 8825, 8831, 8841, 8855, 8859, - 8883, 8895, 8909, 8943, 8951, 8955, 8965, 8999, 9003, 9031, - 9045, 9049, 9071, 9073, 9085, 9095, 9101, 9109, 9123, 9129, - 9137, 9143, 9147, 9185, 9197, 9209, 9227, 9235, 9247, 9253, - 9257, 9277, 9297, 9303, 9313, 9325, 9343, 9347, 9371, 9373, - 9397, 9407, 9409, 9415, 9419, 9443, 9481, 9495, 9501, 9505, - 9517, 9529, 9555, 9557, 9571, 9585, 9591, 9607, 9611, 9621, - 9625, 9631, 9647, 9661, 9669, 9679, 9687, 9707, 9731, 9733, - 9745, 9773, 9791, 9803, 9811, 9817, 9833, 9847, 9851, 9863, - 9875, 9881, 9905, 9911, 9917, 9923, 9963, 9973,10003,10025, - 10043,10063,10071,10077,10091,10099,10105,10115,10129,10145, - 10169,10183,10187,10207,10223,10225,10247,10265,10271,10275, - 10289,10299,10301,10309,10343,10357,10373,10411,10413,10431, - 10445,10453,10463,10467,10473,10491,10505,10511,10513,10523, - 10539,10549,10559,10561,10571,10581,10615,10621,10625,10643, - 10655,10671,10679,10685,10691,10711,10739,10741,10755,10767, - 10781,10785,10803,10805,10829,10857,10863,10865,10875,10877, - 10917,10921,10929,10949,10967,10971,10987,10995,11009,11029, - 11043,11045,11055,11063,11075,11081,11117,11135,11141,11159, - 11163,11181,11187,11225,11237,11261,11279,11297,11307,11309, - 11327,11329,11341,11377,11403,11405,11413,11427,11439,11453, - 11461,11473,11479,11489,11495,11499,11533,11545,11561,11567, - 11575,11579,11589,11611,11623,11637,11657,11663,11687,11691, - 11701,11747,11761,11773,11783,11795,11797,11817,11849,11855, - 11867,11869,11873,11883,11919,11921,11927,11933,11947,11955, - 11961,11999,12027,12029,12037,12041,12049,12055,12095,12097, - 12107,12109,12121,12127,12133,12137,12181,12197,12207,12209, - 12239,12253,12263,12269,12277,12287,12295,12309,12313,12335, - 12361,12367,12391,12409,12415,12433,12449,12469,12479,12481, - 12499,12505,12517,12527,12549,12559,12597,12615,12621,12639, - 12643,12657,12667,12707,12713,12727,12741,12745,12763,12769, - 12779,12781,12787,12799,12809,12815,12829,12839,12857,12875, - 12883,12889,12901,12929,12947,12953,12959,12969,12983,12987, - 12995,13015,13019,13031,13063,13077,13103,13137,13149,13173, - 13207,13211,13227,13241,13249,13255,13269,13283,13285,13303, - 13307,13321,13339,13351,13377,13389,13407,13417,13431,13435, - 13447,13459,13465,13477,13501,13513,13531,13543,13561,13581, - 13599,13605,13617,13623,13637,13647,13661,13677,13683,13695, - 13725,13729,13753,13773,13781,13785,13795,13801,13807,13825, - 13835,13855,13861,13871,13883,13897,13905,13915,13939,13941, - 13969,13979,13981,13997,14027,14035,14037,14051,14063,14085, - 14095,14107,14113,14125,14137,14145,14151,14163,14193,14199, - 14219,14229,14233,14243,14277,14287,14289,14295,14301,14305, - 14323,14339,14341,14359,14365,14375,14387,14411,14425,14441, - 14449,14499,14513,14523,14537,14543,14561,14579,14585,14593, - 14599,14603,14611,14641,14671,14695,14701,14723,14725,14743, - 14753,14759,14765,14795,14797,14803,14831,14839,14845,14855, - 14889,14895,14909,14929,14941,14945,14951,14963,14965,14985, - 15033,15039,15053,15059,15061,15071,15077,15081,15099,15121, - 15147,15149,15157,15167,15187,15193,15203,15205,15215,15217, - 15223,15243,15257,15269,15273,15287,15291,15313,15335,15347, - 15359,15373,15379,15381,15391,15395,15397,15419,15439,15453, - 15469,15491,15503,15517,15527,15531,15545,15559,15593,15611, - 15613,15619,15639,15643,15649,15661,15667,15669,15681,15693, - 15717,15721,15741,15745,15765,15793,15799,15811,15825,15835, - 15847,15851,15865,15877,15881,15887,15899,15915,15935,15937, - 15955,15973,15977,16011,16035,16061,16069,16087,16093,16097, - 16121,16141,16153,16159,16165,16183,16189,16195,16197,16201, - 16209,16215,16225,16259,16265,16273,16299,16309,16355,16375, - 16381 }; + 1019, 1033, 1051, 1063, 1069, 1125, 1135, 1153, 1163, 1221, + 1239, 1255, 1267, 1279, 1293, 1305, 1315, 1329, 1341, 1347, + 1367, 1387, 1413, 1423, 1431, 1441, 1479, 1509, 1527, 1531, + 1555, 1557, 1573, 1591, 1603, 1615, 1627, 1657, 1663, 1673, + 1717, 1729, 1747, 1759, 1789, 1815, 1821, 1825, 1849, 1863, + 1869, 1877, 1881, 1891, 1917, 1933, 1939, 1969, 2011, 2035, + 2041, 2053, 2071, 2091, 2093, 2119, 2147, 2149, 2161, 2171, + 2189, 2197, 2207, 2217, 2225, 2255, 2257, 2273, 2279, 2283, + 2293, 2317, 2323, 2341, 2345, 2363, 2365, 2373, 2377, 2385, + 2395, 2419, 2421, 2431, 2435, 2447, 2475, 2477, 2489, 2503, + 2521, 2533, 2551, 2561, 2567, 2579, 2581, 2601, 2633, 2657, + 2669, 2681, 2687, 2693, 2705, 2717, 2727, 2731, 2739, 2741, + 2773, 2783, 2793, 2799, 2801, 2811, 2819, 2825, 2833, 2867, + 2879, 2881, 2891, 2905, 2911, 2917, 2927, 2941, 2951, 2955, + 2963, 2965, 2991, 2999, 3005, 3017, 3035, 3037, 3047, 3053, + 3083, 3085, 3097, 3103, 3159, 3169, 3179, 3187, 3205, 3209, + 3223, 3227, 3229, 3251, 3263, 3271, 3277, 3283, 3285, 3299, + 3305, 3319, 3331, 3343, 3357, 3367, 3373, 3393, 3399, 3413, + 3417, 3427, 3439, 3441, 3475, 3487, 3497, 3515, 3517, 3529, + 3543, 3547, 3553, 3559, 3573, 3589, 3613, 3617, 3623, 3627, + 3635, 3641, 3655, 3659, 3669, 3679, 3697, 3707, 3709, 3713, + 3731, 3743, 3747, 3771, 3791, 3805, 3827, 3833, 3851, 3865, + 3889, 3895, 3933, 3947, 3949, 3957, 3971, 3985, 3991, 3995, + 4007, 4013, 4021, 4045, 4051, 4069, 4073, 4179, 4201, 4219, + 4221, 4249, 4305, 4331, 4359, 4383, 4387, 4411, 4431, 4439, + 4449, 4459, 4485, 4531, 4569, 4575, 4621, 4663, 4669, 4711, + 4723, 4735, 4793, 4801, 4811, 4879, 4893, 4897, 4921, 4927, + 4941, 4977, 5017, 5027, 5033, 5127, 5169, 5175, 5199, 5213, + 5223, 5237, 5287, 5293, 5331, 5391, 5405, 5453, 5523, 5573, + 5591, 5597, 5611, 5641, 5703, 5717, 5721, 5797, 5821, 5909, + 5913, 5955, 5957, 6005, 6025, 6061, 6067, 6079, 6081, 6231, + 6237, 6289, 6295, 6329, 6383, 6427, 6453, 6465, 6501, 6523, + 6539, 6577, 6589, 6601, 6607, 6631, 6683, 6699, 6707, 6761, + 6795, 6865, 6881, 6901, 6923, 6931, 6943, 6999, 7057, 7079, + 7103, 7105, 7123, 7173, 7185, 7191, 7207, 7245, 7303, 7327, + 7333, 7355, 7365, 7369, 7375, 7411, 7431, 7459, 7491, 7505, + 7515, 7541, 7557, 7561, 7701, 7705, 7727, 7749, 7761, 7783, + 7795, 7823, 7907, 7953, 7963, 7975, 8049, 8089, 8123, 8125, + 8137, 8219, 8231, 8245, 8275, 8293, 8303, 8331, 8333, 8351, + 8357, 8367, 8379, 8381, 8387, 8393, 8417, 8435, 8461, 8469, + 8489, 8495, 8507, 8515, 8551, 8555, 8569, 8585, 8599, 8605, + 8639, 8641, 8647, 8653, 8671, 8675, 8689, 8699, 8729, 8741, + 8759, 8765, 8771, 8795, 8797, 8825, 8831, 8841, 8855, 8859, + 8883, 8895, 8909, 8943, 8951, 8955, 8965, 8999, 9003, 9031, + 9045, 9049, 9071, 9073, 9085, 9095, 9101, 9109, 9123, 9129, + 9137, 9143, 9147, 9185, 9197, 9209, 9227, 9235, 9247, 9253, + 9257, 9277, 9297, 9303, 9313, 9325, 9343, 9347, 9371, 9373, + 9397, 9407, 9409, 9415, 9419, 9443, 9481, 9495, 9501, 9505, + 9517, 9529, 9555, 9557, 9571, 9585, 9591, 9607, 9611, 9621, + 9625, 9631, 9647, 9661, 9669, 9679, 9687, 9707, 9731, 9733, + 9745, 9773, 9791, 9803, 9811, 9817, 9833, 9847, 9851, 9863, + 9875, 9881, 9905, 9911, 9917, 9923, 9963, 9973, 10003, 10025, + 10043, 10063, 10071, 10077, 10091, 10099, 10105, 10115, 10129, 10145, + 10169, 10183, 10187, 10207, 10223, 10225, 10247, 10265, 10271, 10275, + 10289, 10299, 10301, 10309, 10343, 10357, 10373, 10411, 10413, 10431, + 10445, 10453, 10463, 10467, 10473, 10491, 10505, 10511, 10513, 10523, + 10539, 10549, 10559, 10561, 10571, 10581, 10615, 10621, 10625, 10643, + 10655, 10671, 10679, 10685, 10691, 10711, 10739, 10741, 10755, 10767, + 10781, 10785, 10803, 10805, 10829, 10857, 10863, 10865, 10875, 10877, + 10917, 10921, 10929, 10949, 10967, 10971, 10987, 10995, 11009, 11029, + 11043, 11045, 11055, 11063, 11075, 11081, 11117, 11135, 11141, 11159, + 11163, 11181, 11187, 11225, 11237, 11261, 11279, 11297, 11307, 11309, + 11327, 11329, 11341, 11377, 11403, 11405, 11413, 11427, 11439, 11453, + 11461, 11473, 11479, 11489, 11495, 11499, 11533, 11545, 11561, 11567, + 11575, 11579, 11589, 11611, 11623, 11637, 11657, 11663, 11687, 11691, + 11701, 11747, 11761, 11773, 11783, 11795, 11797, 11817, 11849, 11855, + 11867, 11869, 11873, 11883, 11919, 11921, 11927, 11933, 11947, 11955, + 11961, 11999, 12027, 12029, 12037, 12041, 12049, 12055, 12095, 12097, + 12107, 12109, 12121, 12127, 12133, 12137, 12181, 12197, 12207, 12209, + 12239, 12253, 12263, 12269, 12277, 12287, 12295, 12309, 12313, 12335, + 12361, 12367, 12391, 12409, 12415, 12433, 12449, 12469, 12479, 12481, + 12499, 12505, 12517, 12527, 12549, 12559, 12597, 12615, 12621, 12639, + 12643, 12657, 12667, 12707, 12713, 12727, 12741, 12745, 12763, 12769, + 12779, 12781, 12787, 12799, 12809, 12815, 12829, 12839, 12857, 12875, + 12883, 12889, 12901, 12929, 12947, 12953, 12959, 12969, 12983, 12987, + 12995, 13015, 13019, 13031, 13063, 13077, 13103, 13137, 13149, 13173, + 13207, 13211, 13227, 13241, 13249, 13255, 13269, 13283, 13285, 13303, + 13307, 13321, 13339, 13351, 13377, 13389, 13407, 13417, 13431, 13435, + 13447, 13459, 13465, 13477, 13501, 13513, 13531, 13543, 13561, 13581, + 13599, 13605, 13617, 13623, 13637, 13647, 13661, 13677, 13683, 13695, + 13725, 13729, 13753, 13773, 13781, 13785, 13795, 13801, 13807, 13825, + 13835, 13855, 13861, 13871, 13883, 13897, 13905, 13915, 13939, 13941, + 13969, 13979, 13981, 13997, 14027, 14035, 14037, 14051, 14063, 14085, + 14095, 14107, 14113, 14125, 14137, 14145, 14151, 14163, 14193, 14199, + 14219, 14229, 14233, 14243, 14277, 14287, 14289, 14295, 14301, 14305, + 14323, 14339, 14341, 14359, 14365, 14375, 14387, 14411, 14425, 14441, + 14449, 14499, 14513, 14523, 14537, 14543, 14561, 14579, 14585, 14593, + 14599, 14603, 14611, 14641, 14671, 14695, 14701, 14723, 14725, 14743, + 14753, 14759, 14765, 14795, 14797, 14803, 14831, 14839, 14845, 14855, + 14889, 14895, 14909, 14929, 14941, 14945, 14951, 14963, 14965, 14985, + 15033, 15039, 15053, 15059, 15061, 15071, 15077, 15081, 15099, 15121, + 15147, 15149, 15157, 15167, 15187, 15193, 15203, 15205, 15215, 15217, + 15223, 15243, 15257, 15269, 15273, 15287, 15291, 15313, 15335, 15347, + 15359, 15373, 15379, 15381, 15391, 15395, 15397, 15419, 15439, 15453, + 15469, 15491, 15503, 15517, 15527, 15531, 15545, 15559, 15593, 15611, + 15613, 15619, 15639, 15643, 15649, 15661, 15667, 15669, 15681, 15693, + 15717, 15721, 15741, 15745, 15765, 15793, 15799, 15811, 15825, 15835, + 15847, 15851, 15865, 15877, 15881, 15887, 15899, 15915, 15935, 15937, + 15955, 15973, 15977, 16011, 16035, 16061, 16069, 16087, 16093, 16097, + 16121, 16141, 16153, 16159, 16165, 16183, 16189, 16195, 16197, 16201, + 16209, 16215, 16225, 16259, 16265, 16273, 16299, 16309, 16355, 16375, + 16381 + }; static T2 recipd; - static T1 seed_save = - 1; - static T1** v ; - if ( !initialized || dim_num != dim_num_save ) - { - v = new T1 *[DIM_MAX] ; - for( int i = 0 ; i < DIM_MAX ; i++ ) - v[i] = new T1[LOG_MAX]; - initialized = true; - initialize_v_array(DIM_MAX, LOG_MAX, v); - /* - ** Check parameters. - */ - if ( dim_num < 1 || DIM_MAX < dim_num ) + static T1 seed_save = -1; + static T1 **v; + if (!initialized || dim_num != dim_num_save) { - cout << "\n"; - cout << "NEXT_SOBOL - Fatal error!\n"; - cout << " The spatial dimension DIM_NUM should satisfy:\n"; - cout << " 1 <= DIM_NUM <= " << DIM_MAX << "\n"; - cout << " But this input value is DIM_NUM = " << dim_num << "\n"; - exit ( 1 ); + v = new T1 *[DIM_MAX]; + for (int i = 0; i < DIM_MAX; i++) + v[i] = new T1[LOG_MAX]; + initialized = true; + initialize_v_array(DIM_MAX, LOG_MAX, v); + /* + ** Check parameters. + */ + if (dim_num < 1 || DIM_MAX < dim_num) + { + cout << "\n"; + cout << "NEXT_SOBOL - Fatal error!\n"; + cout << " The spatial dimension DIM_NUM should satisfy:\n"; + cout << " 1 <= DIM_NUM <= " << DIM_MAX << "\n"; + cout << " But this input value is DIM_NUM = " << dim_num << "\n"; + exit(1); + } + dim_num_save = dim_num; + /* + ** Set ATMOST = 2^LOG_MAX - 1. + */ + atmost = (T1) 0; + for (int i = 1; i <= LOG_MAX; i++) + atmost = 2 * atmost + 1; + /* + ** Find the highest 1 bit in ATMOST (should be LOG_MAX). + */ + maxcol = bit_hi1(atmost); + /* + ** Initialize row 1 of V. + */ + for (T1 j = 0; j < maxcol; j++) + { + v[0][j] = (T1) 1; + } + /* + ** Initialize the remaining rows of V. + */ + for (int i = 1; i < dim_num; i++) + { + /* + ** The bit pattern of the integer POLY(I) gives the form + ** of polynomial I. + ** + ** Find the degree of polynomial I from binary encoding. + */ + T1 j = poly[i]; + T1 m = 0; + while (true) + { + j = j / 2; + if (j <= 0) + { + break; + } + m = m + 1; + } + /* + ** We expand this bit pattern to separate components + ** of the logical array INCLUD. + */ + j = poly[i]; + for (T1 k = m-1; 0 <= k; k--) + { + T1 j2 = j / 2; + includ[k] = (j != (2 * j2)); + j = j2; + } + /* + ** Calculate the remaining elements of row I as explained + ** in Bratley and Fox, section 2. + ** + ** Some tricky indexing here. Did I change it correctly? + */ + for (j = m; j < maxcol; j++) + { + T1 newv = v[i][j-m]; + l = 1; + for (T1 k = 0; k < m; k++) + { + l = 2 * l; + if (includ[k]) + { + newv = (newv ^ (l * v[i][j-k-1])); + } + } + v[i][j] = newv; + } + } + /* + ** Multiply columns of V by appropriate power of 2. + */ + l = 1; + for (T1 j = maxcol - 2; 0 <= j; j--) + { + l = 2 * l; + for (int i = 0; i < dim_num; i++) + { + v[i][j] = v[i][j] * l; + } + } + /* + ** RECIPD is 1/(common denominator of the elements in V). + */ + recipd = 1.0E+00 / ((T2) (2 * l)); } - dim_num_save = dim_num; - /* - ** Set ATMOST = 2^LOG_MAX - 1. - */ - atmost = (T1) 0; - for ( int i = 1; i <= LOG_MAX; i++ ) - atmost = 2 * atmost + 1; - /* - ** Find the highest 1 bit in ATMOST (should be LOG_MAX). - */ - maxcol = bit_hi1 ( atmost ); - /* - ** Initialize row 1 of V. - */ - for ( T1 j = 0; j < maxcol; j++ ) - { - v[0][j] = (T1) 1; - } - /* - ** Initialize the remaining rows of V. - */ - for ( int i = 1; i < dim_num; i++ ) - { - /* - ** The bit pattern of the integer POLY(I) gives the form - ** of polynomial I. - ** - ** Find the degree of polynomial I from binary encoding. - */ - T1 j = poly[i]; - T1 m = 0; - while ( true ) - { - j = j / 2; - if ( j <= 0 ) - { - break; - } - m = m + 1; - } - /* - ** We expand this bit pattern to separate components - ** of the logical array INCLUD. - */ - j = poly[i]; - for ( T1 k = m-1; 0 <= k; k-- ) - { - T1 j2 = j / 2; - includ[k] = ( j != ( 2 * j2 ) ); - j = j2; - } - /* - ** Calculate the remaining elements of row I as explained - ** in Bratley and Fox, section 2. - ** - ** Some tricky indexing here. Did I change it correctly? - */ - for ( j = m; j < maxcol; j++ ) - { - T1 newv = v[i][j-m]; - l = 1; - for ( T1 k = 0; k < m; k++ ) - { - l = 2 * l; - if ( includ[k] ) - { - newv = ( newv ^ ( l * v[i][j-k-1] ) ); - } - } - v[i][j] = newv; - } - } - /* - ** Multiply columns of V by appropriate power of 2. - */ - l = 1; - for ( T1 j = maxcol - 2; 0 <= j; j-- ) - { - l = 2 * l; - for ( int i = 0; i < dim_num; i++ ) - { - v[i][j] = v[i][j] * l; - } - } - /* - ** RECIPD is 1/(common denominator of the elements in V). - */ - recipd = 1.0E+00 / ( ( T2 ) ( 2 * l ) ); - } - if ( *seed < 0 ) - *seed = 0 ; - - if ( *seed == 0 ) + if (*seed < 0) + *seed = 0; + + if (*seed == 0) { l = 1; - for ( int i = 0; i < dim_num; i++ ) + for (int i = 0; i < dim_num; i++) { lastq[i] = 0; } } - else if ( *seed == seed_save + 1 ) + else if (*seed == seed_save + 1) { - l = bit_lo0 ( *seed ); + l = bit_lo0(*seed); } - else if ( *seed <= seed_save ) + else if (*seed <= seed_save) { seed_save = 0; l = 1; - for ( int i = 0; i < dim_num; i++ ) + for (int i = 0; i < dim_num; i++) lastq[i] = 0; - for ( T1 seed_temp = seed_save; seed_temp <= (*seed)-1; seed_temp++ ) + for (T1 seed_temp = seed_save; seed_temp <= (*seed)-1; seed_temp++) { - l = bit_lo0 ( seed_temp ); - for ( int i = 0; i < dim_num; i++ ) + l = bit_lo0(seed_temp); + for (int i = 0; i < dim_num; i++) { - lastq[i] = ( lastq[i] ^ v[i][l-1] ); + lastq[i] = (lastq[i] ^ v[i][l-1]); } } - l = bit_lo0 ( *seed ); + l = bit_lo0(*seed); } - else if ( seed_save+1 < *seed ) + else if (seed_save+1 < *seed) { - for ( T1 seed_temp = seed_save+1; seed_temp <= (*seed)-1; seed_temp++ ) + for (T1 seed_temp = seed_save+1; seed_temp <= (*seed)-1; seed_temp++) { - l = bit_lo0 ( seed_temp ); - for ( int i = 0; i < dim_num; i++ ) + l = bit_lo0(seed_temp); + for (int i = 0; i < dim_num; i++) { - lastq[i] = ( lastq[i] ^ v[i][l-1] ); + lastq[i] = (lastq[i] ^ v[i][l-1]); } } - l = bit_lo0 ( *seed ); + l = bit_lo0(*seed); } /* ** Check that the user is not calling too many times! */ - if ( maxcol < l ) + if (maxcol < l) { cout << "\n"; cout << "NEXT_SOBOL - Fatal error!\n"; @@ -526,49 +533,52 @@ template<typename T1, typename T2> void next_sobol ( int dim_num, T1 *seed, T2 * cout << " SEED = " << *seed << "\n"; cout << " MAXCOL = " << maxcol << "\n"; cout << " L = " << l << "\n"; - exit ( 2 ); + exit(2); } /* ** Calculate the new components of QUASI. ** The caret indicates the bitwise exclusive OR. */ - for ( int i = 0; i < dim_num; i++ ) + for (int i = 0; i < dim_num; i++) { - quasi[i] = ( ( T2 ) lastq[i] ) * recipd; - lastq[i] = ( lastq[i]^v[i][l-1] ); + quasi[i] = ((T2) lastq[i]) * recipd; + lastq[i] = (lastq[i]^v[i][l-1]); } seed_save = *seed; *seed = *seed + 1; return; } -template<typename T1, typename T2> T1 sobol_block( int dimension, int block_size, T1 seed, T2 *block ) +template<typename T1, typename T2> +T1 +sobol_block(int dimension, int block_size, T1 seed, T2 *block) { - for ( int iter = 0 ; iter < block_size ; iter++ ) + for (int iter = 0; iter < block_size; iter++) { - next_sobol ( dimension, &seed, &block[iter*dimension] ); + next_sobol(dimension, &seed, &block[iter*dimension]); } return seed; } -template<typename T> void expand_unit_hypercube( int dimension, int block_size, T *block, T *lower_bound, T* upper_bound ) +template<typename T> +void +expand_unit_hypercube(int dimension, int block_size, T *block, T *lower_bound, T *upper_bound) { T *hypercube_length = new T[dimension]; - for(int dim = 0 ; dim < dimension ; dim++ ) + for (int dim = 0; dim < dimension; dim++) { - hypercube_length[dim] = upper_bound[dim]-lower_bound[dim] ; + hypercube_length[dim] = upper_bound[dim]-lower_bound[dim]; } int base = 0; - for ( int sim = 0 ; sim < block_size ; sim++ ) + for (int sim = 0; sim < block_size; sim++) { - for (int dim = 0 ; dim < dimension ; dim++ ) + for (int dim = 0; dim < dimension; dim++) { block[base+dim] = lower_bound[dim] + hypercube_length[dim]*block[base+dim]; } - base+= dimension; + base += dimension; } delete[] hypercube_length; } - #undef DIM_MAX diff --git a/others/C/dynare_driver.h b/others/C/dynare_driver.h index 56091c7d7450b9c68f5dcd6ef59ae51b4946688a..14588c2cdf7a5249a8491df6c5f9cae68a1ca6e0 100644 --- a/others/C/dynare_driver.h +++ b/others/C/dynare_driver.h @@ -17,8 +17,9 @@ #ifndef _DYNARE_C_DRIVER_H #define _DYNARE_C_DRIVER_H -struct aux_vars_t { +struct aux_vars_t +{ int endo_index, type, orig_index, orig_lead_lag; -} ; +}; #endif // ! _DYNARE_C_DRIVER_H diff --git a/others/cpp/dynare_cpp_driver.cc b/others/cpp/dynare_cpp_driver.cc index f6701dd4bd37cfd8743dbf1ee8262c9bf13ca283..2beec52600a7bfd0d8130e736aebc81fe61165f0 100644 --- a/others/cpp/dynare_cpp_driver.cc +++ b/others/cpp/dynare_cpp_driver.cc @@ -39,7 +39,7 @@ DynareInfo::DynareInfo(map<string, int > exo_names_arg, exo_nbr = exo_names.size(); exo_det_nbr = exo_det_names.size(); param_nbr = param_names.size(); - + exo_names = exo_names_arg; exo_det_names = exo_det_names_arg; endo_names = endo_names_arg; @@ -54,27 +54,27 @@ DynareInfo::DynareInfo(map<string, int > exo_names_arg, DynareInfo::~DynareInfo() { for (vector<MarkovSwitching *>::iterator it = markov_switching_vector.begin(); - it < markov_switching_vector.end(); it++ ) + it < markov_switching_vector.end(); it++) delete *it; for (vector<ModFilePrior *>::iterator it = prior_vector.begin(); - it < prior_vector.end(); it++ ) + it < prior_vector.end(); it++) delete *it; for (vector<ModFileStructuralInnovationPrior *>::iterator it = structural_innovation_prior_vector.begin(); - it < structural_innovation_prior_vector.end(); it++ ) + it < structural_innovation_prior_vector.end(); it++) delete *it; for (vector<ModFileMeasurementErrorPrior *>::iterator it = measurement_error_prior_vector.begin(); - it < measurement_error_prior_vector.end(); it++ ) + it < measurement_error_prior_vector.end(); it++) delete *it; for (vector<ModFileStructuralInnovationCorrPrior *>::iterator it = structural_innovation_corr_prior_vector.begin(); - it < structural_innovation_corr_prior_vector.end(); it++ ) + it < structural_innovation_corr_prior_vector.end(); it++) delete *it; for (vector<ModFileMeasurementErrorCorrPrior *>::iterator it = measurement_error_corr_prior_vector.begin(); - it < measurement_error_corr_prior_vector.end(); it++ ) + it < measurement_error_corr_prior_vector.end(); it++) delete *it; markov_switching_vector.clear(); diff --git a/others/cpp/dynare_cpp_driver.hh b/others/cpp/dynare_cpp_driver.hh index 9e39ee96e5c06e13154cf414a19f1059da9cf633..afdbc21a2ffa8d23d53e45a69981171f19692cd3 100644 --- a/others/cpp/dynare_cpp_driver.hh +++ b/others/cpp/dynare_cpp_driver.hh @@ -25,11 +25,12 @@ using namespace std; -struct aux_vars_t { +struct aux_vars_t +{ int endo_index, type, orig_index, orig_lead_lag; -} ; +}; -typedef map<pair<int, int >, double> restriction_map_t ; +typedef map<pair<int, int >, double> restriction_map_t; class ValueNotSetException { @@ -57,21 +58,49 @@ public: const vector<double> duration_arg, const restriction_map_t restriction_map_arg); - inline bool number_of_lags_has_val() const { return number_of_lags_was_passed; }; - inline bool restriction_map_has_val() const { return !restriction_map.empty(); }; + inline bool + number_of_lags_has_val() const + { + return number_of_lags_was_passed; + }; + inline bool + restriction_map_has_val() const + { + return !restriction_map.empty(); + }; - inline int get_chain() const { return chain; }; - inline int get_number_of_regimes() const { return number_of_regimes; }; + inline int + get_chain() const + { + return chain; + }; + inline int + get_number_of_regimes() const + { + return number_of_regimes; + }; int get_number_of_lags() throw (ValueNotSetException); - inline vector<int> get_parameters() { return parameters; }; - inline vector<double> get_duration() { return duration; }; + inline vector<int> + get_parameters() + { + return parameters; + }; + inline vector<double> + get_duration() + { + return duration; + }; restriction_map_t get_restriction_map() throw (ValueNotSetException); }; class BasicModFilePrior { private: - inline bool isnan(double x) const { return (x!=x); }; + inline bool + isnan(double x) const + { + return (x != x); + }; protected: const int index; const string shape; @@ -86,14 +115,42 @@ protected: const double variance_arg, const vector <double> domain_arg); public: - inline bool mean_has_val() const { return !isnan(mean); }; - inline bool mode_has_val() const { return !isnan(mode); }; - inline bool stdev_has_val() const { return !isnan(stdev); }; - inline bool variance_has_val() const { return !isnan(variance); }; - inline bool domain_has_val() const { return (domain.size() == 2); }; - - inline int get_index() const { return index; }; - inline string get_shape() const { return shape; }; + inline bool + mean_has_val() const + { + return !isnan(mean); + }; + inline bool + mode_has_val() const + { + return !isnan(mode); + }; + inline bool + stdev_has_val() const + { + return !isnan(stdev); + }; + inline bool + variance_has_val() const + { + return !isnan(variance); + }; + inline bool + domain_has_val() const + { + return (domain.size() == 2); + }; + + inline int + get_index() const + { + return index; + }; + inline string + get_shape() const + { + return shape; + }; double get_mean() throw (ValueNotSetException); double get_mode() throw (ValueNotSetException); double get_stdev() throw (ValueNotSetException); @@ -113,7 +170,7 @@ public: const vector <double> domain_arg); }; -class ModFileStructuralInnovationPrior: public BasicModFilePrior +class ModFileStructuralInnovationPrior : public BasicModFilePrior { public: ModFileStructuralInnovationPrior(const int index_arg, @@ -170,7 +227,11 @@ public: class BasicModFileOption { private: - inline bool isnan(double x) const { return (x!=x); }; + inline bool + isnan(double x) const + { + return (x != x); + }; protected: const int index; const double init; @@ -178,8 +239,16 @@ protected: BasicModFileOption(const int index_arg, const double init_arg); public: - inline int get_index() const { return index; }; - inline double get_init() const { return init; }; + inline int + get_index() const + { + return index; + }; + inline double + get_init() const + { + return init; + }; }; class ModFileOption : public BasicModFileOption @@ -189,7 +258,7 @@ public: const double init_arg); }; -class ModFileStructuralInnovationOption: public BasicModFileOption +class ModFileStructuralInnovationOption : public BasicModFileOption { public: ModFileStructuralInnovationOption(const int index_arg, @@ -257,65 +326,269 @@ public: vector<int> varobs_arg, vector<int> NNZDerivatives_arg); - inline void addMarkovSwitching(MarkovSwitching *ms) { markov_switching_vector.push_back(ms); }; - - inline void addPrior(ModFilePrior *p) { prior_vector.push_back(p); }; - inline void addStructuralInnovationPrior(ModFileStructuralInnovationPrior *sip) { structural_innovation_prior_vector.push_back(sip); }; - inline void addMeasurementErrorPrior(ModFileMeasurementErrorPrior *mep) { measurement_error_prior_vector.push_back(mep); }; - inline void addStructuralInnovationCorrPrior(ModFileStructuralInnovationCorrPrior *sicp) { structural_innovation_corr_prior_vector.push_back(sicp); }; - inline void addMeasurementErrorCorrPrior(ModFileMeasurementErrorCorrPrior *mecp) { measurement_error_corr_prior_vector.push_back(mecp); }; - - inline void addOption(ModFileOption *o) { option_vector.push_back(o); }; - inline void addStructuralInnovationOption(ModFileStructuralInnovationOption *sio) { structural_innovation_option_vector.push_back(sio); }; - inline void addMeasurementErrorOption(ModFileMeasurementErrorOption *meo) { measurement_error_option_vector.push_back(meo); }; - inline void addStructuralInnovationCorrOption(ModFileStructuralInnovationCorrOption *sico) { structural_innovation_corr_option_vector.push_back(sico); }; - inline void addMeasurementErrorCorrOption(ModFileMeasurementErrorCorrOption *meco) { measurement_error_corr_option_vector.push_back(meco); }; - - inline bool markov_switching_has_val() { return !markov_switching_vector.empty(); }; - inline bool prior_has_val() { return !prior_vector.empty(); }; - inline bool structural_innovation_prior_has_val() { return !structural_innovation_prior_vector.empty(); }; - inline bool measurement_error_prior_has_val() { return !measurement_error_prior_vector.empty(); }; - inline bool structural_innovation_corr_prior_has_val() { return !structural_innovation_corr_prior_vector.empty(); }; - inline bool measurement_error_corr_prior_has_val() { return !measurement_error_corr_prior_vector.empty(); }; - - inline bool option_has_val() { return !option_vector.empty(); }; - inline bool structural_innovation_option_has_val() { return !structural_innovation_option_vector.empty(); }; - inline bool measurement_error_option_has_val() { return !measurement_error_option_vector.empty(); }; - inline bool structural_innovation_corr_option_has_val() { return !structural_innovation_corr_option_vector.empty(); }; - inline bool measurement_error_corr_option_has_val() { return !measurement_error_corr_option_vector.empty(); }; - - inline vector<MarkovSwitching *>get_markov_switching() { return markov_switching_vector; }; - inline vector<ModFilePrior *> get_prior() { return prior_vector; }; - inline vector<ModFileStructuralInnovationPrior *> get_structural_innovation_prior() { return structural_innovation_prior_vector; }; - inline vector<ModFileMeasurementErrorPrior *> get_measurement_error_prior() { return measurement_error_prior_vector; }; - inline vector<ModFileStructuralInnovationCorrPrior *> get_structural_innovation_corr_prior() { return structural_innovation_corr_prior_vector; }; - inline vector<ModFileMeasurementErrorCorrPrior *> get_measurement_error_corr_prior() { return measurement_error_corr_prior_vector; }; - - inline vector<ModFileOption *> get_option() { return option_vector; }; - inline vector<ModFileStructuralInnovationOption *> get_structural_innovation_option() { return structural_innovation_option_vector; }; - inline vector<ModFileMeasurementErrorOption *> get_measurement_error_option() { return measurement_error_option_vector; }; - inline vector<ModFileStructuralInnovationCorrOption *> get_structural_innovation_corr_option() { return structural_innovation_corr_option_vector; }; - inline vector<ModFileMeasurementErrorCorrOption *> get_measurement_error_corr_option() { return measurement_error_corr_option_vector; }; - - inline map<string, int > get_exo_names() { return exo_names; }; - inline map<string, int > get_exo_det_names() { return exo_det_names; }; - inline map<string, int > get_endo_names() { return endo_names; }; - inline map<string, int > get_param_names() { return param_names; }; - inline vector<double> get_params() { return params; }; - inline double *get_params_data(void) { return params.data(); }; - inline vector <aux_vars_t> get_aux_vars() { return aux_vars; }; - inline vector <int> get_predetermined_variables() { return predetermined_variables; }; - inline vector <int> get_varobs() { return varobs; }; - inline vector<int> get_NNZDerivatives() { return NNZDerivatives; }; - - inline int get_endo_nbr(void) { return endo_nbr; }; - inline int get_exo_nbr(void) { return exo_nbr; }; - inline int get_exo_det_nbr(void) { return exo_det_nbr; }; - inline int get_param_nbr(void) { return param_nbr; }; - inline vector<size_t> get_zeta_back(void) { return zeta_back; }; - inline vector<size_t> get_zeta_fwrd(void) { return zeta_fwrd; }; - inline vector<size_t> get_zeta_mixed(void) { return zeta_mixed; }; - inline vector<size_t> get_zeta_static(void) { return zeta_static; }; + inline void + addMarkovSwitching(MarkovSwitching *ms) + { + markov_switching_vector.push_back(ms); + }; + + inline void + addPrior(ModFilePrior *p) + { + prior_vector.push_back(p); + }; + inline void + addStructuralInnovationPrior(ModFileStructuralInnovationPrior *sip) + { + structural_innovation_prior_vector.push_back(sip); + }; + inline void + addMeasurementErrorPrior(ModFileMeasurementErrorPrior *mep) + { + measurement_error_prior_vector.push_back(mep); + }; + inline void + addStructuralInnovationCorrPrior(ModFileStructuralInnovationCorrPrior *sicp) + { + structural_innovation_corr_prior_vector.push_back(sicp); + }; + inline void + addMeasurementErrorCorrPrior(ModFileMeasurementErrorCorrPrior *mecp) + { + measurement_error_corr_prior_vector.push_back(mecp); + }; + + inline void + addOption(ModFileOption *o) + { + option_vector.push_back(o); + }; + inline void + addStructuralInnovationOption(ModFileStructuralInnovationOption *sio) + { + structural_innovation_option_vector.push_back(sio); + }; + inline void + addMeasurementErrorOption(ModFileMeasurementErrorOption *meo) + { + measurement_error_option_vector.push_back(meo); + }; + inline void + addStructuralInnovationCorrOption(ModFileStructuralInnovationCorrOption *sico) + { + structural_innovation_corr_option_vector.push_back(sico); + }; + inline void + addMeasurementErrorCorrOption(ModFileMeasurementErrorCorrOption *meco) + { + measurement_error_corr_option_vector.push_back(meco); + }; + + inline bool + markov_switching_has_val() + { + return !markov_switching_vector.empty(); + }; + inline bool + prior_has_val() + { + return !prior_vector.empty(); + }; + inline bool + structural_innovation_prior_has_val() + { + return !structural_innovation_prior_vector.empty(); + }; + inline bool + measurement_error_prior_has_val() + { + return !measurement_error_prior_vector.empty(); + }; + inline bool + structural_innovation_corr_prior_has_val() + { + return !structural_innovation_corr_prior_vector.empty(); + }; + inline bool + measurement_error_corr_prior_has_val() + { + return !measurement_error_corr_prior_vector.empty(); + }; + + inline bool + option_has_val() + { + return !option_vector.empty(); + }; + inline bool + structural_innovation_option_has_val() + { + return !structural_innovation_option_vector.empty(); + }; + inline bool + measurement_error_option_has_val() + { + return !measurement_error_option_vector.empty(); + }; + inline bool + structural_innovation_corr_option_has_val() + { + return !structural_innovation_corr_option_vector.empty(); + }; + inline bool + measurement_error_corr_option_has_val() + { + return !measurement_error_corr_option_vector.empty(); + }; + + inline vector<MarkovSwitching *> + get_markov_switching() + { + return markov_switching_vector; + }; + inline vector<ModFilePrior *> + get_prior() + { + return prior_vector; + }; + inline vector<ModFileStructuralInnovationPrior *> + get_structural_innovation_prior() + { + return structural_innovation_prior_vector; + }; + inline vector<ModFileMeasurementErrorPrior *> + get_measurement_error_prior() + { + return measurement_error_prior_vector; + }; + inline vector<ModFileStructuralInnovationCorrPrior *> + get_structural_innovation_corr_prior() + { + return structural_innovation_corr_prior_vector; + }; + inline vector<ModFileMeasurementErrorCorrPrior *> + get_measurement_error_corr_prior() + { + return measurement_error_corr_prior_vector; + }; + + inline vector<ModFileOption *> + get_option() + { + return option_vector; + }; + inline vector<ModFileStructuralInnovationOption *> + get_structural_innovation_option() + { + return structural_innovation_option_vector; + }; + inline vector<ModFileMeasurementErrorOption *> + get_measurement_error_option() + { + return measurement_error_option_vector; + }; + inline vector<ModFileStructuralInnovationCorrOption *> + get_structural_innovation_corr_option() + { + return structural_innovation_corr_option_vector; + }; + inline vector<ModFileMeasurementErrorCorrOption *> + get_measurement_error_corr_option() + { + return measurement_error_corr_option_vector; + }; + + inline map<string, int > + get_exo_names() + { + return exo_names; + }; + inline map<string, int > + get_exo_det_names() + { + return exo_det_names; + }; + inline map<string, int > + get_endo_names() + { + return endo_names; + }; + inline map<string, int > + get_param_names() + { + return param_names; + }; + inline vector<double> + get_params() + { + return params; + }; + inline double * + get_params_data(void) + { + return params.data(); + }; + inline vector <aux_vars_t> + get_aux_vars() + { + return aux_vars; + }; + inline vector <int> + get_predetermined_variables() + { + return predetermined_variables; + }; + inline vector <int> + get_varobs() + { + return varobs; + }; + inline vector<int> + get_NNZDerivatives() + { + return NNZDerivatives; + }; + + inline int + get_endo_nbr(void) + { + return endo_nbr; + }; + inline int + get_exo_nbr(void) + { + return exo_nbr; + }; + inline int + get_exo_det_nbr(void) + { + return exo_det_nbr; + }; + inline int + get_param_nbr(void) + { + return param_nbr; + }; + inline vector<size_t> + get_zeta_back(void) + { + return zeta_back; + }; + inline vector<size_t> + get_zeta_fwrd(void) + { + return zeta_fwrd; + }; + inline vector<size_t> + get_zeta_mixed(void) + { + return zeta_mixed; + }; + inline vector<size_t> + get_zeta_static(void) + { + return zeta_static; + }; string get_exo_name_by_index(int index) throw (ValueNotSetException); int get_exo_index_by_name(string name) throw (ValueNotSetException); diff --git a/others/cpp/dynare_driver.c b/others/cpp/dynare_driver.c index f6701dd4bd37cfd8743dbf1ee8262c9bf13ca283..2beec52600a7bfd0d8130e736aebc81fe61165f0 100644 --- a/others/cpp/dynare_driver.c +++ b/others/cpp/dynare_driver.c @@ -39,7 +39,7 @@ DynareInfo::DynareInfo(map<string, int > exo_names_arg, exo_nbr = exo_names.size(); exo_det_nbr = exo_det_names.size(); param_nbr = param_names.size(); - + exo_names = exo_names_arg; exo_det_names = exo_det_names_arg; endo_names = endo_names_arg; @@ -54,27 +54,27 @@ DynareInfo::DynareInfo(map<string, int > exo_names_arg, DynareInfo::~DynareInfo() { for (vector<MarkovSwitching *>::iterator it = markov_switching_vector.begin(); - it < markov_switching_vector.end(); it++ ) + it < markov_switching_vector.end(); it++) delete *it; for (vector<ModFilePrior *>::iterator it = prior_vector.begin(); - it < prior_vector.end(); it++ ) + it < prior_vector.end(); it++) delete *it; for (vector<ModFileStructuralInnovationPrior *>::iterator it = structural_innovation_prior_vector.begin(); - it < structural_innovation_prior_vector.end(); it++ ) + it < structural_innovation_prior_vector.end(); it++) delete *it; for (vector<ModFileMeasurementErrorPrior *>::iterator it = measurement_error_prior_vector.begin(); - it < measurement_error_prior_vector.end(); it++ ) + it < measurement_error_prior_vector.end(); it++) delete *it; for (vector<ModFileStructuralInnovationCorrPrior *>::iterator it = structural_innovation_corr_prior_vector.begin(); - it < structural_innovation_corr_prior_vector.end(); it++ ) + it < structural_innovation_corr_prior_vector.end(); it++) delete *it; for (vector<ModFileMeasurementErrorCorrPrior *>::iterator it = measurement_error_corr_prior_vector.begin(); - it < measurement_error_corr_prior_vector.end(); it++ ) + it < measurement_error_corr_prior_vector.end(); it++) delete *it; markov_switching_vector.clear(); diff --git a/others/cpp/dynare_driver.h b/others/cpp/dynare_driver.h index 581cdd6eae7f38d08155081a674516fbcee84b75..3dcb7acd9e0c94ff52943af5c8d24f9f79fd179f 100644 --- a/others/cpp/dynare_driver.h +++ b/others/cpp/dynare_driver.h @@ -25,11 +25,12 @@ using namespace std; -struct aux_vars_t { +struct aux_vars_t +{ int endo_index, type, orig_index, orig_lead_lag; -} ; +}; -typedef map<pair<int, int >, double> restriction_map_t ; +typedef map<pair<int, int >, double> restriction_map_t; class ValueNotSetException { @@ -57,21 +58,49 @@ public: const vector<double> duration_arg, const restriction_map_t restriction_map_arg); - inline bool number_of_lags_has_val() const { return number_of_lags_was_passed; }; - inline bool restriction_map_has_val() const { return !restriction_map.empty(); }; + inline bool + number_of_lags_has_val() const + { + return number_of_lags_was_passed; + }; + inline bool + restriction_map_has_val() const + { + return !restriction_map.empty(); + }; - inline int get_chain() const { return chain; }; - inline int get_number_of_regimes() const { return number_of_regimes; }; + inline int + get_chain() const + { + return chain; + }; + inline int + get_number_of_regimes() const + { + return number_of_regimes; + }; int get_number_of_lags() throw (ValueNotSetException); - inline vector<int> get_parameters() { return parameters; }; - inline vector<double> get_duration() { return duration; }; + inline vector<int> + get_parameters() + { + return parameters; + }; + inline vector<double> + get_duration() + { + return duration; + }; restriction_map_t get_restriction_map() throw (ValueNotSetException); }; class BasicModFilePrior { private: - inline bool isnan(double x) const { return (x!=x); }; + inline bool + isnan(double x) const + { + return (x != x); + }; protected: const int index; const string shape; @@ -86,14 +115,42 @@ protected: const double variance_arg, const vector <double> domain_arg); public: - inline bool mean_has_val() const { return !isnan(mean); }; - inline bool mode_has_val() const { return !isnan(mode); }; - inline bool stdev_has_val() const { return !isnan(stdev); }; - inline bool variance_has_val() const { return !isnan(variance); }; - inline bool domain_has_val() const { return (domain.size() == 2); }; - - inline int get_index() const { return index; }; - inline string get_shape() const { return shape; }; + inline bool + mean_has_val() const + { + return !isnan(mean); + }; + inline bool + mode_has_val() const + { + return !isnan(mode); + }; + inline bool + stdev_has_val() const + { + return !isnan(stdev); + }; + inline bool + variance_has_val() const + { + return !isnan(variance); + }; + inline bool + domain_has_val() const + { + return (domain.size() == 2); + }; + + inline int + get_index() const + { + return index; + }; + inline string + get_shape() const + { + return shape; + }; double get_mean() throw (ValueNotSetException); double get_mode() throw (ValueNotSetException); double get_stdev() throw (ValueNotSetException); @@ -113,7 +170,7 @@ public: const vector <double> domain_arg); }; -class ModFileStructuralInnovationPrior: public BasicModFilePrior +class ModFileStructuralInnovationPrior : public BasicModFilePrior { public: ModFileStructuralInnovationPrior(const int index_arg, @@ -170,7 +227,11 @@ public: class BasicModFileOption { private: - inline bool isnan(double x) const { return (x!=x); }; + inline bool + isnan(double x) const + { + return (x != x); + }; protected: const int index; const double init; @@ -178,8 +239,16 @@ protected: BasicModFileOption(const int index_arg, const double init_arg); public: - inline int get_index() const { return index; }; - inline double get_init() const { return init; }; + inline int + get_index() const + { + return index; + }; + inline double + get_init() const + { + return init; + }; }; class ModFileOption : public BasicModFileOption @@ -189,7 +258,7 @@ public: const double init_arg); }; -class ModFileStructuralInnovationOption: public BasicModFileOption +class ModFileStructuralInnovationOption : public BasicModFileOption { public: ModFileStructuralInnovationOption(const int index_arg, @@ -258,65 +327,269 @@ public: vector<int> NNZDerivatives_arg); ~DynareInfo(); - inline void addMarkovSwitching(MarkovSwitching *ms) { markov_switching_vector.push_back(ms); }; - - inline void addPrior(ModFilePrior *p) { prior_vector.push_back(p); }; - inline void addStructuralInnovationPrior(ModFileStructuralInnovationPrior *sip) { structural_innovation_prior_vector.push_back(sip); }; - inline void addMeasurementErrorPrior(ModFileMeasurementErrorPrior *mep) { measurement_error_prior_vector.push_back(mep); }; - inline void addStructuralInnovationCorrPrior(ModFileStructuralInnovationCorrPrior *sicp) { structural_innovation_corr_prior_vector.push_back(sicp); }; - inline void addMeasurementErrorCorrPrior(ModFileMeasurementErrorCorrPrior *mecp) { measurement_error_corr_prior_vector.push_back(mecp); }; - - inline void addOption(ModFileOption *o) { option_vector.push_back(o); }; - inline void addStructuralInnovationOption(ModFileStructuralInnovationOption *sio) { structural_innovation_option_vector.push_back(sio); }; - inline void addMeasurementErrorOption(ModFileMeasurementErrorOption *meo) { measurement_error_option_vector.push_back(meo); }; - inline void addStructuralInnovationCorrOption(ModFileStructuralInnovationCorrOption *sico) { structural_innovation_corr_option_vector.push_back(sico); }; - inline void addMeasurementErrorCorrOption(ModFileMeasurementErrorCorrOption *meco) { measurement_error_corr_option_vector.push_back(meco); }; - - inline bool markov_switching_has_val() { return !markov_switching_vector.empty(); }; - inline bool prior_has_val() { return !prior_vector.empty(); }; - inline bool structural_innovation_prior_has_val() { return !structural_innovation_prior_vector.empty(); }; - inline bool measurement_error_prior_has_val() { return !measurement_error_prior_vector.empty(); }; - inline bool structural_innovation_corr_prior_has_val() { return !structural_innovation_corr_prior_vector.empty(); }; - inline bool measurement_error_corr_prior_has_val() { return !measurement_error_corr_prior_vector.empty(); }; - - inline bool option_has_val() { return !option_vector.empty(); }; - inline bool structural_innovation_option_has_val() { return !structural_innovation_option_vector.empty(); }; - inline bool measurement_error_option_has_val() { return !measurement_error_option_vector.empty(); }; - inline bool structural_innovation_corr_option_has_val() { return !structural_innovation_corr_option_vector.empty(); }; - inline bool measurement_error_corr_option_has_val() { return !measurement_error_corr_option_vector.empty(); }; - - inline vector<MarkovSwitching *>get_markov_switching() { return markov_switching_vector; }; - inline vector<ModFilePrior *> get_prior() { return prior_vector; }; - inline vector<ModFileStructuralInnovationPrior *> get_structural_innovation_prior() { return structural_innovation_prior_vector; }; - inline vector<ModFileMeasurementErrorPrior *> get_measurement_error_prior() { return measurement_error_prior_vector; }; - inline vector<ModFileStructuralInnovationCorrPrior *> get_structural_innovation_corr_prior() { return structural_innovation_corr_prior_vector; }; - inline vector<ModFileMeasurementErrorCorrPrior *> get_measurement_error_corr_prior() { return measurement_error_corr_prior_vector; }; - - inline vector<ModFileOption *> get_option() { return option_vector; }; - inline vector<ModFileStructuralInnovationOption *> get_structural_innovation_option() { return structural_innovation_option_vector; }; - inline vector<ModFileMeasurementErrorOption *> get_measurement_error_option() { return measurement_error_option_vector; }; - inline vector<ModFileStructuralInnovationCorrOption *> get_structural_innovation_corr_option() { return structural_innovation_corr_option_vector; }; - inline vector<ModFileMeasurementErrorCorrOption *> get_measurement_error_corr_option() { return measurement_error_corr_option_vector; }; - - inline map<string, int > get_exo_names() { return exo_names; }; - inline map<string, int > get_exo_det_names() { return exo_det_names; }; - inline map<string, int > get_endo_names() { return endo_names; }; - inline map<string, int > get_param_names() { return param_names; }; - inline vector<double> get_params() { return params; }; - inline double *get_params_data(void) { return params.data(); }; - inline vector <aux_vars_t> get_aux_vars() { return aux_vars; }; - inline vector <int> get_predetermined_variables() { return predetermined_variables; }; - inline vector <int> get_varobs() { return varobs; }; - inline vector<int> get_NNZDerivatives() { return NNZDerivatives; }; - - inline int get_endo_nbr(void) { return endo_nbr; }; - inline int get_exo_nbr(void) { return exo_nbr; }; - inline int get_exo_det_nbr(void) { return exo_det_nbr; }; - inline int get_param_nbr(void) { return param_nbr; }; - inline vector<size_t> get_zeta_back(void) { return zeta_back; }; - inline vector<size_t> get_zeta_fwrd(void) { return zeta_fwrd; }; - inline vector<size_t> get_zeta_mixed(void) { return zeta_mixed; }; - inline vector<size_t> get_zeta_static(void) { return zeta_static; }; + inline void + addMarkovSwitching(MarkovSwitching *ms) + { + markov_switching_vector.push_back(ms); + }; + + inline void + addPrior(ModFilePrior *p) + { + prior_vector.push_back(p); + }; + inline void + addStructuralInnovationPrior(ModFileStructuralInnovationPrior *sip) + { + structural_innovation_prior_vector.push_back(sip); + }; + inline void + addMeasurementErrorPrior(ModFileMeasurementErrorPrior *mep) + { + measurement_error_prior_vector.push_back(mep); + }; + inline void + addStructuralInnovationCorrPrior(ModFileStructuralInnovationCorrPrior *sicp) + { + structural_innovation_corr_prior_vector.push_back(sicp); + }; + inline void + addMeasurementErrorCorrPrior(ModFileMeasurementErrorCorrPrior *mecp) + { + measurement_error_corr_prior_vector.push_back(mecp); + }; + + inline void + addOption(ModFileOption *o) + { + option_vector.push_back(o); + }; + inline void + addStructuralInnovationOption(ModFileStructuralInnovationOption *sio) + { + structural_innovation_option_vector.push_back(sio); + }; + inline void + addMeasurementErrorOption(ModFileMeasurementErrorOption *meo) + { + measurement_error_option_vector.push_back(meo); + }; + inline void + addStructuralInnovationCorrOption(ModFileStructuralInnovationCorrOption *sico) + { + structural_innovation_corr_option_vector.push_back(sico); + }; + inline void + addMeasurementErrorCorrOption(ModFileMeasurementErrorCorrOption *meco) + { + measurement_error_corr_option_vector.push_back(meco); + }; + + inline bool + markov_switching_has_val() + { + return !markov_switching_vector.empty(); + }; + inline bool + prior_has_val() + { + return !prior_vector.empty(); + }; + inline bool + structural_innovation_prior_has_val() + { + return !structural_innovation_prior_vector.empty(); + }; + inline bool + measurement_error_prior_has_val() + { + return !measurement_error_prior_vector.empty(); + }; + inline bool + structural_innovation_corr_prior_has_val() + { + return !structural_innovation_corr_prior_vector.empty(); + }; + inline bool + measurement_error_corr_prior_has_val() + { + return !measurement_error_corr_prior_vector.empty(); + }; + + inline bool + option_has_val() + { + return !option_vector.empty(); + }; + inline bool + structural_innovation_option_has_val() + { + return !structural_innovation_option_vector.empty(); + }; + inline bool + measurement_error_option_has_val() + { + return !measurement_error_option_vector.empty(); + }; + inline bool + structural_innovation_corr_option_has_val() + { + return !structural_innovation_corr_option_vector.empty(); + }; + inline bool + measurement_error_corr_option_has_val() + { + return !measurement_error_corr_option_vector.empty(); + }; + + inline vector<MarkovSwitching *> + get_markov_switching() + { + return markov_switching_vector; + }; + inline vector<ModFilePrior *> + get_prior() + { + return prior_vector; + }; + inline vector<ModFileStructuralInnovationPrior *> + get_structural_innovation_prior() + { + return structural_innovation_prior_vector; + }; + inline vector<ModFileMeasurementErrorPrior *> + get_measurement_error_prior() + { + return measurement_error_prior_vector; + }; + inline vector<ModFileStructuralInnovationCorrPrior *> + get_structural_innovation_corr_prior() + { + return structural_innovation_corr_prior_vector; + }; + inline vector<ModFileMeasurementErrorCorrPrior *> + get_measurement_error_corr_prior() + { + return measurement_error_corr_prior_vector; + }; + + inline vector<ModFileOption *> + get_option() + { + return option_vector; + }; + inline vector<ModFileStructuralInnovationOption *> + get_structural_innovation_option() + { + return structural_innovation_option_vector; + }; + inline vector<ModFileMeasurementErrorOption *> + get_measurement_error_option() + { + return measurement_error_option_vector; + }; + inline vector<ModFileStructuralInnovationCorrOption *> + get_structural_innovation_corr_option() + { + return structural_innovation_corr_option_vector; + }; + inline vector<ModFileMeasurementErrorCorrOption *> + get_measurement_error_corr_option() + { + return measurement_error_corr_option_vector; + }; + + inline map<string, int > + get_exo_names() + { + return exo_names; + }; + inline map<string, int > + get_exo_det_names() + { + return exo_det_names; + }; + inline map<string, int > + get_endo_names() + { + return endo_names; + }; + inline map<string, int > + get_param_names() + { + return param_names; + }; + inline vector<double> + get_params() + { + return params; + }; + inline double * + get_params_data(void) + { + return params.data(); + }; + inline vector <aux_vars_t> + get_aux_vars() + { + return aux_vars; + }; + inline vector <int> + get_predetermined_variables() + { + return predetermined_variables; + }; + inline vector <int> + get_varobs() + { + return varobs; + }; + inline vector<int> + get_NNZDerivatives() + { + return NNZDerivatives; + }; + + inline int + get_endo_nbr(void) + { + return endo_nbr; + }; + inline int + get_exo_nbr(void) + { + return exo_nbr; + }; + inline int + get_exo_det_nbr(void) + { + return exo_det_nbr; + }; + inline int + get_param_nbr(void) + { + return param_nbr; + }; + inline vector<size_t> + get_zeta_back(void) + { + return zeta_back; + }; + inline vector<size_t> + get_zeta_fwrd(void) + { + return zeta_fwrd; + }; + inline vector<size_t> + get_zeta_mixed(void) + { + return zeta_mixed; + }; + inline vector<size_t> + get_zeta_static(void) + { + return zeta_static; + }; string get_exo_name_by_index(int index) throw (ValueNotSetException); int get_exo_index_by_name(string name) throw (ValueNotSetException); diff --git a/others/cpp/ms_dsge_c_driver.cc b/others/cpp/ms_dsge_c_driver.cc index 6815205312b12c870e39226bb1245a7febf50fb1..b1183a845505421ec184d2b588a8c574cbc82f0d 100644 --- a/others/cpp/ms_dsge_c_driver.cc +++ b/others/cpp/ms_dsge_c_driver.cc @@ -50,27 +50,27 @@ MsDsgeInfo::MsDsgeInfo(map<string, int > exo_names_arg, MsDsgeInfo::~MsDsgeInfo() { for (vector<MarkovSwitching *>::iterator it = markov_switching_vector.begin(); - it < markov_switching_vector.end(); it++ ) + it < markov_switching_vector.end(); it++) delete *it; for (vector<ModFilePrior *>::iterator it = prior_vector.begin(); - it < prior_vector.end(); it++ ) + it < prior_vector.end(); it++) delete *it; for (vector<ModFileStructuralInnovationPrior *>::iterator it = structural_innovation_prior_vector.begin(); - it < structural_innovation_prior_vector.end(); it++ ) + it < structural_innovation_prior_vector.end(); it++) delete *it; for (vector<ModFileMeasurementErrorPrior *>::iterator it = measurement_error_prior_vector.begin(); - it < measurement_error_prior_vector.end(); it++ ) + it < measurement_error_prior_vector.end(); it++) delete *it; for (vector<ModFileStructuralInnovationCorrPrior *>::iterator it = structural_innovation_corr_prior_vector.begin(); - it < structural_innovation_corr_prior_vector.end(); it++ ) + it < structural_innovation_corr_prior_vector.end(); it++) delete *it; for (vector<ModFileMeasurementErrorCorrPrior *>::iterator it = measurement_error_corr_prior_vector.begin(); - it < measurement_error_corr_prior_vector.end(); it++ ) + it < measurement_error_corr_prior_vector.end(); it++) delete *it; markov_switching_vector.clear(); diff --git a/others/cpp/ms_dsge_c_driver.hh b/others/cpp/ms_dsge_c_driver.hh index 9e968b4b6cc08261e76c6cd6944d83b315220ffe..194cfa94dd446a55aefcd5fdcd43b2de83c2df8a 100644 --- a/others/cpp/ms_dsge_c_driver.hh +++ b/others/cpp/ms_dsge_c_driver.hh @@ -25,11 +25,12 @@ using namespace std; -struct aux_vars_t { +struct aux_vars_t +{ int endo_index, type, orig_index, orig_lead_lag; -} ; +}; -typedef map<pair<int, int >, double> restriction_map_t ; +typedef map<pair<int, int >, double> restriction_map_t; class ValueNotSetException { @@ -57,21 +58,49 @@ public: const vector<double> duration_arg, const restriction_map_t restriction_map_arg); - inline bool number_of_lags_has_val() const { return number_of_lags_was_passed; }; - inline bool restriction_map_has_val() const { return !restriction_map.empty(); }; + inline bool + number_of_lags_has_val() const + { + return number_of_lags_was_passed; + }; + inline bool + restriction_map_has_val() const + { + return !restriction_map.empty(); + }; - inline int get_chain() const { return chain; }; - inline int get_number_of_regimes() const { return number_of_regimes; }; + inline int + get_chain() const + { + return chain; + }; + inline int + get_number_of_regimes() const + { + return number_of_regimes; + }; int get_number_of_lags() throw (ValueNotSetException); - inline vector<int> get_parameters() { return parameters; }; - inline vector<double> get_duration() { return duration; }; + inline vector<int> + get_parameters() + { + return parameters; + }; + inline vector<double> + get_duration() + { + return duration; + }; restriction_map_t get_restriction_map() throw (ValueNotSetException); }; class BasicModFilePrior { private: - inline bool isnan(double x) const { return (x!=x); }; + inline bool + isnan(double x) const + { + return (x != x); + }; protected: const int index; const string shape; @@ -86,14 +115,42 @@ protected: const double variance_arg, const vector <double> domain_arg); public: - inline bool mean_has_val() const { return !isnan(mean); }; - inline bool mode_has_val() const { return !isnan(mode); }; - inline bool stdev_has_val() const { return !isnan(stdev); }; - inline bool variance_has_val() const { return !isnan(variance); }; - inline bool domain_has_val() const { return (domain.size() == 2); }; - - inline int get_index() const { return index; }; - inline string get_shape() const { return shape; }; + inline bool + mean_has_val() const + { + return !isnan(mean); + }; + inline bool + mode_has_val() const + { + return !isnan(mode); + }; + inline bool + stdev_has_val() const + { + return !isnan(stdev); + }; + inline bool + variance_has_val() const + { + return !isnan(variance); + }; + inline bool + domain_has_val() const + { + return (domain.size() == 2); + }; + + inline int + get_index() const + { + return index; + }; + inline string + get_shape() const + { + return shape; + }; double get_mean() throw (ValueNotSetException); double get_mode() throw (ValueNotSetException); double get_stdev() throw (ValueNotSetException); @@ -113,7 +170,7 @@ public: const vector <double> domain_arg); }; -class ModFileStructuralInnovationPrior: public BasicModFilePrior +class ModFileStructuralInnovationPrior : public BasicModFilePrior { public: ModFileStructuralInnovationPrior(const int index_arg, @@ -170,7 +227,11 @@ public: class BasicModFileOption { private: - inline bool isnan(double x) const { return (x!=x); }; + inline bool + isnan(double x) const + { + return (x != x); + }; protected: const int index; const double init; @@ -178,8 +239,16 @@ protected: BasicModFileOption(const int index_arg, const double init_arg); public: - inline int get_index() const { return index; }; - inline double get_init() const { return init; }; + inline int + get_index() const + { + return index; + }; + inline double + get_init() const + { + return init; + }; }; class ModFileOption : public BasicModFileOption @@ -189,7 +258,7 @@ public: const double init_arg); }; -class ModFileStructuralInnovationOption: public BasicModFileOption +class ModFileStructuralInnovationOption : public BasicModFileOption { public: ModFileStructuralInnovationOption(const int index_arg, @@ -242,7 +311,7 @@ private: vector<aux_vars_t> aux_vars; vector<int> predetermined_variables; vector<int> varobs; - vector<vector<int > >lead_lag_incidence; + vector<vector<int > > lead_lag_incidence; vector<double> NNZDerivatives; public: DynareInfo(map<string, int > exo_names_arg, @@ -257,56 +326,228 @@ public: vector<double> NNZDerivatives_arg); ~DynareInfo(); - inline void addMarkovSwitching(MarkovSwitching *ms) { markov_switching_vector.push_back(ms); }; - - inline void addPrior(ModFilePrior *p) { prior_vector.push_back(p); }; - inline void addStructuralInnovationPrior(ModFileStructuralInnovationPrior *sip) { structural_innovation_prior_vector.push_back(sip); }; - inline void addMeasurementErrorPrior(ModFileMeasurementErrorPrior *mep) { measurement_error_prior_vector.push_back(mep); }; - inline void addStructuralInnovationCorrPrior(ModFileStructuralInnovationCorrPrior *sicp) { structural_innovation_corr_prior_vector.push_back(sicp); }; - inline void addMeasurementErrorCorrPrior(ModFileMeasurementErrorCorrPrior *mecp) { measurement_error_corr_prior_vector.push_back(mecp); }; - - inline void addOption(ModFileOption *o) { option_vector.push_back(o); }; - inline void addStructuralInnovationOption(ModFileStructuralInnovationOption *sio) { structural_innovation_option_vector.push_back(sio); }; - inline void addMeasurementErrorOption(ModFileMeasurementErrorOption *meo) { measurement_error_option_vector.push_back(meo); }; - inline void addStructuralInnovationCorrOption(ModFileStructuralInnovationCorrOption *sico) { structural_innovation_corr_option_vector.push_back(sico); }; - inline void addMeasurementErrorCorrOption(ModFileMeasurementErrorCorrOption *meco) { measurement_error_corr_option_vector.push_back(meco); }; - - inline bool markov_switching_has_val() { return !markov_switching_vector.empty(); }; - inline bool prior_has_val() { return !prior_vector.empty(); }; - inline bool structural_innovation_prior_has_val() { return !structural_innovation_prior_vector.empty(); }; - inline bool measurement_error_prior_has_val() { return !measurement_error_prior_vector.empty(); }; - inline bool structural_innovation_corr_prior_has_val() { return !structural_innovation_corr_prior_vector.empty(); }; - inline bool measurement_error_corr_prior_has_val() { return !measurement_error_corr_prior_vector.empty(); }; - - inline bool option_has_val() { return !option_vector.empty(); }; - inline bool structural_innovation_option_has_val() { return !structural_innovation_option_vector.empty(); }; - inline bool measurement_error_option_has_val() { return !measurement_error_option_vector.empty(); }; - inline bool structural_innovation_corr_option_has_val() { return !structural_innovation_corr_option_vector.empty(); }; - inline bool measurement_error_corr_option_has_val() { return !measurement_error_corr_option_vector.empty(); }; - - inline vector<MarkovSwitching *>get_markov_switching() { return markov_switching_vector; }; - inline vector<ModFilePrior *> get_prior() { return prior_vector; }; - inline vector<ModFileStructuralInnovationPrior *> get_structural_innovation_prior() { return structural_innovation_prior_vector; }; - inline vector<ModFileMeasurementErrorPrior *> get_measurement_error_prior() { return measurement_error_prior_vector; }; - inline vector<ModFileStructuralInnovationCorrPrior *> get_structural_innovation_corr_prior() { return structural_innovation_corr_prior_vector; }; - inline vector<ModFileMeasurementErrorCorrPrior *> get_measurement_error_corr_prior() { return measurement_error_corr_prior_vector; }; - - inline vector<ModFileOption *> get_option() { return option_vector; }; - inline vector<ModFileStructuralInnovationOption *> get_structural_innovation_option() { return structural_innovation_option_vector; }; - inline vector<ModFileMeasurementErrorOption *> get_measurement_error_option() { return measurement_error_option_vector; }; - inline vector<ModFileStructuralInnovationCorrOption *> get_structural_innovation_corr_option() { return structural_innovation_corr_option_vector; }; - inline vector<ModFileMeasurementErrorCorrOption *> get_measurement_error_corr_option() { return measurement_error_corr_option_vector; }; - - inline map<string, int > get_exo_names() { return exo_names; }; - inline map<string, int > get_exo_det_names() { return exo_det_names; }; - inline map<string, int > get_endo_names() { return endo_names; }; - inline map<string, int > get_param_names() { return param_names; }; - inline map<int, double > get_params() { return params; }; - inline vector <aux_vars_t> get_aux_vars() { return aux_vars; }; - inline vector <int> get_predetermined_variables() { return predetermined_variables; }; - inline vector <int> get_varobs() { return varobs; }; - inline vector<vector<int > > get_lead_lag_incidence() { return lead_lag_incidence; }; - inline vector<double> get_NNZDerivatives() { return NNZDerivatives; }; + inline void + addMarkovSwitching(MarkovSwitching *ms) + { + markov_switching_vector.push_back(ms); + }; + + inline void + addPrior(ModFilePrior *p) + { + prior_vector.push_back(p); + }; + inline void + addStructuralInnovationPrior(ModFileStructuralInnovationPrior *sip) + { + structural_innovation_prior_vector.push_back(sip); + }; + inline void + addMeasurementErrorPrior(ModFileMeasurementErrorPrior *mep) + { + measurement_error_prior_vector.push_back(mep); + }; + inline void + addStructuralInnovationCorrPrior(ModFileStructuralInnovationCorrPrior *sicp) + { + structural_innovation_corr_prior_vector.push_back(sicp); + }; + inline void + addMeasurementErrorCorrPrior(ModFileMeasurementErrorCorrPrior *mecp) + { + measurement_error_corr_prior_vector.push_back(mecp); + }; + + inline void + addOption(ModFileOption *o) + { + option_vector.push_back(o); + }; + inline void + addStructuralInnovationOption(ModFileStructuralInnovationOption *sio) + { + structural_innovation_option_vector.push_back(sio); + }; + inline void + addMeasurementErrorOption(ModFileMeasurementErrorOption *meo) + { + measurement_error_option_vector.push_back(meo); + }; + inline void + addStructuralInnovationCorrOption(ModFileStructuralInnovationCorrOption *sico) + { + structural_innovation_corr_option_vector.push_back(sico); + }; + inline void + addMeasurementErrorCorrOption(ModFileMeasurementErrorCorrOption *meco) + { + measurement_error_corr_option_vector.push_back(meco); + }; + + inline bool + markov_switching_has_val() + { + return !markov_switching_vector.empty(); + }; + inline bool + prior_has_val() + { + return !prior_vector.empty(); + }; + inline bool + structural_innovation_prior_has_val() + { + return !structural_innovation_prior_vector.empty(); + }; + inline bool + measurement_error_prior_has_val() + { + return !measurement_error_prior_vector.empty(); + }; + inline bool + structural_innovation_corr_prior_has_val() + { + return !structural_innovation_corr_prior_vector.empty(); + }; + inline bool + measurement_error_corr_prior_has_val() + { + return !measurement_error_corr_prior_vector.empty(); + }; + + inline bool + option_has_val() + { + return !option_vector.empty(); + }; + inline bool + structural_innovation_option_has_val() + { + return !structural_innovation_option_vector.empty(); + }; + inline bool + measurement_error_option_has_val() + { + return !measurement_error_option_vector.empty(); + }; + inline bool + structural_innovation_corr_option_has_val() + { + return !structural_innovation_corr_option_vector.empty(); + }; + inline bool + measurement_error_corr_option_has_val() + { + return !measurement_error_corr_option_vector.empty(); + }; + + inline vector<MarkovSwitching *> + get_markov_switching() + { + return markov_switching_vector; + }; + inline vector<ModFilePrior *> + get_prior() + { + return prior_vector; + }; + inline vector<ModFileStructuralInnovationPrior *> + get_structural_innovation_prior() + { + return structural_innovation_prior_vector; + }; + inline vector<ModFileMeasurementErrorPrior *> + get_measurement_error_prior() + { + return measurement_error_prior_vector; + }; + inline vector<ModFileStructuralInnovationCorrPrior *> + get_structural_innovation_corr_prior() + { + return structural_innovation_corr_prior_vector; + }; + inline vector<ModFileMeasurementErrorCorrPrior *> + get_measurement_error_corr_prior() + { + return measurement_error_corr_prior_vector; + }; + + inline vector<ModFileOption *> + get_option() + { + return option_vector; + }; + inline vector<ModFileStructuralInnovationOption *> + get_structural_innovation_option() + { + return structural_innovation_option_vector; + }; + inline vector<ModFileMeasurementErrorOption *> + get_measurement_error_option() + { + return measurement_error_option_vector; + }; + inline vector<ModFileStructuralInnovationCorrOption *> + get_structural_innovation_corr_option() + { + return structural_innovation_corr_option_vector; + }; + inline vector<ModFileMeasurementErrorCorrOption *> + get_measurement_error_corr_option() + { + return measurement_error_corr_option_vector; + }; + + inline map<string, int > + get_exo_names() + { + return exo_names; + }; + inline map<string, int > + get_exo_det_names() + { + return exo_det_names; + }; + inline map<string, int > + get_endo_names() + { + return endo_names; + }; + inline map<string, int > + get_param_names() + { + return param_names; + }; + inline map<int, double > + get_params() + { + return params; + }; + inline vector <aux_vars_t> + get_aux_vars() + { + return aux_vars; + }; + inline vector <int> + get_predetermined_variables() + { + return predetermined_variables; + }; + inline vector <int> + get_varobs() + { + return varobs; + }; + inline vector<vector<int > > + get_lead_lag_incidence() + { + return lead_lag_incidence; + }; + inline vector<double> + get_NNZDerivatives() + { + return NNZDerivatives; + }; string get_exo_name_by_index(int index) throw (ValueNotSetException); int get_exo_index_by_name(string name) throw (ValueNotSetException); @@ -317,7 +558,7 @@ public: string get_param_name_by_index(int index) throw (ValueNotSetException); int get_param_index_by_name(string name) throw (ValueNotSetException); double get_param_value_by_index(int index) throw (ValueNotSetException); - vector<int >get_lead_lag_incidence_for_endo_var_by_index(int index) throw (ValueNotSetException); + vector<int > get_lead_lag_incidence_for_endo_var_by_index(int index) throw (ValueNotSetException); }; #endif // ! _DYNARE_CPP_DRIVER_HH diff --git a/others/cpp/tests/snes_1.cc b/others/cpp/tests/snes_1.cc index a5ddda6b23abef3e25b107eb47dfc41f38a2b3ac..1f03026e099b6d15b7c70baeeba8554617995bfd 100644 --- a/others/cpp/tests/snes_1.cc +++ b/others/cpp/tests/snes_1.cc @@ -6,40 +6,44 @@ #include "main_tao.h" DynareInfo *preprocessorOutput(void); -PetscErrorCode FormFunction(SNES snes,Vec y,Vec f,void *ctx); -PetscErrorCode FormJacobian(SNES snes,Vec y,Mat J, Mat B,void *ctx); -PetscErrorCode Monitor(SNES,PetscInt,PetscReal,void*); -PetscErrorCode PreCheck(SNESLineSearch,Vec,Vec,PetscBool*,void*); -PetscErrorCode PostCheck(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*); -PetscErrorCode PostSetSubKSP(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*); -PetscErrorCode MatrixFreePreconditioner(PC,Vec,Vec); +PetscErrorCode FormFunction(SNES snes, Vec y, Vec f, void *ctx); +PetscErrorCode FormJacobian(SNES snes, Vec y, Mat J, Mat B, void *ctx); +PetscErrorCode Monitor(SNES, PetscInt, PetscReal, void *); +PetscErrorCode PreCheck(SNESLineSearch, Vec, Vec, PetscBool *, void *); +PetscErrorCode PostCheck(SNESLineSearch, Vec, Vec, Vec, PetscBool *, PetscBool *, void *); +PetscErrorCode PostSetSubKSP(SNESLineSearch, Vec, Vec, Vec, PetscBool *, PetscBool *, void *); +PetscErrorCode MatrixFreePreconditioner(PC, Vec, Vec); static char help[] = "Testing"; /* - User-defined context for monitoring + User-defined context for monitoring */ -typedef struct { +typedef struct +{ PetscViewer viewer; } MonitorCtx; /* - User-defined context for checking candidate iterates that are - determined by line search methods + User-defined context for checking candidate iterates that are + determined by line search methods */ -typedef struct { +typedef struct +{ Vec last_step; /* previous iterate */ PetscReal tolerance; /* tolerance for changes between successive iterates */ AppCtx *user; } StepCheckCtx; -typedef struct { +typedef struct +{ PetscInt its0; /* num of prevous outer KSP iterations */ } SetSubKSPCtx; #undef __FUNCT__ #define __FUNCT__ "main" -int main(int argc, char **argv) +int +main(int argc, char **argv) { DynareInfo model_info; @@ -49,7 +53,7 @@ int main(int argc, char **argv) // Steady state double *steady_state = new double[endo_nbr]; int info; - steadystate(NULL,params, steady_state, &info); + steadystate(NULL, params, steady_state, &info); vector<int> NNZDerivatives = model_info.get_NNZDerivatives(); AppCtx user; /* user-defined work context */ user.exogenous = new double[exo_nbr]; @@ -65,237 +69,245 @@ int main(int argc, char **argv) user.val_ptr = new double[NNZDerivatives[0]]; user.initial_values = new double[user.endo_nbr]; user.terminal_values = new double[user.endo_nbr]; - for (int i=0; i < user.endo_nbr; ++i) + for (int i = 0; i < user.endo_nbr; ++i) { user.initial_values[i] = user.steady_state[i]; user.terminal_values[i] = user.steady_state[i]; } /* Initialize PETSc */ - PetscInitialize(&argc, &argv, (char *)0, help); + PetscInitialize(&argc, &argv, (char *) 0, help); PetscErrorCode ierr; /* Get number of processors */ PetscInt size; - ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr); + ierr = MPI_Comm_size(PETSC_COMM_WORLD, &size); CHKERRQ(ierr); /* Set periods a multiple of processor nbr */ - user.periods = size*ceil((double)user.periods/size); + user.periods = size*ceil((double) user.periods/size); user.nb_row_x = user.periods + 1; user.X = new double[user.nb_row_x*user.exo_nbr]; - for(double* px=user.X; px < user.X+user.nb_row_x*user.exo_nbr; px++) *px = 0.0; + for (double *px = user.X; px < user.X+user.nb_row_x*user.exo_nbr; px++) + *px = 0.0; user.X[1] = 0.01; user.X[1+user.nb_row_x] = 0.01; std::cout << size << " " << user.periods << " " << std::endl; PetscInt N = user.periods*user.endo_nbr; /* Create DMA */ - DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_GHOSTED,N,1,user.endo_nbr,NULL,&user.da); + DMDACreate1d(PETSC_COMM_WORLD, DM_BOUNDARY_GHOSTED, N, 1, user.endo_nbr, NULL, &user.da); - /* Allocate vector and Jacobian matrix */\ + /* Allocate vector and Jacobian matrix */ \ Vec Y, R; - DMCreateGlobalVector(user.da,&Y); - VecDuplicate(Y,&R); + DMCreateGlobalVector(user.da, &Y); + VecDuplicate(Y, &R); - Mat J ; - ierr = MatCreate(PETSC_COMM_WORLD,&J);CHKERRQ(ierr); - ierr = MatSetSizes(J,PETSC_DECIDE,PETSC_DECIDE,N,N);CHKERRQ(ierr); - ierr = MatSetFromOptions(J);CHKERRQ(ierr); - ierr = MatSetUp(J);CHKERRQ(ierr); + Mat J; + ierr = MatCreate(PETSC_COMM_WORLD, &J); CHKERRQ(ierr); + ierr = MatSetSizes(J, PETSC_DECIDE, PETSC_DECIDE, N, N); CHKERRQ(ierr); + ierr = MatSetFromOptions(J); CHKERRQ(ierr); + ierr = MatSetUp(J); CHKERRQ(ierr); /* - Get local grid boundaries (for 1-dimensional DMDA): - xs, xm - starting grid index, width of local grid (no ghost points) + Get local grid boundaries (for 1-dimensional DMDA): + xs, xm - starting grid index, width of local grid (no ghost points) */ PetscInt xs, xm, xsg, xmg; - DMDAGetCorners(user.da,&xs,NULL,NULL,&xm,NULL,NULL); + DMDAGetCorners(user.da, &xs, NULL, NULL, &xm, NULL, NULL); std::cout << xs << " " << xm << std::endl; - DMDAGetGhostCorners(user.da,&xsg,NULL,NULL,&xmg,NULL,NULL); + DMDAGetGhostCorners(user.da, &xsg, NULL, NULL, &xmg, NULL, NULL); std::cout << "ghost " << xsg << " " << xmg << std::endl; /* Get pointers to vector data */ PetscScalar *YY; - DMDAVecGetArray(user.da,Y,&YY); - + DMDAVecGetArray(user.da, Y, &YY); + /* Compute local vector entries */ - for (int i=xs; i<xs+xm; i += user.endo_nbr) - for (int j=0; j < user.endo_nbr; j++) + for (int i = xs; i < xs+xm; i += user.endo_nbr) + for (int j = 0; j < user.endo_nbr; j++) YY[i+j] = steady_state[j]; /* Restore vectors */ - DMDAVecRestoreArray(user.da,Y,&YY); + DMDAVecRestoreArray(user.da, Y, &YY); SNES snes; - ierr = SNESCreate(PETSC_COMM_WORLD,&snes);CHKERRQ(ierr); - + ierr = SNESCreate(PETSC_COMM_WORLD, &snes); CHKERRQ(ierr); + // SNES snes; SNESLineSearch linesearch; /* SNESLineSearch context */ MonitorCtx monP; /* monitoring context */ StepCheckCtx checkP; /* step-checking context */ SetSubKSPCtx checkP1; - PetscBool pre_check,post_check,post_setsubksp; /* flag indicating whether we're checking candidate iterates */ - PetscReal abstol,rtol,stol,norm; - PetscInt its,maxit,maxf; + PetscBool pre_check, post_check, post_setsubksp; /* flag indicating whether we're checking candidate iterates */ + PetscReal abstol, rtol, stol, norm; + PetscInt its, maxit, maxf; PetscBool flg; - + /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create nonlinear solver context - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ - ierr = SNESCreate(PETSC_COMM_WORLD,&snes);CHKERRQ(ierr); + ierr = SNESCreate(PETSC_COMM_WORLD, &snes); CHKERRQ(ierr); /* - Set function evaluation routine and vector. Whenever the nonlinear - solver needs to compute the nonlinear function, it will call this - routine. - - Note that the final routine argument is the user-defined - context that provides application-specific data for the - function evaluation routine. + Set function evaluation routine and vector. Whenever the nonlinear + solver needs to compute the nonlinear function, it will call this + routine. + - Note that the final routine argument is the user-defined + context that provides application-specific data for the + function evaluation routine. */ - ierr = SNESSetFunction(snes,R,FormFunction,&user);CHKERRQ(ierr); + ierr = SNESSetFunction(snes, R, FormFunction, &user); CHKERRQ(ierr); /* - Set Jacobian matrix data structure and default Jacobian evaluation - routine. Whenever the nonlinear solver needs to compute the - Jacobian matrix, it will call this routine. - - Note that the final routine argument is the user-defined - context that provides application-specific data for the - Jacobian evaluation routine. + Set Jacobian matrix data structure and default Jacobian evaluation + routine. Whenever the nonlinear solver needs to compute the + Jacobian matrix, it will call this routine. + - Note that the final routine argument is the user-defined + context that provides application-specific data for the + Jacobian evaluation routine. */ - ierr = SNESSetJacobian(snes,J,J,FormJacobian,&user);CHKERRQ(ierr); + ierr = SNESSetJacobian(snes, J, J, FormJacobian, &user); CHKERRQ(ierr); /* - Optional allow user provided preconditioner - */ - ierr = PetscOptionsHasName(NULL,NULL,"-user_precond",&flg);CHKERRQ(ierr); - if (flg) { - KSP ksp; - PC pc; - ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr); - ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr); - ierr = PCSetType(pc,PCSHELL);CHKERRQ(ierr); - ierr = PCShellSetApply(pc,MatrixFreePreconditioner);CHKERRQ(ierr); - } + Optional allow user provided preconditioner + */ + ierr = PetscOptionsHasName(NULL, NULL, "-user_precond", &flg); CHKERRQ(ierr); + if (flg) + { + KSP ksp; + PC pc; + ierr = SNESGetKSP(snes, &ksp); CHKERRQ(ierr); + ierr = KSPGetPC(ksp, &pc); CHKERRQ(ierr); + ierr = PCSetType(pc, PCSHELL); CHKERRQ(ierr); + ierr = PCShellSetApply(pc, MatrixFreePreconditioner); CHKERRQ(ierr); + } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Customize nonlinear solver; set runtime options - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* - Set an optional user-defined monitoring routine + Set an optional user-defined monitoring routine */ - ierr = PetscViewerDrawOpen(PETSC_COMM_WORLD,0,0,0,0,400,400,&monP.viewer);CHKERRQ(ierr); - ierr = SNESMonitorSet(snes,Monitor,&monP,0);CHKERRQ(ierr); + ierr = PetscViewerDrawOpen(PETSC_COMM_WORLD, 0, 0, 0, 0, 400, 400, &monP.viewer); CHKERRQ(ierr); + ierr = SNESMonitorSet(snes, Monitor, &monP, 0); CHKERRQ(ierr); /* - Set names for some vectors to facilitate monitoring (optional) + Set names for some vectors to facilitate monitoring (optional) */ - ierr = PetscObjectSetName((PetscObject)Y,"Approximate Solution");CHKERRQ(ierr); + ierr = PetscObjectSetName((PetscObject) Y, "Approximate Solution"); CHKERRQ(ierr); // ierr = PetscObjectSetName((PetscObject)U,"Exact Solution");CHKERRQ(ierr); /* - Set SNES/KSP/KSP/PC runtime options, e.g., - -snes_view -snes_monitor -ksp_type <ksp> -pc_type <pc> + Set SNES/KSP/KSP/PC runtime options, e.g., + -snes_view -snes_monitor -ksp_type <ksp> -pc_type <pc> */ KSP ksp; PC pc; - ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr); - ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr); - ierr = PCSetType(pc,PCLU);CHKERRQ(ierr); + ierr = SNESGetKSP(snes, &ksp); CHKERRQ(ierr); + ierr = KSPGetPC(ksp, &pc); CHKERRQ(ierr); + ierr = PCSetType(pc, PCLU); CHKERRQ(ierr); // PetscOptionsSetValue(NULL,"-pc_type","lu"); - ierr = SNESSetFromOptions(snes);CHKERRQ(ierr); + ierr = SNESSetFromOptions(snes); CHKERRQ(ierr); /* - Set an optional user-defined routine to check the validity of candidate - iterates that are determined by line search methods + Set an optional user-defined routine to check the validity of candidate + iterates that are determined by line search methods */ - ierr = SNESGetLineSearch(snes, &linesearch);CHKERRQ(ierr); - ierr = PetscOptionsHasName(NULL,NULL,"-post_check_iterates",&post_check);CHKERRQ(ierr); + ierr = SNESGetLineSearch(snes, &linesearch); CHKERRQ(ierr); + ierr = PetscOptionsHasName(NULL, NULL, "-post_check_iterates", &post_check); CHKERRQ(ierr); - if (post_check) { - ierr = PetscPrintf(PETSC_COMM_WORLD,"Activating post step checking routine\n");CHKERRQ(ierr); - ierr = SNESLineSearchSetPostCheck(linesearch,PostCheck,&checkP);CHKERRQ(ierr); - ierr = VecDuplicate(Y,&(checkP.last_step));CHKERRQ(ierr); + if (post_check) + { + ierr = PetscPrintf(PETSC_COMM_WORLD, "Activating post step checking routine\n"); CHKERRQ(ierr); + ierr = SNESLineSearchSetPostCheck(linesearch, PostCheck, &checkP); CHKERRQ(ierr); + ierr = VecDuplicate(Y, &(checkP.last_step)); CHKERRQ(ierr); - checkP.tolerance = 1.0; - checkP.user = &user; + checkP.tolerance = 1.0; + checkP.user = &user; - ierr = PetscOptionsGetReal(NULL,NULL,"-check_tol",&checkP.tolerance,NULL);CHKERRQ(ierr); - } + ierr = PetscOptionsGetReal(NULL, NULL, "-check_tol", &checkP.tolerance, NULL); CHKERRQ(ierr); + } - ierr = PetscOptionsHasName(NULL,NULL,"-post_setsubksp",&post_setsubksp);CHKERRQ(ierr); - if (post_setsubksp) { - ierr = PetscPrintf(PETSC_COMM_WORLD,"Activating post setsubksp\n");CHKERRQ(ierr); - ierr = SNESLineSearchSetPostCheck(linesearch,PostSetSubKSP,&checkP1);CHKERRQ(ierr); - } + ierr = PetscOptionsHasName(NULL, NULL, "-post_setsubksp", &post_setsubksp); CHKERRQ(ierr); + if (post_setsubksp) + { + ierr = PetscPrintf(PETSC_COMM_WORLD, "Activating post setsubksp\n"); CHKERRQ(ierr); + ierr = SNESLineSearchSetPostCheck(linesearch, PostSetSubKSP, &checkP1); CHKERRQ(ierr); + } - ierr = PetscOptionsHasName(NULL,NULL,"-pre_check_iterates",&pre_check);CHKERRQ(ierr); - if (pre_check) { - ierr = PetscPrintf(PETSC_COMM_WORLD,"Activating pre step checking routine\n");CHKERRQ(ierr); - ierr = SNESLineSearchSetPreCheck(linesearch,PreCheck,&checkP);CHKERRQ(ierr); - } + ierr = PetscOptionsHasName(NULL, NULL, "-pre_check_iterates", &pre_check); CHKERRQ(ierr); + if (pre_check) + { + ierr = PetscPrintf(PETSC_COMM_WORLD, "Activating pre step checking routine\n"); CHKERRQ(ierr); + ierr = SNESLineSearchSetPreCheck(linesearch, PreCheck, &checkP); CHKERRQ(ierr); + } /* - Print parameters used for convergence testing (optional) ... just - to demonstrate this routine; this information is also printed with - the option -snes_view + Print parameters used for convergence testing (optional) ... just + to demonstrate this routine; this information is also printed with + the option -snes_view */ - ierr = SNESGetTolerances(snes,&abstol,&rtol,&stol,&maxit,&maxf);CHKERRQ(ierr); - ierr = PetscPrintf(PETSC_COMM_WORLD,"atol=%g, rtol=%g, stol=%g, maxit=%D, maxf=%D\n",(double)abstol,(double)rtol,(double)stol,maxit,maxf);CHKERRQ(ierr); + ierr = SNESGetTolerances(snes, &abstol, &rtol, &stol, &maxit, &maxf); CHKERRQ(ierr); + ierr = PetscPrintf(PETSC_COMM_WORLD, "atol=%g, rtol=%g, stol=%g, maxit=%D, maxf=%D\n", (double) abstol, (double) rtol, (double) stol, maxit, maxf); CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Evaluate initial guess; then solve nonlinear system - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* - Note: The user should initialize the vector, x, with the initial guess - for the nonlinear solver prior to calling SNESSolve(). In particular, - to employ an initial guess of zero, the user should explicitly set - this vector to zero by calling VecSet(). + Note: The user should initialize the vector, x, with the initial guess + for the nonlinear solver prior to calling SNESSolve(). In particular, + to employ an initial guess of zero, the user should explicitly set + this vector to zero by calling VecSet(). */ - ierr = SNESSolve(snes,NULL,Y);CHKERRQ(ierr); - ierr = SNESGetIterationNumber(snes,&its);CHKERRQ(ierr); - ierr = PetscPrintf(PETSC_COMM_WORLD,"Number of SNES iterations = %D\n",its);CHKERRQ(ierr); + ierr = SNESSolve(snes, NULL, Y); CHKERRQ(ierr); + ierr = SNESGetIterationNumber(snes, &its); CHKERRQ(ierr); + ierr = PetscPrintf(PETSC_COMM_WORLD, "Number of SNES iterations = %D\n", its); CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Check solution and clean up - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* - Free work space. All PETSc objects should be destroyed when they - are no longer needed. + Free work space. All PETSc objects should be destroyed when they + are no longer needed. */ - ierr = PetscViewerDestroy(&monP.viewer);CHKERRQ(ierr); - if (post_check) {ierr = VecDestroy(&checkP.last_step);CHKERRQ(ierr);} - ierr = SNESDestroy(&snes);CHKERRQ(ierr); - ierr = DMDestroy(&user.da);CHKERRQ(ierr); + ierr = PetscViewerDestroy(&monP.viewer); CHKERRQ(ierr); + if (post_check) + { + ierr = VecDestroy(&checkP.last_step); CHKERRQ(ierr); + } + ierr = SNESDestroy(&snes); CHKERRQ(ierr); + ierr = DMDestroy(&user.da); CHKERRQ(ierr); - - ierr = MatDestroy(&J);CHKERRQ(ierr); - ierr = VecDestroy(&Y);CHKERRQ(ierr); - ierr = VecDestroy(&R);CHKERRQ(ierr); - ierr = PetscFinalize();CHKERRQ(ierr); + ierr = MatDestroy(&J); CHKERRQ(ierr); + ierr = VecDestroy(&Y); CHKERRQ(ierr); + ierr = VecDestroy(&R); CHKERRQ(ierr); + ierr = PetscFinalize(); CHKERRQ(ierr); PetscFunctionReturn(0); } -PetscErrorCode FormFunction(SNES snes,Vec y,Vec f,void *ctx) +PetscErrorCode +FormFunction(SNES snes, Vec y, Vec f, void *ctx) { - AppCtx *user = (AppCtx*) ctx; + AppCtx *user = (AppCtx *) ctx; DM da = user->da; - PetscScalar *yy,*ff; - PetscInt M,ys,ym; + PetscScalar *yy, *ff; + PetscInt M, ys, ym; Vec ylocal; - DMGetLocalVector(da,&ylocal); + DMGetLocalVector(da, &ylocal); /* Scatter ghost points to local vector, using the 2-step process DMGlobalToLocalBegin(), DMGlobalToLocalEnd(). By placing code between these two statements, computations can be done while messages are in transition. */ - DMGlobalToLocalBegin(da,y,INSERT_VALUES,ylocal); - DMGlobalToLocalEnd(da,y,INSERT_VALUES,ylocal); + DMGlobalToLocalBegin(da, y, INSERT_VALUES, ylocal); + DMGlobalToLocalEnd(da, y, INSERT_VALUES, ylocal); /* Get pointers to vector data. @@ -303,15 +315,15 @@ PetscErrorCode FormFunction(SNES snes,Vec y,Vec f,void *ctx) NOT include ghost points. - Using DMDAVecGetArray() allows accessing the values using global ordering */ - DMDAVecGetArray(da,ylocal,&yy); - DMDAVecGetArray(da,f,&ff); + DMDAVecGetArray(da, ylocal, &yy); + DMDAVecGetArray(da, f, &ff); /* Get local grid boundaries (for 1-dimensional DMDA): ys, ym - starting grid index, width of local grid (no ghost points) */ - DMDAGetCorners(da,&ys,NULL,NULL,&ym,NULL,NULL); - DMDAGetInfo(da,NULL,&M,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); + DMDAGetCorners(da, &ys, NULL, NULL, &ym, NULL, NULL); + DMDAGetInfo(da, NULL, &M, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); /* Set function values for boundary points; define local interior grid point range: @@ -321,8 +333,10 @@ PetscErrorCode FormFunction(SNES snes,Vec y,Vec f,void *ctx) if (ys == 0) /* left boundary */ { PetscReal *y1 = new PetscReal[3*user->endo_nbr]; - for (int i=0; i < user->endo_nbr; ++i) y1[i] = user->initial_values[i]; - for (int i=0; i < 2*user->endo_nbr; ++i) y1[i+user->endo_nbr] = yy[i]; + for (int i = 0; i < user->endo_nbr; ++i) + y1[i] = user->initial_values[i]; + for (int i = 0; i < 2*user->endo_nbr; ++i) + y1[i+user->endo_nbr] = yy[i]; Residuals(y1, user->X, user->nb_row_x, user->params, user->steady_state, 1, ff); ys += user->endo_nbr; ym -= user->endo_nbr; @@ -331,7 +345,7 @@ PetscErrorCode FormFunction(SNES snes,Vec y,Vec f,void *ctx) /* Compute function over locally owned part of the grid (interior points only) */ - while ( (ym >= user->endo_nbr) && (ys + 2*user->endo_nbr <= M) ) + while ((ym >= user->endo_nbr) && (ys + 2*user->endo_nbr <= M)) { int it = ys/user->endo_nbr + 2; Residuals(yy+ys-user->endo_nbr, user->X, user->nb_row_x, user->params, user->steady_state, it, ff+ys); @@ -339,42 +353,44 @@ PetscErrorCode FormFunction(SNES snes,Vec y,Vec f,void *ctx) ym -= user->endo_nbr; } - - if ( (ym >= user->endo_nbr) && (ys + 2*user->endo_nbr >= M) ) + if ((ym >= user->endo_nbr) && (ys + 2*user->endo_nbr >= M)) { int it = ys/user->endo_nbr + 1; PetscReal *y1 = new PetscReal[3*user->endo_nbr]; - for (int i=0; i < 2*user->endo_nbr; ++i) y1[i] = yy[ys+i-user->endo_nbr]; - for (int i=0; i < user->endo_nbr; ++i) y1[i+2*user->endo_nbr] = user->terminal_values[i]; + for (int i = 0; i < 2*user->endo_nbr; ++i) + y1[i] = yy[ys+i-user->endo_nbr]; + for (int i = 0; i < user->endo_nbr; ++i) + y1[i+2*user->endo_nbr] = user->terminal_values[i]; Residuals(y1, user->X, user->nb_row_x, user->params, user->steady_state, it, ff+ys); } /* Restore vectors */ - DMDAVecRestoreArray(da,ylocal,&yy); - DMDAVecRestoreArray(da,f,&ff); - DMRestoreLocalVector(da,&ylocal); - return(0); + DMDAVecRestoreArray(da, ylocal, &yy); + DMDAVecRestoreArray(da, f, &ff); + DMRestoreLocalVector(da, &ylocal); + return (0); } -PetscErrorCode FormJacobian(SNES snes,Vec y,Mat J, Mat B,void *ctx) +PetscErrorCode +FormJacobian(SNES snes, Vec y, Mat J, Mat B, void *ctx) { - AppCtx *user = (AppCtx*) ctx; + AppCtx *user = (AppCtx *) ctx; DM da = user->da; PetscScalar *yy; - PetscInt M,ys,ym,ierr; + PetscInt M, ys, ym, ierr; Vec ylocal; - DMGetLocalVector(da,&ylocal); + DMGetLocalVector(da, &ylocal); /* Scatter ghost points to local vector, using the 2-step process DMGlobalToLocalBegin(), DMGlobalToLocalEnd(). By placing code between these two statements, computations can be done while messages are in transition. */ - DMGlobalToLocalBegin(da,y,INSERT_VALUES,ylocal); - DMGlobalToLocalEnd(da,y,INSERT_VALUES,ylocal); + DMGlobalToLocalBegin(da, y, INSERT_VALUES, ylocal); + DMGlobalToLocalEnd(da, y, INSERT_VALUES, ylocal); /* Get pointers to vector data. @@ -382,14 +398,14 @@ PetscErrorCode FormJacobian(SNES snes,Vec y,Mat J, Mat B,void *ctx) NOT include ghost points. - Using DMDAVecGetArray() allows accessing the values using global ordering */ - DMDAVecGetArray(da,ylocal,&yy); + DMDAVecGetArray(da, ylocal, &yy); /* Get local grid boundaries (for 1-dimensional DMDA): ys, ym - starting grid index, width of local grid (no ghost points) */ - DMDAGetCorners(da,&ys,NULL,NULL,&ym,NULL,NULL); - DMDAGetInfo(da,NULL,&M,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); + DMDAGetCorners(da, &ys, NULL, NULL, &ym, NULL, NULL); + DMDAGetInfo(da, NULL, &M, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); /* Set function values for boundary points; define local interior grid point range: @@ -400,32 +416,34 @@ PetscErrorCode FormJacobian(SNES snes,Vec y,Mat J, Mat B,void *ctx) if (ys == 0) /* left boundary */ { PetscReal *y1 = new PetscReal[3*user->endo_nbr]; - for (int i=0; i < user->endo_nbr; ++i) y1[i] = user->initial_values[i]; - for (int i=0; i < 2*user->endo_nbr; ++i) y1[i+user->endo_nbr] = yy[i]; + for (int i = 0; i < user->endo_nbr; ++i) + y1[i] = user->initial_values[i]; + for (int i = 0; i < 2*user->endo_nbr; ++i) + y1[i+user->endo_nbr] = yy[i]; FirstDerivatives(y1, user->X, user->nb_row_x, user->params, user->steady_state, 1, NULL, user->row_ptr, user->col_ptr, user->val_ptr); - for (int* r=user->row_ptr; r < user->row_ptr+user->endo_nbr; r++) - { - int first_col = 0; - int ncol = 0; - int *pc = user->col_ptr + *r; - while(*(pc) < user->endo_nbr) - { - ++first_col; - ++pc; - } - while(pc < ((user->col_ptr)+*(r+1))) - { - if (*pc < 3*(user->endo_nbr)) - { - ++ncol; - *pc -= user->endo_nbr; - } - ++pc; - } - ierr = MatSetValues(J,1,&row,ncol,user->col_ptr + *r + first_col,user->val_ptr + *r + first_col,INSERT_VALUES); - CHKERRQ(ierr); - ++row; - } + for (int *r = user->row_ptr; r < user->row_ptr+user->endo_nbr; r++) + { + int first_col = 0; + int ncol = 0; + int *pc = user->col_ptr + *r; + while (*(pc) < user->endo_nbr) + { + ++first_col; + ++pc; + } + while (pc < ((user->col_ptr)+*(r+1))) + { + if (*pc < 3*(user->endo_nbr)) + { + ++ncol; + *pc -= user->endo_nbr; + } + ++pc; + } + ierr = MatSetValues(J, 1, &row, ncol, user->col_ptr + *r + first_col, user->val_ptr + *r + first_col, INSERT_VALUES); + CHKERRQ(ierr); + ++row; + } ys += user->endo_nbr; ym -= user->endo_nbr; } @@ -433,88 +451,90 @@ PetscErrorCode FormJacobian(SNES snes,Vec y,Mat J, Mat B,void *ctx) /* Compute function over locally owned part of the grid (interior points only) */ - while ( (ym >= user->endo_nbr) && (ys + 2*user->endo_nbr <= M) ) + while ((ym >= user->endo_nbr) && (ys + 2*user->endo_nbr <= M)) { int it = ys/user->endo_nbr + 2; FirstDerivatives(yy+ys-user->endo_nbr, user->X, user->nb_row_x, user->params, user->steady_state, it, NULL, user->row_ptr, user->col_ptr, user->val_ptr); - for (int* r=user->row_ptr; r < user->row_ptr+user->endo_nbr; r++) - { - int ncol = 0; - for(int *pc = user->col_ptr + *r; pc < user->col_ptr + *(r+1); ++pc) - if(*pc < 3*user->endo_nbr) - { - *pc += ys - user->endo_nbr; - ++ncol; - } - ierr = MatSetValues(J,1,&row,ncol,user->col_ptr + *r,user->val_ptr + *r,INSERT_VALUES); - CHKERRQ(ierr); - ++row; - } + for (int *r = user->row_ptr; r < user->row_ptr+user->endo_nbr; r++) + { + int ncol = 0; + for (int *pc = user->col_ptr + *r; pc < user->col_ptr + *(r+1); ++pc) + if (*pc < 3*user->endo_nbr) + { + *pc += ys - user->endo_nbr; + ++ncol; + } + ierr = MatSetValues(J, 1, &row, ncol, user->col_ptr + *r, user->val_ptr + *r, INSERT_VALUES); + CHKERRQ(ierr); + ++row; + } ys += user->endo_nbr; ym -= user->endo_nbr; } - - if ( (ym >= user->endo_nbr) && (ys + 2*user->endo_nbr >= M) ) + if ((ym >= user->endo_nbr) && (ys + 2*user->endo_nbr >= M)) { int it = ys/user->endo_nbr + 1; PetscReal *y1 = new PetscReal[3*user->endo_nbr]; - for (int i=0; i < 2*user->endo_nbr; ++i) y1[i] = yy[ys+i-user->endo_nbr]; - for (int i=0; i < user->endo_nbr; ++i) y1[i+2*user->endo_nbr] = user->terminal_values[i]; + for (int i = 0; i < 2*user->endo_nbr; ++i) + y1[i] = yy[ys+i-user->endo_nbr]; + for (int i = 0; i < user->endo_nbr; ++i) + y1[i+2*user->endo_nbr] = user->terminal_values[i]; FirstDerivatives(y1, user->X, user->nb_row_x, user->params, user->steady_state, it, NULL, user->row_ptr, user->col_ptr, user->val_ptr); - for (int* r=user->row_ptr; r < user->row_ptr+user->endo_nbr; r++) - { - int *pc = user->col_ptr + *r; - int ncol = 0; - while((*pc < 2*user->endo_nbr) && (pc < user->col_ptr + *(r+1))) - { - ++ncol; - *pc += ys - user->endo_nbr; - ++pc; - } - ierr = MatSetValues(J,1,&row,ncol,user->col_ptr + *r,user->val_ptr + *r,INSERT_VALUES); - CHKERRQ(ierr); - ++row; - } + for (int *r = user->row_ptr; r < user->row_ptr+user->endo_nbr; r++) + { + int *pc = user->col_ptr + *r; + int ncol = 0; + while ((*pc < 2*user->endo_nbr) && (pc < user->col_ptr + *(r+1))) + { + ++ncol; + *pc += ys - user->endo_nbr; + ++pc; + } + ierr = MatSetValues(J, 1, &row, ncol, user->col_ptr + *r, user->val_ptr + *r, INSERT_VALUES); + CHKERRQ(ierr); + ++row; + } } /* Restore vectors */ - ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); - DMDAVecRestoreArray(da,ylocal,&yy); - DMRestoreLocalVector(da,&ylocal); - ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); - return(0); + ierr = MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); + DMDAVecRestoreArray(da, ylocal, &yy); + DMRestoreLocalVector(da, &ylocal); + ierr = MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY); CHKERRQ(ierr); + return (0); } #undef __FUNCT__ #define __FUNCT__ "Monitor" /* - Monitor - Optional user-defined monitoring routine that views the - current iterate with an x-window plot. Set by SNESMonitorSet(). - - Input Parameters: - snes - the SNES context - its - iteration number - norm - 2-norm function value (may be estimated) - ctx - optional user-defined context for private data for the - monitor routine, as set by SNESMonitorSet() - - Note: - See the manpage for PetscViewerDrawOpen() for useful runtime options, - such as -nox to deactivate all x-window output. - */ -PetscErrorCode Monitor(SNES snes,PetscInt its,PetscReal fnorm,void *ctx) + Monitor - Optional user-defined monitoring routine that views the + current iterate with an x-window plot. Set by SNESMonitorSet(). + + Input Parameters: + snes - the SNES context + its - iteration number + norm - 2-norm function value (may be estimated) + ctx - optional user-defined context for private data for the + monitor routine, as set by SNESMonitorSet() + + Note: + See the manpage for PetscViewerDrawOpen() for useful runtime options, + such as -nox to deactivate all x-window output. +*/ +PetscErrorCode +Monitor(SNES snes, PetscInt its, PetscReal fnorm, void *ctx) { PetscErrorCode ierr; - MonitorCtx *monP = (MonitorCtx*) ctx; + MonitorCtx *monP = (MonitorCtx *) ctx; Vec x; PetscFunctionBeginUser; - ierr = PetscPrintf(PETSC_COMM_WORLD,"iter = %D,SNES Function norm %g\n",its,(double)fnorm);CHKERRQ(ierr); - ierr = SNESGetSolution(snes,&x);CHKERRQ(ierr); - ierr = VecView(x,monP->viewer);CHKERRQ(ierr); + ierr = PetscPrintf(PETSC_COMM_WORLD, "iter = %D,SNES Function norm %g\n", its, (double) fnorm); CHKERRQ(ierr); + ierr = SNESGetSolution(snes, &x); CHKERRQ(ierr); + ierr = VecView(x, monP->viewer); CHKERRQ(ierr); PetscFunctionReturn(0); } @@ -522,19 +542,20 @@ PetscErrorCode Monitor(SNES snes,PetscInt its,PetscReal fnorm,void *ctx) #undef __FUNCT__ #define __FUNCT__ "PreCheck" /* - PreCheck - Optional user-defined routine that checks the validity of - candidate steps of a line search method. Set by SNESLineSearchSetPreCheck(). - - Input Parameters: - snes - the SNES context - xcurrent - current solution - y - search direction and length - - Output Parameters: - y - proposed step (search direction and length) (possibly changed) - changed_y - tells if the step has changed or not - */ -PetscErrorCode PreCheck(SNESLineSearch linesearch,Vec xcurrent,Vec y, PetscBool *changed_y, void * ctx) + PreCheck - Optional user-defined routine that checks the validity of + candidate steps of a line search method. Set by SNESLineSearchSetPreCheck(). + + Input Parameters: + snes - the SNES context + xcurrent - current solution + y - search direction and length + + Output Parameters: + y - proposed step (search direction and length) (possibly changed) + changed_y - tells if the step has changed or not +*/ +PetscErrorCode +PreCheck(SNESLineSearch linesearch, Vec xcurrent, Vec y, PetscBool *changed_y, void *ctx) { PetscFunctionBeginUser; *changed_y = PETSC_FALSE; @@ -545,29 +566,30 @@ PetscErrorCode PreCheck(SNESLineSearch linesearch,Vec xcurrent,Vec y, PetscBool #undef __FUNCT__ #define __FUNCT__ "PostCheck" /* - PostCheck - Optional user-defined routine that checks the validity of - candidate steps of a line search method. Set by SNESLineSearchSetPostCheck(). - - Input Parameters: - snes - the SNES context - ctx - optional user-defined context for private data for the - monitor routine, as set by SNESLineSearchSetPostCheck() - xcurrent - current solution - y - search direction and length - x - the new candidate iterate - - Output Parameters: - y - proposed step (search direction and length) (possibly changed) - x - current iterate (possibly modified) - - */ -PetscErrorCode PostCheck(SNESLineSearch linesearch,Vec xcurrent,Vec y,Vec x,PetscBool *changed_y,PetscBool *changed_x, void * ctx) + PostCheck - Optional user-defined routine that checks the validity of + candidate steps of a line search method. Set by SNESLineSearchSetPostCheck(). + + Input Parameters: + snes - the SNES context + ctx - optional user-defined context for private data for the + monitor routine, as set by SNESLineSearchSetPostCheck() + xcurrent - current solution + y - search direction and length + x - the new candidate iterate + + Output Parameters: + y - proposed step (search direction and length) (possibly changed) + x - current iterate (possibly modified) + +*/ +PetscErrorCode +PostCheck(SNESLineSearch linesearch, Vec xcurrent, Vec y, Vec x, PetscBool *changed_y, PetscBool *changed_x, void *ctx) { PetscErrorCode ierr; - PetscInt i,iter,xs,xm; + PetscInt i, iter, xs, xm; StepCheckCtx *check; AppCtx *user; - PetscScalar *xa,*xa_last,tmp; + PetscScalar *xa, *xa_last, tmp; PetscReal rdiff; DM da; SNES snes; @@ -576,116 +598,124 @@ PetscErrorCode PostCheck(SNESLineSearch linesearch,Vec xcurrent,Vec y,Vec x,Pets *changed_x = PETSC_FALSE; *changed_y = PETSC_FALSE; - ierr = SNESLineSearchGetSNES(linesearch, &snes);CHKERRQ(ierr); - check = (StepCheckCtx*)ctx; + ierr = SNESLineSearchGetSNES(linesearch, &snes); CHKERRQ(ierr); + check = (StepCheckCtx *) ctx; user = check->user; - ierr = SNESGetIterationNumber(snes,&iter);CHKERRQ(ierr); - ierr = SNESLineSearchGetPreCheck(linesearch, NULL, (void**)&check);CHKERRQ(ierr); + ierr = SNESGetIterationNumber(snes, &iter); CHKERRQ(ierr); + ierr = SNESLineSearchGetPreCheck(linesearch, NULL, (void **) &check); CHKERRQ(ierr); /* iteration 1 indicates we are working on the second iteration */ - if (iter > 0) { - da = user->da; - ierr = PetscPrintf(PETSC_COMM_WORLD,"Checking candidate step at iteration %D with tolerance %g\n",iter,(double)check->tolerance);CHKERRQ(ierr); - - /* Access local array data */ - ierr = DMDAVecGetArray(da,check->last_step,&xa_last);CHKERRQ(ierr); - ierr = DMDAVecGetArray(da,x,&xa);CHKERRQ(ierr); - ierr = DMDAGetCorners(da,&xs,NULL,NULL,&xm,NULL,NULL);CHKERRQ(ierr); - - /* - If we fail the user-defined check for validity of the candidate iterate, - then modify the iterate as we like. (Note that the particular modification - below is intended simply to demonstrate how to manipulate this data, not - as a meaningful or appropriate choice.) - */ - for (i=xs; i<xs+xm; i++) { - if (!PetscAbsScalar(xa[i])) rdiff = 2*check->tolerance; - else rdiff = PetscAbsScalar((xa[i] - xa_last[i])/xa[i]); - if (rdiff > check->tolerance) { - tmp = xa[i]; - xa[i] = .5*(xa[i] + xa_last[i]); - *changed_x = PETSC_TRUE; - ierr = PetscPrintf(PETSC_COMM_WORLD," Altering entry %D: x=%g, x_last=%g, diff=%g, x_new=%g\n", - i,(double)PetscAbsScalar(tmp),(double)PetscAbsScalar(xa_last[i]),(double)rdiff,(double)PetscAbsScalar(xa[i]));CHKERRQ(ierr); - } + if (iter > 0) + { + da = user->da; + ierr = PetscPrintf(PETSC_COMM_WORLD, "Checking candidate step at iteration %D with tolerance %g\n", iter, (double) check->tolerance); CHKERRQ(ierr); + + /* Access local array data */ + ierr = DMDAVecGetArray(da, check->last_step, &xa_last); CHKERRQ(ierr); + ierr = DMDAVecGetArray(da, x, &xa); CHKERRQ(ierr); + ierr = DMDAGetCorners(da, &xs, NULL, NULL, &xm, NULL, NULL); CHKERRQ(ierr); + + /* + If we fail the user-defined check for validity of the candidate iterate, + then modify the iterate as we like. (Note that the particular modification + below is intended simply to demonstrate how to manipulate this data, not + as a meaningful or appropriate choice.) + */ + for (i = xs; i < xs+xm; i++) + { + if (!PetscAbsScalar(xa[i])) + rdiff = 2*check->tolerance; + else + rdiff = PetscAbsScalar((xa[i] - xa_last[i])/xa[i]); + if (rdiff > check->tolerance) + { + tmp = xa[i]; + xa[i] = .5*(xa[i] + xa_last[i]); + *changed_x = PETSC_TRUE; + ierr = PetscPrintf(PETSC_COMM_WORLD, " Altering entry %D: x=%g, x_last=%g, diff=%g, x_new=%g\n", + i, (double) PetscAbsScalar(tmp), (double) PetscAbsScalar(xa_last[i]), (double) rdiff, (double) PetscAbsScalar(xa[i])); CHKERRQ(ierr); + } + } + ierr = DMDAVecRestoreArray(da, check->last_step, &xa_last); CHKERRQ(ierr); + ierr = DMDAVecRestoreArray(da, x, &xa); CHKERRQ(ierr); } - ierr = DMDAVecRestoreArray(da,check->last_step,&xa_last);CHKERRQ(ierr); - ierr = DMDAVecRestoreArray(da,x,&xa);CHKERRQ(ierr); - } - ierr = VecCopy(x,check->last_step);CHKERRQ(ierr); + ierr = VecCopy(x, check->last_step); CHKERRQ(ierr); PetscFunctionReturn(0); } - /* ------------------------------------------------------------------- */ #undef __FUNCT__ #define __FUNCT__ "PostSetSubKSP" /* - PostSetSubKSP - Optional user-defined routine that reset SubKSP options when hierarchical bjacobi PC is used - e.g, - mpiexec -n 8 ./ex3 -nox -n 10000 -ksp_type fgmres -pc_type bjacobi -pc_bjacobi_blocks 4 -sub_ksp_type gmres -sub_ksp_max_it 3 -post_setsubksp -sub_ksp_rtol 1.e-16 - Set by SNESLineSearchSetPostCheck(). - - Input Parameters: - linesearch - the LineSearch context - xcurrent - current solution - y - search direction and length - x - the new candidate iterate - - Output Parameters: - y - proposed step (search direction and length) (possibly changed) - x - current iterate (possibly modified) - - */ -PetscErrorCode PostSetSubKSP(SNESLineSearch linesearch,Vec xcurrent,Vec y,Vec x,PetscBool *changed_y,PetscBool *changed_x, void * ctx) + PostSetSubKSP - Optional user-defined routine that reset SubKSP options when hierarchical bjacobi PC is used + e.g, + mpiexec -n 8 ./ex3 -nox -n 10000 -ksp_type fgmres -pc_type bjacobi -pc_bjacobi_blocks 4 -sub_ksp_type gmres -sub_ksp_max_it 3 -post_setsubksp -sub_ksp_rtol 1.e-16 + Set by SNESLineSearchSetPostCheck(). + + Input Parameters: + linesearch - the LineSearch context + xcurrent - current solution + y - search direction and length + x - the new candidate iterate + + Output Parameters: + y - proposed step (search direction and length) (possibly changed) + x - current iterate (possibly modified) + +*/ +PetscErrorCode +PostSetSubKSP(SNESLineSearch linesearch, Vec xcurrent, Vec y, Vec x, PetscBool *changed_y, PetscBool *changed_x, void *ctx) { PetscErrorCode ierr; SetSubKSPCtx *check; - PetscInt iter,its,sub_its,maxit; - KSP ksp,sub_ksp,*sub_ksps; + PetscInt iter, its, sub_its, maxit; + KSP ksp, sub_ksp, *sub_ksps; PC pc; PetscReal ksp_ratio; SNES snes; PetscFunctionBeginUser; - ierr = SNESLineSearchGetSNES(linesearch, &snes);CHKERRQ(ierr); - check = (SetSubKSPCtx*)ctx; - ierr = SNESGetIterationNumber(snes,&iter);CHKERRQ(ierr); - ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr); - ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr); - ierr = PCBJacobiGetSubKSP(pc,NULL,NULL,&sub_ksps);CHKERRQ(ierr); + ierr = SNESLineSearchGetSNES(linesearch, &snes); CHKERRQ(ierr); + check = (SetSubKSPCtx *) ctx; + ierr = SNESGetIterationNumber(snes, &iter); CHKERRQ(ierr); + ierr = SNESGetKSP(snes, &ksp); CHKERRQ(ierr); + ierr = KSPGetPC(ksp, &pc); CHKERRQ(ierr); + ierr = PCBJacobiGetSubKSP(pc, NULL, NULL, &sub_ksps); CHKERRQ(ierr); sub_ksp = sub_ksps[0]; - ierr = KSPGetIterationNumber(ksp,&its);CHKERRQ(ierr); /* outer KSP iteration number */ - ierr = KSPGetIterationNumber(sub_ksp,&sub_its);CHKERRQ(ierr); /* inner KSP iteration number */ - - if (iter) { - ierr = PetscPrintf(PETSC_COMM_WORLD," ...PostCheck snes iteration %D, ksp_it %d %d, subksp_it %d\n",iter,check->its0,its,sub_its);CHKERRQ(ierr); - ksp_ratio = ((PetscReal)(its))/check->its0; - maxit = (PetscInt)(ksp_ratio*sub_its + 0.5); - if (maxit < 2) maxit = 2; - ierr = KSPSetTolerances(sub_ksp,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT,maxit);CHKERRQ(ierr); - ierr = PetscPrintf(PETSC_COMM_WORLD," ...ksp_ratio %g, new maxit %d\n\n",ksp_ratio,maxit);CHKERRQ(ierr); - } + ierr = KSPGetIterationNumber(ksp, &its); CHKERRQ(ierr); /* outer KSP iteration number */ + ierr = KSPGetIterationNumber(sub_ksp, &sub_its); CHKERRQ(ierr); /* inner KSP iteration number */ + + if (iter) + { + ierr = PetscPrintf(PETSC_COMM_WORLD, " ...PostCheck snes iteration %D, ksp_it %d %d, subksp_it %d\n", iter, check->its0, its, sub_its); CHKERRQ(ierr); + ksp_ratio = ((PetscReal) (its))/check->its0; + maxit = (PetscInt) (ksp_ratio*sub_its + 0.5); + if (maxit < 2) + maxit = 2; + ierr = KSPSetTolerances(sub_ksp, PETSC_DEFAULT, PETSC_DEFAULT, PETSC_DEFAULT, maxit); CHKERRQ(ierr); + ierr = PetscPrintf(PETSC_COMM_WORLD, " ...ksp_ratio %g, new maxit %d\n\n", ksp_ratio, maxit); CHKERRQ(ierr); + } check->its0 = its; /* save current outer KSP iteration number */ PetscFunctionReturn(0); } /* ------------------------------------------------------------------- */ /* - MatrixFreePreconditioner - This routine demonstrates the use of a - user-provided preconditioner. This code implements just the null - preconditioner, which of course is not recommended for general use. + MatrixFreePreconditioner - This routine demonstrates the use of a + user-provided preconditioner. This code implements just the null + preconditioner, which of course is not recommended for general use. - Input Parameters: -+ pc - preconditioner -- x - input vector + Input Parameters: + + pc - preconditioner + - x - input vector - Output Parameter: -. y - preconditioned vector + Output Parameter: + . y - preconditioned vector */ -PetscErrorCode MatrixFreePreconditioner(PC pc,Vec x,Vec y) +PetscErrorCode +MatrixFreePreconditioner(PC pc, Vec x, Vec y) { PetscErrorCode ierr; - ierr = VecCopy(x,y);CHKERRQ(ierr); + ierr = VecCopy(x, y); CHKERRQ(ierr); return 0; } diff --git a/others/cpp/tests/test1.cc b/others/cpp/tests/test1.cc index 9e2c1304d8d8770f6edf34a2ef6aacda15931026..b5d773ac2063744ef393486fb7ceae20590072aa 100644 --- a/others/cpp/tests/test1.cc +++ b/others/cpp/tests/test1.cc @@ -3,9 +3,9 @@ #include "DecisionRules.hh" DynareInfo *preprocessorOutput(void); -extern "C"{ -void steadystate(double const*, double const*, double *, int *); -void FirstDerivatives(const double *y, double *x, int nb_row_x, double *params, double *steady_state, int it_, double *residual, double *g1, double *v2, double *v3); +extern "C" { + void steadystate(double const *, double const *, double *, int *); + void FirstDerivatives(const double *y, double *x, int nb_row_x, double *params, double *steady_state, int it_, double *residual, double *g1, double *v2, double *v3); } main(int argc, char **argv) { @@ -17,8 +17,8 @@ main(int argc, char **argv) // Steady state double *steady_state = new double[endo_nbr]; int info; - steadystate(NULL,params, steady_state, &info); - for (int i=0; i < endo_nbr; ++i) + steadystate(NULL, params, steady_state, &info); + for (int i = 0; i < endo_nbr; ++i) std::cout << model_info.get_endo_name_by_index(i) << " " << steady_state[i] << "\n"; // 1st order approximation @@ -54,7 +54,7 @@ main(int argc, char **argv) std::cout << "g1[44] = " << jacob_data[44] << endl; MatrixView jacob_tmp(jacob_data, endo_nbr, jacobian_col_nbr, endo_nbr); std::cout << "g1[44] = " << jacob_data[44] << endl; - std::cout << "jacob_tmp(2,7) = "<< jacob_tmp(2,7) << endl; + std::cout << "jacob_tmp(2,7) = "<< jacob_tmp(2, 7) << endl; Matrix jacobian(endo_nbr, jacobian_col_nbr), g_y(endo_nbr, nback+nmixed), g_u(endo_nbr, exo_nbr); jacobian = jacob_tmp; diff --git a/preprocessor/CodeInterpreter.hh b/preprocessor/CodeInterpreter.hh index ed695fc27761b477cb410b414fcb7ab3eeb9736f..7be9a05665f01cbd53550a201d075385d77c2a60 100644 --- a/preprocessor/CodeInterpreter.hh +++ b/preprocessor/CodeInterpreter.hh @@ -228,15 +228,15 @@ enum TrinaryOpcode }; enum external_function_type -{ - ExternalFunctionWithoutDerivative, - ExternalFunctionWithFirstDerivative, - ExternalFunctionWithFirstandSecondDerivative, - ExternalFunctionNumericalFirstDerivative, - ExternalFunctionFirstDerivative, - ExternalFunctionNumericalSecondDerivative, - ExternalFunctionSecondDerivative -}; + { + ExternalFunctionWithoutDerivative, + ExternalFunctionWithFirstDerivative, + ExternalFunctionWithFirstandSecondDerivative, + ExternalFunctionNumericalFirstDerivative, + ExternalFunctionFirstDerivative, + ExternalFunctionNumericalSecondDerivative, + ExternalFunctionSecondDerivative + }; enum PriorDistributions { @@ -1451,9 +1451,9 @@ public: exogenous = vector<unsigned int>(exogenous_arg); other_endogenous = vector<unsigned int>(other_endogenous_arg); is_linear = is_linear_arg; endo_nbr = endo_nbr_arg; Max_Lag = Max_Lag_arg; Max_Lead = Max_Lead_arg; u_count_int = u_count_int_arg; - nb_col_jacob = nb_col_jacob_arg; - det_exo_size = det_exo_size_arg; nb_col_det_exo_jacob = nb_col_det_exo_jacob_arg; - exo_size = exo_size_arg; nb_col_exo_jacob = nb_col_exo_jacob_arg; + nb_col_jacob = nb_col_jacob_arg; + det_exo_size = det_exo_size_arg; nb_col_det_exo_jacob = nb_col_det_exo_jacob_arg; + exo_size = exo_size_arg; nb_col_exo_jacob = nb_col_exo_jacob_arg; other_endo_size = other_endo_size_arg; nb_col_other_endo_jacob = nb_col_other_endo_jacob_arg; }; inline @@ -1467,7 +1467,7 @@ public: is_linear = is_linear_arg; endo_nbr = endo_nbr_arg; Max_Lag = Max_Lag_arg; Max_Lead = Max_Lead_arg; u_count_int = u_count_int_arg; nb_col_jacob = nb_col_jacob_arg; det_exo_size = 0; exo_size = 0; other_endo_size = 0; - nb_col_det_exo_jacob = 0;nb_col_exo_jacob = 0;nb_col_other_endo_jacob = 0; + nb_col_det_exo_jacob = 0; nb_col_exo_jacob = 0; nb_col_other_endo_jacob = 0; } inline unsigned int get_size() @@ -2025,4 +2025,3 @@ public: #endif #pragma pack(pop) #endif - diff --git a/preprocessor/ComputingTasks.cc b/preprocessor/ComputingTasks.cc index d441eca186cab27df9e1d88750c0dc3e34441962..859770dc08cda2d58726c5b99fb37b45412d15bd 100644 --- a/preprocessor/ComputingTasks.cc +++ b/preprocessor/ComputingTasks.cc @@ -150,11 +150,11 @@ PriorPosteriorFunctionStatement::checkPass(ModFileStructure &mod_file_struct, Wa { OptionsList::string_options_t::const_iterator it2 = options_list.string_options.find("function"); if (it2 == options_list.string_options.end() || it2->second.empty()) - { - cerr << "ERROR: both the prior_function and posterior_function commands require the 'function' argument" - << endl; - exit(EXIT_FAILURE); - } + { + cerr << "ERROR: both the prior_function and posterior_function commands require the 'function' argument" + << endl; + exit(EXIT_FAILURE); + } } void @@ -163,7 +163,7 @@ PriorPosteriorFunctionStatement::writeOutput(ostream &output, const string &base options_list.writeOutput(output); string type = "posterior"; if (prior_func) - type = "prior"; + type = "prior"; output << "oo_ = execute_prior_posterior_function(" << "'" << options_list.string_options.find("function")->second << "', " @@ -202,14 +202,14 @@ StochSimulStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli it = options_list.num_options.find("hp_filter"); OptionsList::num_options_t::const_iterator it1 = options_list.num_options.find("bandpass.indicator"); OptionsList::num_options_t::const_iterator it2 = options_list.num_options.find("one_sided_hp_filter"); - if ((it != options_list.num_options.end() && it1 != options_list.num_options.end()) || - (it != options_list.num_options.end() && it2 != options_list.num_options.end()) || - (it1 != options_list.num_options.end() && it2 != options_list.num_options.end())) - { - cerr << "ERROR: stoch_simul: can only use one of hp, one-sided hp, and bandpass filters" - << endl; - exit(EXIT_FAILURE); - } + if ((it != options_list.num_options.end() && it1 != options_list.num_options.end()) + || (it != options_list.num_options.end() && it2 != options_list.num_options.end()) + || (it1 != options_list.num_options.end() && it2 != options_list.num_options.end())) + { + cerr << "ERROR: stoch_simul: can only use one of hp, one-sided hp, and bandpass filters" + << endl; + exit(EXIT_FAILURE); + } } void @@ -243,7 +243,7 @@ ForecastStatement::writeOutput(ostream &output, const string &basename, bool min } RamseyModelStatement::RamseyModelStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg) : + const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), options_list(options_list_arg) { @@ -307,7 +307,7 @@ RamseyConstraintsStatement::RamseyConstraintsStatement(const constraints_t &cons void RamseyConstraintsStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) { - if ((mod_file_struct.ramsey_model_present != true) || ( mod_file_struct.ramsey_policy_present != true)) + if ((mod_file_struct.ramsey_model_present != true) || (mod_file_struct.ramsey_policy_present != true)) cerr << "ramsey_constraints: can only be used with ramsey_model or ramsey_policy" << endl; } @@ -318,26 +318,26 @@ RamseyConstraintsStatement::writeOutput(ostream &output, const string &basename, for (RamseyConstraintsStatement::constraints_t::const_iterator it = constraints.begin(); it != constraints.end(); ++it) { if (it != constraints.begin()) - output << ", "; + output << ", "; output << "{" << it->endo + 1 << ", '"; - switch(it->code) - { - case oLess: - output << '<'; - break; - case oGreater: - output << '>'; - break; - case oLessEqual: - output << "<="; - break; - case oGreaterEqual: - output << ">="; - break; - default: - cerr << "Ramsey constraints: this shouldn't happen." << endl; - exit(EXIT_FAILURE); - } + switch (it->code) + { + case oLess: + output << '<'; + break; + case oGreater: + output << '>'; + break; + case oLessEqual: + output << "<="; + break; + case oGreaterEqual: + output << ">="; + break; + default: + cerr << "Ramsey constraints: this shouldn't happen." << endl; + exit(EXIT_FAILURE); + } output << "', '"; it->expression->writeOutput(output); output << "'}" << endl; @@ -416,7 +416,7 @@ RamseyPolicyStatement::checkPass(ModFileStructure &mod_file_struct, WarningConso { // ramsey_model_present indicates that the model is augmented with the FOC of the planner problem mod_file_struct.ramsey_model_present = true; - // ramsey_policy_present indicates that ramsey_policy instruction for computation of first order approximation + // ramsey_policy_present indicates that ramsey_policy instruction for computation of first order approximation // of a stochastic Ramsey problem if present in the *.mod file mod_file_struct.ramsey_policy_present = true; @@ -490,7 +490,7 @@ RamseyPolicyStatement::writeOutput(ostream &output, const string &basename, bool } DiscretionaryPolicyStatement::DiscretionaryPolicyStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg) : + const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), options_list(options_list_arg) { @@ -566,16 +566,16 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli if (it != options_list.num_options.end()) { int order = atoi(it->second.c_str()); - + if (order > 2) { cerr << "ERROR: order > 2 is not supported in estimation" << endl; exit(EXIT_FAILURE); } - + mod_file_struct.order_option = max(mod_file_struct.order_option, order); } - + // Fill in mod_file_struct.partial_information it = options_list.num_options.find("partial_information"); if (it != options_list.num_options.end() && it->second == "1") @@ -588,8 +588,8 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli it = options_list.num_options.find("dsge_var"); if (it != options_list.num_options.end()) - // Fill in mod_file_struct.dsge_var_calibrated - mod_file_struct.dsge_var_calibrated = it->second; + // Fill in mod_file_struct.dsge_var_calibrated + mod_file_struct.dsge_var_calibrated = it->second; // Fill in mod_file_struct.dsge_var_estimated OptionsList::string_options_t::const_iterator it_str = options_list.string_options.find("dsge_var"); @@ -618,15 +618,15 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli exit(EXIT_FAILURE); } - if (options_list.string_options.find("datafile") == options_list.string_options.end() && - !mod_file_struct.estimation_data_statement_present) + if (options_list.string_options.find("datafile") == options_list.string_options.end() + && !mod_file_struct.estimation_data_statement_present) { cerr << "ERROR: The estimation statement requires a data file to be supplied via the datafile option." << endl; exit(EXIT_FAILURE); } - if (options_list.string_options.find("mode_file") != options_list.string_options.end() && - mod_file_struct.estim_params_use_calib) + if (options_list.string_options.find("mode_file") != options_list.string_options.end() + && mod_file_struct.estim_params_use_calib) { cerr << "ERROR: The mode_file option of the estimation statement is incompatible with the use_calibration option of the estimated_params_init block." << endl; exit(EXIT_FAILURE); @@ -686,7 +686,7 @@ DynareSensitivityStatement::writeOutput(ostream &output, const string &basename, OptionsList::string_options_t::const_iterator it2 = options_list.string_options.find("graph_format"); if (it2 != options_list.string_options.end()) output << "options_.graph_format = '" << it2->second << "';" << endl; - + output << "dynare_sensitivity(options_gsa);" << endl; } @@ -710,7 +710,7 @@ void UnitRootVarsStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const { output << "options_.diffuse_filter = 1;" << endl - << "options_.steadystate.nocheck = 1;" << endl; + << "options_.steadystate.nocheck = 1;" << endl; } PeriodsStatement::PeriodsStatement(int periods_arg) : periods(periods_arg) @@ -1369,8 +1369,8 @@ MSSBVAREstimationStatement::checkPass(ModFileStructure &mod_file_struct, Warning mod_file_struct.bvar_present = true; if (options_list.num_options.find("ms.create_init") == options_list.num_options.end()) - if (options_list.string_options.find("datafile") == options_list.string_options.end() || - options_list.num_options.find("ms.initial_year") == options_list.num_options.end()) + if (options_list.string_options.find("datafile") == options_list.string_options.end() + || options_list.num_options.find("ms.initial_year") == options_list.num_options.end()) { cerr << "ERROR: If you do not pass no_create_init to ms_estimation, " << "you must pass the datafile and initial_year options." << endl; @@ -1462,7 +1462,7 @@ MSSBVARComputeProbabilitiesStatement::writeOutput(ostream &output, const string } MSSBVARIrfStatement::MSSBVARIrfStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg) : + const OptionsList &options_list_arg) : symbol_list(symbol_list_arg), options_list(options_list_arg) { @@ -1489,14 +1489,14 @@ MSSBVARIrfStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli if (it != options_list.num_options.end()) filtered_probabilities_present = true; - if ((filtered_probabilities_present && regime_present) || - (filtered_probabilities_present && regimes_present) || - (regimes_present && regime_present)) - { - cerr << "ERROR: You may only pass one of regime, regimes and " - << "filtered_probabilities to ms_irf" << endl; - exit(EXIT_FAILURE); - } + if ((filtered_probabilities_present && regime_present) + || (filtered_probabilities_present && regimes_present) + || (regimes_present && regime_present)) + { + cerr << "ERROR: You may only pass one of regime, regimes and " + << "filtered_probabilities to ms_irf" << endl; + exit(EXIT_FAILURE); + } } void @@ -1560,14 +1560,14 @@ MSSBVARVarianceDecompositionStatement::checkPass(ModFileStructure &mod_file_stru if (it != options_list.num_options.end()) filtered_probabilities_present = true; - if ((filtered_probabilities_present && regime_present) || - (filtered_probabilities_present && regimes_present) || - (regimes_present && regime_present)) - { - cerr << "ERROR: You may only pass one of regime, regimes and " - << "filtered_probabilities to ms_variance_decomposition" << endl; - exit(EXIT_FAILURE); - } + if ((filtered_probabilities_present && regime_present) + || (filtered_probabilities_present && regimes_present) + || (regimes_present && regime_present)) + { + cerr << "ERROR: You may only pass one of regime, regimes and " + << "filtered_probabilities to ms_variance_decomposition" << endl; + exit(EXIT_FAILURE); + } } void @@ -1831,19 +1831,19 @@ SvarIdentificationStatement::writeOutput(ostream &output, const string &basename for (svar_identification_restrictions_t::const_iterator it = restrictions.begin(); it != restrictions.end(); it++) { assert(it->lag >= 0); - if (it->lag == 0) + if (it->lag == 0) output << "options_.ms.Qi{" << it->equation << "}(" << it->restriction_nbr << ", " << it->variable + 1 << ") = "; - else - { - int col = (it->lag-1)*n+it->variable+1; - if (col > k) + else + { + int col = (it->lag-1)*n+it->variable+1; + if (col > k) { cerr << "ERROR: lag =" << it->lag << ", num endog vars = " << n << "current endog var index = " << it->variable << ". Index " << "out of bounds. If the above does not represent a logical error, please report this to the Dyanre Team." << endl; exit(EXIT_FAILURE); } - output << "options_.ms.Ri{" << it->equation << "}(" << it->restriction_nbr << ", " << col << ") = "; - } + output << "options_.ms.Ri{" << it->equation << "}(" << it->restriction_nbr << ", " << col << ") = "; + } it->value->writeOutput(output); output << ";" << endl; } @@ -1858,21 +1858,21 @@ MarkovSwitchingStatement::MarkovSwitchingStatement(const OptionsList &options_li if (it_num != options_list.num_options.end()) { using namespace boost; - OptionsList::num_options_t::const_iterator it_num_regimes = - options_list.num_options.find("ms.number_of_regimes"); + OptionsList::num_options_t::const_iterator it_num_regimes + = options_list.num_options.find("ms.number_of_regimes"); assert(it_num_regimes != options_list.num_options.end()); int num_regimes = lexical_cast< int >(it_num_regimes->second); vector<string> tokenizedRestrictions; split(tokenizedRestrictions, it_num->second, is_any_of("["), token_compress_on); for (vector<string>::iterator it = tokenizedRestrictions.begin(); - it != tokenizedRestrictions.end(); it++ ) + it != tokenizedRestrictions.end(); it++) if (it->size() > 0) { vector<string> restriction; split(restriction, *it, is_any_of("], ")); for (vector<string>::iterator it1 = restriction.begin(); - it1 != restriction.end(); ) + it1 != restriction.end();) if (it1->empty()) restriction.erase(it1); else @@ -1941,16 +1941,16 @@ MarkovSwitchingStatement::checkPass(ModFileStructure &mod_file_struct, WarningCo if (it_num != options_list.num_options.end()) { using namespace boost; - OptionsList::num_options_t::const_iterator it_num_regimes = - options_list.num_options.find("ms.number_of_regimes"); + OptionsList::num_options_t::const_iterator it_num_regimes + = options_list.num_options.find("ms.number_of_regimes"); assert(it_num_regimes != options_list.num_options.end()); int num_regimes = lexical_cast< int >(it_num_regimes->second); - vector<double> col_trans_prob_sum (num_regimes, 0); - vector<double> row_trans_prob_sum (num_regimes, 0); - vector<bool> all_restrictions_in_row (num_regimes, true); - vector<bool> all_restrictions_in_col (num_regimes, true); - for (int row=0; row<num_regimes; row++) - for (int col=0; col<num_regimes; col++) + vector<double> col_trans_prob_sum(num_regimes, 0); + vector<double> row_trans_prob_sum(num_regimes, 0); + vector<bool> all_restrictions_in_row(num_regimes, true); + vector<bool> all_restrictions_in_col(num_regimes, true); + for (int row = 0; row < num_regimes; row++) + for (int col = 0; col < num_regimes; col++) if (restriction_map.find(make_pair(row+1, col+1)) != restriction_map.end()) { row_trans_prob_sum[row] += restriction_map[make_pair(row+1, col+1)]; @@ -1962,41 +1962,41 @@ MarkovSwitchingStatement::checkPass(ModFileStructure &mod_file_struct, WarningCo all_restrictions_in_col[col] = false; } - for (int i=0; i<num_regimes; i++) + for (int i = 0; i < num_regimes; i++) { if (all_restrictions_in_row[i]) - { - if (row_trans_prob_sum[i] != 1.0) + { + if (row_trans_prob_sum[i] != 1.0) + { + cerr << "ERROR: When all transitions probabilities are specified for a certain " + << "regime, they must sum to 1" << endl; + exit(EXIT_FAILURE); + } + } + else + if (row_trans_prob_sum[i] >= 1.0) { - cerr << "ERROR: When all transitions probabilities are specified for a certain " - << "regime, they must sum to 1" << endl; + cerr << "ERROR: When transition probabilites are not specified for every regime, " + << "their sum must be < 1" << endl; exit(EXIT_FAILURE); } - } - else - if (row_trans_prob_sum[i] >= 1.0) + + if (all_restrictions_in_col[i]) { - cerr << "ERROR: When transition probabilites are not specified for every regime, " - << "their sum must be < 1" << endl; - exit(EXIT_FAILURE); + if (col_trans_prob_sum[i] != 1.0) + { + cerr << "ERROR: When all transitions probabilities are specified for a certain " + << "regime, they must sum to 1" << endl; + exit(EXIT_FAILURE); + } } - - if (all_restrictions_in_col[i]) - { - if (col_trans_prob_sum[i] != 1.0) + else + if (col_trans_prob_sum[i] >= 1.0) { - cerr << "ERROR: When all transitions probabilities are specified for a certain " - << "regime, they must sum to 1" << endl; + cerr << "ERROR: When transition probabilites are not specified for every regime, " + << "their sum must be < 1" << endl; exit(EXIT_FAILURE); } - } - else - if (col_trans_prob_sum[i] >= 1.0) - { - cerr << "ERROR: When transition probabilites are not specified for every regime, " - << "their sum must be < 1" << endl; - exit(EXIT_FAILURE); - } } } @@ -2033,7 +2033,7 @@ MarkovSwitchingStatement::writeOutput(ostream &output, const string &basename, b } int restrictions_index = 0; - for (itR=restriction_map.begin(); itR != restriction_map.end(); itR++) + for (itR = restriction_map.begin(); itR != restriction_map.end(); itR++) output << "options_.ms.ms_chain(" << itChain->second << ").restrictions(" << ++restrictions_index << ") = {[" << itR->first.first << ", " << itR->first.second << ", " << itR->second << "]};" << endl; @@ -2044,8 +2044,8 @@ MarkovSwitchingStatement::writeCOutput(ostream &output, const string &basename) { output << endl; - OptionsList::num_options_t::const_iterator it = - options_list.num_options.find("ms.chain"); + OptionsList::num_options_t::const_iterator it + = options_list.num_options.find("ms.chain"); assert(it != options_list.num_options.end()); output << "chain = " << it->second << ";" << endl; @@ -2067,17 +2067,17 @@ MarkovSwitchingStatement::writeCOutput(ostream &output, const string &basename) vector<string> tokenizedDomain; split(tokenizedDomain, it->second, is_any_of("[ ]"), token_compress_on); for (vector<string>::iterator itvs = tokenizedDomain.begin(); - itvs != tokenizedDomain.end(); itvs++ ) + itvs != tokenizedDomain.end(); itvs++) if (!itvs->empty()) output << "duration.push_back(" << *itvs << ");" << endl; - OptionsList::symbol_list_options_t::const_iterator itsl = - options_list.symbol_list_options.find("ms.parameters"); + OptionsList::symbol_list_options_t::const_iterator itsl + = options_list.symbol_list_options.find("ms.parameters"); assert(itsl != options_list.symbol_list_options.end()); vector<string> parameters = itsl->second.get_symbols(); output << "parameters.clear();" << endl; for (vector<string>::iterator itp = parameters.begin(); - itp != parameters.end(); itp++ ) + itp != parameters.end(); itp++) output << "parameters.push_back(param_names[\"" << *itp << "\"]);" << endl; output << "restriction_map.clear();" << endl; @@ -2104,13 +2104,13 @@ SvarStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation it2 = options_list.string_options.find("ms.constants"); assert((it0 != options_list.string_options.end() && it1 == options_list.string_options.end() - && it2 == options_list.string_options.end()) || - (it0 == options_list.string_options.end() - && it1 != options_list.string_options.end() - && it2 == options_list.string_options.end()) || - (it0 == options_list.string_options.end() - && it1 == options_list.string_options.end() - && it2 != options_list.string_options.end())); + && it2 == options_list.string_options.end()) + || (it0 == options_list.string_options.end() + && it1 != options_list.string_options.end() + && it2 == options_list.string_options.end()) + || (it0 == options_list.string_options.end() + && it1 == options_list.string_options.end() + && it2 != options_list.string_options.end())); } void @@ -2193,15 +2193,15 @@ EstimationDataStatement::checkPass(ModFileStructure &mod_file_struct, WarningCon exit(EXIT_FAILURE); } - if ((options_list.string_options.find("file") == options_list.string_options.end()) && - (options_list.string_options.find("series") == options_list.string_options.end())) + if ((options_list.string_options.find("file") == options_list.string_options.end()) + && (options_list.string_options.find("series") == options_list.string_options.end())) { cerr << "ERROR: The file or series option must be passed to the data statement." << endl; exit(EXIT_FAILURE); } - if ((options_list.string_options.find("file") != options_list.string_options.end()) && - (options_list.string_options.find("series") != options_list.string_options.end())) + if ((options_list.string_options.find("file") != options_list.string_options.end()) + && (options_list.string_options.find("series") != options_list.string_options.end())) { cerr << "ERROR: The file and series options cannot be used simultaneously in the data statement." << endl; exit(EXIT_FAILURE); @@ -2373,8 +2373,8 @@ JointPriorStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli exit(EXIT_FAILURE); } - if (options_list.num_options.find("mean") == options_list.num_options.end() && - options_list.num_options.find("mode") == options_list.num_options.end()) + if (options_list.num_options.find("mean") == options_list.num_options.end() + && options_list.num_options.find("mode") == options_list.num_options.end()) { cerr << "ERROR: You must pass at least one of mean and mode to the prior statement." << endl; exit(EXIT_FAILURE); @@ -2397,13 +2397,13 @@ JointPriorStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli void JointPriorStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const { - for (vector<string>::const_iterator it = joint_parameters.begin() ; it != joint_parameters.end(); it++) + for (vector<string>::const_iterator it = joint_parameters.begin(); it != joint_parameters.end(); it++) output << "eifind = get_new_or_existing_ei_index('joint_parameter_prior_index', '" << *it << "', '');" << endl << "estimation_info.joint_parameter_prior_index(eifind) = {'" << *it << "'};" << endl; output << "key = {["; - for (vector<string>::const_iterator it = joint_parameters.begin() ; it != joint_parameters.end(); it++) + for (vector<string>::const_iterator it = joint_parameters.begin(); it != joint_parameters.end(); it++) output << "get_new_or_existing_ei_index('joint_parameter_prior_index', '" << *it << "', '') ..." << endl << " "; output << "]};" << endl; @@ -2444,18 +2444,17 @@ JointPriorStatement::writeOutputHelper(ostream &output, const string &field, con { OptionsList::num_options_t::const_iterator itn = options_list.num_options.find(field); output << lhs_field << "." << field << " = {"; - if (field=="variance") + if (field == "variance") output << "{"; if (itn != options_list.num_options.end()) output << itn->second; else output << "{}"; - if (field=="variance") + if (field == "variance") output << "}"; output << "};" << endl; } - BasicPriorStatement::~BasicPriorStatement() { } @@ -2482,16 +2481,16 @@ BasicPriorStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli exit(EXIT_FAILURE); } - if (options_list.num_options.find("mean") == options_list.num_options.end() && - options_list.num_options.find("mode") == options_list.num_options.end()) + if (options_list.num_options.find("mean") == options_list.num_options.end() + && options_list.num_options.find("mode") == options_list.num_options.end()) { cerr << "ERROR: You must pass at least one of mean and mode to the prior statement." << endl; exit(EXIT_FAILURE); } OptionsList::num_options_t::const_iterator it_stdev = options_list.num_options.find("stdev"); - if ((it_stdev == options_list.num_options.end() && variance == NULL) || - (it_stdev != options_list.num_options.end() && variance != NULL)) + if ((it_stdev == options_list.num_options.end() && variance == NULL) + || (it_stdev != options_list.num_options.end() && variance != NULL)) { cerr << "ERROR: You must pass exactly one of stdev and variance to the prior statement." << endl; exit(EXIT_FAILURE); @@ -2598,7 +2597,7 @@ BasicPriorStatement::writeCDomain(ostream &output) const vector<string> tokenizedDomain; split(tokenizedDomain, it_num->second, is_any_of("[ ]"), token_compress_on); for (vector<string>::iterator it = tokenizedDomain.begin(); - it != tokenizedDomain.end(); it++ ) + it != tokenizedDomain.end(); it++) if (!it->empty()) output << "domain.push_back(" << *it << ");" << endl; } @@ -2621,28 +2620,28 @@ BasicPriorStatement::writeCShape(ostream &output) const switch (prior_shape) { case eBeta: - output << "\"beta\";" << endl; + output << "\"beta\";" << endl; break; case eGamma: - output << "\"gamma\";" << endl; + output << "\"gamma\";" << endl; break; case eNormal: - output << "\"normal\";" << endl; + output << "\"normal\";" << endl; break; case eInvGamma: - output << "\"inv_gamma\";" << endl; + output << "\"inv_gamma\";" << endl; break; case eUniform: - output << "\"uniform\";" << endl; + output << "\"uniform\";" << endl; break; case eInvGamma2: - output << "\"inv_gamma2\";" << endl; + output << "\"inv_gamma2\";" << endl; break; case eDirichlet: - output << "\"dirichlet\";" << endl; + output << "\"dirichlet\";" << endl; break; case eWeibull: - output << "\"weibull\";" << endl; + output << "\"weibull\";" << endl; break; case eNoShape: assert(prior_shape != eNoShape); @@ -2689,7 +2688,7 @@ StdPriorStatement::StdPriorStatement(const string &name_arg, const PriorDistributions &prior_shape_arg, const expr_t &variance_arg, const OptionsList &options_list_arg, - const SymbolTable &symbol_table_arg ) : + const SymbolTable &symbol_table_arg) : BasicPriorStatement(name_arg, subsample_name_arg, prior_shape_arg, variance_arg, options_list_arg), symbol_table(symbol_table_arg) { @@ -2738,7 +2737,7 @@ CorrPriorStatement::CorrPriorStatement(const string &name_arg1, const string &na const PriorDistributions &prior_shape_arg, const expr_t &variance_arg, const OptionsList &options_list_arg, - const SymbolTable &symbol_table_arg ) : + const SymbolTable &symbol_table_arg) : BasicPriorStatement(name_arg1, subsample_name_arg, prior_shape_arg, variance_arg, options_list_arg), name1(name_arg2), symbol_table(symbol_table_arg) @@ -2829,8 +2828,8 @@ PriorEqualStatement::PriorEqualStatement(const string &to_declaration_type_arg, void PriorEqualStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) { - if ((to_declaration_type != "par" && to_declaration_type != "std" && to_declaration_type != "corr") || - (from_declaration_type != "par" && from_declaration_type != "std" && from_declaration_type != "corr")) + if ((to_declaration_type != "par" && to_declaration_type != "std" && to_declaration_type != "corr") + || (from_declaration_type != "par" && from_declaration_type != "std" && from_declaration_type != "corr")) { cerr << "Internal Dynare Error" << endl; exit(EXIT_FAILURE); @@ -2861,7 +2860,6 @@ PriorEqualStatement::writeOutput(ostream &output, const string &basename, bool m else get_base_name(symbol_table.getType(from_name1), rhs_field); - if (to_declaration_type == "corr") lhs_field += "_corr"; @@ -3014,7 +3012,7 @@ OptionsStatement::writeCOutput(ostream &output, const string &basename) StdOptionsStatement::StdOptionsStatement(const string &name_arg, const string &subsample_name_arg, const OptionsList &options_list_arg, - const SymbolTable &symbol_table_arg ) : + const SymbolTable &symbol_table_arg) : BasicOptionsStatement(name_arg, subsample_name_arg, options_list_arg), symbol_table(symbol_table_arg) { @@ -3056,7 +3054,7 @@ StdOptionsStatement::writeCOutput(ostream &output, const string &basename) CorrOptionsStatement::CorrOptionsStatement(const string &name_arg1, const string &name_arg2, const string &subsample_name_arg, const OptionsList &options_list_arg, - const SymbolTable &symbol_table_arg ) : + const SymbolTable &symbol_table_arg) : BasicOptionsStatement(name_arg1, subsample_name_arg, options_list_arg), name1(name_arg2), symbol_table(symbol_table_arg) @@ -3141,8 +3139,8 @@ OptionsEqualStatement::OptionsEqualStatement(const string &to_declaration_type_a void OptionsEqualStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) { - if ((to_declaration_type != "par" && to_declaration_type != "std" && to_declaration_type != "corr") || - (from_declaration_type != "par" && from_declaration_type != "std" && from_declaration_type != "corr")) + if ((to_declaration_type != "par" && to_declaration_type != "std" && to_declaration_type != "corr") + || (from_declaration_type != "par" && from_declaration_type != "std" && from_declaration_type != "corr")) { cerr << "Internal Dynare Error" << endl; exit(EXIT_FAILURE); @@ -3173,7 +3171,6 @@ OptionsEqualStatement::writeOutput(ostream &output, const string &basename, bool else get_base_name(symbol_table.getType(from_name1), rhs_field); - if (to_declaration_type == "corr") lhs_field += "_corr"; diff --git a/preprocessor/ComputingTasks.hh b/preprocessor/ComputingTasks.hh index 8319bd893d9e9ac6e046949140853491c1ba1625..c36eb155dcb353b74a6fa859364d063ccb17d389 100644 --- a/preprocessor/ComputingTasks.hh +++ b/preprocessor/ComputingTasks.hh @@ -128,7 +128,7 @@ private: const OptionsList options_list; public: RamseyModelStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg); + const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; }; @@ -136,11 +136,12 @@ public: class RamseyConstraintsStatement : public Statement { public: - struct Constraint { + struct Constraint + { int endo; BinaryOpcode code; expr_t expression; - }; + }; typedef vector<Constraint> constraints_t; private: const constraints_t constraints; @@ -173,7 +174,7 @@ private: const OptionsList options_list; public: DiscretionaryPolicyStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg); + const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; }; @@ -423,7 +424,8 @@ public: /*! \param model_tree_arg the model tree used to store the objective function. It is owned by the PlannerObjectiveStatement, and will be deleted by its destructor */ PlannerObjectiveStatement(StaticModel *model_tree_arg); - virtual ~PlannerObjectiveStatement(); + virtual + ~PlannerObjectiveStatement(); /*! \todo check there are only endogenous variables at the current period in the objective (no exogenous, no lead/lag) */ virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); @@ -513,7 +515,7 @@ private: const OptionsList options_list; public: MSSBVARIrfStatement(const SymbolList &symbol_list_arg, - const OptionsList &options_list_arg); + const OptionsList &options_list_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; }; @@ -673,7 +675,7 @@ public: int lag; int variable; expr_t value; - }; + }; typedef vector< svar_identification_restriction > svar_identification_restrictions_t; private: @@ -687,7 +689,7 @@ public: SvarIdentificationStatement(const svar_identification_restrictions_t &restrictions_arg, const bool &upper_cholesky_present_arg, const bool &lower_cholesky_present_arg, - const bool &constants_exclusion_present_arg, + const bool &constants_exclusion_present_arg, const SymbolTable &symbol_table_arg); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; @@ -792,11 +794,11 @@ public: void writeOutputHelper(ostream &output, const string &field, const string &lhs_field) const; }; - class BasicPriorStatement : public Statement { public: - virtual ~BasicPriorStatement(); + virtual + ~BasicPriorStatement(); protected: const string name; const string subsample_name; @@ -899,7 +901,8 @@ public: class BasicOptionsStatement : public Statement { public: - virtual ~BasicOptionsStatement(); + virtual + ~BasicOptionsStatement(); protected: const string name; const string subsample_name; diff --git a/preprocessor/ConfigFile.cc b/preprocessor/ConfigFile.cc index d1fbd8b7bfb2528025e4ff5182729bd359ca780f..36a1faa7d164be55fe3668b09545d07f53b5d0d3 100644 --- a/preprocessor/ConfigFile.cc +++ b/preprocessor/ConfigFile.cc @@ -102,7 +102,7 @@ ConfigFile::getConfigFileInfo(const string &config_file) if (config_file.empty()) { - string defaultConfigFile (""); + string defaultConfigFile(""); // Test OS and try to open default file #if defined(_WIN32) || defined(__CYGWIN32__) if (getenv("APPDATA") == NULL) @@ -122,42 +122,41 @@ ConfigFile::getConfigFileInfo(const string &config_file) defaultConfigFile += "\\dynare.ini"; } #else - if (getenv("HOME") == NULL) - { - if (parallel || parallel_test) - cerr << "ERROR: "; - else - cerr << "WARNING: "; - cerr << "HOME environment variable not found." << endl; - if (parallel || parallel_test) - exit(EXIT_FAILURE); - } - else - { - defaultConfigFile += getenv("HOME"); - defaultConfigFile += "/.dynare"; - } -#endif - configFile = new ifstream(defaultConfigFile.c_str(), fstream::in); - if (!configFile->is_open()) + if (getenv("HOME") == NULL) + { if (parallel || parallel_test) - { - cerr << "ERROR: Could not open the default config file (" << defaultConfigFile << ")" << endl; - exit(EXIT_FAILURE); - } + cerr << "ERROR: "; else - return; - } - else - { - configFile = new ifstream(config_file.c_str(), fstream::in); - if (!configFile->is_open()) + cerr << "WARNING: "; + cerr << "HOME environment variable not found." << endl; + if (parallel || parallel_test) + exit(EXIT_FAILURE); + } + else + { + defaultConfigFile += getenv("HOME"); + defaultConfigFile += "/.dynare"; + } +#endif + configFile = new ifstream(defaultConfigFile.c_str(), fstream::in); + if (!configFile->is_open()) + if (parallel || parallel_test) { - cerr << "ERROR: Couldn't open file " << config_file << endl;; + cerr << "ERROR: Could not open the default config file (" << defaultConfigFile << ")" << endl; exit(EXIT_FAILURE); } - } - + else + return; + } + else + { + configFile = new ifstream(config_file.c_str(), fstream::in); + if (!configFile->is_open()) + { + cerr << "ERROR: Couldn't open file " << config_file << endl;; + exit(EXIT_FAILURE); + } + } string name, computerName, port, userName, password, remoteDrive, remoteDirectory, dynarePath, matlabOctavePath, operatingSystem, @@ -271,7 +270,7 @@ ConfigFile::getConfigFileInfo(const string &config_file) vector<string> tokenizedPath; split(tokenizedPath, tokenizedLine.back(), is_any_of(":"), token_compress_on); for (vector<string>::iterator it = tokenizedPath.begin(); - it != tokenizedPath.end(); it++ ) + it != tokenizedPath.end(); it++) if (!it->empty()) { trim(*it); @@ -375,7 +374,7 @@ ConfigFile::getConfigFileInfo(const string &config_file) for (tokenizer<char_separator<char> >::iterator it = tokens.begin(); it != tokens.end(); it++) { - string token (*it); + string token(*it); if (token.compare("(") == 0) { begin_weight = true; @@ -525,10 +524,10 @@ void ConfigFile::checkPass(WarningConsolidation &warnings) const { bool global_init_file_declared = false; - for (vector<Hook *>::const_iterator it = hooks.begin() ; it != hooks.end(); it++) + for (vector<Hook *>::const_iterator it = hooks.begin(); it != hooks.end(); it++) { const map <string, string> hookmap = (*it)->get_hooks(); - for (map <string, string>::const_iterator mapit = hookmap.begin() ; mapit != hookmap.end(); mapit++) + for (map <string, string>::const_iterator mapit = hookmap.begin(); mapit != hookmap.end(); mapit++) if (mapit->first.compare("global_init_file") == 0) if (global_init_file_declared == true) { @@ -686,10 +685,10 @@ vector<string> ConfigFile::getIncludePaths() const { vector<string> include_paths; - for (vector<Path *>::const_iterator it = paths.begin() ; it != paths.end(); it++) + for (vector<Path *>::const_iterator it = paths.begin(); it != paths.end(); it++) { map <string, vector<string> > pathmap = (*it)->get_paths(); - for (map <string, vector<string> >::const_iterator mapit = pathmap.begin() ; mapit != pathmap.end(); mapit++) + for (map <string, vector<string> >::const_iterator mapit = pathmap.begin(); mapit != pathmap.end(); mapit++) for (vector<string>::const_iterator vecit = mapit->second.begin(); vecit != mapit->second.end(); vecit++) include_paths.push_back(*vecit); } @@ -699,10 +698,10 @@ ConfigFile::getIncludePaths() const void ConfigFile::writeHooks(ostream &output) const { - for (vector<Hook *>::const_iterator it = hooks.begin() ; it != hooks.end(); it++) + for (vector<Hook *>::const_iterator it = hooks.begin(); it != hooks.end(); it++) { map <string, string> hookmap = (*it)->get_hooks(); - for (map <string, string>::const_iterator mapit = hookmap.begin() ; mapit != hookmap.end(); mapit++) + for (map <string, string>::const_iterator mapit = hookmap.begin(); mapit != hookmap.end(); mapit++) output << "options_." << mapit->first << " = '" << mapit->second << "';" << endl; } } diff --git a/preprocessor/ConfigFile.hh b/preprocessor/ConfigFile.hh index 3c761753b6edb4da167beb9849a72c3de6cc2a81..e054922f71d00d8d2bcdafffbf1f736100bd2d6c 100644 --- a/preprocessor/ConfigFile.hh +++ b/preprocessor/ConfigFile.hh @@ -37,18 +37,26 @@ public: private: map<string, string> hooks; public: - inline map<string, string>get_hooks() { return hooks; }; + inline map<string, string> + get_hooks() + { + return hooks; + }; }; class Path { public: - Path(vector<string> &includepath_arg); + Path(vector<string> &includepath_arg); ~Path(); private: map<string, vector<string> > paths; public: - inline map<string, vector<string> >get_paths() { return paths; }; + inline map<string, vector<string> > + get_paths() + { + return paths; + }; }; class SlaveNode diff --git a/preprocessor/DataTree.hh b/preprocessor/DataTree.hh index 83e59471cb76ce29bd016a0d46c3bf3076c668ed..d7a1de5d831732f93241a421e9d382b03425903a 100644 --- a/preprocessor/DataTree.hh +++ b/preprocessor/DataTree.hh @@ -104,7 +104,8 @@ private: public: DataTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg, ExternalFunctionsTable &external_functions_table_arg); - virtual ~DataTree(); + virtual + ~DataTree(); //! Some predefined constants expr_t Zero, One, Two, MinusOne, NaN, Infinity, MinusInfinity, Pi; diff --git a/preprocessor/DynamicModel.cc b/preprocessor/DynamicModel.cc index 32e3f38412964f15dc8ec49fc3f1d678e4088639..6ade565173a1b5d910c614dbe3e136563dbb0f4f 100644 --- a/preprocessor/DynamicModel.cc +++ b/preprocessor/DynamicModel.cc @@ -881,7 +881,7 @@ DynamicModel::writeModelEquationsCode(string &file_name, const string &bin_basen count_col_det_exo++; } } - + FBEGINBLOCK_ fbeginblock(symbol_table.endo_nbr(), simulation_type, 0, @@ -1140,30 +1140,30 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++) { count_col_det_exo++; - if (find (exo_det.begin(), exo_det.end(), *it1) == exo_det.end()) + if (find(exo_det.begin(), exo_det.end(), *it1) == exo_det.end()) exo_det.push_back(*it1); } - + unsigned int count_col_exo = 0; vector<unsigned int> exo; for (lag_var_t::const_iterator it = exo_block[block].begin(); it != exo_block[block].end(); it++) for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++) { count_col_exo++; - if (find (exo.begin(), exo.end(), *it1) == exo.end()) + if (find(exo.begin(), exo.end(), *it1) == exo.end()) exo.push_back(*it1); } - + vector<unsigned int> other_endo; unsigned int count_col_other_endo = 0; for (lag_var_t::const_iterator it = other_endo_block[block].begin(); it != other_endo_block[block].end(); it++) for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++) { count_col_other_endo++; - if (find (other_endo.begin(), other_endo.end(), *it1) == other_endo.end()) - other_endo.push_back(*it1); + if (find(other_endo.begin(), other_endo.end(), *it1) == other_endo.end()) + other_endo.push_back(*it1); } - + FBEGINBLOCK_ fbeginblock(block_mfs, simulation_type, getBlockFirstEquation(block), @@ -1187,7 +1187,7 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin other_endo ); fbeginblock.write(code_file, instruction_number); - + // The equations for (i = 0; i < (int) block_size; i++) { @@ -1202,10 +1202,10 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin if (dynamic_cast<AbstractExternalFunctionNode *>(*it) != NULL) (*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt2, map_idx, true, false, tef_terms); - FNUMEXPR_ fnumexpr(TemporaryTerm, (int) (map_idx.find((*it)->idx)->second)); + FNUMEXPR_ fnumexpr(TemporaryTerm, (int)(map_idx.find((*it)->idx)->second)); fnumexpr.write(code_file, instruction_number); (*it)->compile(code_file, instruction_number, false, tt2, map_idx, true, false, tef_terms); - FSTPT_ fstpt((int) (map_idx.find((*it)->idx)->second)); + FSTPT_ fstpt((int)(map_idx.find((*it)->idx)->second)); fstpt.write(code_file, instruction_number); // Insert current node into tt2 tt2.insert(*it); @@ -1543,7 +1543,7 @@ DynamicModel::writeDynamicMFile(const string &dynamic_basename) const << "% Outputs:" << endl << "% residual [M_.endo_nbr by 1] double vector of residuals of the dynamic model equations in order of " << endl << "% declaration of the equations." << endl - << "% Dynare may prepend auxiliary equations, see M_.aux_vars" << endl + << "% Dynare may prepend auxiliary equations, see M_.aux_vars" << endl << "% g1 [M_.endo_nbr by #dynamic variables] double Jacobian matrix of the dynamic model equations;" << endl << "% rows: equations in order of declaration" << endl << "% columns: variables in order stored in M_.lead_lag_incidence followed by the ones in M_.exo_names" << endl @@ -1554,7 +1554,7 @@ DynamicModel::writeDynamicMFile(const string &dynamic_basename) const << "% rows: equations in order of declaration" << endl << "% columns: variables in order stored in M_.lead_lag_incidence followed by the ones in M_.exo_names" << endl << "%" << endl - << "%" << endl + << "%" << endl << "% Warning : this file is generated automatically by Dynare" << endl << "% from model file (.mod)" << endl << endl; @@ -1959,11 +1959,11 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri << " else" << endl << " mthd='UNKNOWN';" << endl << " end;" << endl - << " if options_.verbosity" << endl + << " if options_.verbosity" << endl << " printline(41)" << endl << " disp(sprintf('MODEL SIMULATION (method=%s):',mthd))" << endl - << " skipline()" << endl - << " end" << endl + << " skipline()" << endl + << " end" << endl << " periods=options_.periods;" << endl << " maxit_=options_.simul.maxit;" << endl << " solve_tolf=options_.solve_tolf;" << endl @@ -2000,7 +2000,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri mDynamicModelFile << " g1=[];g2=[];g3=[];\n"; mDynamicModelFile << " y=" << dynamic_basename << "_" << block + 1 << "(y, x, params, steady_state, 0, y_kmin, periods);\n"; mDynamicModelFile << " tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n"; - mDynamicModelFile << " if any(isnan(tmp) | isinf(tmp))\n"; + mDynamicModelFile << " if any(isnan(tmp) | isinf(tmp))\n"; mDynamicModelFile << " disp(['Inf or Nan value during the evaluation of block " << block <<"']);\n"; mDynamicModelFile << " oo_.deterministic_simulation.status = 0;\n"; mDynamicModelFile << " oo_.deterministic_simulation.error = 100;\n"; @@ -2375,7 +2375,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia << jacobian_output.str() << endl - // Initialize g2 matrix + // Initialize g2 matrix << "if nargout >= 3," << endl << " %" << endl << " % Hessian matrix" << endl @@ -2565,17 +2565,17 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de output << modstruct << "lead_lag_incidence = ["; // Loop on endogenous variables - int nstatic = 0, - nfwrd = 0, - npred = 0, - nboth = 0; + int nstatic = 0, + nfwrd = 0, + npred = 0, + nboth = 0; for (int endoID = 0; endoID < symbol_table.endo_nbr(); endoID++) { output << endl; - int sstatic = 1, - sfwrd = 0, - spred = 0, - sboth = 0; + int sstatic = 1, + sfwrd = 0, + spred = 0, + sboth = 0; // Loop on periods for (int lag = -max_endo_lag; lag <= max_endo_lead; lag++) { @@ -2771,29 +2771,29 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de i++; } output << "];\n"; - + //vector<int> inter_state_var; output << "block_structure.block(" << block+1 << ").tm1 = zeros(" << i << ", " << state_var.size() << ");\n"; int count_other_endogenous = 1; for (set<int>::const_iterator it_other_endogenous = other_endogenous.begin(); it_other_endogenous != other_endogenous.end(); it_other_endogenous++) { - for (vector<int>::const_iterator it=state_var.begin(); it != state_var.end(); it++) + for (vector<int>::const_iterator it = state_var.begin(); it != state_var.end(); it++) { //cout << "block = " << block+1 << " state_var = " << *it << " it_other_endogenous=" << *it_other_endogenous + 1 << "\n"; if (*it == *it_other_endogenous + 1) { - output << "block_structure.block(" << block+1 << ").tm1(" - << count_other_endogenous << ", " + output << "block_structure.block(" << block+1 << ").tm1(" + << count_other_endogenous << ", " << it - state_var.begin()+1 << ") = 1;\n"; - /*output << "block_structure.block(" << block+1 << ").tm1(" - << it - state_var.begin()+1 << ", " - << count_other_endogenous << ") = 1;\n";*/ + /*output << "block_structure.block(" << block+1 << ").tm1(" + << it - state_var.begin()+1 << ", " + << count_other_endogenous << ") = 1;\n";*/ //cout << "=>\n"; } } count_other_endogenous++; } - + output << "block_structure.block(" << block+1 << ").other_endo_nbr = " << i << ";\n"; tmp_s.str(""); @@ -2820,10 +2820,10 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } else if (lag == 0) { - if (find( local_state_var.begin(), local_state_var.end(), getBlockVariableID(block, it->first.second.first)+1) == local_state_var.end()) + if (find(local_state_var.begin(), local_state_var.end(), getBlockVariableID(block, it->first.second.first)+1) == local_state_var.end()) { - local_stat_var.push_back(getBlockVariableID(block, it->first.second.first)+1); - n_static++; + local_stat_var.push_back(getBlockVariableID(block, it->first.second.first)+1); + n_static++; } } else @@ -2835,7 +2835,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } else { - if (find(local_stat_var.begin(), local_stat_var.end(),getBlockVariableID(block, it->first.second.first)+1) != local_stat_var.end()) + if (find(local_stat_var.begin(), local_stat_var.end(), getBlockVariableID(block, it->first.second.first)+1) != local_stat_var.end()) n_static--; n_forward++; } @@ -2855,13 +2855,13 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de tmp_s.str(""); } vector<int> inter_state_var; - for (vector<int>::const_iterator it_l=local_state_var.begin(); it_l != local_state_var.end(); it_l++) - for (vector<int>::const_iterator it=state_var.begin(); it != state_var.end(); it++) + for (vector<int>::const_iterator it_l = local_state_var.begin(); it_l != local_state_var.end(); it_l++) + for (vector<int>::const_iterator it = state_var.begin(); it != state_var.end(); it++) if (*it == *it_l) inter_state_var.push_back(it - state_var.begin()+1); output << "block_structure.block(" << block+1 << ").sorted_col_dr_ghx = ["; - for (vector<int>::const_iterator it=inter_state_var.begin(); it != inter_state_var.end(); it++) - output << *it << " "; + for (vector<int>::const_iterator it = inter_state_var.begin(); it != inter_state_var.end(); it++) + output << *it << " "; output << "];\n"; count_lead_lag_incidence = 0; output << "block_structure.block(" << block+1 << ").lead_lag_incidence_other = [];\n"; @@ -2906,10 +2906,10 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de output << "];\n"; vector<int> variable_inv_reordered(nb_endo); - for (int i = 0; i< nb_endo; i++) + for (int i = 0; i < nb_endo; i++) variable_inv_reordered[variable_reordered[i]] = i; - - for (vector<int>::const_iterator it=state_var.begin(); it != state_var.end(); it++) + + for (vector<int>::const_iterator it = state_var.begin(); it != state_var.end(); it++) state_equ.push_back(equation_reordered[variable_inv_reordered[*it - 1]]+1); map<pair< int, pair<int, int> >, int> lag_row_incidence; @@ -2962,11 +2962,11 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de i_nz_state_var[i] = n; unsigned int lp = n_obs; - for (unsigned int block = 0; block < nb_blocks; block++) + for (unsigned int block = 0; block < nb_blocks; block++) { int block_size = getBlockSize(block); int nze = 0; - + for (int i = 0; i < block_size; i++) { int var = getBlockVariableID(block, i); @@ -2985,22 +2985,21 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de vector<int>::const_iterator it_state_equ = find(state_equ.begin(), state_equ.end(), getBlockEquationID(block, it->first.first)+1); if (it_state_equ != state_equ.end()) row_state_var_incidence.insert(make_pair(it_state_equ - state_equ.begin(), it_state_var - state_var.begin())); - } - - + } + } /*tmp_block_endo_derivative[make_pair(it->second.first, make_pair(it->first.second, it->first.first))] = it->second.second; - if (block == 0) - { - - vector<int>::const_iterator it_state_equ = find(state_equ.begin(), state_equ.end(), getBlockEquationID(block, i)+1); - if (it_state_equ != state_equ.end()) - { - cout << "row_state_var_incidence[make_pair([" << *it_state_equ << "] " << it_state_equ - state_equ.begin() << ", [" << *it_state_var << "] " << it_state_var - state_var.begin() << ")] = 1;\n"; - row_state_var_incidence.insert(make_pair(it_state_equ - state_equ.begin(), it_state_var - state_var.begin())); - } - }*/ - set<pair<int,int> >::const_iterator row_state_var_incidence_it = row_state_var_incidence.begin(); + if (block == 0) + { + + vector<int>::const_iterator it_state_equ = find(state_equ.begin(), state_equ.end(), getBlockEquationID(block, i)+1); + if (it_state_equ != state_equ.end()) + { + cout << "row_state_var_incidence[make_pair([" << *it_state_equ << "] " << it_state_equ - state_equ.begin() << ", [" << *it_state_var << "] " << it_state_var - state_var.begin() << ")] = 1;\n"; + row_state_var_incidence.insert(make_pair(it_state_equ - state_equ.begin(), it_state_var - state_var.begin())); + } + }*/ + set<pair<int, int> >::const_iterator row_state_var_incidence_it = row_state_var_incidence.begin(); bool diag = true; int nb_diag_r = 0; while (row_state_var_incidence_it != row_state_var_incidence.end() && diag) @@ -3013,12 +3012,12 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de if (equ != row_state_var_incidence_it->first) nb_diag_r++; } - + } - set<pair<int,int> > col_state_var_incidence; - for(set<pair<int,int> >::const_iterator row_state_var_incidence_it = row_state_var_incidence.begin();row_state_var_incidence_it != row_state_var_incidence.end(); row_state_var_incidence_it++) + set<pair<int, int> > col_state_var_incidence; + for (set<pair<int, int> >::const_iterator row_state_var_incidence_it = row_state_var_incidence.begin(); row_state_var_incidence_it != row_state_var_incidence.end(); row_state_var_incidence_it++) col_state_var_incidence.insert(make_pair(row_state_var_incidence_it->second, row_state_var_incidence_it->first)); - set<pair<int,int> >::const_iterator col_state_var_incidence_it = col_state_var_incidence.begin(); + set<pair<int, int> >::const_iterator col_state_var_incidence_it = col_state_var_incidence.begin(); diag = true; int nb_diag_c = 0; while (col_state_var_incidence_it != col_state_var_incidence.end() && diag) @@ -3032,13 +3031,13 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de nb_diag_c++; } } - nb_diag = min( nb_diag_r, nb_diag_c); + nb_diag = min(nb_diag_r, nb_diag_c); row_state_var_incidence.clear(); col_state_var_incidence.clear(); } for (int i = 0; i < nze; i++) - i_nz_state_var[lp + i] = lp + nze; - lp += nze; + i_nz_state_var[lp + i] = lp + nze; + lp += nze; } output << modstruct << "nz_state_var = ["; for (unsigned int i = 0; i < lp; i++) @@ -3046,8 +3045,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de output << "];" << endl; output << modstruct << "n_diag = " << nb_diag << ";" << endl; KF_index_file.write(reinterpret_cast<char *>(&nb_diag), sizeof(nb_diag)); - - + typedef pair<int, pair<int, int > > index_KF; vector<index_KF> v_index_KF; for (int i = 0; i < n; i++) @@ -3055,7 +3053,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de for (int j = n_obs; j < n; j++) { int j1 = j - n_obs; - int j1_n_state = j1 * n_state - n_obs ; + int j1_n_state = j1 * n_state - n_obs; if ((i < n_obs) || (i >= nb_diag + n_obs) || (j1 >= nb_diag)) for (int k = n_obs; k < i_nz_state_var[i]; k++) { @@ -3064,14 +3062,14 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } int size_v_index_KF = v_index_KF.size(); - KF_index_file.write(reinterpret_cast<char *>(&size_v_index_KF), sizeof(size_v_index_KF)); + KF_index_file.write(reinterpret_cast<char *>(&size_v_index_KF), sizeof(size_v_index_KF)); for (vector<index_KF>::iterator it = v_index_KF.begin(); it != v_index_KF.end(); it++) KF_index_file.write(reinterpret_cast<char *>(&(*it)), sizeof(index_KF)); vector<index_KF> v_index_KF_2; int n_n_obs = n * n_obs; for (int i = 0; i < n; i++) - //i = 0; + //i = 0; for (int j = i; j < n; j++) { if ((i < n_obs) || (i >= nb_diag + n_obs) || (j < n_obs) || (j >= nb_diag + n_obs)) @@ -3083,16 +3081,16 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de } int size_v_index_KF_2 = v_index_KF_2.size(); - KF_index_file.write(reinterpret_cast<char *>(&size_v_index_KF_2), sizeof(size_v_index_KF_2)); + KF_index_file.write(reinterpret_cast<char *>(&size_v_index_KF_2), sizeof(size_v_index_KF_2)); for (vector<index_KF>::iterator it = v_index_KF_2.begin(); it != v_index_KF_2.end(); it++) - KF_index_file.write(reinterpret_cast<char *>(&(*it)), sizeof(index_KF)); + KF_index_file.write(reinterpret_cast<char *>(&(*it)), sizeof(index_KF)); KF_index_file.close(); } - output << modstruct << "state_var = ["; + output << modstruct << "state_var = ["; - for (vector<int>::const_iterator it=state_var.begin(); it != state_var.end(); it++) - output << *it << " "; - output << "];" << endl; + for (vector<int>::const_iterator it = state_var.begin(); it != state_var.end(); it++) + output << *it << " "; + output << "];" << endl; } // Writing initialization for some other variables @@ -3106,21 +3104,21 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de output << modstruct << "maximum_endo_lag = " << max_endo_lag << ";" << endl << modstruct << "maximum_endo_lead = " << max_endo_lead << ";" << endl - << outstruct << "steady_state = zeros(" << symbol_table.endo_nbr() << (julia ? ")" : ", 1);" ) << endl; + << outstruct << "steady_state = zeros(" << symbol_table.endo_nbr() << (julia ? ")" : ", 1);") << endl; output << modstruct << "maximum_exo_lag = " << max_exo_lag << ";" << endl << modstruct << "maximum_exo_lead = " << max_exo_lead << ";" << endl - << outstruct << "exo_steady_state = zeros(" << symbol_table.exo_nbr() << (julia ? ")" : ", 1);" ) << endl; + << outstruct << "exo_steady_state = zeros(" << symbol_table.exo_nbr() << (julia ? ")" : ", 1);") << endl; if (symbol_table.exo_det_nbr()) { output << modstruct << "maximum_exo_det_lag = " << max_exo_det_lag << ";" << endl << modstruct << "maximum_exo_det_lead = " << max_exo_det_lead << ";" << endl - << outstruct << "exo_det_steady_state = zeros(" << symbol_table.exo_det_nbr() << (julia ? ")" : ", 1);" ) << endl; + << outstruct << "exo_det_steady_state = zeros(" << symbol_table.exo_det_nbr() << (julia ? ")" : ", 1);") << endl; } output << modstruct << "params = " << (julia ? "fill(NaN, " : "NaN(") - << symbol_table.param_nbr() << (julia ? ")" : ", 1);" ) << endl; + << symbol_table.param_nbr() << (julia ? ")" : ", 1);") << endl; if (compute_xrefs) writeXrefs(output); @@ -3128,7 +3126,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de // Write number of non-zero derivatives // Use -1 if the derivatives have not been computed output << modstruct << (julia ? "nnzderivatives" : "NNZDerivatives") - << " = [" << NNZDerivatives[0] << "; "; + << " = [" << NNZDerivatives[0] << "; "; if (order > 1) output << NNZDerivatives[1] << "; "; else @@ -3174,7 +3172,7 @@ DynamicModel::computingPass(bool jacobianExo, bool hessian, bool thirdDerivative assert(jacobianExo || !(hessian || thirdDerivatives || paramsDerivsOrder)); initializeVariablesAndEquations(); - + // Prepare for derivation computeDerivIDs(); @@ -3537,7 +3535,7 @@ DynamicModel::collect_block_first_order_derivatives() int var = symbol_table.getTypeSpecificID(getSymbIDByDerivID(it2->first.second)); int lag = getLagByDerivID(it2->first.second); int block_eq = equation_2_block[eq]; - int block_var=0; + int block_var = 0; derivative_t tmp_derivative; lag_var_t lag_var; switch (getTypeByDerivID(it2->first.second)) @@ -4483,7 +4481,6 @@ DynamicModel::substituteLeadLagInternal(aux_var_t type, bool deterministic_model equations[i] = substeq; } - // Substitute in aux_equations // Without this loop, the auxiliary equations in equations // will diverge from those in aux_equations @@ -4683,7 +4680,7 @@ DynamicModel::fillEvalContext(eval_context_t &eval_context) const vector <int> trendVars = symbol_table.getTrendVarIds(); for (vector <int>::const_iterator it = trendVars.begin(); it != trendVars.end(); it++) - eval_context[*it] = 2; //not <= 0 bc of log, not 1 bc of powers + eval_context[*it] = 2; //not <= 0 bc of log, not 1 bc of powers } bool @@ -4729,7 +4726,7 @@ DynamicModel::dynamicOnlyEquationsNbr() const } #ifndef PRIVATE_BUFFER_SIZE -#define PRIVATE_BUFFER_SIZE 1024 +# define PRIVATE_BUFFER_SIZE 1024 #endif bool @@ -4790,10 +4787,10 @@ DynamicModel::isChecksumMatching(const string &basename) const } char private_buffer[PRIVATE_BUFFER_SIZE]; - while(buffer) + while (buffer) { - buffer.get(private_buffer,PRIVATE_BUFFER_SIZE); - result.process_bytes(private_buffer,strlen(private_buffer)); + buffer.get(private_buffer, PRIVATE_BUFFER_SIZE); + result.process_bytes(private_buffer, strlen(private_buffer)); } bool basename_dir_exists = false; @@ -4805,8 +4802,8 @@ DynamicModel::isChecksumMatching(const string &basename) const if (r < 0) if (errno != EEXIST) { - perror("ERROR"); - exit(EXIT_FAILURE); + perror("ERROR"); + exit(EXIT_FAILURE); } else basename_dir_exists = true; @@ -4821,25 +4818,25 @@ DynamicModel::isChecksumMatching(const string &basename) const { checksum_file.open(filename.c_str(), ios::in | ios::binary); if (checksum_file.is_open()) - { - checksum_file >> old_checksum; - checksum_file.close(); - } + { + checksum_file >> old_checksum; + checksum_file.close(); + } } // write new checksum file if none or different from old checksum if (old_checksum != result.checksum()) - { - checksum_file.open(filename.c_str(), ios::out | ios::binary); - if (!checksum_file.is_open()) - { - cerr << "ERROR: Can't open file " << filename << endl; - exit(EXIT_FAILURE); - } - checksum_file << result.checksum(); - checksum_file.close(); - return false; - } - + { + checksum_file.open(filename.c_str(), ios::out | ios::binary); + if (!checksum_file.is_open()) + { + cerr << "ERROR: Can't open file " << filename << endl; + exit(EXIT_FAILURE); + } + checksum_file << result.checksum(); + checksum_file.close(); + return false; + } + return true; } @@ -4853,26 +4850,26 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d { // Loop on periods for (int lag = 0; lag <= 2; lag++) - { - lag_presence[lag] = 1; + { + lag_presence[lag] = 1; try { getDerivID(symbol_table.getID(eEndogenous, endoID), lag-1); } catch (UnknownDerivIDException &e) { - lag_presence[lag] = 0; + lag_presence[lag] = 0; } } if (lag_presence[0] == 1) - if (lag_presence[2] == 1) - zeta_mixed.push_back(endoID); - else - zeta_back.push_back(endoID); + if (lag_presence[2] == 1) + zeta_mixed.push_back(endoID); + else + zeta_back.push_back(endoID); else if (lag_presence[2] == 1) - zeta_fwrd.push_back(endoID); + zeta_fwrd.push_back(endoID); else - zeta_static.push_back(endoID); + zeta_static.push_back(endoID); } output << "size_t nstatic = " << zeta_static.size() << ";" << endl @@ -4882,8 +4879,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d output << "size_t zeta_static[" << zeta_static.size() << "] = {"; for (vector<int>::iterator i = zeta_static.begin(); i != zeta_static.end(); ++i) { - if ( i != zeta_static.begin() ) - output << ","; + if (i != zeta_static.begin()) + output << ","; output << *i; } output << "};" << endl; @@ -4891,8 +4888,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d output << "size_t zeta_back[" << zeta_back.size() << "] = {"; for (vector<int>::iterator i = zeta_back.begin(); i != zeta_back.end(); ++i) { - if ( i != zeta_back.begin() ) - output << ","; + if (i != zeta_back.begin()) + output << ","; output << *i; } output << "};" << endl; @@ -4900,8 +4897,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d output << "size_t zeta_fwrd[" << zeta_fwrd.size() << "] = {"; for (vector<int>::iterator i = zeta_fwrd.begin(); i != zeta_fwrd.end(); ++i) { - if ( i != zeta_fwrd.begin() ) - output << ","; + if (i != zeta_fwrd.begin()) + output << ","; output << *i; } output << "};" << endl; @@ -4909,8 +4906,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d output << "size_t zeta_mixed[" << zeta_mixed.size() << "] = {"; for (vector<int>::iterator i = zeta_mixed.begin(); i != zeta_mixed.end(); ++i) { - if ( i != zeta_mixed.begin() ) - output << ","; + if (i != zeta_mixed.begin()) + output << ","; output << *i; } output << "};" << endl; @@ -4930,8 +4927,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d output << NNZDerivatives[0] << "," << NNZDerivatives[1] << "," << NNZDerivatives[2] << "};" << endl; break; default: - cerr << "Order larger than 3 not implemented" << endl; - exit(EXIT_FAILURE); + cerr << "Order larger than 3 not implemented" << endl; + exit(EXIT_FAILURE); } } @@ -4983,7 +4980,7 @@ DynamicModel::writeResidualsC(const string &basename, bool cuda) const << endl << " /* Residual equations */" << endl << model_output.str() - << "}" << endl; + << "}" << endl; writePowerDeriv(mDynamicModelFile); writeNormcdf(mDynamicModelFile); @@ -5095,7 +5092,6 @@ DynamicModel::writeFirstDerivativesC_csr(const string &basename, bool cuda) cons // this is always empty here, but needed by d1->writeOutput deriv_node_temp_terms_t tef_terms; - // Indexing derivatives in column order vector<derivative> D; for (first_derivatives_t::const_iterator it = first_derivatives.begin(); @@ -5108,35 +5104,35 @@ DynamicModel::writeFirstDerivativesC_csr(const string &basename, bool cuda) cons SymbolType type = getTypeByDerivID(dynvar); int tsid = symbol_table.getTypeSpecificID(symb_id); int col_id; - switch(type) - { - case eEndogenous: - col_id = tsid+(lag+1)*symbol_table.endo_nbr(); - break; - case eExogenous: - col_id = tsid+3*symbol_table.endo_nbr(); - break; - case eExogenousDet: - col_id = tsid+3*symbol_table.endo_nbr()+symbol_table.exo_nbr(); - break; - default: - std::cerr << "This case shouldn't happen" << std::endl; - exit(EXIT_FAILURE); - } - derivative deriv(col_id + eq*cols_nbr,col_id,eq,it->second); + switch (type) + { + case eEndogenous: + col_id = tsid+(lag+1)*symbol_table.endo_nbr(); + break; + case eExogenous: + col_id = tsid+3*symbol_table.endo_nbr(); + break; + case eExogenousDet: + col_id = tsid+3*symbol_table.endo_nbr()+symbol_table.exo_nbr(); + break; + default: + std::cerr << "This case shouldn't happen" << std::endl; + exit(EXIT_FAILURE); + } + derivative deriv(col_id + eq *cols_nbr, col_id, eq, it->second); D.push_back(deriv); } - sort(D.begin(), D.end(), derivative_less_than() ); + sort(D.begin(), D.end(), derivative_less_than()); // writing sparse Jacobian vector<int> row_ptr(equations.size()); - fill(row_ptr.begin(),row_ptr.end(),0.0); + fill(row_ptr.begin(), row_ptr.end(), 0.0); int k = 0; - for(vector<derivative>::const_iterator it = D.begin(); it != D.end(); ++it) + for (vector<derivative>::const_iterator it = D.begin(); it != D.end(); ++it) { row_ptr[it->row_nbr]++; mDynamicModelFile << "col_ptr[" << k << "] " - << "=" << it->col_nbr << ";" << endl; + << "=" << it->col_nbr << ";" << endl; mDynamicModelFile << "value[" << k << "] = "; // oCstaticModel makes reference to the static variables it->value->writeOutput(mDynamicModelFile, oCDynamic2Model, temporary_terms, tef_terms); @@ -5147,20 +5143,20 @@ DynamicModel::writeFirstDerivativesC_csr(const string &basename, bool cuda) cons // row_ptr must point to the relative address of the first element of the row int cumsum = 0; mDynamicModelFile << "int row_ptr_data[" << row_ptr.size() + 1 << "] = { 0"; - for (vector<int>::iterator it=row_ptr.begin(); it != row_ptr.end(); ++it) + for (vector<int>::iterator it = row_ptr.begin(); it != row_ptr.end(); ++it) { cumsum += *it; mDynamicModelFile << ", " << cumsum; } mDynamicModelFile << "};" << endl - << "int i;" << endl - << "for (i=0; i < " << row_ptr.size() + 1 << "; i++) row_ptr[i] = row_ptr_data[i];" << endl; + << "int i;" << endl + << "for (i=0; i < " << row_ptr.size() + 1 << "; i++) row_ptr[i] = row_ptr_data[i];" << endl; mDynamicModelFile << "}" << endl; mDynamicModelFile.close(); } - void +void DynamicModel::writeSecondDerivativesC_csr(const string &basename, bool cuda) const { @@ -5216,26 +5212,26 @@ DynamicModel::writeSecondDerivativesC_csr(const string &basename, bool cuda) con int col_nb = id1 * dynJacobianColsNbr + id2; - derivative deriv(col_nb + eq*hessianColsNbr,col_nb,eq,it->second); + derivative deriv(col_nb + eq *hessianColsNbr, col_nb, eq, it->second); D.push_back(deriv); if (id1 != id2) - { - col_nb = id2 * dynJacobianColsNbr + id1; - derivative deriv(col_nb + eq*hessianColsNbr,col_nb,eq,it->second); - D.push_back(deriv); - } + { + col_nb = id2 * dynJacobianColsNbr + id1; + derivative deriv(col_nb + eq *hessianColsNbr, col_nb, eq, it->second); + D.push_back(deriv); + } } - sort(D.begin(), D.end(), derivative_less_than() ); + sort(D.begin(), D.end(), derivative_less_than()); // Writing Hessian vector<int> row_ptr(equations.size()); - fill(row_ptr.begin(),row_ptr.end(),0.0); + fill(row_ptr.begin(), row_ptr.end(), 0.0); int k = 0; - for(vector<derivative>::const_iterator it = D.begin(); it != D.end(); ++it) + for (vector<derivative>::const_iterator it = D.begin(); it != D.end(); ++it) { row_ptr[it->row_nbr]++; mDynamicModelFile << "col_ptr[" << k << "] " - << "=" << it->col_nbr << ";" << endl; + << "=" << it->col_nbr << ";" << endl; mDynamicModelFile << "value[" << k << "] = "; // oCstaticModel makes reference to the static variables it->value->writeOutput(mDynamicModelFile, oCStaticModel, temporary_terms, tef_terms); @@ -5246,7 +5242,7 @@ DynamicModel::writeSecondDerivativesC_csr(const string &basename, bool cuda) con // row_ptr must point to the relative address of the first element of the row int cumsum = 0; mDynamicModelFile << "row_ptr = [ 0"; - for (vector<int>::iterator it=row_ptr.begin(); it != row_ptr.end(); ++it) + for (vector<int>::iterator it = row_ptr.begin(); it != row_ptr.end(); ++it) { cumsum += *it; mDynamicModelFile << ", " << cumsum; @@ -5319,55 +5315,55 @@ DynamicModel::writeThirdDerivativesC_csr(const string &basename, bool cuda) cons vector<long unsigned int> cols; long unsigned int col_nb = id1 * hessianColsNbr + id2 * dynJacobianColsNbr + id3; int thirdDColsNbr = hessianColsNbr*dynJacobianColsNbr; - derivative deriv(col_nb + eq*thirdDColsNbr,col_nb,eq,it->second); + derivative deriv(col_nb + eq *thirdDColsNbr, col_nb, eq, it->second); D.push_back(deriv); cols.push_back(col_nb); col_nb = id1 * hessianColsNbr + id3 * dynJacobianColsNbr + id2; - if (find(cols.begin(),cols.end(),col_nb) == cols.end()) - { - derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); - D.push_back(deriv); - cols.push_back(col_nb); - } + if (find(cols.begin(), cols.end(), col_nb) == cols.end()) + { + derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second); + D.push_back(deriv); + cols.push_back(col_nb); + } col_nb = id2 * hessianColsNbr + id1 * dynJacobianColsNbr + id3; - if (find(cols.begin(),cols.end(),col_nb) == cols.end()) - { - derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); - D.push_back(deriv); - cols.push_back(col_nb); - } + if (find(cols.begin(), cols.end(), col_nb) == cols.end()) + { + derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second); + D.push_back(deriv); + cols.push_back(col_nb); + } col_nb = id2 * hessianColsNbr + id3 * dynJacobianColsNbr + id1; - if (find(cols.begin(),cols.end(),col_nb) == cols.end()) - { - derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); - D.push_back(deriv); - cols.push_back(col_nb); - } + if (find(cols.begin(), cols.end(), col_nb) == cols.end()) + { + derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second); + D.push_back(deriv); + cols.push_back(col_nb); + } col_nb = id3 * hessianColsNbr + id1 * dynJacobianColsNbr + id2; - if (find(cols.begin(),cols.end(),col_nb) == cols.end()) - { - derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); - D.push_back(deriv); - cols.push_back(col_nb); - } + if (find(cols.begin(), cols.end(), col_nb) == cols.end()) + { + derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second); + D.push_back(deriv); + cols.push_back(col_nb); + } col_nb = id3 * hessianColsNbr + id2 * dynJacobianColsNbr + id1; - if (find(cols.begin(),cols.end(),col_nb) == cols.end()) - { - derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); - D.push_back(deriv); - } + if (find(cols.begin(), cols.end(), col_nb) == cols.end()) + { + derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second); + D.push_back(deriv); + } } - sort(D.begin(), D.end(), derivative_less_than() ); + sort(D.begin(), D.end(), derivative_less_than()); vector<int> row_ptr(equations.size()); - fill(row_ptr.begin(),row_ptr.end(),0.0); + fill(row_ptr.begin(), row_ptr.end(), 0.0); int k = 0; - for(vector<derivative>::const_iterator it = D.begin(); it != D.end(); ++it) + for (vector<derivative>::const_iterator it = D.begin(); it != D.end(); ++it) { row_ptr[it->row_nbr]++; mDynamicModelFile << "col_ptr[" << k << "] " - << "=" << it->col_nbr << ";" << endl; + << "=" << it->col_nbr << ";" << endl; mDynamicModelFile << "value[" << k << "] = "; // oCstaticModel makes reference to the static variables it->value->writeOutput(mDynamicModelFile, oCStaticModel, temporary_terms, tef_terms); @@ -5378,7 +5374,7 @@ DynamicModel::writeThirdDerivativesC_csr(const string &basename, bool cuda) cons // row_ptr must point to the relative address of the first element of the row int cumsum = 0; mDynamicModelFile << "row_ptr = [ 0"; - for (vector<int>::iterator it=row_ptr.begin(); it != row_ptr.end(); ++it) + for (vector<int>::iterator it = row_ptr.begin(); it != row_ptr.end(); ++it) { cumsum += *it; mDynamicModelFile << ", " << cumsum; @@ -5402,26 +5398,26 @@ DynamicModel::writeCCOutput(ostream &output, const string &basename, bool block_ { // Loop on periods for (int lag = 0; lag <= 2; lag++) - { - lag_presence[lag] = 1; + { + lag_presence[lag] = 1; try { getDerivID(symbol_table.getID(eEndogenous, endoID), lag-1); } catch (UnknownDerivIDException &e) { - lag_presence[lag] = 0; + lag_presence[lag] = 0; } } if (lag_presence[0] == 1) - if (lag_presence[2] == 1) - output << "zeta_mixed.push_back(" << endoID << ");" << endl; - else - output << "zeta_back.push_back(" << endoID << ");" << endl; + if (lag_presence[2] == 1) + output << "zeta_mixed.push_back(" << endoID << ");" << endl; + else + output << "zeta_back.push_back(" << endoID << ");" << endl; else if (lag_presence[2] == 1) - output << "zeta_fwrd.push_back(" << endoID << ");" << endl; + output << "zeta_fwrd.push_back(" << endoID << ");" << endl; else - output << "zeta_static.push_back(" << endoID << ");" << endl; + output << "zeta_static.push_back(" << endoID << ");" << endl; } output << "nstatic = zeta_static.size();" << endl diff --git a/preprocessor/DynamicModel.hh b/preprocessor/DynamicModel.hh index 7988a3658e66400610525508ebd6636733fa4313..c66cbdd5cd4715ef0dc7094c1caca799ba342a1c 100644 --- a/preprocessor/DynamicModel.hh +++ b/preprocessor/DynamicModel.hh @@ -273,7 +273,7 @@ public: //! Returns number of static only equations size_t staticOnlyEquationsNbr() const; - + //! Returns number of dynamic only equations size_t dynamicOnlyEquationsNbr() const; @@ -325,7 +325,7 @@ public: //! Transforms the model by creating aux vars for the diff of forward vars /*! If subset is empty, does the transformation for all fwrd vars; otherwise - restrict it to the vars in subset */ + restrict it to the vars in subset */ void differentiateForwardVars(const vector<string> &subset); //! Fills eval context with values of model local variables and auxiliary variables @@ -523,7 +523,7 @@ DynamicModel::checkHessianZero() const return second_derivatives.empty(); } -//! Classes to re-order derivatives for various sparse storage formats +//! Classes to re-order derivatives for various sparse storage formats class derivative { public: @@ -531,14 +531,17 @@ public: long unsigned int col_nbr; unsigned int row_nbr; expr_t value; - derivative(long unsigned int arg1, long unsigned int arg2, int arg3, expr_t arg4): - linear_address(arg1), col_nbr(arg2), row_nbr(arg3), value(arg4) {}; + derivative(long unsigned int arg1, long unsigned int arg2, int arg3, expr_t arg4) : + linear_address(arg1), col_nbr(arg2), row_nbr(arg3), value(arg4) + { + }; }; class derivative_less_than { public: - bool operator()(const derivative & d1, const derivative & d2) const + bool + operator()(const derivative &d1, const derivative &d2) const { return d1.linear_address < d2.linear_address; } diff --git a/preprocessor/DynareMain.cc b/preprocessor/DynareMain.cc index adbb1b6821f2afdcc799949a6f99d16d1699406a..51fa776725c3d452d6303c7d5a66435a6ceba9d6 100644 --- a/preprocessor/DynareMain.cc +++ b/preprocessor/DynareMain.cc @@ -124,8 +124,8 @@ main(int argc, char **argv) clear_all = false; else if (strlen(argv[arg]) >= 19 && !strncmp(argv[arg], "params_derivs_order", 19)) { - if (strlen(argv[arg]) >= 22 || argv[arg][19] != '=' || - !(argv[arg][20] == '0' || argv[arg][20] == '1' || argv[arg][20] == '2')) + if (strlen(argv[arg]) >= 22 || argv[arg][19] != '=' + || !(argv[arg][20] == '0' || argv[arg][20] == '1' || argv[arg][20] == '2')) { cerr << "Incorrect syntax for params_derivs_order option" << endl; usage(); @@ -222,12 +222,12 @@ main(int argc, char **argv) size_t equal_index = string(argv[arg]).find('='); if (equal_index != string::npos) { - string key = string(argv[arg]).erase(equal_index).erase(0,2); + string key = string(argv[arg]).erase(equal_index).erase(0, 2); defines[key] = string(argv[arg]).erase(0, equal_index+1); } else { - string key = string(argv[arg]).erase(0,2); + string key = string(argv[arg]).erase(0, 2); defines[key] = "1"; } } @@ -239,36 +239,36 @@ main(int argc, char **argv) << "must not be separated from -I by whitespace." << endl; usage(); } - path.push_back(string(argv[arg]).erase(0,2)); + path.push_back(string(argv[arg]).erase(0, 2)); } else if (strlen(argv[arg]) >= 6 && !strncmp(argv[arg], "output", 6)) { - if (strlen(argv[arg]) <= 7 || argv[arg][6] != '=') - { - cerr << "Incorrect syntax for ouput option" << endl; - usage(); - } - if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 7, "dynamic", 7)) - output_mode = dynamic; - else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 7, "first", 5)) - output_mode = first; - else if (strlen(argv[arg]) == 13 && !strncmp(argv[arg] + 7, "second", 6)) - output_mode = second; - else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 7, "third", 5)) - output_mode = third; - else - { - cerr << "Incorrect syntax for ouput option" << endl; - usage(); + if (strlen(argv[arg]) <= 7 || argv[arg][6] != '=') + { + cerr << "Incorrect syntax for ouput option" << endl; + usage(); + } + if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 7, "dynamic", 7)) + output_mode = dynamic; + else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 7, "first", 5)) + output_mode = first; + else if (strlen(argv[arg]) == 13 && !strncmp(argv[arg] + 7, "second", 6)) + output_mode = second; + else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 7, "third", 5)) + output_mode = third; + else + { + cerr << "Incorrect syntax for ouput option" << endl; + usage(); } } else if (strlen(argv[arg]) >= 8 && !strncmp(argv[arg], "language", 8)) { - if (strlen(argv[arg]) <= 9 || argv[arg][8] != '=') - { - cerr << "Incorrect syntax for language option" << endl; - usage(); - } + if (strlen(argv[arg]) <= 9 || argv[arg][8] != '=') + { + cerr << "Incorrect syntax for language option" << endl; + usage(); + } if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 9, "julia", 5)) language = julia; diff --git a/preprocessor/DynareMain2.cc b/preprocessor/DynareMain2.cc index b5d1e00646207f775e407cf34b1d7e28634376e2..dc9420ca0a6a12f6b6b1f709cc173847ccc91d76 100644 --- a/preprocessor/DynareMain2.cc +++ b/preprocessor/DynareMain2.cc @@ -60,9 +60,9 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear mod_file->writeOutputFiles(basename, clear_all, clear_global, no_log, no_warn, console, nograph, nointeractive, config_file, check_model_changes, minimal_workspace, compute_xrefs #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) - , cygwin, msvc, mingw + , cygwin, msvc, mingw #endif - ); + ); delete mod_file; diff --git a/preprocessor/ExprNode.cc b/preprocessor/ExprNode.cc index 4d723fa7ef38a4cbca1aed654538fd6a21064ee6..2aa85568eb218393741f2ae4b0226418691c24eb 100644 --- a/preprocessor/ExprNode.cc +++ b/preprocessor/ExprNode.cc @@ -100,7 +100,7 @@ ExprNode::collectVariables(SymbolType type, set<int> &result) const set<pair<int, int> > symbs_lags; collectDynamicVariables(type, symbs_lags); transform(symbs_lags.begin(), symbs_lags.end(), inserter(result, result.begin()), - boost::bind(&pair<int,int>::first,_1)); + boost::bind(&pair<int, int>::first, _1)); } void @@ -514,7 +514,6 @@ NumConstNode::substituteStaticAuxiliaryVariable() const return const_cast<NumConstNode *>(this); } - VariableNode::VariableNode(DataTree &datatree_arg, int symb_id_arg, int lag_arg) : ExprNode(datatree_arg), symb_id(symb_id_arg), @@ -864,7 +863,7 @@ VariableNode::substituteStaticAuxiliaryVariable() const } return const_cast<VariableNode *>(this); } - + double VariableNode::eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException) { @@ -973,17 +972,17 @@ VariableNode::collectDynamicVariables(SymbolType type_arg, set<pair<int, int> > pair<int, expr_t> VariableNode::normalizeEquation(int var_endo, vector<pair<int, pair<expr_t, expr_t> > > &List_of_Op_RHS) const { - /* The equation has to be normalized with respect to the current endogenous variable ascribed to it. - The two input arguments are : - - The ID of the endogenous variable associated to the equation. - - The list of operators and operands needed to normalize the equation* - - The pair returned by NormalizeEquation is composed of - - a flag indicating if the expression returned contains (flag = 1) or not (flag = 0) - the endogenous variable related to the equation. - If the expression contains more than one occurence of the associated endogenous variable, - the flag is equal to 2. - - an expression equal to the RHS if flag = 0 and equal to NULL elsewhere + /* The equation has to be normalized with respect to the current endogenous variable ascribed to it. + The two input arguments are : + - The ID of the endogenous variable associated to the equation. + - The list of operators and operands needed to normalize the equation* + + The pair returned by NormalizeEquation is composed of + - a flag indicating if the expression returned contains (flag = 1) or not (flag = 0) + the endogenous variable related to the equation. + If the expression contains more than one occurence of the associated endogenous variable, + the flag is equal to 2. + - an expression equal to the RHS if flag = 0 and equal to NULL elsewhere */ if (type == eEndogenous) { @@ -1461,7 +1460,7 @@ VariableNode::removeTrendLeadLag(map<int, expr_t> trend_symbols_map) const expr_t noTrendLeadLagNode = new VariableNode(datatree, it->first, 0); bool log_trend = get_type() == eLogTrend; expr_t trend = it->second; - + if (get_lag() > 0) { expr_t growthFactorSequence = trend->decreaseLeadsLags(-1); @@ -2166,9 +2165,9 @@ UnaryOpNode::normalizeEquation(int var_endo, vector<pair<int, pair<expr_t, expr_ if (is_endogenous_present == 2) /* The equation could not be normalized and the process is given-up*/ return (make_pair(2, (expr_t) NULL)); - else if (is_endogenous_present) /* The argument of the function contains the current values of - the endogenous variable associated to the equation. - In order to normalized, we have to apply the invert function to the RHS.*/ + else if (is_endogenous_present) /* The argument of the function contains the current values of + the endogenous variable associated to the equation. + In order to normalized, we have to apply the invert function to the RHS.*/ { switch (op_code) { @@ -2237,7 +2236,7 @@ UnaryOpNode::normalizeEquation(int var_endo, vector<pair<int, pair<expr_t, expr_ } } else - { /* If the argument of the function do not contain the current values of the endogenous variable + { /* If the argument of the function do not contain the current values of the endogenous variable related to the equation, the function with its argument is stored in the RHS*/ switch (op_code) { @@ -2474,7 +2473,7 @@ UnaryOpNode::substituteExoLag(subst_table_t &subst_table, vector<BinaryOpNode *> expr_t UnaryOpNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool partial_information_model) const { - if (op_code==oExpectation) + if (op_code == oExpectation) { subst_table_t::iterator it = subst_table.find(const_cast<UnaryOpNode *>(this)); if (it != subst_table.end()) @@ -3336,7 +3335,7 @@ BinaryOpNode::Compute_RHS(expr_t arg1, expr_t arg2, int op, int op_type) const pair<int, expr_t> BinaryOpNode::normalizeEquation(int var_endo, vector<pair<int, pair<expr_t, expr_t> > > &List_of_Op_RHS) const { - /* Checks if the current value of the endogenous variable related to the equation + /* Checks if the current value of the endogenous variable related to the equation is present in the arguments of the binary operator. */ vector<pair<int, pair<expr_t, expr_t> > > List_of_Op_RHS1, List_of_Op_RHS2; int is_endogenous_present_1, is_endogenous_present_2; @@ -3349,17 +3348,17 @@ BinaryOpNode::normalizeEquation(int var_endo, vector<pair<int, pair<expr_t, expr res = arg2->normalizeEquation(var_endo, List_of_Op_RHS2); is_endogenous_present_2 = res.first; expr_t_2 = res.second; - + /* If the two expressions contains the current value of the endogenous variable associated to the equation the equation could not be normalized and the process is given-up.*/ if (is_endogenous_present_1 == 2 || is_endogenous_present_2 == 2) return (make_pair(2, (expr_t) NULL)); else if (is_endogenous_present_1 && is_endogenous_present_2) return (make_pair(2, (expr_t) NULL)); - else if (is_endogenous_present_1) /*If the current values of the endogenous variable associated to the equation + else if (is_endogenous_present_1) /*If the current values of the endogenous variable associated to the equation is present only in the first operand of the expression, we try to normalize the equation*/ { - if (op_code == oEqual) /* The end of the normalization process : + if (op_code == oEqual) /* The end of the normalization process : All the operations needed to normalize the equation are applied. */ { pair<int, pair<expr_t, expr_t> > it; @@ -3374,7 +3373,7 @@ BinaryOpNode::normalizeEquation(int var_endo, vector<pair<int, pair<expr_t, expr expr_t_2 = Compute_RHS(it.second.second, expr_t_2, it.first, 1); else if (it.second.second && it.second.first) /*Binary operator*/ expr_t_2 = Compute_RHS(it.second.first, it.second.second, it.first, 1); - else /*Unary operator*/ + else /*Unary operator*/ expr_t_2 = Compute_RHS((UnaryOpNode *) expr_t_2, (UnaryOpNode *) it.second.first, it.first, 0); } } @@ -3807,7 +3806,6 @@ BinaryOpNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOpN return buildSimilarBinaryOpNode(arg1subst, arg2subst, datatree); } - expr_t BinaryOpNode::differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const { @@ -4483,7 +4481,6 @@ TrinaryOpNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOp return buildSimilarTrinaryOpNode(arg1subst, arg2subst, arg3subst, datatree); } - expr_t TrinaryOpNode::differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const { diff --git a/preprocessor/ExprNode.hh b/preprocessor/ExprNode.hh index e784c60d9b46f97514aa51da0f507446f24a1a0a..6bf7bc2efdc3ad8ac27dc01bb5f5ac36722cb746 100644 --- a/preprocessor/ExprNode.hh +++ b/preprocessor/ExprNode.hh @@ -89,16 +89,16 @@ enum ExprNodeOutputType || (output_type) == oMatlabDynamicSparseSteadyStateOperator \ || (output_type) == oSteadyStateFile) -#define IS_JULIA(output_type) ((output_type) == oJuliaStaticModel \ - || (output_type) == oJuliaDynamicModel \ +#define IS_JULIA(output_type) ((output_type) == oJuliaStaticModel \ + || (output_type) == oJuliaDynamicModel \ || (output_type) == oJuliaDynamicSteadyStateOperator \ || (output_type) == oJuliaSteadyStateFile) -#define IS_C(output_type) ((output_type) == oCDynamicModel \ - || (output_type) == oCDynamic2Model \ - || (output_type) == oCStaticModel \ - || (output_type) == oCDynamicSteadyStateOperator \ - || (output_type) == oCSteadyStateFile) +#define IS_C(output_type) ((output_type) == oCDynamicModel \ + || (output_type) == oCDynamic2Model \ + || (output_type) == oCStaticModel \ + || (output_type) == oCDynamicSteadyStateOperator \ + || (output_type) == oCSteadyStateFile) #define IS_LATEX(output_type) ((output_type) == oLatexStaticModel \ || (output_type) == oLatexDynamicModel \ @@ -122,334 +122,335 @@ enum ExprNodeOutputType #define MIN_COST(is_matlab) ((is_matlab) ? MIN_COST_MATLAB : MIN_COST_C) //! Base class for expression nodes -class ExprNode -{ - friend class DataTree; - friend class DynamicModel; - friend class StaticModel; - friend class ModelTree; - friend struct ExprNodeLess; - friend class NumConstNode; - friend class VariableNode; - friend class UnaryOpNode; - friend class BinaryOpNode; - friend class TrinaryOpNode; - friend class AbstractExternalFunctionNode; -private: - //! Computes derivative w.r. to a derivation ID (but doesn't store it in derivatives map) - /*! You shoud use getDerivative() to get the benefit of symbolic a priori and of caching */ - virtual expr_t computeDerivative(int deriv_id) = 0; - -protected: - //! Reference to the enclosing DataTree - DataTree &datatree; - - //! Index number - int idx; - - //! Is the data member non_null_derivatives initialized ? - bool preparedForDerivation; - - //! Set of derivation IDs with respect to which the derivative is potentially non-null - set<int> non_null_derivatives; - - //! Used for caching of first order derivatives (when non-null) - map<int, expr_t> derivatives; - - //! Cost of computing current node - /*! Nodes included in temporary_terms are considered having a null cost */ - virtual int cost(int cost, bool is_matlab) const; - virtual int cost(const temporary_terms_t &temporary_terms, bool is_matlab) const; - virtual int cost(const map<NodeTreeReference, temporary_terms_t> &temp_terms_map, bool is_matlab) const; - - //! For creating equation cross references - struct EquationInfo - { - set<pair<int, int> > param; - set<pair<int, int> > endo; - set<pair<int, int> > exo; - set<pair<int, int> > exo_det; - }; - -public: - ExprNode(DataTree &datatree_arg); - virtual ~ExprNode(); - - //! Initializes data member non_null_derivatives - virtual void prepareForDerivation() = 0; - - //! Returns derivative w.r. to derivation ID - /*! Uses a symbolic a priori to pre-detect null derivatives, and caches the result for other derivatives (to avoid computing it several times) - For an equal node, returns the derivative of lhs minus rhs */ - expr_t getDerivative(int deriv_id); - - //! Computes derivatives by applying the chain rule for some variables - /*! - \param deriv_id The derivation ID with respect to which we are derivating - \param recursive_variables Contains the derivation ID for which chain rules must be applied. Keys are derivation IDs, values are equations of the form x=f(y) where x is the key variable and x doesn't appear in y - */ - virtual expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables) = 0; - - //! Returns precedence of node - /*! Equals 100 for constants, variables, unary ops, and temporary terms */ - virtual int precedence(ExprNodeOutputType output_t, const temporary_terms_t &temporary_terms) const; - - //! Fills temporary_terms set, using reference counts - /*! A node will be marked as a temporary term if it is referenced at least two times (i.e. has at least two parents), and has a computing cost (multiplied by reference count) greater to datatree.min_cost */ - virtual void computeTemporaryTerms(map<expr_t, pair<int, NodeTreeReference> > &reference_count, - map<NodeTreeReference, temporary_terms_t> &temp_terms_map, - bool is_matlab, NodeTreeReference tr) const; - - //! Writes output of node, using a Txxx notation for nodes in temporary_terms, and specifiying the set of already written external functions - /*! - \param[in] output the output stream - \param[in] output_type the type of output (MATLAB, C, LaTeX...) - \param[in] temporary_terms the nodes that are marked as temporary terms - \param[in,out] tef_terms the set of already written external function nodes - */ - virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; - - //! returns true if the expr node contains an external function - virtual bool containsExternalFunction() const = 0; - - //! Writes output of node (with no temporary terms and with "outside model" output type) - void writeOutput(ostream &output) const; - - //! Writes output of node (with no temporary terms) - void writeOutput(ostream &output, ExprNodeOutputType output_type) const; - - //! Writes output of node, using a Txxx notation for nodes in temporary_terms - void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms) const; - - //! Writes the output for an external function, ensuring that the external function is called as few times as possible using temporary terms - virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, - const temporary_terms_t &temporary_terms, - deriv_node_temp_terms_t &tef_terms) const; - - virtual void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, - bool lhs_rhs, const temporary_terms_t &temporary_terms, - const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, - deriv_node_temp_terms_t &tef_terms) const; - - //! Computes the set of all variables of a given symbol type in the expression (with information on lags) - /*! - Variables are stored as integer pairs of the form (symb_id, lag). - They are added to the set given in argument. - Note that model local variables are substituted by their expression in the computation - (and added if type_arg = ModelLocalVariable). - */ - virtual void collectDynamicVariables(SymbolType type_arg, set<pair<int, int> > &result) const = 0; - - //! Computes the set of all variables of a given symbol type in the expression (without information on lags) - /*! - Variables are stored as symb_id. - They are added to the set given in argument. - Note that model local variables are substituted by their expression in the computation - (and added if type_arg = ModelLocalVariable). - */ - void collectVariables(SymbolType type_arg, set<int> &result) const; - - //! Computes the set of endogenous variables in the expression - /*! - Endogenous are stored as integer pairs of the form (type_specific_id, lag). - They are added to the set given in argument. - Note that model local variables are substituted by their expression in the computation. - */ - virtual void collectEndogenous(set<pair<int, int> > &result) const; - - //! Computes the set of exogenous variables in the expression - /*! - Exogenous are stored as integer pairs of the form (type_specific_id, lag). - They are added to the set given in argument. - Note that model local variables are substituted by their expression in the computation. - */ - virtual void collectExogenous(set<pair<int, int> > &result) const; - - virtual void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const = 0; - - virtual void computeTemporaryTerms(map<expr_t, int> &reference_count, - temporary_terms_t &temporary_terms, - map<expr_t, pair<int, int> > &first_occurence, - int Curr_block, - vector< vector<temporary_terms_t> > &v_temporary_terms, - int equation) const; - - class EvalException - - { - }; - - class EvalExternalFunctionException : public EvalException - - { - }; - - virtual double eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException) = 0; - virtual void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, deriv_node_temp_terms_t &tef_terms) const = 0; - void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic) const; - //! Creates a static version of this node - /*! - This method duplicates the current node by creating a similar node from which all leads/lags have been stripped, - adds the result in the static_datatree argument (and not in the original datatree), and returns it. - */ - virtual expr_t toStatic(DataTree &static_datatree) const = 0; - - /*! - Compute cross references for equations - */ - // virtual void computeXrefs(set<int> ¶m, set<int> &endo, set<int> &exo, set<int> &exo_det) const = 0; - virtual void computeXrefs(EquationInfo &ei) const = 0; - //! Try to normalize an equation linear in its endogenous variable - virtual pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<pair<int, pair<expr_t, expr_t> > > &List_of_Op_RHS) const = 0; - - //! Returns the maximum lead of endogenous in this expression - /*! Always returns a non-negative value */ - virtual int maxEndoLead() const = 0; - - //! Returns the maximum lead of exogenous in this expression - /*! Always returns a non-negative value */ - virtual int maxExoLead() const = 0; - - //! Returns the maximum lag of endogenous in this expression - /*! Always returns a non-negative value */ - virtual int maxEndoLag() const = 0; - - //! Returns the maximum lag of exogenous in this expression - /*! Always returns a non-negative value */ - virtual int maxExoLag() const = 0; - - //! Returns the relative period of the most forward term in this expression - /*! A negative value means that the expression contains only lagged variables */ - virtual int maxLead() const = 0; - - //! Returns a new expression where all the leads/lags have been shifted backwards by the same amount - /*! - Only acts on endogenous, exogenous, exogenous det - \param[in] n The number of lags by which to shift - \return The same expression except that leads/lags have been shifted backwards - */ - virtual expr_t decreaseLeadsLags(int n) const = 0; - - //! Type for the substitution map used in the process of creating auxiliary vars for leads >= 2 - typedef map<const ExprNode *, const VariableNode *> subst_table_t; - - //! Creates auxiliary endo lead variables corresponding to this expression - /*! - If maximum endogenous lead >= 3, this method will also create intermediary auxiliary var, and will add the equations of the form aux1 = aux2(+1) to the substitution table. - \pre This expression is assumed to have maximum endogenous lead >= 2 - \param[in,out] subst_table The table to which new auxiliary variables and their correspondance will be added - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - \return The new variable node corresponding to the current expression - */ - VariableNode *createEndoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const; - - //! Creates auxiliary exo lead variables corresponding to this expression - /*! - If maximum exogenous lead >= 2, this method will also create intermediary auxiliary var, and will add the equations of the form aux1 = aux2(+1) to the substitution table. - \pre This expression is assumed to have maximum exogenous lead >= 1 - \param[in,out] subst_table The table to which new auxiliary variables and their correspondance will be added - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - \return The new variable node corresponding to the current expression - */ - VariableNode *createExoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const; - - //! Constructs a new expression where sub-expressions with max endo lead >= 2 have been replaced by auxiliary variables - /*! - \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - - If the method detects a sub-expr which needs to be substituted, two cases are possible: - - if this expr is in the table, then it will use the corresponding variable and return the substituted expression - - if this expr is not in the table, then it will create an auxiliary endogenous variable, add the substitution in the table and return the substituted expression - - \return A new equivalent expression where sub-expressions with max endo lead >= 2 have been replaced by auxiliary variables - */ - virtual expr_t substituteEndoLeadGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const = 0; - - //! Constructs a new expression where endo variables with max endo lag >= 2 have been replaced by auxiliary variables - /*! - \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - */ - virtual expr_t substituteEndoLagGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; - - //! Constructs a new expression where exogenous variables with a lead have been replaced by auxiliary variables - /*! - \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - */ - virtual expr_t substituteExoLead(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const = 0; - //! Constructs a new expression where exogenous variables with a lag have been replaced by auxiliary variables - /*! - \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - */ - virtual expr_t substituteExoLag(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; - - //! Constructs a new expression where the expectation operator has been replaced by auxiliary variables - /*! - \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - \param[in] partial_information_model Are we substituting in a partial information model? - */ - virtual expr_t substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool partial_information_model) const = 0; - - virtual expr_t decreaseLeadsLagsPredeterminedVariables() const = 0; - - //! Constructs a new expression where forward variables (supposed to be at most in t+1) have been replaced by themselves at t, plus a new aux var representing their (time) differentiate - /*! - \param[in] subset variables to which to limit the transformation; transform - all fwrd vars if empty - \param[in,out] subst_table Map used to store mapping between a given - forward variable and the aux var that contains its differentiate - \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. - */ - virtual expr_t differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; - - //! Return true if the nodeID is a numerical constant equal to value and false otherwise - /*! - \param[in] value of the numerical constante - \param[out] the boolean equal to true if NodeId is a constant equal to value - */ - virtual bool isNumConstNodeEqualTo(double value) const = 0; - - //! Returns true if the expression contains one or several endogenous variable - virtual bool containsEndogenous(void) const = 0; - - //! Returns true if the expression contains one or several exogenous variable - virtual bool containsExogenous() const = 0; - - //! Return true if the nodeID is a variable withe a type equal to type_arg, a specific variable id aqual to varfiable_id and a lag equal to lag_arg and false otherwise - /*! - \param[in] the type (type_arg), specifique variable id (variable_id and the lag (lag_arg) - \param[out] the boolean equal to true if NodeId is the variable - */ - virtual bool isVariableNodeEqualTo(SymbolType type_arg, int variable_id, int lag_arg) const = 0; - - //! Replaces the Trend var with datatree.One - virtual expr_t replaceTrendVar() const = 0; - - //! Constructs a new expression where the variable indicated by symb_id has been detrended - /*! - \param[in] symb_id indicating the variable to be detrended - \param[in] log_trend indicates if the trend is in log - \param[in] trend indicating the trend - \return the new binary op pointing to a detrended variable - */ - virtual expr_t detrend(int symb_id, bool log_trend, expr_t trend) const = 0; - - //! Add ExprNodes to the provided datatree - virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const = 0; - - //! Move a trend variable with lag/lead to time t by dividing/multiplying by its growth factor - virtual expr_t removeTrendLeadLag(map<int, expr_t> trend_symbols_map) const = 0; - - //! Returns true if the expression is in static form (no lead, no lag, no expectation, no STEADY_STATE) - virtual bool isInStaticForm() const = 0; - - //! Substitute auxiliary variables by their expression in static model - virtual expr_t substituteStaticAuxiliaryVariable() const = 0; -}; + class ExprNode + { + friend class DataTree; + friend class DynamicModel; + friend class StaticModel; + friend class ModelTree; + friend struct ExprNodeLess; + friend class NumConstNode; + friend class VariableNode; + friend class UnaryOpNode; + friend class BinaryOpNode; + friend class TrinaryOpNode; + friend class AbstractExternalFunctionNode; + private: + //! Computes derivative w.r. to a derivation ID (but doesn't store it in derivatives map) + /*! You shoud use getDerivative() to get the benefit of symbolic a priori and of caching */ + virtual expr_t computeDerivative(int deriv_id) = 0; + + protected: + //! Reference to the enclosing DataTree + DataTree &datatree; + + //! Index number + int idx; + + //! Is the data member non_null_derivatives initialized ? + bool preparedForDerivation; + + //! Set of derivation IDs with respect to which the derivative is potentially non-null + set<int> non_null_derivatives; + + //! Used for caching of first order derivatives (when non-null) + map<int, expr_t> derivatives; + + //! Cost of computing current node + /*! Nodes included in temporary_terms are considered having a null cost */ + virtual int cost(int cost, bool is_matlab) const; + virtual int cost(const temporary_terms_t &temporary_terms, bool is_matlab) const; + virtual int cost(const map<NodeTreeReference, temporary_terms_t> &temp_terms_map, bool is_matlab) const; + + //! For creating equation cross references + struct EquationInfo + { + set<pair<int, int> > param; + set<pair<int, int> > endo; + set<pair<int, int> > exo; + set<pair<int, int> > exo_det; + }; + + public: + ExprNode(DataTree &datatree_arg); + virtual + ~ExprNode(); + + //! Initializes data member non_null_derivatives + virtual void prepareForDerivation() = 0; + + //! Returns derivative w.r. to derivation ID + /*! Uses a symbolic a priori to pre-detect null derivatives, and caches the result for other derivatives (to avoid computing it several times) + For an equal node, returns the derivative of lhs minus rhs */ + expr_t getDerivative(int deriv_id); + + //! Computes derivatives by applying the chain rule for some variables + /*! + \param deriv_id The derivation ID with respect to which we are derivating + \param recursive_variables Contains the derivation ID for which chain rules must be applied. Keys are derivation IDs, values are equations of the form x=f(y) where x is the key variable and x doesn't appear in y + */ + virtual expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables) = 0; + + //! Returns precedence of node + /*! Equals 100 for constants, variables, unary ops, and temporary terms */ + virtual int precedence(ExprNodeOutputType output_t, const temporary_terms_t &temporary_terms) const; + + //! Fills temporary_terms set, using reference counts + /*! A node will be marked as a temporary term if it is referenced at least two times (i.e. has at least two parents), and has a computing cost (multiplied by reference count) greater to datatree.min_cost */ + virtual void computeTemporaryTerms(map<expr_t, pair<int, NodeTreeReference> > &reference_count, + map<NodeTreeReference, temporary_terms_t> &temp_terms_map, + bool is_matlab, NodeTreeReference tr) const; + + //! Writes output of node, using a Txxx notation for nodes in temporary_terms, and specifiying the set of already written external functions + /*! + \param[in] output the output stream + \param[in] output_type the type of output (MATLAB, C, LaTeX...) + \param[in] temporary_terms the nodes that are marked as temporary terms + \param[in,out] tef_terms the set of already written external function nodes + */ + virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; + + //! returns true if the expr node contains an external function + virtual bool containsExternalFunction() const = 0; + + //! Writes output of node (with no temporary terms and with "outside model" output type) + void writeOutput(ostream &output) const; + + //! Writes output of node (with no temporary terms) + void writeOutput(ostream &output, ExprNodeOutputType output_type) const; + + //! Writes output of node, using a Txxx notation for nodes in temporary_terms + void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms) const; + + //! Writes the output for an external function, ensuring that the external function is called as few times as possible using temporary terms + virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type, + const temporary_terms_t &temporary_terms, + deriv_node_temp_terms_t &tef_terms) const; + + virtual void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, + bool lhs_rhs, const temporary_terms_t &temporary_terms, + const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, + deriv_node_temp_terms_t &tef_terms) const; + + //! Computes the set of all variables of a given symbol type in the expression (with information on lags) + /*! + Variables are stored as integer pairs of the form (symb_id, lag). + They are added to the set given in argument. + Note that model local variables are substituted by their expression in the computation + (and added if type_arg = ModelLocalVariable). + */ + virtual void collectDynamicVariables(SymbolType type_arg, set<pair<int, int> > &result) const = 0; + + //! Computes the set of all variables of a given symbol type in the expression (without information on lags) + /*! + Variables are stored as symb_id. + They are added to the set given in argument. + Note that model local variables are substituted by their expression in the computation + (and added if type_arg = ModelLocalVariable). + */ + void collectVariables(SymbolType type_arg, set<int> &result) const; + + //! Computes the set of endogenous variables in the expression + /*! + Endogenous are stored as integer pairs of the form (type_specific_id, lag). + They are added to the set given in argument. + Note that model local variables are substituted by their expression in the computation. + */ + virtual void collectEndogenous(set<pair<int, int> > &result) const; + + //! Computes the set of exogenous variables in the expression + /*! + Exogenous are stored as integer pairs of the form (type_specific_id, lag). + They are added to the set given in argument. + Note that model local variables are substituted by their expression in the computation. + */ + virtual void collectExogenous(set<pair<int, int> > &result) const; + + virtual void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const = 0; + + virtual void computeTemporaryTerms(map<expr_t, int> &reference_count, + temporary_terms_t &temporary_terms, + map<expr_t, pair<int, int> > &first_occurence, + int Curr_block, + vector< vector<temporary_terms_t> > &v_temporary_terms, + int equation) const; + + class EvalException + + { + }; + + class EvalExternalFunctionException : public EvalException + + { + }; + + virtual double eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException) = 0; + virtual void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, deriv_node_temp_terms_t &tef_terms) const = 0; + void compile(ostream &CompileCode, unsigned int &instruction_number, bool lhs_rhs, const temporary_terms_t &temporary_terms, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic) const; + //! Creates a static version of this node + /*! + This method duplicates the current node by creating a similar node from which all leads/lags have been stripped, + adds the result in the static_datatree argument (and not in the original datatree), and returns it. + */ + virtual expr_t toStatic(DataTree &static_datatree) const = 0; + + /*! + Compute cross references for equations + */ + // virtual void computeXrefs(set<int> ¶m, set<int> &endo, set<int> &exo, set<int> &exo_det) const = 0; + virtual void computeXrefs(EquationInfo &ei) const = 0; + //! Try to normalize an equation linear in its endogenous variable + virtual pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<pair<int, pair<expr_t, expr_t> > > &List_of_Op_RHS) const = 0; + + //! Returns the maximum lead of endogenous in this expression + /*! Always returns a non-negative value */ + virtual int maxEndoLead() const = 0; + + //! Returns the maximum lead of exogenous in this expression + /*! Always returns a non-negative value */ + virtual int maxExoLead() const = 0; + + //! Returns the maximum lag of endogenous in this expression + /*! Always returns a non-negative value */ + virtual int maxEndoLag() const = 0; + + //! Returns the maximum lag of exogenous in this expression + /*! Always returns a non-negative value */ + virtual int maxExoLag() const = 0; + + //! Returns the relative period of the most forward term in this expression + /*! A negative value means that the expression contains only lagged variables */ + virtual int maxLead() const = 0; + + //! Returns a new expression where all the leads/lags have been shifted backwards by the same amount + /*! + Only acts on endogenous, exogenous, exogenous det + \param[in] n The number of lags by which to shift + \return The same expression except that leads/lags have been shifted backwards + */ + virtual expr_t decreaseLeadsLags(int n) const = 0; + + //! Type for the substitution map used in the process of creating auxiliary vars for leads >= 2 + typedef map<const ExprNode *, const VariableNode *> subst_table_t; + + //! Creates auxiliary endo lead variables corresponding to this expression + /*! + If maximum endogenous lead >= 3, this method will also create intermediary auxiliary var, and will add the equations of the form aux1 = aux2(+1) to the substitution table. + \pre This expression is assumed to have maximum endogenous lead >= 2 + \param[in,out] subst_table The table to which new auxiliary variables and their correspondance will be added + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + \return The new variable node corresponding to the current expression + */ + VariableNode *createEndoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const; + + //! Creates auxiliary exo lead variables corresponding to this expression + /*! + If maximum exogenous lead >= 2, this method will also create intermediary auxiliary var, and will add the equations of the form aux1 = aux2(+1) to the substitution table. + \pre This expression is assumed to have maximum exogenous lead >= 1 + \param[in,out] subst_table The table to which new auxiliary variables and their correspondance will be added + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + \return The new variable node corresponding to the current expression + */ + VariableNode *createExoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const; + + //! Constructs a new expression where sub-expressions with max endo lead >= 2 have been replaced by auxiliary variables + /*! + \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + + If the method detects a sub-expr which needs to be substituted, two cases are possible: + - if this expr is in the table, then it will use the corresponding variable and return the substituted expression + - if this expr is not in the table, then it will create an auxiliary endogenous variable, add the substitution in the table and return the substituted expression + + \return A new equivalent expression where sub-expressions with max endo lead >= 2 have been replaced by auxiliary variables + */ + virtual expr_t substituteEndoLeadGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const = 0; + + //! Constructs a new expression where endo variables with max endo lag >= 2 have been replaced by auxiliary variables + /*! + \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + */ + virtual expr_t substituteEndoLagGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; + + //! Constructs a new expression where exogenous variables with a lead have been replaced by auxiliary variables + /*! + \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + */ + virtual expr_t substituteExoLead(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const = 0; + //! Constructs a new expression where exogenous variables with a lag have been replaced by auxiliary variables + /*! + \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + */ + virtual expr_t substituteExoLag(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; + + //! Constructs a new expression where the expectation operator has been replaced by auxiliary variables + /*! + \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr. + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + \param[in] partial_information_model Are we substituting in a partial information model? + */ + virtual expr_t substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool partial_information_model) const = 0; + + virtual expr_t decreaseLeadsLagsPredeterminedVariables() const = 0; + + //! Constructs a new expression where forward variables (supposed to be at most in t+1) have been replaced by themselves at t, plus a new aux var representing their (time) differentiate + /*! + \param[in] subset variables to which to limit the transformation; transform + all fwrd vars if empty + \param[in,out] subst_table Map used to store mapping between a given + forward variable and the aux var that contains its differentiate + \param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. + */ + virtual expr_t differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const = 0; + + //! Return true if the nodeID is a numerical constant equal to value and false otherwise + /*! + \param[in] value of the numerical constante + \param[out] the boolean equal to true if NodeId is a constant equal to value + */ + virtual bool isNumConstNodeEqualTo(double value) const = 0; + + //! Returns true if the expression contains one or several endogenous variable + virtual bool containsEndogenous(void) const = 0; + + //! Returns true if the expression contains one or several exogenous variable + virtual bool containsExogenous() const = 0; + + //! Return true if the nodeID is a variable withe a type equal to type_arg, a specific variable id aqual to varfiable_id and a lag equal to lag_arg and false otherwise + /*! + \param[in] the type (type_arg), specifique variable id (variable_id and the lag (lag_arg) + \param[out] the boolean equal to true if NodeId is the variable + */ + virtual bool isVariableNodeEqualTo(SymbolType type_arg, int variable_id, int lag_arg) const = 0; + + //! Replaces the Trend var with datatree.One + virtual expr_t replaceTrendVar() const = 0; + + //! Constructs a new expression where the variable indicated by symb_id has been detrended + /*! + \param[in] symb_id indicating the variable to be detrended + \param[in] log_trend indicates if the trend is in log + \param[in] trend indicating the trend + \return the new binary op pointing to a detrended variable + */ + virtual expr_t detrend(int symb_id, bool log_trend, expr_t trend) const = 0; + + //! Add ExprNodes to the provided datatree + virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const = 0; + + //! Move a trend variable with lag/lead to time t by dividing/multiplying by its growth factor + virtual expr_t removeTrendLeadLag(map<int, expr_t> trend_symbols_map) const = 0; + + //! Returns true if the expression is in static form (no lead, no lag, no expectation, no STEADY_STATE) + virtual bool isInStaticForm() const = 0; + + //! Substitute auxiliary variables by their expression in static model + virtual expr_t substituteStaticAuxiliaryVariable() const = 0; + }; //! Object used to compare two nodes (using their indexes) struct ExprNodeLess @@ -550,7 +551,11 @@ public: { return symb_id; }; - int get_lag() const { return lag; }; + int + get_lag() const + { + return lag; + }; virtual pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<pair<int, pair<expr_t, expr_t> > > &List_of_Op_RHS) const; virtual expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables); virtual int maxEndoLead() const; diff --git a/preprocessor/ExtendedPreprocessorTypes.hh b/preprocessor/ExtendedPreprocessorTypes.hh index e0a955f2c8222b611512d31a296902b9e4e65fbd..4c6869a38a9f9940e9e808ea925704ac9467e799 100644 --- a/preprocessor/ExtendedPreprocessorTypes.hh +++ b/preprocessor/ExtendedPreprocessorTypes.hh @@ -24,9 +24,9 @@ enum FileOutputType { none, // outputs files for Matlab/Octave processing dynamic, // outputs <fname>_dynamic.* and related files - first, // outputs <fname>_first_derivatives.* and related files - second, // outputs <fname>_first_derivatives.*, <fname>_second_derivatives.* and related files - third, // outputs <fname>_first_derivatives.*, <fname>_second_derivatives.*, <fname>_third_derivatives.* and related files + first, // outputs <fname>_first_derivatives.* and related files + second, // outputs <fname>_first_derivatives.*, <fname>_second_derivatives.* and related files + third, // outputs <fname>_first_derivatives.*, <fname>_second_derivatives.*, <fname>_third_derivatives.* and related files }; enum LanguageOutputType diff --git a/preprocessor/MinimumFeedbackSet.cc b/preprocessor/MinimumFeedbackSet.cc index 479c8f227cee2544e952048c3c8a89ccd2a71e35..a84a994aba5dcef4da1674b99039310617ddbb90 100644 --- a/preprocessor/MinimumFeedbackSet.cc +++ b/preprocessor/MinimumFeedbackSet.cc @@ -175,7 +175,7 @@ namespace MFS if (in_degree(vertex, G) > 0 && out_degree(vertex, G) > 0) for (tie(it_in, in_end) = in_edges(vertex, G); it_in != in_end; ++it_in) for (tie(it_out, out_end) = out_edges(vertex, G); it_out != out_end; ++it_out) - if (source(*it_in, G) == target(*it_out, G) && source(*it_in, G) != target(*it_in, G)) // not a loop + if (source(*it_in, G) == target(*it_out, G) && source(*it_in, G) != target(*it_in, G)) // not a loop Doublet.push_back(source(*it_in, G)); return Doublet; } diff --git a/preprocessor/ModFile.cc b/preprocessor/ModFile.cc index 629d4b423b0fffc669db78c80667b671588eef1d..a10d1308eb468cf480ed6a063fd47d98e3f1d187 100644 --- a/preprocessor/ModFile.cc +++ b/preprocessor/ModFile.cc @@ -39,7 +39,7 @@ ModFile::ModFile(WarningConsolidation &warnings_arg) orig_ramsey_dynamic_model(symbol_table, num_constants, external_functions_table), static_model(symbol_table, num_constants, external_functions_table), steady_state_model(symbol_table, num_constants, external_functions_table, static_model), - linear(false), block(false), byte_code(false), use_dll(false), no_static(false), + linear(false), block(false), byte_code(false), use_dll(false), no_static(false), differentiate_forward_vars(false), nonstationary_variables(false), param_used_with_lead_lag(false), warnings(warnings_arg) { @@ -148,10 +148,10 @@ ModFile::checkPass(bool nostrict) exit(EXIT_FAILURE); } - if (((mod_file_struct.ramsey_model_present || mod_file_struct.discretionary_policy_present) + if (((mod_file_struct.ramsey_model_present || mod_file_struct.discretionary_policy_present) && !mod_file_struct.planner_objective_present) || (!(mod_file_struct.ramsey_model_present || mod_file_struct.discretionary_policy_present) - && mod_file_struct.planner_objective_present)) + && mod_file_struct.planner_objective_present)) { cerr << "ERROR: A planner_objective statement must be used with a ramsey_model, a ramsey_policy or a discretionary_policy statement and vice versa." << endl; exit(EXIT_FAILURE); @@ -256,38 +256,38 @@ ModFile::checkPass(bool nostrict) cerr << "ERROR: the number of equations marked [static] must be equal to the number of equations marked [dynamic]" << endl; exit(EXIT_FAILURE); } - - if (dynamic_model.staticOnlyEquationsNbr() > 0 && - (mod_file_struct.ramsey_model_present || mod_file_struct.discretionary_policy_present)) + + if (dynamic_model.staticOnlyEquationsNbr() > 0 + && (mod_file_struct.ramsey_model_present || mod_file_struct.discretionary_policy_present)) { cerr << "ERROR: marking equations as [static] or [dynamic] is not possible with ramsey_model, ramsey_policy or discretionary_policy" << endl; exit(EXIT_FAILURE); } - if (stochastic_statement_present && - (dynamic_model.isUnaryOpUsed(oSign) - || dynamic_model.isUnaryOpUsed(oAbs) - || dynamic_model.isBinaryOpUsed(oMax) - || dynamic_model.isBinaryOpUsed(oMin) - || dynamic_model.isBinaryOpUsed(oGreater) - || dynamic_model.isBinaryOpUsed(oLess) - || dynamic_model.isBinaryOpUsed(oGreaterEqual) - || dynamic_model.isBinaryOpUsed(oLessEqual) - || dynamic_model.isBinaryOpUsed(oEqualEqual) - || dynamic_model.isBinaryOpUsed(oDifferent))) + if (stochastic_statement_present + && (dynamic_model.isUnaryOpUsed(oSign) + || dynamic_model.isUnaryOpUsed(oAbs) + || dynamic_model.isBinaryOpUsed(oMax) + || dynamic_model.isBinaryOpUsed(oMin) + || dynamic_model.isBinaryOpUsed(oGreater) + || dynamic_model.isBinaryOpUsed(oLess) + || dynamic_model.isBinaryOpUsed(oGreaterEqual) + || dynamic_model.isBinaryOpUsed(oLessEqual) + || dynamic_model.isBinaryOpUsed(oEqualEqual) + || dynamic_model.isBinaryOpUsed(oDifferent))) warnings << "WARNING: you are using a function (max, min, abs, sign) or an operator (<, >, <=, >=, ==, !=) which is unsuitable for a stochastic context; see the reference manual, section about \"Expressions\", for more details." << endl; - if (linear && - (dynamic_model.isUnaryOpUsed(oSign) - || dynamic_model.isUnaryOpUsed(oAbs) - || dynamic_model.isBinaryOpUsed(oMax) - || dynamic_model.isBinaryOpUsed(oMin) - || dynamic_model.isBinaryOpUsed(oGreater) - || dynamic_model.isBinaryOpUsed(oLess) - || dynamic_model.isBinaryOpUsed(oGreaterEqual) - || dynamic_model.isBinaryOpUsed(oLessEqual) - || dynamic_model.isBinaryOpUsed(oEqualEqual) - || dynamic_model.isBinaryOpUsed(oDifferent))) + if (linear + && (dynamic_model.isUnaryOpUsed(oSign) + || dynamic_model.isUnaryOpUsed(oAbs) + || dynamic_model.isBinaryOpUsed(oMax) + || dynamic_model.isBinaryOpUsed(oMin) + || dynamic_model.isBinaryOpUsed(oGreater) + || dynamic_model.isBinaryOpUsed(oLess) + || dynamic_model.isBinaryOpUsed(oGreaterEqual) + || dynamic_model.isBinaryOpUsed(oLessEqual) + || dynamic_model.isBinaryOpUsed(oEqualEqual) + || dynamic_model.isBinaryOpUsed(oDifferent))) warnings << "WARNING: you have declared your model 'linear' but you are using a function (max, min, abs, sign) or an operator (<, >, <=, >=, ==, !=) which potentially makes it non-linear." << endl; // Test if some estimated parameters are used within the values of shocks @@ -302,7 +302,7 @@ ModFile::checkPass(bool nostrict) { cerr << "ERROR: some estimated parameters ("; for (set<int>::const_iterator it = parameters_intersect.begin(); - it != parameters_intersect.end(); ) + it != parameters_intersect.end();) { cerr << symbol_table.getName(*it); if (++it != parameters_intersect.end()) @@ -376,7 +376,7 @@ ModFile::transformPass(bool nostrict, bool compute_xrefs) /* clone the model then clone the new equations back to the original because we have to call computeDerivIDs (in computeRamseyPolicyFOCs and computingPass) - */ + */ if (linear) dynamic_model.cloneDynamic(orig_ramsey_dynamic_model); dynamic_model.cloneDynamic(ramsey_FOC_equations_dynamic_model); @@ -510,64 +510,64 @@ ModFile::computingPass(bool no_tmp_terms, FileOutputType output, int params_deri // Compute static model and its derivatives dynamic_model.toStatic(static_model); if (!no_static) - { - if (mod_file_struct.stoch_simul_present - || mod_file_struct.estimation_present || mod_file_struct.osr_present - || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present - || mod_file_struct.calib_smoother_present) - static_model.set_cutoff_to_zero(); - - const bool static_hessian = mod_file_struct.identification_present - || mod_file_struct.estimation_analytic_derivation; + { + if (mod_file_struct.stoch_simul_present + || mod_file_struct.estimation_present || mod_file_struct.osr_present + || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present + || mod_file_struct.calib_smoother_present) + static_model.set_cutoff_to_zero(); + + const bool static_hessian = mod_file_struct.identification_present + || mod_file_struct.estimation_analytic_derivation; int paramsDerivsOrder = 0; if (mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation) paramsDerivsOrder = params_derivs_order; - static_model.computingPass(global_eval_context, no_tmp_terms, static_hessian, - false, paramsDerivsOrder, block, byte_code); - } + static_model.computingPass(global_eval_context, no_tmp_terms, static_hessian, + false, paramsDerivsOrder, block, byte_code); + } // Set things to compute for dynamic model if (mod_file_struct.perfect_foresight_solver_present || mod_file_struct.check_present - || mod_file_struct.stoch_simul_present - || mod_file_struct.estimation_present || mod_file_struct.osr_present - || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present - || mod_file_struct.calib_smoother_present) - { - if (mod_file_struct.perfect_foresight_solver_present) - dynamic_model.computingPass(true, false, false, none, global_eval_context, no_tmp_terms, block, use_dll, byte_code); - else - { - if (mod_file_struct.stoch_simul_present - || mod_file_struct.estimation_present || mod_file_struct.osr_present - || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present - || mod_file_struct.calib_smoother_present) - dynamic_model.set_cutoff_to_zero(); - if (mod_file_struct.order_option < 1 || mod_file_struct.order_option > 3) - { - cerr << "ERROR: Incorrect order option..." << endl; - exit(EXIT_FAILURE); - } - bool hessian = mod_file_struct.order_option >= 2 - || mod_file_struct.identification_present - || mod_file_struct.estimation_analytic_derivation - || linear - || output == second - || output == third; - bool thirdDerivatives = mod_file_struct.order_option == 3 - || mod_file_struct.estimation_analytic_derivation - || output == third; - int paramsDerivsOrder = 0; - if (mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation) - paramsDerivsOrder = params_derivs_order; - dynamic_model.computingPass(true, hessian, thirdDerivatives, paramsDerivsOrder, global_eval_context, no_tmp_terms, block, use_dll, byte_code); - if (linear && mod_file_struct.ramsey_model_present) - orig_ramsey_dynamic_model.computingPass(true, true, false, paramsDerivsOrder, global_eval_context, no_tmp_terms, block, use_dll, byte_code); - } - } - else // No computing task requested, compute derivatives up to 2nd order by default - dynamic_model.computingPass(true, true, false, none, global_eval_context, no_tmp_terms, block, use_dll, byte_code); - - if ((linear && !mod_file_struct.ramsey_model_present && !dynamic_model.checkHessianZero()) || - (linear && mod_file_struct.ramsey_model_present && !orig_ramsey_dynamic_model.checkHessianZero())) + || mod_file_struct.stoch_simul_present + || mod_file_struct.estimation_present || mod_file_struct.osr_present + || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present + || mod_file_struct.calib_smoother_present) + { + if (mod_file_struct.perfect_foresight_solver_present) + dynamic_model.computingPass(true, false, false, none, global_eval_context, no_tmp_terms, block, use_dll, byte_code); + else + { + if (mod_file_struct.stoch_simul_present + || mod_file_struct.estimation_present || mod_file_struct.osr_present + || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present + || mod_file_struct.calib_smoother_present) + dynamic_model.set_cutoff_to_zero(); + if (mod_file_struct.order_option < 1 || mod_file_struct.order_option > 3) + { + cerr << "ERROR: Incorrect order option..." << endl; + exit(EXIT_FAILURE); + } + bool hessian = mod_file_struct.order_option >= 2 + || mod_file_struct.identification_present + || mod_file_struct.estimation_analytic_derivation + || linear + || output == second + || output == third; + bool thirdDerivatives = mod_file_struct.order_option == 3 + || mod_file_struct.estimation_analytic_derivation + || output == third; + int paramsDerivsOrder = 0; + if (mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation) + paramsDerivsOrder = params_derivs_order; + dynamic_model.computingPass(true, hessian, thirdDerivatives, paramsDerivsOrder, global_eval_context, no_tmp_terms, block, use_dll, byte_code); + if (linear && mod_file_struct.ramsey_model_present) + orig_ramsey_dynamic_model.computingPass(true, true, false, paramsDerivsOrder, global_eval_context, no_tmp_terms, block, use_dll, byte_code); + } + } + else // No computing task requested, compute derivatives up to 2nd order by default + dynamic_model.computingPass(true, true, false, none, global_eval_context, no_tmp_terms, block, use_dll, byte_code); + + if ((linear && !mod_file_struct.ramsey_model_present && !dynamic_model.checkHessianZero()) + || (linear && mod_file_struct.ramsey_model_present && !orig_ramsey_dynamic_model.checkHessianZero())) { map<int, string> eqs; if (mod_file_struct.ramsey_model_present) @@ -633,18 +633,18 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo if (clear_all) mOutputFile << "if isoctave || matlab_ver_less_than('8.6')" << endl << " clear all" << endl - << "else" << endl - << " clearvars -global" << endl - << " clear_persistent_variables(fileparts(which('dynare')), false)" << endl - << "end" << endl; + << "else" << endl + << " clearvars -global" << endl + << " clear_persistent_variables(fileparts(which('dynare')), false)" << endl + << "end" << endl; else if (clear_global) mOutputFile << "clear M_ options_ oo_ estim_params_ bayestopt_ dataset_ dataset_info estimation_info ys0_ ex0_;" << endl; mOutputFile << "tic0 = tic;" << endl - << "% Save empty dates and dseries objects in memory." << endl - << "dates('initialize');" << endl - << "dseries('initialize');" << endl - << "% Define global variables." << endl + << "% Save empty dates and dseries objects in memory." << endl + << "dates('initialize');" << endl + << "dseries('initialize');" << endl + << "% Define global variables." << endl << "global M_ options_ oo_ estim_params_ bayestopt_ dataset_ dataset_info estimation_info ys0_ ex0_" << endl << "options_ = [];" << endl << "M_.fname = '" << basename << "';" << endl @@ -734,7 +734,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo bool hasModelChanged = !dynamic_model.isChecksumMatching(basename); if (!check_model_changes) hasModelChanged = true; - + if (hasModelChanged) { // Erase possible remnants of previous runs @@ -749,7 +749,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo unlink((basename + "_steadystate2.m").c_str()); unlink((basename + "_set_auxiliary_variables.m").c_str()); } - + if (!use_dll) { mOutputFile << "erase_compiled_function('" + basename + "_static');" << endl; @@ -757,7 +757,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo } #if defined(_WIN32) || defined(__CYGWIN32__) -#if (defined(_MSC_VER) && _MSC_VER < 1700) +# if (defined(_MSC_VER) && _MSC_VER < 1700) // If using USE_DLL with MSVC 10.0 or earlier, check that the user didn't use a function not supported by the compiler (because MSVC <= 10.0 doesn't comply with C99 standard) if (use_dll && msvc) { @@ -777,7 +777,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo exit(EXIT_FAILURE); } } -#endif +# endif #endif // Compile the dynamic MEX file for use_dll option @@ -787,10 +787,10 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) if (msvc) // MATLAB/Windows + Microsoft Visual C++ - mOutputFile << "dyn_mex('msvc', '" << basename << "', " << !check_model_changes << ")" << endl; + mOutputFile << "dyn_mex('msvc', '" << basename << "', " << !check_model_changes << ")" << endl; else if (cygwin) // MATLAB/Windows + Cygwin g++ - mOutputFile << "dyn_mex('cygwin', '" << basename << "', " << !check_model_changes << ")" << endl; + mOutputFile << "dyn_mex('cygwin', '" << basename << "', " << !check_model_changes << ")" << endl; else if (mingw) // MATLAB/Windows + MinGW g++ mOutputFile << "dyn_mex('mingw', '" << basename << "', " << !check_model_changes << ")" << endl; @@ -868,7 +868,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo config_file.writeEndParallel(mOutputFile); mOutputFile << endl << endl - << "disp(['Total computing time : ' dynsec2hms(toc(tic0)) ]);" << endl; + << "disp(['Total computing time : ' dynsec2hms(toc(tic0)) ]);" << endl; if (!no_warn) { @@ -879,7 +879,6 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo << " disp('Note: warning(s) encountered in MATLAB/Octave code')" << endl << "end" << endl; } - if (!no_log) mOutputFile << "diary off" << endl; @@ -890,16 +889,16 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo { // Create static and dynamic files if (dynamic_model.equation_number() > 0) - { - if (!no_static) - { - static_model.writeStaticFile(basename, block, byte_code, use_dll, false); - static_model.writeParamsDerivativesFile(basename, false); - } + { + if (!no_static) + { + static_model.writeStaticFile(basename, block, byte_code, use_dll, false); + static_model.writeParamsDerivativesFile(basename, false); + } - dynamic_model.writeDynamicFile(basename, block, byte_code, use_dll, mod_file_struct.order_option, false); - dynamic_model.writeParamsDerivativesFile(basename, false); - } + dynamic_model.writeDynamicFile(basename, block, byte_code, use_dll, mod_file_struct.order_option, false); + dynamic_model.writeParamsDerivativesFile(basename, false); + } // Create steady state file steady_state_model.writeSteadyStateFile(basename, mod_file_struct.ramsey_model_present, false); @@ -911,7 +910,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo void ModFile::writeExternalFiles(const string &basename, FileOutputType output, LanguageOutputType language) const { - switch(language) + switch (language) { case c: writeExternalFilesC(basename, output); @@ -939,7 +938,6 @@ ModFile::writeExternalFilesC(const string &basename, FileOutputType output) cons if (!no_static) static_model.writeStaticFile(basename, false, false, true, false); - // static_model.writeStaticCFile(basename, block, byte_code, use_dll); // static_model.writeParamsDerivativesFileC(basename, cuda); // static_model.writeAuxVarInitvalC(mOutputFile, oMatlabOutsideModel, cuda); @@ -952,8 +950,8 @@ ModFile::writeExternalFilesC(const string &basename, FileOutputType output) cons dynamic_model.writeSecondDerivativesC_csr(basename, cuda); else if (output == third) { - dynamic_model.writeSecondDerivativesC_csr(basename, cuda); - dynamic_model.writeThirdDerivativesC_csr(basename, cuda); + dynamic_model.writeSecondDerivativesC_csr(basename, cuda); + dynamic_model.writeThirdDerivativesC_csr(basename, cuda); } } @@ -997,7 +995,7 @@ ModFile::writeModelC(const string &basename) const // Print statements for (vector<Statement *>::const_iterator it = statements.begin(); it != statements.end(); it++) - (*it)->writeCOutput(mDriverCFile, basename); + (*it)->writeCOutput(mDriverCFile, basename); mDriverCFile << "} DynareInfo;" << endl; mDriverCFile.close(); @@ -1057,8 +1055,8 @@ ModFile::writeExternalFilesCC(const string &basename, FileOutputType output) con dynamic_model.writeSecondDerivativesC_csr(basename, cuda); else if (output == third) { - dynamic_model.writeSecondDerivativesC_csr(basename, cuda); - dynamic_model.writeThirdDerivativesC_csr(basename, cuda); + dynamic_model.writeSecondDerivativesC_csr(basename, cuda); + dynamic_model.writeThirdDerivativesC_csr(basename, cuda); } } @@ -1102,7 +1100,7 @@ ModFile::writeModelCC(const string &basename) const // Print statements for (vector<Statement *>::const_iterator it = statements.begin(); it != statements.end(); it++) - (*it)->writeCOutput(mDriverCFile, basename); + (*it)->writeCOutput(mDriverCFile, basename); mDriverCFile << "};" << endl; mDriverCFile.close(); @@ -1178,7 +1176,7 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output) << "if isfile(\"" << basename << "SteadyState2.jl" "\")" << endl << " using " << basename << "SteadyState2" << endl << "end" << endl << endl - << "export model_, options_, oo_" << endl; + << "export model_, options_, oo_" << endl; // Write Output jlOutputFile << endl @@ -1236,9 +1234,9 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output) steady_state_model.writeSteadyStateFile(basename, mod_file_struct.ramsey_model_present, true); // Print statements (includes parameter values) - for (vector<Statement *>::const_iterator it = statements.begin(); - it != statements.end(); it++) - (*it)->writeJuliaOutput(jlOutputFile, basename); + for (vector<Statement *>::const_iterator it = statements.begin(); + it != statements.end(); it++) + (*it)->writeJuliaOutput(jlOutputFile, basename); jlOutputFile << "model_.static = " << basename << "Static.static!" << endl << "model_.dynamic = " << basename << "Dynamic.dynamic!" << endl @@ -1258,7 +1256,7 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output) << " using " << basename << "DynamicParamsDerivs" << endl << " model_.dynamic_params_derivs = " << basename << "DynamicParamsDerivs.params_derivs" << endl << "end" << endl - << "end" << endl; + << "end" << endl; jlOutputFile.close(); cout << "done" << endl; } diff --git a/preprocessor/ModFile.hh b/preprocessor/ModFile.hh index 68df1adfaab9c78158c9e5403b4c26a0c500994b..a4812471ee502fe2bb7f288a2d6cc688273a2c9c 100644 --- a/preprocessor/ModFile.hh +++ b/preprocessor/ModFile.hh @@ -41,7 +41,7 @@ using namespace std; // for checksum computation #ifndef PRIVATE_BUFFER_SIZE -#define PRIVATE_BUFFER_SIZE 1024 +# define PRIVATE_BUFFER_SIZE 1024 #endif //! The abstract representation of a "mod" file @@ -91,9 +91,9 @@ public: bool differentiate_forward_vars; /*! If the 'differentiate_forward_vars' option is used, contains the set of - endogenous with respect to which to do the transformation; - if empty, means that the transformation must be applied to all endos - with a lead */ + endogenous with respect to which to do the transformation; + if empty, means that the transformation must be applied to all endos + with a lead */ vector<string> differentiate_forward_vars_subset; //! Are nonstationary variables present ? diff --git a/preprocessor/ModelTree.cc b/preprocessor/ModelTree.cc index ed5ecdbeb83459dae77acad7c9d9499aa02b5ef5..9bfb30eaff3b0a0ad3aa7f13853b2de4bf9dc3a1 100644 --- a/preprocessor/ModelTree.cc +++ b/preprocessor/ModelTree.cc @@ -212,7 +212,7 @@ ModelTree::computeNonSingularNormalization(jacob_map_t &contemporaneous_jacobian if (first_derivatives.find(make_pair(it->first.first, getDerivID(symbol_table.getID(eEndogenous, it->first.second), 0))) == first_derivatives.end()) first_derivatives[make_pair(it->first.first, getDerivID(symbol_table.getID(eEndogenous, it->first.second), 0))] = Zero; } - catch(DataTree::UnknownDerivIDException &e) + catch (DataTree::UnknownDerivIDException &e) { cerr << "The variable " << symbol_table.getName(symbol_table.getID(eEndogenous, it->first.second)) << " does not appear at the current period (i.e. with no lead and no lag); this case is not handled by the 'block' option of the 'model' block." << endl; @@ -332,19 +332,19 @@ ModelTree::computePrologueAndEpilogue(const jacob_map_t &static_jacobian_arg, ve eq2endo[*it] = i; equation_reordered[i] = i; variable_reordered[*it] = i; - } - if (cutoff == 0) - { + } + if (cutoff == 0) + { set<pair<int, int> > endo; for (int i = 0; i < n; i++) - { + { endo.clear(); - equations[i]->collectEndogenous(endo); - for (set<pair<int, int> >::const_iterator it = endo.begin(); it != endo.end(); it++) - IM[i * n + endo2eq[it->first]] = true; - } - } - else + equations[i]->collectEndogenous(endo); + for (set<pair<int, int> >::const_iterator it = endo.begin(); it != endo.end(); it++) + IM[i * n + endo2eq[it->first]] = true; + } + } + else for (jacob_map_t::const_iterator it = static_jacobian_arg.begin(); it != static_jacobian_arg.end(); it++) IM[it->first.first * n + endo2eq[it->first.second]] = true; bool something_has_been_done = true; @@ -546,22 +546,22 @@ ModelTree::computeBlockDecompositionAndFeedbackVariablesForEachBlock(const jacob { reverse_equation_reordered[equation_reordered[i]] = i; reverse_variable_reordered[variable_reordered[i]] = i; - } - jacob_map_t tmp_normalized_contemporaneous_jacobian; - if (cutoff == 0) - { + } + jacob_map_t tmp_normalized_contemporaneous_jacobian; + if (cutoff == 0) + { set<pair<int, int> > endo; for (int i = 0; i < nb_var; i++) - { + { endo.clear(); - equations[i]->collectEndogenous(endo); - for (set<pair<int, int> >::const_iterator it = endo.begin(); it != endo.end(); it++) - tmp_normalized_contemporaneous_jacobian[make_pair(i, it->first)] = 1; - - } - } - else - tmp_normalized_contemporaneous_jacobian = static_jacobian; + equations[i]->collectEndogenous(endo); + for (set<pair<int, int> >::const_iterator it = endo.begin(); it != endo.end(); it++) + tmp_normalized_contemporaneous_jacobian[make_pair(i, it->first)] = 1; + + } + } + else + tmp_normalized_contemporaneous_jacobian = static_jacobian; for (jacob_map_t::const_iterator it = tmp_normalized_contemporaneous_jacobian.begin(); it != tmp_normalized_contemporaneous_jacobian.end(); it++) if (reverse_equation_reordered[it->first.first] >= (int) prologue && reverse_equation_reordered[it->first.first] < (int) (nb_var - epilogue) && reverse_variable_reordered[it->first.second] >= (int) prologue && reverse_variable_reordered[it->first.second] < (int) (nb_var - epilogue) @@ -887,7 +887,7 @@ ModelTree::reduceBlocksAndTypeDetermination(const dynamic_jacob_map_t &dynamic_j int c_Size = (block_type_size_mfs[block_type_size_mfs.size()-1]).second.first; int first_equation = (block_type_size_mfs[block_type_size_mfs.size()-1]).first.second; if (c_Size > 0 && ((prev_Type == EVALUATE_FORWARD && Simulation_Type == EVALUATE_FORWARD && !is_lead) - || (prev_Type == EVALUATE_BACKWARD && Simulation_Type == EVALUATE_BACKWARD && !is_lag))) + || (prev_Type == EVALUATE_BACKWARD && Simulation_Type == EVALUATE_BACKWARD && !is_lag))) { for (int j = first_equation; j < first_equation+c_Size; j++) { @@ -1125,10 +1125,10 @@ ModelTree::computeTemporaryTerms(bool is_matlab) temporary_terms_g2.clear(); temporary_terms_g3.clear(); map<NodeTreeReference, temporary_terms_t> temp_terms_map; - temp_terms_map[eResiduals]=temporary_terms_res; - temp_terms_map[eFirstDeriv]=temporary_terms_g1; - temp_terms_map[eSecondDeriv]=temporary_terms_g2; - temp_terms_map[eThirdDeriv]=temporary_terms_g3; + temp_terms_map[eResiduals] = temporary_terms_res; + temp_terms_map[eFirstDeriv] = temporary_terms_g1; + temp_terms_map[eSecondDeriv] = temporary_terms_g2; + temp_terms_map[eThirdDeriv] = temporary_terms_g3; for (vector<BinaryOpNode *>::iterator it = equations.begin(); it != equations.end(); it++) @@ -1332,17 +1332,17 @@ ModelTree::compileTemporaryTerms(ostream &code_file, unsigned int &instruction_n (*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt2, map_idx, dynamic, steady_dynamic, tef_terms); } - FNUMEXPR_ fnumexpr(TemporaryTerm, (int) (map_idx.find((*it)->idx)->second)); + FNUMEXPR_ fnumexpr(TemporaryTerm, (int)(map_idx.find((*it)->idx)->second)); fnumexpr.write(code_file, instruction_number); (*it)->compile(code_file, instruction_number, false, tt2, map_idx, dynamic, steady_dynamic, tef_terms); if (dynamic) { - FSTPT_ fstpt((int) (map_idx.find((*it)->idx)->second)); + FSTPT_ fstpt((int)(map_idx.find((*it)->idx)->second)); fstpt.write(code_file, instruction_number); } else { - FSTPST_ fstpst((int) (map_idx.find((*it)->idx)->second)); + FSTPST_ fstpst((int)(map_idx.find((*it)->idx)->second)); fstpst.write(code_file, instruction_number); } // Insert current node into tt2 @@ -1577,7 +1577,7 @@ ModelTree::writeLatexModelFile(const string &basename, ExprNodeOutputType output bool wrote_eq_tag = false; if (write_equation_tags) { - for (vector<pair<int,pair<string,string> > >::const_iterator iteqt = equation_tags.begin(); + for (vector<pair<int, pair<string, string> > >::const_iterator iteqt = equation_tags.begin(); iteqt != equation_tags.end(); iteqt++) if (iteqt->first == eq) { @@ -1792,11 +1792,11 @@ ModelTree::computeParamsDerivativesTemporaryTerms() map<expr_t, pair<int, NodeTreeReference > > reference_count; params_derivs_temporary_terms.clear(); map<NodeTreeReference, temporary_terms_t> temp_terms_map; - temp_terms_map[eResidualsParamsDeriv]=params_derivs_temporary_terms_res; - temp_terms_map[eJacobianParamsDeriv]=params_derivs_temporary_terms_g1; - temp_terms_map[eResidualsParamsSecondDeriv]=params_derivs_temporary_terms_res2; - temp_terms_map[eJacobianParamsSecondDeriv]=params_derivs_temporary_terms_g12; - temp_terms_map[eHessianParamsDeriv]=params_derivs_temporary_terms_g2; + temp_terms_map[eResidualsParamsDeriv] = params_derivs_temporary_terms_res; + temp_terms_map[eJacobianParamsDeriv] = params_derivs_temporary_terms_g1; + temp_terms_map[eResidualsParamsSecondDeriv] = params_derivs_temporary_terms_res2; + temp_terms_map[eJacobianParamsSecondDeriv] = params_derivs_temporary_terms_g12; + temp_terms_map[eHessianParamsDeriv] = params_derivs_temporary_terms_g2; for (first_derivatives_t::iterator it = residuals_params_derivatives.begin(); it != residuals_params_derivatives.end(); it++) @@ -1839,9 +1839,9 @@ ModelTree::computeParamsDerivativesTemporaryTerms() params_derivs_temporary_terms_g2 = temp_terms_map[eHessianParamsDeriv]; } -bool ModelTree::isNonstationary(int symb_id) const +bool +ModelTree::isNonstationary(int symb_id) const { return (nonstationary_symbols_map.find(symb_id) != nonstationary_symbols_map.end()); } - diff --git a/preprocessor/ModelTree.hh b/preprocessor/ModelTree.hh index 1de07d4b353d9516478289bd29c85762a75dc59c..f3c34836480b1fe8d7fa35b41306879e13e999a7 100644 --- a/preprocessor/ModelTree.hh +++ b/preprocessor/ModelTree.hh @@ -128,7 +128,6 @@ protected: */ third_derivatives_t hessian_params_derivatives; - //! Temporary terms for the static/dynamic file (those which will be noted Txxxx) temporary_terms_t temporary_terms; temporary_terms_t temporary_terms_res; @@ -144,7 +143,6 @@ protected: temporary_terms_t params_derivs_temporary_terms_g12; temporary_terms_t params_derivs_temporary_terms_g2; - //! Trend variables and their growth factors map<int, expr_t> trend_symbols_map; @@ -177,7 +175,7 @@ protected: void computeTemporaryTerms(bool is_matlab); //! Computes temporary terms for the file containing parameters derivatives void computeParamsDerivativesTemporaryTerms(); -//! Writes temporary terms + //! Writes temporary terms void writeTemporaryTerms(const temporary_terms_t &tt, const temporary_terms_t &ttm1, ostream &output, ExprNodeOutputType output_type, deriv_node_temp_terms_t &tef_terms) const; //! Compiles temporary terms void compileTemporaryTerms(ostream &code_file, unsigned int &instruction_number, const temporary_terms_t &tt, map_idx_t map_idx, bool dynamic, bool steady_dynamic) const; @@ -268,11 +266,12 @@ protected: virtual unsigned int getBlockMaxLag(int block_number) const = 0; //! Return the maximum lead in a block virtual unsigned int getBlockMaxLead(int block_number) const = 0; - inline void setBlockLeadLag(int block, int max_lag, int max_lead) - { - block_lag_lead[block] = make_pair(max_lag, max_lead); - }; - + inline void + setBlockLeadLag(int block, int max_lag, int max_lead) + { + block_lag_lead[block] = make_pair(max_lag, max_lead); + }; + //! Return the type of equation (equation_number) belonging to the block block_number virtual EquationType getBlockEquationType(int block_number, int equation_number) const = 0; //! Return true if the equation has been normalized diff --git a/preprocessor/ParsingDriver.cc b/preprocessor/ParsingDriver.cc index bce5408512e6d8f6c80526c172e1d97153d43073..32b1b3ac24043f92e191d64845f523c4b8422649 100644 --- a/preprocessor/ParsingDriver.cc +++ b/preprocessor/ParsingDriver.cc @@ -134,7 +134,7 @@ ParsingDriver::create_error_string(const Dynare::parser::location_type &l, const stream << ", cols " << l.begin.column << "-" << l.end.column - 1; else stream << ", col " << l.begin.column << " -" - << " line " << l.end.line << ", col " << l.end.column - 1; + << " line " << l.end.line << ", col " << l.end.column - 1; stream << ": " << m << endl; } @@ -259,8 +259,8 @@ void ParsingDriver::declare_statement_local_variable(string *name) { if (mod_file->symbol_table.exists(*name)) - error("Symbol " + *name + " cannot be assigned within a statement " + - "while being assigned elsewhere in the modfile"); + error("Symbol " + *name + " cannot be assigned within a statement " + +"while being assigned elsewhere in the modfile"); declare_symbol(name, eStatementDeclaredVariable, NULL, NULL); delete name; } @@ -366,7 +366,7 @@ ParsingDriver::add_model_variable(string *name) { // This could be endog or param too. Just declare something to continue parsing, // knowing that processing will end at the end of parsing of the model block - declare_exogenous(new string (*name)); + declare_exogenous(new string(*name)); undeclared_model_vars.insert(*name); symb_id = mod_file->symbol_table.getID(*name); } @@ -752,7 +752,7 @@ ParsingDriver::add_det_shock(string *var, bool conditional_forecast) } det_shocks[symb_id] = v; - + det_shocks_periods.clear(); det_shocks_values.clear(); delete var; @@ -888,7 +888,7 @@ ParsingDriver::end_svar_identification() mod_file->addStatement(new SvarIdentificationStatement(svar_ident_restrictions, svar_upper_cholesky, svar_lower_cholesky, - svar_constants_exclusion, + svar_constants_exclusion, mod_file->symbol_table)); svar_restriction_symbols.clear(); svar_equation_restrictions.clear(); @@ -910,19 +910,19 @@ ParsingDriver::combine_lag_and_restriction(string *lag) for (map<int, vector<int> >::const_iterator it = svar_equation_restrictions.begin(); it != svar_equation_restrictions.end(); it++) for (vector<int>::const_iterator it1 = it->second.begin(); - it1 != it->second.end(); it1++) + it1 != it->second.end(); it1++) { - SvarIdentificationStatement::svar_identification_restriction new_restriction; - new_restriction.equation = it->first; - if (current_lag > 0) - new_restriction.restriction_nbr = ++svar_Ri_restriction_nbr[it->first]; - else - new_restriction.restriction_nbr = ++svar_Qi_restriction_nbr[it->first]; - new_restriction.lag = current_lag; - new_restriction.variable = *it1; - new_restriction.value = data_tree->One; - svar_ident_restrictions.push_back(new_restriction); - } + SvarIdentificationStatement::svar_identification_restriction new_restriction; + new_restriction.equation = it->first; + if (current_lag > 0) + new_restriction.restriction_nbr = ++svar_Ri_restriction_nbr[it->first]; + else + new_restriction.restriction_nbr = ++svar_Qi_restriction_nbr[it->first]; + new_restriction.lag = current_lag; + new_restriction.variable = *it1; + new_restriction.value = data_tree->One; + svar_ident_restrictions.push_back(new_restriction); + } // svar_ident_exclusion_values[make_pair(current_lag, it->first)] = it->second; svar_upper_cholesky = false; @@ -962,7 +962,7 @@ ParsingDriver::add_in_svar_restriction_symbols(string *tmp_var) delete tmp_var; } -void +void ParsingDriver::add_restriction_equation_nbr(string *eq_nbr) { svar_equation_nbr = atoi(eq_nbr->c_str()); @@ -986,14 +986,14 @@ ParsingDriver::add_positive_restriction_element(expr_t value, string *variable, // if the expression is not on the left handside, change its sign if (!svar_left_handside) value = add_uminus(value); - + add_restriction_element(value, variable, lag); } void ParsingDriver::add_positive_restriction_element(string *variable, string *lag) { - expr_t value(data_tree->One); + expr_t value(data_tree->One); // if the expression is not on the left handside, change its sign if (!svar_left_handside) @@ -1015,7 +1015,7 @@ ParsingDriver::add_negative_restriction_element(expr_t value, string *variable, void ParsingDriver::add_negative_restriction_element(string *variable, string *lag) { - expr_t value(data_tree->One); + expr_t value(data_tree->One); // if the expression is on the left handside, change its sign if (svar_left_handside) @@ -1034,21 +1034,21 @@ ParsingDriver::add_restriction_element(expr_t value, string *variable, string *l if (svar_restriction_type == ParsingDriver::NOT_SET) { if (current_lag == 0) - { - svar_restriction_type = ParsingDriver::Qi_TYPE; - ++svar_Qi_restriction_nbr[svar_equation_nbr]; - } + { + svar_restriction_type = ParsingDriver::Qi_TYPE; + ++svar_Qi_restriction_nbr[svar_equation_nbr]; + } else - { - svar_restriction_type = ParsingDriver::Ri_TYPE; - ++svar_Ri_restriction_nbr[svar_equation_nbr]; - } + { + svar_restriction_type = ParsingDriver::Ri_TYPE; + ++svar_Ri_restriction_nbr[svar_equation_nbr]; + } } else { if ((svar_restriction_type == Qi_TYPE && current_lag > 0) - || (svar_restriction_type == Ri_TYPE && current_lag == 0)) - error("SVAR_IDENTIFICATION: a single restrictions must affect either Qi or Ri, but not both"); + || (svar_restriction_type == Ri_TYPE && current_lag == 0)) + error("SVAR_IDENTIFICATION: a single restrictions must affect either Qi or Ri, but not both"); } SvarIdentificationStatement::svar_identification_restriction new_restriction; new_restriction.equation = svar_equation_nbr; @@ -1213,7 +1213,7 @@ ParsingDriver::option_symbol_list(const string &name_option) != options_list.symbol_list_options.end()) error("option " + name_option + " declared twice"); - if (name_option.compare("irf_shocks")==0) + if (name_option.compare("irf_shocks") == 0) { vector<string> shocks = symbol_list.get_symbols(); for (vector<string>::const_iterator it = shocks.begin(); @@ -1222,7 +1222,7 @@ ParsingDriver::option_symbol_list(const string &name_option) error("Variables passed to irf_shocks must be exogenous. Caused by: " + *it); } - if (name_option.compare("ms.parameters")==0) + if (name_option.compare("ms.parameters") == 0) { vector<string> parameters = symbol_list.get_symbols(); for (vector<string>::const_iterator it = parameters.begin(); @@ -1415,7 +1415,7 @@ ParsingDriver::copy_subsamples(string *to_name1, string *to_name2, string *from_ if (!from_name2->empty()) check_symbol_existence(*from_name2); - if (subsample_declarations.find(make_pair(*from_name1,*from_name2)) == subsample_declarations.end()) + if (subsample_declarations.find(make_pair(*from_name1, *from_name2)) == subsample_declarations.end()) { string err = *from_name1; if (!from_name2->empty()) @@ -1426,8 +1426,8 @@ ParsingDriver::copy_subsamples(string *to_name1, string *to_name2, string *from_ mod_file->addStatement(new SubsamplesEqualStatement(*to_name1, *to_name2, *from_name1, *from_name2, mod_file->symbol_table)); - subsample_declarations[make_pair(*to_name1, *to_name2)] = - subsample_declarations[make_pair(*from_name1, *from_name2)]; + subsample_declarations[make_pair(*to_name1, *to_name2)] + = subsample_declarations[make_pair(*from_name1, *from_name2)]; delete to_name1; delete to_name2; @@ -1461,7 +1461,7 @@ ParsingDriver::check_subsample_declaration_exists(string *name1, string *subsamp if (subsample_name->empty()) return; - string *str_empty = new string (""); + string *str_empty = new string(""); check_subsample_declaration_exists(name1, str_empty, subsample_name); delete str_empty; } @@ -1474,13 +1474,13 @@ ParsingDriver::check_subsample_declaration_exists(string *name1, string *name2, check_symbol_existence(*name1); if (!name2->empty()) - check_symbol_existence(*name2); + check_symbol_existence(*name2); subsample_declarations_t::const_iterator it = subsample_declarations.find(make_pair(*name1, *name2)); if (it == subsample_declarations.end()) { it = subsample_declarations.find(make_pair(*name2, *name1)); - if (it== subsample_declarations.end()) + if (it == subsample_declarations.end()) { string err = *name1; if (!name2->empty()) @@ -1494,7 +1494,6 @@ ParsingDriver::check_subsample_declaration_exists(string *name1, string *name2, error("The subsample name " + *subsample_name + " was not previously declared in a subsample statement."); } - void ParsingDriver::set_prior(string *name, string *subsample_name) { @@ -1509,9 +1508,9 @@ ParsingDriver::set_prior(string *name, string *subsample_name) } void -ParsingDriver::set_joint_prior(vector<string *>*symbol_vec) +ParsingDriver::set_joint_prior(vector<string *> *symbol_vec) { - for (vector<string *>::const_iterator it=symbol_vec->begin(); it != symbol_vec->end(); it++) + for (vector<string *>::const_iterator it = symbol_vec->begin(); it != symbol_vec->end(); it++) add_joint_parameter(*it); mod_file->addStatement(new JointPriorStatement(joint_parameters, prior_shape, options_list)); joint_parameters.clear(); @@ -1621,7 +1620,7 @@ ParsingDriver::check_symbol_is_endogenous_or_exogenous(string *name) { check_symbol_existence(*name); int symb_id = mod_file->symbol_table.getID(*name); - switch(mod_file->symbol_table.getType(symb_id)) + switch (mod_file->symbol_table.getType(symb_id)) { case eEndogenous: case eExogenous: @@ -2034,7 +2033,7 @@ ParsingDriver::ms_compute_probabilities() void ParsingDriver::ms_irf() { - mod_file->addStatement(new MSSBVARIrfStatement(symbol_list,options_list)); + mod_file->addStatement(new MSSBVARIrfStatement(symbol_list, options_list)); symbol_list.clear(); options_list.clear(); } @@ -2199,7 +2198,7 @@ ParsingDriver::add_model_equal(expr_t arg1, expr_t arg2) expr_t id = model_tree->AddEqual(arg1, arg2); // Detect if the equation is tagged [static] - bool is_static_only = false; + bool is_static_only = false; for (vector<pair<string, string> >::const_iterator it = eq_tags.begin(); it != eq_tags.end(); ++it) if (it->first == "static") @@ -2212,7 +2211,7 @@ ParsingDriver::add_model_equal(expr_t arg1, expr_t arg2) { if (!id->isInStaticForm()) error("An equation tagged [static] cannot contain leads, lags, expectations or STEADY_STATE operators"); - + dynamic_model->addStaticOnlyEquation(id, location.begin.line); } else @@ -2705,7 +2704,7 @@ ParsingDriver::add_model_var_or_external_function(string *function_name, bool in if (rv.first) { // assume it's a lead/lagged variable - declare_exogenous(new string (*function_name)); + declare_exogenous(new string(*function_name)); return add_model_variable(mod_file->symbol_table.getID(*function_name), (int) rv.second); } else @@ -2870,18 +2869,19 @@ ParsingDriver::add_moment_calibration_item(string *endo1, string *endo2, string c.lags = *lags; delete lags; - + assert(range->size() == 2); c.lower_bound = *((*range)[0]); c.upper_bound = *((*range)[1]); delete (*range)[0]; delete (*range)[1]; delete range; - + moment_calibration_constraints.push_back(c); } -void ParsingDriver::end_moment_calibration() +void +ParsingDriver::end_moment_calibration() { mod_file->addStatement(new MomentCalibration(moment_calibration_constraints, mod_file->symbol_table)); @@ -2907,18 +2907,19 @@ ParsingDriver::add_irf_calibration_item(string *endo, string *periods, string *e if (mod_file->symbol_table.getType(*exo) != eExogenous) error("Variable " + *endo + " is not an exogenous."); delete exo; - + assert(range->size() == 2); c.lower_bound = *((*range)[0]); c.upper_bound = *((*range)[1]); delete (*range)[0]; delete (*range)[1]; delete range; - + irf_calibration_constraints.push_back(c); } -void ParsingDriver::end_irf_calibration() +void +ParsingDriver::end_irf_calibration() { mod_file->addStatement(new IrfCalibration(irf_calibration_constraints, mod_file->symbol_table, @@ -2940,7 +2941,6 @@ ParsingDriver::histval_file(string *filename) delete filename; } - void ParsingDriver::perfect_foresight_setup() { @@ -2958,7 +2958,7 @@ ParsingDriver::perfect_foresight_solver() void ParsingDriver::prior_posterior_function(bool prior_func) { - mod_file->addStatement(new PriorPosteriorFunctionStatement((bool)prior_func, options_list)); + mod_file->addStatement(new PriorPosteriorFunctionStatement((bool) prior_func, options_list)); options_list.clear(); } @@ -2972,25 +2972,25 @@ ParsingDriver::add_ramsey_constraints_statement() void ParsingDriver::ramsey_constraint_add_less(const string *name, const expr_t rhs) { - add_ramsey_constraint(name,oLess,rhs); + add_ramsey_constraint(name, oLess, rhs); } void ParsingDriver::ramsey_constraint_add_greater(const string *name, const expr_t rhs) { - add_ramsey_constraint(name,oGreater,rhs); + add_ramsey_constraint(name, oGreater, rhs); } void ParsingDriver::ramsey_constraint_add_less_equal(const string *name, const expr_t rhs) { - add_ramsey_constraint(name,oLessEqual,rhs); + add_ramsey_constraint(name, oLessEqual, rhs); } void ParsingDriver::ramsey_constraint_add_greater_equal(const string *name, const expr_t rhs) { - add_ramsey_constraint(name,oGreaterEqual,rhs); + add_ramsey_constraint(name, oGreaterEqual, rhs); } void @@ -3027,7 +3027,6 @@ ParsingDriver::add_shock_group_element(string *name) delete name; } - void ParsingDriver::add_shock_group(string *name) { diff --git a/preprocessor/ParsingDriver.hh b/preprocessor/ParsingDriver.hh index b25105f437736158d5fa941da09d90a702cf40b2..f6f04f8a06d0465944fd6e7d462930d729aa1da7 100644 --- a/preprocessor/ParsingDriver.hh +++ b/preprocessor/ParsingDriver.hh @@ -171,7 +171,7 @@ private: map<int, vector<int> > svar_equation_restrictions; //! Temporary storage for restrictions in an equation within an svar_identification block vector<int> svar_restriction_symbols; - //! Temporary storage for constants exculsion within an svar_identification + //! Temporary storage for constants exculsion within an svar_identification bool svar_constants_exclusion; //! Temporary storage for upper cholesky within an svar_identification block bool svar_upper_cholesky; @@ -182,8 +182,8 @@ private: //! Temporary storage for left/right handside of a restriction equation within an svar_identificaton block bool svar_left_handside; //! Temporary storage for current restriction number in svar_identification block - map<int,int> svar_Qi_restriction_nbr; - map<int,int> svar_Ri_restriction_nbr; + map<int, int> svar_Qi_restriction_nbr; + map<int, int> svar_Ri_restriction_nbr; //! Stores undeclared model variables set<string> undeclared_model_vars; //! Temporary storage for restriction type @@ -239,7 +239,9 @@ private: ostringstream model_errors; public: - ParsingDriver(WarningConsolidation &warnings_arg, bool nostrict_arg) : warnings(warnings_arg), nostrict(nostrict_arg), model_error_encountered(false) { }; + ParsingDriver(WarningConsolidation &warnings_arg, bool nostrict_arg) : warnings(warnings_arg), nostrict(nostrict_arg), model_error_encountered(false) + { + }; //! Starts parsing, and constructs the MOD file representation /*! The returned pointer should be deleted after use */ @@ -449,11 +451,11 @@ public: //! Sets the prior for a parameter void set_prior(string *arg1, string *arg2); //! Sets the joint prior for a set of parameters - void set_joint_prior(vector<string *>*symbol_vec); + void set_joint_prior(vector<string *> *symbol_vec); //! Adds a parameters to the list of joint parameters void add_joint_parameter(string *name); //! Adds the variance option to its temporary holding place - void set_prior_variance(expr_t variance=NULL); + void set_prior_variance(expr_t variance = NULL); //! Copies the prior from_name to_name void copy_prior(string *to_declaration_type, string *to_name1, string *to_name2, string *to_subsample_name, string *from_declaration_type, string *from_name1, string *from_name2, string *from_subsample_name); @@ -468,7 +470,7 @@ public: void set_std_options(string *arg1, string *arg2); //! Sets the prior for estimated correlation void set_corr_prior(string *arg1, string *arg2, string *arg3); - //! Sets the options for estimated correlation + //! Sets the options for estimated correlation void set_corr_options(string *arg1, string *arg2, string *arg3); //! Runs estimation process void run_estimation(); @@ -501,11 +503,11 @@ public: void add_restriction_equation_nbr(string *eq_nbr); //! Svar_Identification Statement: record presence of equal sign void add_restriction_equal(); - //! Svar_Idenditification Statement: add coefficient of a linear restriction (positive value) + //! Svar_Idenditification Statement: add coefficient of a linear restriction (positive value) void add_positive_restriction_element(expr_t value, string *variable, string *lag); - //! Svar_Idenditification Statement: add unit coefficient of a linear restriction + //! Svar_Idenditification Statement: add unit coefficient of a linear restriction void add_positive_restriction_element(string *variable, string *lag); - //! Svar_Idenditification Statement: add coefficient of a linear restriction (negative value) + //! Svar_Idenditification Statement: add coefficient of a linear restriction (negative value) void add_negative_restriction_element(expr_t value, string *variable, string *lag); //! Svar_Idenditification Statement: add negative unit coefficient of a linear restriction void add_negative_restriction_element(string *variable, string *lag); @@ -534,7 +536,7 @@ public: void run_load_params_and_steady_state(string *filename); void run_save_params_and_steady_state(string *filename); void run_identification(); - void add_mc_filename(string *filename, string *prior = new string("1")); + void add_mc_filename(string *filename, string *prior = new string ("1")); void run_model_comparison(); //! Begin a planner_objective statement void begin_planner_objective(); diff --git a/preprocessor/Shocks.cc b/preprocessor/Shocks.cc index af40262414e6dc343874707a73d11814580c7590..0aa7fdfa601605ed3079fcd1904f213472d6bc86 100644 --- a/preprocessor/Shocks.cc +++ b/preprocessor/Shocks.cc @@ -94,9 +94,9 @@ ShocksStatement::writeOutput(ostream &output, const string &basename, bool minim output << "M_.det_shocks = [];" << endl; output << "M_.Sigma_e = zeros(" << symbol_table.exo_nbr() << ", " - << symbol_table.exo_nbr() << ");" << endl - << "M_.Correlation_matrix = eye(" << symbol_table.exo_nbr() << ", " - << symbol_table.exo_nbr() << ");" << endl; + << symbol_table.exo_nbr() << ");" << endl + << "M_.Correlation_matrix = eye(" << symbol_table.exo_nbr() << ", " + << symbol_table.exo_nbr() << ");" << endl; if (has_calibrated_measurement_errors()) output << "M_.H = zeros(" << symbol_table.observedVariablesNbr() << ", " @@ -254,7 +254,7 @@ ShocksStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidati { int symb_id1 = it->first.first; int symb_id2 = it->first.second; - + if (!((symbol_table.getType(symb_id1) == eExogenous && symbol_table.getType(symb_id2) == eExogenous) || (symbol_table.isObservedVariable(symb_id1) @@ -272,7 +272,7 @@ ShocksStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidati { int symb_id1 = it->first.first; int symb_id2 = it->first.second; - + if (!((symbol_table.getType(symb_id1) == eExogenous && symbol_table.getType(symb_id2) == eExogenous) || (symbol_table.isObservedVariable(symb_id1) @@ -465,7 +465,7 @@ ShockGroupsStatement::writeOutput(ostream &output, const string &basename, bool { int i = 1; bool unique_label = true; - for (vector<Group>::const_iterator it = shock_groups.begin(); it != shock_groups.end(); it++, unique_label=true) + for (vector<Group>::const_iterator it = shock_groups.begin(); it != shock_groups.end(); it++, unique_label = true) { for (vector<Group>::const_iterator it1 = it+1; it1 != shock_groups.end(); it1++) if (it->name == it1->name) @@ -482,7 +482,7 @@ ShockGroupsStatement::writeOutput(ostream &output, const string &basename, bool << ".group" << i << ".label = '" << it->name << "';" << endl << "M_.shock_groups." << name << ".group" << i << ".shocks = {"; - for ( vector<string>::const_iterator it1 = it->list.begin(); it1 != it->list.end(); it1++) + for (vector<string>::const_iterator it1 = it->list.begin(); it1 != it->list.end(); it1++) output << " '" << *it1 << "'"; output << "};" << endl; i++; diff --git a/preprocessor/Shocks.hh b/preprocessor/Shocks.hh index f89e1fba1ec51d035aa4707129c84c8e59720bb3..1c7abb9135935d1292e6d9cdb40d7626a02655a2 100644 --- a/preprocessor/Shocks.hh +++ b/preprocessor/Shocks.hh @@ -160,5 +160,5 @@ public: ShockGroupsStatement(const group_t &shock_groups_arg, const string &name_arg); virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; }; - + #endif diff --git a/preprocessor/Statement.cc b/preprocessor/Statement.cc index d43d11444ee05b6c8d963cfc62d6f962b4f4dbe9..d1a34bd2cc158bffe279b5d7c6219b0ef7049de1 100644 --- a/preprocessor/Statement.cc +++ b/preprocessor/Statement.cc @@ -77,7 +77,8 @@ Statement::writeCOutput(ostream &output, const string &basename) { } -void Statement::writeJuliaOutput(ostream &output, const string &basename) +void +Statement::writeJuliaOutput(ostream &output, const string &basename) { } @@ -100,7 +101,7 @@ NativeStatement::writeOutput(ostream &output, const string &basename, bool minim sregex regex_dollar = sregex::compile("(\\$)"+date_regex); string ns = regex_replace(native_statement, regex_lookbehind, "dates('$&')"); - ns = regex_replace(ns, regex_dollar, "$2" ); //replace $DATE with DATE + ns = regex_replace(ns, regex_dollar, "$2"); //replace $DATE with DATE output << ns << endl; } @@ -161,9 +162,9 @@ OptionsList::writeOutput(ostream &output, const string &option_group) const { // Initialize option_group as an empty struct iff the field does not exist! unsigned idx = option_group.find_last_of("."); - if (idx<UINT_MAX) + if (idx < UINT_MAX) { - output << "if ~isfield(" << option_group.substr(0,idx) << ",'" << option_group.substr(idx+1) << "')" << endl; + output << "if ~isfield(" << option_group.substr(0, idx) << ",'" << option_group.substr(idx+1) << "')" << endl; output << " " << option_group << " = struct();" << endl; output << "end" << endl; } diff --git a/preprocessor/Statement.hh b/preprocessor/Statement.hh index adfbdd6aabd94d82482c72d88437dab22dc91fe4..f26c097014ece4eddc439f169b3515f23a7b7d71 100644 --- a/preprocessor/Statement.hh +++ b/preprocessor/Statement.hh @@ -117,7 +117,7 @@ public: bool occbin_option; //! Stores the original number of equations in the model_block int orig_eq_nbr; - //! Stores the number of equations added to the Ramsey model + //! Stores the number of equations added to the Ramsey model int ramsey_eq_nbr; }; @@ -125,7 +125,8 @@ public: class Statement { public: - virtual ~Statement(); + virtual + ~Statement(); //! Do some internal check, and fill the ModFileStructure class /*! Don't forget to update ComputingTasks.hh, Shocks.hh and NumericalInitialization.hh if you modify the signature of this diff --git a/preprocessor/StaticModel.cc b/preprocessor/StaticModel.cc index 1d176027470005acbdb8eb460372ab8c656e43ce..1038ac5324ea78680faf314d00fd27cea17cc53f 100644 --- a/preprocessor/StaticModel.cc +++ b/preprocessor/StaticModel.cc @@ -661,10 +661,10 @@ StaticModel::writeModelEquationsCode_Block(const string file_name, const string if (dynamic_cast<AbstractExternalFunctionNode *>(*it) != NULL) (*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt2, map_idx, false, false, tef_terms); - FNUMEXPR_ fnumexpr(TemporaryTerm, (int) (map_idx.find((*it)->idx)->second)); + FNUMEXPR_ fnumexpr(TemporaryTerm, (int)(map_idx.find((*it)->idx)->second)); fnumexpr.write(code_file, instruction_number); (*it)->compile(code_file, instruction_number, false, tt2, map_idx, false, false, tef_terms); - FSTPST_ fstpst((int) (map_idx.find((*it)->idx)->second)); + FSTPST_ fstpst((int)(map_idx.find((*it)->idx)->second)); fstpst.write(code_file, instruction_number); // Insert current node into tt2 tt2.insert(*it); @@ -854,12 +854,12 @@ StaticModel::writeModelEquationsCode_Block(const string file_name, const string if (dynamic_cast<AbstractExternalFunctionNode *>(*it) != NULL) (*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt3, map_idx2[block], false, false, tef_terms2); - FNUMEXPR_ fnumexpr(TemporaryTerm, (int) (map_idx2[block].find((*it)->idx)->second)); + FNUMEXPR_ fnumexpr(TemporaryTerm, (int)(map_idx2[block].find((*it)->idx)->second)); fnumexpr.write(code_file, instruction_number); (*it)->compile(code_file, instruction_number, false, tt3, map_idx2[block], false, false, tef_terms); - FSTPST_ fstpst((int) (map_idx2[block].find((*it)->idx)->second)); + FSTPST_ fstpst((int)(map_idx2[block].find((*it)->idx)->second)); fstpst.write(code_file, instruction_number); // Insert current node into tt2 tt3.insert(*it); @@ -1058,14 +1058,14 @@ StaticModel::computingPass(const eval_context_t &eval_context, bool no_tmp_terms neweqs.push_back(dynamic_cast<BinaryOpNode *>(eq_tmp->toStatic(*this))); } - for (unsigned int eq = 0; eq < aux_equations.size(); eq++) + for (unsigned int eq = 0; eq < aux_equations.size(); eq++) { expr_t eq_tmp = aux_equations[eq]->substituteStaticAuxiliaryDefinition(); neweqs.push_back(dynamic_cast<BinaryOpNode *>(eq_tmp->toStatic(*this))); } - + equations.clear(); - copy(neweqs.begin(),neweqs.end(),back_inserter(equations)); + copy(neweqs.begin(), neweqs.end(), back_inserter(equations)); // Compute derivatives w.r. to all endogenous, and possibly exogenous and exogenous deterministic set<int> vars; @@ -1074,8 +1074,8 @@ StaticModel::computingPass(const eval_context_t &eval_context, bool no_tmp_terms int id = symbol_table.getID(eEndogenous, i); // if (!symbol_table.isAuxiliaryVariableButNotMultiplier(id)) vars.insert(getDerivID(id, 0)); - } - + } + // Launch computations cout << "Computing static model derivatives:" << endl << " - order 1" << endl; @@ -1190,7 +1190,7 @@ StaticModel::writeStaticMFile(const string &func_name) const << "% columns: variables in declaration order" << endl << "% rows: equations in order of declaration" << endl << "%" << endl - << "%" << endl + << "%" << endl << "% Warning : this file is generated automatically by Dynare" << endl << "% from model file (.mod)" << endl << endl; @@ -1338,7 +1338,6 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c int id2 = getSymbIDByDerivID(var2); int id3 = getSymbIDByDerivID(var3); - // Reference column number for the g3 matrix int ref_col = id1 * hessianColsNbr + id2 * JacobianColsNbr + id3; @@ -1440,15 +1439,15 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c // Initialize g3 matrix StaticOutput << "if nargout >= 4," << endl - << " %" << endl - << " % Third order derivatives" << endl - << " %" << endl - << endl; + << " %" << endl + << " % Third order derivatives" << endl + << " %" << endl + << endl; int ncols = hessianColsNbr * JacobianColsNbr; if (third_derivatives.size()) StaticOutput << " v3 = zeros(" << NNZDerivatives[2] << ",3);" << endl - << third_derivatives_output.str() - << " g3 = sparse(v3(:,1),v3(:,2),v3(:,3)," << nrows << "," << ncols << ");" << endl; + << third_derivatives_output.str() + << " g3 = sparse(v3(:,1),v3(:,2),v3(:,3)," << nrows << "," << ncols << ");" << endl; else // Either 3rd derivatives is all zero, or we didn't compute it StaticOutput << " g3 = sparse([],[],[]," << nrows << "," << ncols << ");" << endl; StaticOutput << "end" << endl @@ -1622,7 +1621,6 @@ StaticModel::writeStaticCFile(const string &func_name) const output << "#define max(a, b) (((a) > (b)) ? (a) : (b))" << endl << "#define min(a, b) (((a) > (b)) ? (b) : (a))" << endl; - // Write function definition if oPowerDeriv is used writePowerDerivCHeader(output); writeNormcdfCHeader(output); @@ -1754,7 +1752,7 @@ StaticModel::writeStaticFile(const string &basename, bool block, bool bytecode, chdir(".."); writeStaticBlockMFSFile(basename); } - else if(use_dll) + else if (use_dll) writeStaticCFile(basename); else if (julia) writeStaticJuliaFile(basename); @@ -1859,7 +1857,7 @@ StaticModel::writeOutput(ostream &output, bool block) const for (int i = 0; i < nb_endo; i++) output << " " << equation_reordered[i]+1; output << "];\n"; - + map<pair<int, int>, int> row_incidence; for (first_derivatives_t::const_iterator it = first_derivatives.begin(); it != first_derivatives.end(); it++) @@ -2129,9 +2127,10 @@ StaticModel::writeAuxVarInitval(ostream &output, ExprNodeOutputType output_type) } } -void StaticModel::writeSetAuxiliaryVariables(const string &basename, const bool julia) const +void +StaticModel::writeSetAuxiliaryVariables(const string &basename, const bool julia) const { - + string func_name = basename + "_set_auxiliary_variables"; string filename = julia ? func_name + ".jl" : func_name + ".m"; string comment = julia ? "#" : "%"; @@ -2311,7 +2310,6 @@ StaticModel::writeParamsDerivativesFile(const string &basename, bool julia) cons third_derivs1_output << ";" << endl; } - ofstream paramsDerivsFile; string filename = julia ? basename + "StaticParamsDerivs.jl" : basename + "_static_params_derivs.m"; paramsDerivsFile.open(filename.c_str(), ios::out | ios::binary); diff --git a/preprocessor/StaticModel.hh b/preprocessor/StaticModel.hh index 8535a714077f900d0b1a156d5796506c77abdf46..abf2aa01b29f17c763dffc4a9b6cae525679565e 100644 --- a/preprocessor/StaticModel.hh +++ b/preprocessor/StaticModel.hh @@ -215,12 +215,14 @@ public: return (block_type_firstequation_size_mfs[block_number].second.first); }; //! Return the number of exogenous variable in the block block_number - virtual unsigned int getBlockExoSize(int block_number) const + virtual unsigned int + getBlockExoSize(int block_number) const { return 0; }; //! Return the number of colums in the jacobian matrix for exogenous variable in the block block_number - virtual unsigned int getBlockExoColSize(int block_number) const + virtual unsigned int + getBlockExoColSize(int block_number) const { return 0; } diff --git a/preprocessor/SteadyStateModel.cc b/preprocessor/SteadyStateModel.cc index 7630823ff9387a5087a90c03f36e05dd5390437c..5fc9dc1de01da099628361f47fe6b6a58fa68adf 100644 --- a/preprocessor/SteadyStateModel.cc +++ b/preprocessor/SteadyStateModel.cc @@ -72,7 +72,7 @@ SteadyStateModel::checkPass(bool ramsey_model, WarningConsolidation &warnings) c if (find(so_far_defined.begin(), so_far_defined.end(), symb_ids[j]) != so_far_defined.end()) warnings << "WARNING: in the 'steady_state_model' block, variable '" << symbol_table.getName(symb_ids[j]) << "' is declared twice" << endl; - + // Check that expression has no undefined symbol if (!ramsey_model) { @@ -187,15 +187,15 @@ SteadyStateModel::writeSteadyStateFileC(const string &basename, bool ramsey_mode output << "#include <math.h>" << endl; output << "void steadystate(" - << "const double *exo_, const double *params, double *ys_, int *info)" << endl + << "const double *exo_, const double *params, double *ys_, int *info)" << endl << "// Steady state file generated by Dynare preprocessor" << endl - << "{" << endl + << "{" << endl << " *info = 0;" << endl; if (def_table.size() == 0) { output << " return;" << endl - << "}" << endl; + << "}" << endl; return; } @@ -204,11 +204,11 @@ SteadyStateModel::writeSteadyStateFileC(const string &basename, bool ramsey_mode const vector<int> &symb_ids = def_table[i].first; output << " "; if (symb_ids.size() > 1) - std::cout << "Error: in C, multiple returns are not permitted in steady_state_model" << std::endl; + std::cout << "Error: in C, multiple returns are not permitted in steady_state_model" << std::endl; variable_node_map_t::const_iterator it = variable_node_map.find(make_pair(symb_ids[0], 0)); assert(it != variable_node_map.end()); if (it->second->get_type() == eModFileLocalVariable) - output << "double "; + output << "double "; dynamic_cast<ExprNode *>(it->second)->writeOutput(output, oCSteadyStateFile); output << "="; def_table[i].second->writeOutput(output, oCSteadyStateFile); diff --git a/preprocessor/SymbolList.hh b/preprocessor/SymbolList.hh index cbb51cabac2733ecb22f6e29bfe18a89ce6bbddd..950ae0a6093b31eac713fa8d15def7ba82598741 100644 --- a/preprocessor/SymbolList.hh +++ b/preprocessor/SymbolList.hh @@ -42,9 +42,17 @@ public: //! Clears all content void clear(); //! Get a copy of the string vector - vector<string> get_symbols() const { return symbols; }; + vector<string> + get_symbols() const + { + return symbols; + }; //! Is Empty - int empty() const { return symbols.empty(); }; + int + empty() const + { + return symbols.empty(); + }; }; #endif diff --git a/preprocessor/SymbolTable.cc b/preprocessor/SymbolTable.cc index 17b63e953136a1fd482a0ebaf361d724abedc2cb..7af7ffed4d3d01a146ad48e93aa11834dc4d6bbf 100644 --- a/preprocessor/SymbolTable.cc +++ b/preprocessor/SymbolTable.cc @@ -42,7 +42,7 @@ SymbolTable::SymbolTable() : frozen(false), size(0) } int -SymbolTable::addSymbol(const string &name, SymbolType type, const string &tex_name, const vector<pair<string * , string *> *> *partition_value) throw (AlreadyDeclaredException, FrozenException) +SymbolTable::addSymbol(const string &name, SymbolType type, const string &tex_name, const vector<pair<string *, string *> *> *partition_value) throw (AlreadyDeclaredException, FrozenException) { if (frozen) throw FrozenException(); @@ -88,7 +88,7 @@ SymbolTable::addSymbol(const string &name, SymbolType type, const string &tex_na { map<string, string> pmv; for (vector<pair<string *, string *> *>::const_iterator it = partition_value->begin(); - it != partition_value->end(); it++) + it != partition_value->end(); it++) pmv[*((*it)->first)] = *((*it)->second); partition_value_map[id] = pmv; } @@ -216,7 +216,6 @@ SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException) << "M_.exo_names_tex = char(M_.exo_names_tex, '" << getTeXName(exo_ids[id]) << "');" << endl << "M_.exo_names_long = char(M_.exo_names_long, '" << getLongName(exo_ids[id]) << "');" << endl; - map<string, map<int, string> > partitions = getPartitionsForType(eExogenous); for (map<string, map<int, string> >::const_iterator it = partitions.begin(); it != partitions.end(); it++) @@ -292,7 +291,7 @@ SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException) output << it1->second; output << "' "; } - output << "};" << endl; + output << "};" << endl; } } @@ -408,7 +407,7 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException) { output << "char *exo_names[" << exo_nbr() << "];" << endl; for (int id = 0; id < exo_nbr(); id++) - output << "exo_names[" << id << "] = \"" << getName(exo_ids[id]) << "\";" << endl; + output << "exo_names[" << id << "] = \"" << getName(exo_ids[id]) << "\";" << endl; } output << endl @@ -417,7 +416,7 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException) { output << "char *exo_det_names[" << exo_det_nbr() << "];" << endl; for (int id = 0; id < exo_det_nbr(); id++) - output << "exo_det_names[" << id << "] = \"" << getName(exo_det_ids[id]) << "\";" << endl; + output << "exo_det_names[" << id << "] = \"" << getName(exo_det_ids[id]) << "\";" << endl; } output << endl @@ -426,7 +425,7 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException) { output << "char *endo_names[" << endo_nbr() << "];" << endl; for (int id = 0; id < endo_nbr(); id++) - output << "endo_names[" << id << "] = \"" << getName(endo_ids[id]) << "\";" << endl; + output << "endo_names[" << id << "] = \"" << getName(endo_ids[id]) << "\";" << endl; } output << endl @@ -435,7 +434,7 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException) { output << "char *param_names[" << param_nbr() << "];" << endl; for (int id = 0; id < param_nbr(); id++) - output << "param_names[" << id << "] = \"" << getName(param_ids[id]) << "\";" << endl; + output << "param_names[" << id << "] = \"" << getName(param_ids[id]) << "\";" << endl; } // Write the auxiliary variable table @@ -444,37 +443,37 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException) { output << "struct aux_vars_t *av[" << aux_vars.size() << "];" << endl; for (int i = 0; i < (int) aux_vars.size(); i++) - { - output << "av[" << i << "].endo_index = " << getTypeSpecificID(aux_vars[i].get_symb_id()) << ";" << endl - << "av[" << i << "].type = " << aux_vars[i].get_type() << ";" << endl; - switch (aux_vars[i].get_type()) - { - case avEndoLead: - case avExoLead: - case avExpectation: - case avMultiplier: - case avDiffForward: - break; - case avEndoLag: - case avExoLag: - output << "av[" << i << "].orig_index = " << getTypeSpecificID(aux_vars[i].get_orig_symb_id()) << ";" << endl - << "av[" << i << "].orig_lead_lag = " << aux_vars[i].get_orig_lead_lag() << ";" << endl; - break; - } - } + { + output << "av[" << i << "].endo_index = " << getTypeSpecificID(aux_vars[i].get_symb_id()) << ";" << endl + << "av[" << i << "].type = " << aux_vars[i].get_type() << ";" << endl; + switch (aux_vars[i].get_type()) + { + case avEndoLead: + case avExoLead: + case avExpectation: + case avMultiplier: + case avDiffForward: + break; + case avEndoLag: + case avExoLag: + output << "av[" << i << "].orig_index = " << getTypeSpecificID(aux_vars[i].get_orig_symb_id()) << ";" << endl + << "av[" << i << "].orig_lead_lag = " << aux_vars[i].get_orig_lead_lag() << ";" << endl; + break; + } + } } output << "int predeterminedNbr = " << predeterminedNbr() << ";" << endl; if (predeterminedNbr() > 0) { - output << "int predetermined_variables[" << predeterminedNbr() << "] = {"; + output << "int predetermined_variables[" << predeterminedNbr() << "] = {"; for (set<int>::const_iterator it = predetermined_variables.begin(); - it != predetermined_variables.end(); it++) - { - if ( it != predetermined_variables.begin() ) - output << ","; - output << getTypeSpecificID(*it); - } + it != predetermined_variables.end(); it++) + { + if (it != predetermined_variables.begin()) + output << ","; + output << getTypeSpecificID(*it); + } output << "};" << endl; } @@ -483,13 +482,13 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException) { output << "int varobs[" << observedVariablesNbr() << "] = {"; for (vector<int>::const_iterator it = varobs.begin(); - it != varobs.end(); it++) - { - if ( it != varobs.begin() ) - output << ","; - output << getTypeSpecificID(*it); - } - output << "};" << endl; + it != varobs.end(); it++) + { + if (it != varobs.begin()) + output << ","; + output << getTypeSpecificID(*it); + } + output << "};" << endl; } } @@ -928,25 +927,25 @@ SymbolTable::writeJuliaOutput(ostream &output) const throw (NotYetFrozenExceptio output << "]" << endl; } - if (predeterminedNbr() > 0) - { - output << "# Predetermined Variables" << endl - << "model_.pred_vars = [ " << endl; - for (set<int>::const_iterator it = predetermined_variables.begin(); - it != predetermined_variables.end(); it++) - output << " DynareModel.PredVars(" - << getTypeSpecificID(*it)+1 << ")" << endl; - output << " ]" << endl; - } + if (predeterminedNbr() > 0) + { + output << "# Predetermined Variables" << endl + << "model_.pred_vars = [ " << endl; + for (set<int>::const_iterator it = predetermined_variables.begin(); + it != predetermined_variables.end(); it++) + output << " DynareModel.PredVars(" + << getTypeSpecificID(*it)+1 << ")" << endl; + output << " ]" << endl; + } - if (observedVariablesNbr() > 0) - { - output << "# Observed Variables" << endl - << "options_.obs_vars = [" << endl; - for (vector<int>::const_iterator it = varobs.begin(); - it != varobs.end(); it++) - output << " DynareModel.ObsVars(" - << getTypeSpecificID(*it)+1 << ")" << endl; - output << " ]" << endl; - } + if (observedVariablesNbr() > 0) + { + output << "# Observed Variables" << endl + << "options_.obs_vars = [" << endl; + for (vector<int>::const_iterator it = varobs.begin(); + it != varobs.end(); it++) + output << " DynareModel.ObsVars(" + << getTypeSpecificID(*it)+1 << ")" << endl; + output << " ]" << endl; + } } diff --git a/preprocessor/SymbolTable.hh b/preprocessor/SymbolTable.hh index c99dd462ffac9be892a67e9209e2624644e6fb05..ceb5d535951e670d6ef4d68c274f6f8d389bf854 100644 --- a/preprocessor/SymbolTable.hh +++ b/preprocessor/SymbolTable.hh @@ -58,13 +58,41 @@ private: expr_t expr_node; //! Auxiliary variable definition public: AuxVarInfo(int symb_id_arg, aux_var_t type_arg, int orig_symb_id, int orig_lead_lag, int equation_number_for_multiplier_arg, int information_set_arg, expr_t expr_node_arg); - int get_symb_id() const { return symb_id; }; - aux_var_t get_type() const { return type; }; - int get_orig_symb_id() const { return orig_symb_id; }; - int get_orig_lead_lag() const { return orig_lead_lag; }; - int get_equation_number_for_multiplier() const { return equation_number_for_multiplier; }; - int get_information_set() const { return information_set; }; - expr_t get_expr_node() const { return expr_node; } ; + int + get_symb_id() const + { + return symb_id; + }; + aux_var_t + get_type() const + { + return type; + }; + int + get_orig_symb_id() const + { + return orig_symb_id; + }; + int + get_orig_lead_lag() const + { + return orig_lead_lag; + }; + int + get_equation_number_for_multiplier() const + { + return equation_number_for_multiplier; + }; + int + get_information_set() const + { + return information_set; + }; + expr_t + get_expr_node() const + { + return expr_node; + }; }; //! Stores the symbol table @@ -249,7 +277,11 @@ public: */ int searchAuxiliaryVars(int orig_symb_id, int orig_lead_lag) const throw (SearchFailedException); //! Returns the number of auxiliary variables - int AuxVarsSize() const { return aux_vars.size(); }; + int + AuxVarsSize() const + { + return aux_vars.size(); + }; //! Retruns expr_node for an auxiliary variable expr_t getAuxiliaryVarsExprNode(int symb_id) const throw (SearchFailedException); //! Tests if symbol already exists diff --git a/preprocessor/WarningConsolidation.cc b/preprocessor/WarningConsolidation.cc index 653d473053b469ae74a08a057512db2a65a8c9fe..f026dea8f3bf7375b93b2a0878a0cc6558c665b3 100644 --- a/preprocessor/WarningConsolidation.cc +++ b/preprocessor/WarningConsolidation.cc @@ -20,8 +20,9 @@ #include "WarningConsolidation.hh" #include <ostream> -WarningConsolidation& -operator<< (WarningConsolidation& wcc, const string &warning) +WarningConsolidation +& +operator<<(WarningConsolidation &wcc, const string &warning) { if (wcc.no_warn) return wcc; @@ -31,8 +32,8 @@ operator<< (WarningConsolidation& wcc, const string &warning) return wcc; }; -WarningConsolidation& -operator<< (WarningConsolidation& wcc, const Dynare::location& loc) +WarningConsolidation & +operator<<(WarningConsolidation &wcc, const Dynare::location &loc) { if (wcc.no_warn) return wcc; @@ -54,8 +55,8 @@ operator<< (WarningConsolidation& wcc, const Dynare::location& loc) return wcc; }; -WarningConsolidation& -operator<< (WarningConsolidation& wcc, ostream& (*pf) (ostream&)) +WarningConsolidation & +operator<<(WarningConsolidation &wcc, ostream & (*pf)(ostream &)) { if (wcc.no_warn) return wcc; diff --git a/preprocessor/WarningConsolidation.hh b/preprocessor/WarningConsolidation.hh index 135a54a39d6b6fdcb518a339cb039a19ceb8b0be..582af0f43fea7b9c8c890d7bdac1aa955cd39d66 100644 --- a/preprocessor/WarningConsolidation.hh +++ b/preprocessor/WarningConsolidation.hh @@ -34,16 +34,28 @@ private: bool no_warn; public: - WarningConsolidation(bool no_warn_arg) : no_warn(no_warn_arg) { }; - ~WarningConsolidation() { }; + WarningConsolidation(bool no_warn_arg) : no_warn(no_warn_arg) + { + }; + ~WarningConsolidation() + { + }; //! Add A Warning to the StringStream - friend WarningConsolidation& operator<< (WarningConsolidation& wcc, const string &warning); - friend WarningConsolidation& operator<< (WarningConsolidation& wcc, const Dynare::location &loc); - friend WarningConsolidation& operator<< (WarningConsolidation& wcc, ostream& (*pf) (ostream&)); + friend WarningConsolidation &operator<<(WarningConsolidation &wcc, const string &warning); + friend WarningConsolidation &operator<<(WarningConsolidation &wcc, const Dynare::location &loc); + friend WarningConsolidation &operator<<(WarningConsolidation &wcc, ostream & (*pf)(ostream &)); - inline void addWarning(const string &w) { warnings << w; }; - inline void addWarning(ostream& (*pf) (ostream&)) { warnings << pf; }; + inline void + addWarning(const string &w) + { + warnings << w; + }; + inline void + addWarning(ostream & (*pf)(ostream &)) + { + warnings << pf; + }; //! Write Warnings to m file void writeOutput(ostream &output) const; diff --git a/preprocessor/macro/MacroDriver.cc b/preprocessor/macro/MacroDriver.cc index 1d13c5cee984fde412b12a3f6c5198044c8cad0c..c5193cc6bb2d18f5d9421d5e9c304f1c8572accb 100644 --- a/preprocessor/macro/MacroDriver.cc +++ b/preprocessor/macro/MacroDriver.cc @@ -55,14 +55,14 @@ MacroDriver::parse(const string &f, ostream &out, bool debug, bool no_line_macro an @#endif or an @#endfor - but no newline - no longer trigger an error. */ stringstream file_with_endl; - for (map<string,string>::iterator it=defines.begin(); - it!=defines.end(); it++) + for (map<string, string>::iterator it = defines.begin(); + it != defines.end(); it++) try { boost::lexical_cast<int>(it->second); file_with_endl << "@#define " << it->first << " = " << it->second << endl; } - catch(boost::bad_lexical_cast &) + catch (boost::bad_lexical_cast &) { file_with_endl << "@#define " << it->first << " = \"" << it->second << "\"" << endl; } diff --git a/preprocessor/macro/MacroDriver.hh b/preprocessor/macro/MacroDriver.hh index 83828b2edc25f76ec95b341bb8e727bc08cd73ff..7b828b0286d8383cfbda5d7cc5ef700a21656d80 100644 --- a/preprocessor/macro/MacroDriver.hh +++ b/preprocessor/macro/MacroDriver.hh @@ -177,12 +177,13 @@ public: //! Constructor MacroDriver(); //! Destructor - virtual ~MacroDriver(); + virtual + ~MacroDriver(); //! Starts parsing a file, returns output in out /*! \param no_line_macro should we omit the @#line statements ? */ void parse(const string &f, ostream &out, bool debug, bool no_line_macro, - map<string,string> defines, vector<string> path); + map<string, string> defines, vector<string> path); //! Name of main file being parsed string file; diff --git a/preprocessor/macro/MacroValue.hh b/preprocessor/macro/MacroValue.hh index c9da9c3ddf2697e7b2be026968692e464b6b2429..64f0cdef73a6310f50642606ebdc6376f78f33e3 100644 --- a/preprocessor/macro/MacroValue.hh +++ b/preprocessor/macro/MacroValue.hh @@ -49,7 +49,8 @@ public: { }; MacroValue(MacroDriver &driver_arg); - virtual ~MacroValue(); + virtual + ~MacroValue(); //! Applies + operator virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError) = 0; //! Applies unary + operator @@ -118,7 +119,8 @@ private: const int value; public: IntMV(MacroDriver &driver, int value_arg); - virtual ~IntMV(); + virtual + ~IntMV(); //! Computes arithmetic addition virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError); //! Unary plus @@ -158,7 +160,11 @@ public: If mv2 < mv1, returns an empty range (for consistency with MATLAB). */ static const MacroValue *new_range(MacroDriver &driver, const MacroValue *mv1, const MacroValue *mv2) throw (TypeError); - inline int get_int_value() const { return value; }; + inline int + get_int_value() const + { + return value; + }; }; //! Represents a string value in macro language @@ -170,7 +176,8 @@ private: const string value; public: StringMV(MacroDriver &driver, const string &value_arg); - virtual ~StringMV(); + virtual + ~StringMV(); //! Computes string concatenation virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError); virtual const MacroValue *operator==(const MacroValue &mv) const throw (TypeError); @@ -202,7 +209,8 @@ private: const vector<T> values; public: ArrayMV(MacroDriver &driver, const vector<T> &values_arg); - virtual ~ArrayMV(); + virtual + ~ArrayMV(); //! Computes array concatenation /*! Both array must be of same type */ virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError);