Fixed code indentation.

issue#70
Stéphane Adjemian (Charybdis) 2017-06-14 07:01:31 +02:00
parent 3eddd5ce88
commit 51feda7d02
35 changed files with 1325 additions and 1255 deletions

View File

@ -228,15 +228,15 @@ enum TrinaryOpcode
}; };
enum external_function_type enum external_function_type
{ {
ExternalFunctionWithoutDerivative, ExternalFunctionWithoutDerivative,
ExternalFunctionWithFirstDerivative, ExternalFunctionWithFirstDerivative,
ExternalFunctionWithFirstandSecondDerivative, ExternalFunctionWithFirstandSecondDerivative,
ExternalFunctionNumericalFirstDerivative, ExternalFunctionNumericalFirstDerivative,
ExternalFunctionFirstDerivative, ExternalFunctionFirstDerivative,
ExternalFunctionNumericalSecondDerivative, ExternalFunctionNumericalSecondDerivative,
ExternalFunctionSecondDerivative ExternalFunctionSecondDerivative
}; };
enum PriorDistributions enum PriorDistributions
{ {
@ -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; 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; nb_col_jacob = nb_col_jacob_arg;
det_exo_size = 0; exo_size = 0; other_endo_size = 0; 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 inline unsigned int
get_size() get_size()
@ -2025,4 +2025,3 @@ public:
#endif #endif
#pragma pack(pop) #pragma pack(pop)
#endif #endif

View File

@ -222,11 +222,11 @@ PriorPosteriorFunctionStatement::checkPass(ModFileStructure &mod_file_struct, Wa
{ {
OptionsList::string_options_t::const_iterator it2 = options_list.string_options.find("function"); OptionsList::string_options_t::const_iterator it2 = options_list.string_options.find("function");
if (it2 == options_list.string_options.end() || it2->second.empty()) if (it2 == options_list.string_options.end() || it2->second.empty())
{ {
cerr << "ERROR: both the prior_function and posterior_function commands require the 'function' argument" cerr << "ERROR: both the prior_function and posterior_function commands require the 'function' argument"
<< endl; << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
void void
@ -235,7 +235,7 @@ PriorPosteriorFunctionStatement::writeOutput(ostream &output, const string &base
options_list.writeOutput(output); options_list.writeOutput(output);
string type = "posterior"; string type = "posterior";
if (prior_func) if (prior_func)
type = "prior"; type = "prior";
output << "oo_ = execute_prior_posterior_function(" output << "oo_ = execute_prior_posterior_function("
<< "'" << options_list.string_options.find("function")->second << "', " << "'" << options_list.string_options.find("function")->second << "', "
@ -248,7 +248,7 @@ PriorPosteriorFunctionStatement::writeJsonOutput(ostream &output) const
{ {
string type = "posterior"; string type = "posterior";
if (prior_func) if (prior_func)
type = "prior"; type = "prior";
output << "{\"statementName\": \"prior_posterior_function\", \"type\": \"" << type << "\""; output << "{\"statementName\": \"prior_posterior_function\", \"type\": \"" << type << "\"";
if (options_list.getNumberOfOptions()) if (options_list.getNumberOfOptions())
{ {
@ -289,14 +289,14 @@ StochSimulStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
it = options_list.num_options.find("hp_filter"); 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 it1 = options_list.num_options.find("bandpass.indicator");
OptionsList::num_options_t::const_iterator it2 = options_list.num_options.find("one_sided_hp_filter"); 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()) || 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()) || || (it != options_list.num_options.end() && it2 != options_list.num_options.end())
(it1 != 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" cerr << "ERROR: stoch_simul: can only use one of hp, one-sided hp, and bandpass filters"
<< endl; << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
void void
@ -364,7 +364,7 @@ ForecastStatement::writeJsonOutput(ostream &output) const
} }
RamseyModelStatement::RamseyModelStatement(const SymbolList &symbol_list_arg, RamseyModelStatement::RamseyModelStatement(const SymbolList &symbol_list_arg,
const OptionsList &options_list_arg) : const OptionsList &options_list_arg) :
symbol_list(symbol_list_arg), symbol_list(symbol_list_arg),
options_list(options_list_arg) options_list(options_list_arg)
{ {
@ -441,7 +441,7 @@ RamseyConstraintsStatement::RamseyConstraintsStatement(const SymbolTable &symbol
void void
RamseyConstraintsStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) 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; cerr << "ramsey_constraints: can only be used with ramsey_model or ramsey_policy" << endl;
} }
@ -452,26 +452,26 @@ RamseyConstraintsStatement::writeOutput(ostream &output, const string &basename,
for (RamseyConstraintsStatement::constraints_t::const_iterator it = constraints.begin(); it != constraints.end(); ++it) for (RamseyConstraintsStatement::constraints_t::const_iterator it = constraints.begin(); it != constraints.end(); ++it)
{ {
if (it != constraints.begin()) if (it != constraints.begin())
output << ", "; output << ", ";
output << "{" << it->endo + 1 << ", '"; output << "{" << it->endo + 1 << ", '";
switch(it->code) switch (it->code)
{ {
case oLess: case oLess:
output << '<'; output << '<';
break; break;
case oGreater: case oGreater:
output << '>'; output << '>';
break; break;
case oLessEqual: case oLessEqual:
output << "<="; output << "<=";
break; break;
case oGreaterEqual: case oGreaterEqual:
output << ">="; output << ">=";
break; break;
default: default:
cerr << "Ramsey constraints: this shouldn't happen." << endl; cerr << "Ramsey constraints: this shouldn't happen." << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
output << "', '"; output << "', '";
it->expression->writeOutput(output); it->expression->writeOutput(output);
output << "'}" << endl; output << "'}" << endl;
@ -488,26 +488,26 @@ RamseyConstraintsStatement::writeJsonOutput(ostream &output) const
for (RamseyConstraintsStatement::constraints_t::const_iterator it = constraints.begin(); it != constraints.end(); ++it) for (RamseyConstraintsStatement::constraints_t::const_iterator it = constraints.begin(); it != constraints.end(); ++it)
{ {
if (it != constraints.begin()) if (it != constraints.begin())
output << ", "; output << ", ";
output << "{\"constraint\": \"" << symbol_table.getName(it->endo) << " "; output << "{\"constraint\": \"" << symbol_table.getName(it->endo) << " ";
switch(it->code) switch (it->code)
{ {
case oLess: case oLess:
output << '<'; output << '<';
break; break;
case oGreater: case oGreater:
output << '>'; output << '>';
break; break;
case oLessEqual: case oLessEqual:
output << "<="; output << "<=";
break; break;
case oGreaterEqual: case oGreaterEqual:
output << ">="; output << ">=";
break; break;
default: default:
cerr << "Ramsey constraints: this shouldn't happen." << endl; cerr << "Ramsey constraints: this shouldn't happen." << endl;
exit(1); exit(1);
} }
output << " "; output << " ";
it->expression->writeJsonOutput(output, temporary_terms_t(), tef_terms); it->expression->writeJsonOutput(output, temporary_terms_t(), tef_terms);
output << "\"}" << endl; output << "\"}" << endl;
@ -682,7 +682,7 @@ RamseyPolicyStatement::writeJsonOutput(ostream &output) const
} }
DiscretionaryPolicyStatement::DiscretionaryPolicyStatement(const SymbolList &symbol_list_arg, DiscretionaryPolicyStatement::DiscretionaryPolicyStatement(const SymbolList &symbol_list_arg,
const OptionsList &options_list_arg) : const OptionsList &options_list_arg) :
symbol_list(symbol_list_arg), symbol_list(symbol_list_arg),
options_list(options_list_arg) options_list(options_list_arg)
{ {
@ -797,8 +797,8 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
it = options_list.num_options.find("dsge_var"); it = options_list.num_options.find("dsge_var");
if (it != options_list.num_options.end()) if (it != options_list.num_options.end())
// Fill in mod_file_struct.dsge_var_calibrated // Fill in mod_file_struct.dsge_var_calibrated
mod_file_struct.dsge_var_calibrated = it->second; mod_file_struct.dsge_var_calibrated = it->second;
// Fill in mod_file_struct.dsge_var_estimated // Fill in mod_file_struct.dsge_var_estimated
OptionsList::string_options_t::const_iterator it_str = options_list.string_options.find("dsge_var"); OptionsList::string_options_t::const_iterator it_str = options_list.string_options.find("dsge_var");
@ -827,15 +827,15 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (options_list.string_options.find("datafile") == options_list.string_options.end() && if (options_list.string_options.find("datafile") == options_list.string_options.end()
!mod_file_struct.estimation_data_statement_present) && !mod_file_struct.estimation_data_statement_present)
{ {
cerr << "ERROR: The estimation statement requires a data file to be supplied via the datafile option." << endl; cerr << "ERROR: The estimation statement requires a data file to be supplied via the datafile option." << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (options_list.string_options.find("mode_file") != options_list.string_options.end() && if (options_list.string_options.find("mode_file") != options_list.string_options.end()
mod_file_struct.estim_params_use_calib) && 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; 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); exit(EXIT_FAILURE);
@ -960,7 +960,7 @@ void
UnitRootVarsStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const UnitRootVarsStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const
{ {
output << "options_.diffuse_filter = 1;" << endl output << "options_.diffuse_filter = 1;" << endl
<< "options_.steadystate.nocheck = 1;" << endl; << "options_.steadystate.nocheck = 1;" << endl;
} }
void void
@ -1976,8 +1976,8 @@ MSSBVAREstimationStatement::checkPass(ModFileStructure &mod_file_struct, Warning
mod_file_struct.bvar_present = true; mod_file_struct.bvar_present = true;
if (options_list.num_options.find("ms.create_init") == options_list.num_options.end()) 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() || 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()) || 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, " cerr << "ERROR: If you do not pass no_create_init to ms_estimation, "
<< "you must pass the datafile and initial_year options." << endl; << "you must pass the datafile and initial_year options." << endl;
@ -2117,7 +2117,7 @@ MSSBVARComputeProbabilitiesStatement::writeJsonOutput(ostream &output) const
} }
MSSBVARIrfStatement::MSSBVARIrfStatement(const SymbolList &symbol_list_arg, MSSBVARIrfStatement::MSSBVARIrfStatement(const SymbolList &symbol_list_arg,
const OptionsList &options_list_arg) : const OptionsList &options_list_arg) :
symbol_list(symbol_list_arg), symbol_list(symbol_list_arg),
options_list(options_list_arg) options_list(options_list_arg)
{ {
@ -2144,14 +2144,14 @@ MSSBVARIrfStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
if (it != options_list.num_options.end()) if (it != options_list.num_options.end())
filtered_probabilities_present = true; filtered_probabilities_present = true;
if ((filtered_probabilities_present && regime_present) || if ((filtered_probabilities_present && regime_present)
(filtered_probabilities_present && regimes_present) || || (filtered_probabilities_present && regimes_present)
(regimes_present && regime_present)) || (regimes_present && regime_present))
{ {
cerr << "ERROR: You may only pass one of regime, regimes and " cerr << "ERROR: You may only pass one of regime, regimes and "
<< "filtered_probabilities to ms_irf" << endl; << "filtered_probabilities to ms_irf" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
void void
@ -2244,14 +2244,14 @@ MSSBVARVarianceDecompositionStatement::checkPass(ModFileStructure &mod_file_stru
if (it != options_list.num_options.end()) if (it != options_list.num_options.end())
filtered_probabilities_present = true; filtered_probabilities_present = true;
if ((filtered_probabilities_present && regime_present) || if ((filtered_probabilities_present && regime_present)
(filtered_probabilities_present && regimes_present) || || (filtered_probabilities_present && regimes_present)
(regimes_present && regime_present)) || (regimes_present && regime_present))
{ {
cerr << "ERROR: You may only pass one of regime, regimes and " cerr << "ERROR: You may only pass one of regime, regimes and "
<< "filtered_probabilities to ms_variance_decomposition" << endl; << "filtered_probabilities to ms_variance_decomposition" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
void void
@ -2551,19 +2551,19 @@ SvarIdentificationStatement::writeOutput(ostream &output, const string &basename
for (svar_identification_restrictions_t::const_iterator it = restrictions.begin(); it != restrictions.end(); it++) for (svar_identification_restrictions_t::const_iterator it = restrictions.begin(); it != restrictions.end(); it++)
{ {
assert(it->lag >= 0); assert(it->lag >= 0);
if (it->lag == 0) if (it->lag == 0)
output << "options_.ms.Qi{" << it->equation << "}(" << it->restriction_nbr << ", " << it->variable + 1 << ") = "; output << "options_.ms.Qi{" << it->equation << "}(" << it->restriction_nbr << ", " << it->variable + 1 << ") = ";
else else
{ {
int col = (it->lag-1)*n+it->variable+1; int col = (it->lag-1)*n+it->variable+1;
if (col > k) if (col > k)
{ {
cerr << "ERROR: lag =" << it->lag << ", num endog vars = " << n << "current endog var index = " << it->variable << ". Index " 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; << "out of bounds. If the above does not represent a logical error, please report this to the Dyanre Team." << endl;
exit(EXIT_FAILURE); 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); it->value->writeOutput(output);
output << ";" << endl; output << ";" << endl;
} }
@ -2614,21 +2614,21 @@ MarkovSwitchingStatement::MarkovSwitchingStatement(const OptionsList &options_li
if (it_num != options_list.num_options.end()) if (it_num != options_list.num_options.end())
{ {
using namespace boost; using namespace boost;
OptionsList::num_options_t::const_iterator it_num_regimes = OptionsList::num_options_t::const_iterator it_num_regimes
options_list.num_options.find("ms.number_of_regimes"); = options_list.num_options.find("ms.number_of_regimes");
assert(it_num_regimes != options_list.num_options.end()); assert(it_num_regimes != options_list.num_options.end());
int num_regimes = lexical_cast< int >(it_num_regimes->second); int num_regimes = lexical_cast< int >(it_num_regimes->second);
vector<string> tokenizedRestrictions; vector<string> tokenizedRestrictions;
split(tokenizedRestrictions, it_num->second, is_any_of("["), token_compress_on); split(tokenizedRestrictions, it_num->second, is_any_of("["), token_compress_on);
for (vector<string>::iterator it = tokenizedRestrictions.begin(); for (vector<string>::iterator it = tokenizedRestrictions.begin();
it != tokenizedRestrictions.end(); it++ ) it != tokenizedRestrictions.end(); it++)
if (it->size() > 0) if (it->size() > 0)
{ {
vector<string> restriction; vector<string> restriction;
split(restriction, *it, is_any_of("], ")); split(restriction, *it, is_any_of("], "));
for (vector<string>::iterator it1 = restriction.begin(); for (vector<string>::iterator it1 = restriction.begin();
it1 != restriction.end(); ) it1 != restriction.end();)
if (it1->empty()) if (it1->empty())
restriction.erase(it1); restriction.erase(it1);
else else
@ -2697,16 +2697,16 @@ MarkovSwitchingStatement::checkPass(ModFileStructure &mod_file_struct, WarningCo
if (it_num != options_list.num_options.end()) if (it_num != options_list.num_options.end())
{ {
using namespace boost; using namespace boost;
OptionsList::num_options_t::const_iterator it_num_regimes = OptionsList::num_options_t::const_iterator it_num_regimes
options_list.num_options.find("ms.number_of_regimes"); = options_list.num_options.find("ms.number_of_regimes");
assert(it_num_regimes != options_list.num_options.end()); assert(it_num_regimes != options_list.num_options.end());
int num_regimes = lexical_cast< int >(it_num_regimes->second); int num_regimes = lexical_cast< int >(it_num_regimes->second);
vector<double> col_trans_prob_sum (num_regimes, 0); vector<double> col_trans_prob_sum(num_regimes, 0);
vector<double> row_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_row(num_regimes, true);
vector<bool> all_restrictions_in_col (num_regimes, true); vector<bool> all_restrictions_in_col(num_regimes, true);
for (int row=0; row<num_regimes; row++) for (int row = 0; row < num_regimes; row++)
for (int col=0; col<num_regimes; col++) for (int col = 0; col < num_regimes; col++)
if (restriction_map.find(make_pair(row+1, col+1)) != restriction_map.end()) 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)]; row_trans_prob_sum[row] += restriction_map[make_pair(row+1, col+1)];
@ -2718,41 +2718,41 @@ MarkovSwitchingStatement::checkPass(ModFileStructure &mod_file_struct, WarningCo
all_restrictions_in_col[col] = false; 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 (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 " cerr << "ERROR: When transition probabilites are not specified for every regime, "
<< "regime, they must sum to 1" << endl; << "their sum must be < 1" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
}
else
if (row_trans_prob_sum[i] >= 1.0)
{
cerr << "ERROR: When transition probabilites are not specified for every regime, "
<< "their sum must be < 1" << endl;
exit(EXIT_FAILURE);
}
if (all_restrictions_in_col[i]) if (all_restrictions_in_col[i])
{ {
if (col_trans_prob_sum[i] != 1.0) if (col_trans_prob_sum[i] != 1.0)
{
cerr << "ERROR: When all transitions probabilities are specified for a certain "
<< "regime, they must sum to 1" << endl;
exit(EXIT_FAILURE);
}
}
else
if (col_trans_prob_sum[i] >= 1.0)
{ {
cerr << "ERROR: When all transitions probabilities are specified for a certain " cerr << "ERROR: When transition probabilites are not specified for every regime, "
<< "regime, they must sum to 1" << endl; << "their sum must be < 1" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
}
else
if (col_trans_prob_sum[i] >= 1.0)
{
cerr << "ERROR: When transition probabilites are not specified for every regime, "
<< "their sum must be < 1" << endl;
exit(EXIT_FAILURE);
}
} }
} }
@ -2789,7 +2789,7 @@ MarkovSwitchingStatement::writeOutput(ostream &output, const string &basename, b
} }
int restrictions_index = 0; 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(" output << "options_.ms.ms_chain(" << itChain->second << ").restrictions("
<< ++restrictions_index << ") = {[" << itR->first.first << ", " << ++restrictions_index << ") = {[" << itR->first.first << ", "
<< itR->first.second << ", " << itR->second << "]};" << endl; << itR->first.second << ", " << itR->second << "]};" << endl;
@ -2800,8 +2800,8 @@ MarkovSwitchingStatement::writeCOutput(ostream &output, const string &basename)
{ {
output << endl; output << endl;
OptionsList::num_options_t::const_iterator it = OptionsList::num_options_t::const_iterator it
options_list.num_options.find("ms.chain"); = options_list.num_options.find("ms.chain");
assert(it != options_list.num_options.end()); assert(it != options_list.num_options.end());
output << "chain = " << it->second << ";" << endl; output << "chain = " << it->second << ";" << endl;
@ -2823,17 +2823,17 @@ MarkovSwitchingStatement::writeCOutput(ostream &output, const string &basename)
vector<string> tokenizedDomain; vector<string> tokenizedDomain;
split(tokenizedDomain, it->second, is_any_of("[ ]"), token_compress_on); split(tokenizedDomain, it->second, is_any_of("[ ]"), token_compress_on);
for (vector<string>::iterator itvs = tokenizedDomain.begin(); for (vector<string>::iterator itvs = tokenizedDomain.begin();
itvs != tokenizedDomain.end(); itvs++ ) itvs != tokenizedDomain.end(); itvs++)
if (!itvs->empty()) if (!itvs->empty())
output << "duration.push_back(" << *itvs << ");" << endl; output << "duration.push_back(" << *itvs << ");" << endl;
OptionsList::symbol_list_options_t::const_iterator itsl = OptionsList::symbol_list_options_t::const_iterator itsl
options_list.symbol_list_options.find("ms.parameters"); = options_list.symbol_list_options.find("ms.parameters");
assert(itsl != options_list.symbol_list_options.end()); assert(itsl != options_list.symbol_list_options.end());
vector<string> parameters = itsl->second.get_symbols(); vector<string> parameters = itsl->second.get_symbols();
output << "parameters.clear();" << endl; output << "parameters.clear();" << endl;
for (vector<string>::iterator itp = parameters.begin(); for (vector<string>::iterator itp = parameters.begin();
itp != parameters.end(); itp++ ) itp != parameters.end(); itp++)
output << "parameters.push_back(param_names[\"" << *itp << "\"]);" << endl; output << "parameters.push_back(param_names[\"" << *itp << "\"]);" << endl;
output << "restriction_map.clear();" << endl; output << "restriction_map.clear();" << endl;
@ -2887,13 +2887,13 @@ SvarStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation
it2 = options_list.string_options.find("ms.constants"); it2 = options_list.string_options.find("ms.constants");
assert((it0 != options_list.string_options.end() assert((it0 != options_list.string_options.end()
&& it1 == 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() || (it0 == options_list.string_options.end()
&& it1 != 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() || (it0 == options_list.string_options.end()
&& it1 == options_list.string_options.end() && it1 == options_list.string_options.end()
&& it2 != options_list.string_options.end())); && it2 != options_list.string_options.end()));
} }
void void
@ -3006,15 +3006,15 @@ EstimationDataStatement::checkPass(ModFileStructure &mod_file_struct, WarningCon
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if ((options_list.string_options.find("file") == 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())) && (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; cerr << "ERROR: The file or series option must be passed to the data statement." << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if ((options_list.string_options.find("file") != 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())) && (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; cerr << "ERROR: The file and series options cannot be used simultaneously in the data statement." << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
@ -3235,8 +3235,8 @@ JointPriorStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (options_list.num_options.find("mean") == 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()) && 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; cerr << "ERROR: You must pass at least one of mean and mode to the prior statement." << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
@ -3259,13 +3259,13 @@ JointPriorStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
void void
JointPriorStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const 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', '" output << "eifind = get_new_or_existing_ei_index('joint_parameter_prior_index', '"
<< *it << "', '');" << endl << *it << "', '');" << endl
<< "estimation_info.joint_parameter_prior_index(eifind) = {'" << *it << "'};" << endl; << "estimation_info.joint_parameter_prior_index(eifind) = {'" << *it << "'};" << endl;
output << "key = {["; 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 << "', '') ..." output << "get_new_or_existing_ei_index('joint_parameter_prior_index', '" << *it << "', '') ..."
<< endl << " "; << endl << " ";
output << "]};" << endl; output << "]};" << endl;
@ -3306,13 +3306,13 @@ JointPriorStatement::writeOutputHelper(ostream &output, const string &field, con
{ {
OptionsList::num_options_t::const_iterator itn = options_list.num_options.find(field); OptionsList::num_options_t::const_iterator itn = options_list.num_options.find(field);
output << lhs_field << "." << field << " = {"; output << lhs_field << "." << field << " = {";
if (field=="variance") if (field == "variance")
output << "{"; output << "{";
if (itn != options_list.num_options.end()) if (itn != options_list.num_options.end())
output << itn->second; output << itn->second;
else else
output << "{}"; output << "{}";
if (field=="variance") if (field == "variance")
output << "}"; output << "}";
output << "};" << endl; output << "};" << endl;
} }
@ -3322,7 +3322,7 @@ JointPriorStatement::writeJsonOutput(ostream &output) const
{ {
output << "{\"statementName\": \"joint_prior\"" output << "{\"statementName\": \"joint_prior\""
<< ", \"key\": ["; << ", \"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++)
{ {
if (it != joint_parameters.begin()) if (it != joint_parameters.begin())
output << ", "; output << ", ";
@ -3337,31 +3337,31 @@ JointPriorStatement::writeJsonOutput(ostream &output) const
} }
output << ", \"shape\": "; output << ", \"shape\": ";
switch(prior_shape) switch (prior_shape)
{ {
case eBeta: case eBeta:
output << "\"beta\""; output << "\"beta\"";
break; break;
case eGamma: case eGamma:
output << "\"gamma\""; output << "\"gamma\"";
break; break;
case eNormal: case eNormal:
output << "\"normal\""; output << "\"normal\"";
break; break;
case eInvGamma: case eInvGamma:
output << "\"inv_gamma\""; output << "\"inv_gamma\"";
break; break;
case eUniform: case eUniform:
output << "\"uniform\""; output << "\"uniform\"";
break; break;
case eInvGamma2: case eInvGamma2:
output << "\"inv_gamma2\""; output << "\"inv_gamma2\"";
break; break;
case eDirichlet: case eDirichlet:
output << "\"dirichlet\""; output << "\"dirichlet\"";
break; break;
case eWeibull: case eWeibull:
output << "\"weibull\""; output << "\"weibull\"";
break; break;
case eNoShape: case eNoShape:
cerr << "Impossible case." << endl; cerr << "Impossible case." << endl;
@ -3396,16 +3396,16 @@ BasicPriorStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (options_list.num_options.find("mean") == 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()) && 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; cerr << "ERROR: You must pass at least one of mean and mode to the prior statement." << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
OptionsList::num_options_t::const_iterator it_stdev = options_list.num_options.find("stdev"); OptionsList::num_options_t::const_iterator it_stdev = options_list.num_options.find("stdev");
if ((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)) || (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; cerr << "ERROR: You must pass exactly one of stdev and variance to the prior statement." << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
@ -3533,7 +3533,7 @@ BasicPriorStatement::writeCDomain(ostream &output) const
vector<string> tokenizedDomain; vector<string> tokenizedDomain;
split(tokenizedDomain, it_num->second, is_any_of("[ ]"), token_compress_on); split(tokenizedDomain, it_num->second, is_any_of("[ ]"), token_compress_on);
for (vector<string>::iterator it = tokenizedDomain.begin(); for (vector<string>::iterator it = tokenizedDomain.begin();
it != tokenizedDomain.end(); it++ ) it != tokenizedDomain.end(); it++)
if (!it->empty()) if (!it->empty())
output << "domain.push_back(" << *it << ");" << endl; output << "domain.push_back(" << *it << ");" << endl;
} }
@ -3556,28 +3556,28 @@ BasicPriorStatement::writeCShape(ostream &output) const
switch (prior_shape) switch (prior_shape)
{ {
case eBeta: case eBeta:
output << "\"beta\";" << endl; output << "\"beta\";" << endl;
break; break;
case eGamma: case eGamma:
output << "\"gamma\";" << endl; output << "\"gamma\";" << endl;
break; break;
case eNormal: case eNormal:
output << "\"normal\";" << endl; output << "\"normal\";" << endl;
break; break;
case eInvGamma: case eInvGamma:
output << "\"inv_gamma\";" << endl; output << "\"inv_gamma\";" << endl;
break; break;
case eUniform: case eUniform:
output << "\"uniform\";" << endl; output << "\"uniform\";" << endl;
break; break;
case eInvGamma2: case eInvGamma2:
output << "\"inv_gamma2\";" << endl; output << "\"inv_gamma2\";" << endl;
break; break;
case eDirichlet: case eDirichlet:
output << "\"dirichlet\";" << endl; output << "\"dirichlet\";" << endl;
break; break;
case eWeibull: case eWeibull:
output << "\"weibull\";" << endl; output << "\"weibull\";" << endl;
break; break;
case eNoShape: case eNoShape:
assert(prior_shape != eNoShape); assert(prior_shape != eNoShape);
@ -3591,28 +3591,28 @@ BasicPriorStatement::writeJsonShape(ostream &output) const
switch (prior_shape) switch (prior_shape)
{ {
case eBeta: case eBeta:
output << "\"beta\""; output << "\"beta\"";
break; break;
case eGamma: case eGamma:
output << "\"gamma\""; output << "\"gamma\"";
break; break;
case eNormal: case eNormal:
output << "\"normal\""; output << "\"normal\"";
break; break;
case eInvGamma: case eInvGamma:
output << "\"inv_gamma\""; output << "\"inv_gamma\"";
break; break;
case eUniform: case eUniform:
output << "\"uniform\""; output << "\"uniform\"";
break; break;
case eInvGamma2: case eInvGamma2:
output << "\"inv_gamma2\""; output << "\"inv_gamma2\"";
break; break;
case eDirichlet: case eDirichlet:
output << "\"dirichlet\""; output << "\"dirichlet\"";
break; break;
case eWeibull: case eWeibull:
output << "\"weibull\""; output << "\"weibull\"";
break; break;
case eNoShape: case eNoShape:
assert(prior_shape != eNoShape); assert(prior_shape != eNoShape);
@ -3667,7 +3667,7 @@ StdPriorStatement::StdPriorStatement(const string &name_arg,
const PriorDistributions &prior_shape_arg, const PriorDistributions &prior_shape_arg,
const expr_t &variance_arg, const expr_t &variance_arg,
const OptionsList &options_list_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), BasicPriorStatement(name_arg, subsample_name_arg, prior_shape_arg, variance_arg, options_list_arg),
symbol_table(symbol_table_arg) symbol_table(symbol_table_arg)
{ {
@ -3724,7 +3724,7 @@ CorrPriorStatement::CorrPriorStatement(const string &name_arg1, const string &na
const PriorDistributions &prior_shape_arg, const PriorDistributions &prior_shape_arg,
const expr_t &variance_arg, const expr_t &variance_arg,
const OptionsList &options_list_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), BasicPriorStatement(name_arg1, subsample_name_arg, prior_shape_arg, variance_arg, options_list_arg),
name1(name_arg2), name1(name_arg2),
symbol_table(symbol_table_arg) symbol_table(symbol_table_arg)
@ -3824,8 +3824,8 @@ PriorEqualStatement::PriorEqualStatement(const string &to_declaration_type_arg,
void void
PriorEqualStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) PriorEqualStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
{ {
if ((to_declaration_type != "par" && to_declaration_type != "std" && to_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")) || (from_declaration_type != "par" && from_declaration_type != "std" && from_declaration_type != "corr"))
{ {
cerr << "Internal Dynare Error" << endl; cerr << "Internal Dynare Error" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
@ -3856,7 +3856,6 @@ PriorEqualStatement::writeOutput(ostream &output, const string &basename, bool m
else else
get_base_name(symbol_table.getType(from_name1), rhs_field); get_base_name(symbol_table.getType(from_name1), rhs_field);
if (to_declaration_type == "corr") if (to_declaration_type == "corr")
lhs_field += "_corr"; lhs_field += "_corr";
@ -4045,7 +4044,7 @@ OptionsStatement::writeCOutput(ostream &output, const string &basename)
StdOptionsStatement::StdOptionsStatement(const string &name_arg, StdOptionsStatement::StdOptionsStatement(const string &name_arg,
const string &subsample_name_arg, const string &subsample_name_arg,
const OptionsList &options_list_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), BasicOptionsStatement(name_arg, subsample_name_arg, options_list_arg),
symbol_table(symbol_table_arg) symbol_table(symbol_table_arg)
{ {
@ -4095,7 +4094,7 @@ StdOptionsStatement::writeCOutput(ostream &output, const string &basename)
CorrOptionsStatement::CorrOptionsStatement(const string &name_arg1, const string &name_arg2, CorrOptionsStatement::CorrOptionsStatement(const string &name_arg1, const string &name_arg2,
const string &subsample_name_arg, const string &subsample_name_arg,
const OptionsList &options_list_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), BasicOptionsStatement(name_arg1, subsample_name_arg, options_list_arg),
name1(name_arg2), name1(name_arg2),
symbol_table(symbol_table_arg) symbol_table(symbol_table_arg)
@ -4189,8 +4188,8 @@ OptionsEqualStatement::OptionsEqualStatement(const string &to_declaration_type_a
void void
OptionsEqualStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) OptionsEqualStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
{ {
if ((to_declaration_type != "par" && to_declaration_type != "std" && to_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")) || (from_declaration_type != "par" && from_declaration_type != "std" && from_declaration_type != "corr"))
{ {
cerr << "Internal Dynare Error" << endl; cerr << "Internal Dynare Error" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
@ -4236,7 +4235,6 @@ OptionsEqualStatement::writeOutput(ostream &output, const string &basename, bool
else else
get_base_name(symbol_table.getType(from_name1), rhs_field); get_base_name(symbol_table.getType(from_name1), rhs_field);
if (to_declaration_type == "corr") if (to_declaration_type == "corr")
lhs_field += "_corr"; lhs_field += "_corr";

View File

@ -137,7 +137,7 @@ private:
const OptionsList options_list; const OptionsList options_list;
public: public:
RamseyModelStatement(const SymbolList &symbol_list_arg, 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 checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings);
virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const;
virtual void writeJsonOutput(ostream &output) const; virtual void writeJsonOutput(ostream &output) const;
@ -146,7 +146,8 @@ public:
class RamseyConstraintsStatement : public Statement class RamseyConstraintsStatement : public Statement
{ {
public: public:
struct Constraint { struct Constraint
{
int endo; int endo;
BinaryOpcode code; BinaryOpcode code;
expr_t expression; expr_t expression;
@ -186,7 +187,7 @@ private:
const OptionsList options_list; const OptionsList options_list;
public: public:
DiscretionaryPolicyStatement(const SymbolList &symbol_list_arg, 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 checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings);
virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const;
virtual void writeJsonOutput(ostream &output) const; virtual void writeJsonOutput(ostream &output) const;
@ -455,7 +456,8 @@ public:
/*! \param model_tree_arg the model tree used to store the objective function. /*! \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 */ It is owned by the PlannerObjectiveStatement, and will be deleted by its destructor */
PlannerObjectiveStatement(StaticModel *model_tree_arg); PlannerObjectiveStatement(StaticModel *model_tree_arg);
virtual ~PlannerObjectiveStatement(); virtual
~PlannerObjectiveStatement();
/*! \todo check there are only endogenous variables at the current period in the objective /*! \todo check there are only endogenous variables at the current period in the objective
(no exogenous, no lead/lag) */ (no exogenous, no lead/lag) */
virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings);
@ -553,7 +555,7 @@ private:
const OptionsList options_list; const OptionsList options_list;
public: public:
MSSBVARIrfStatement(const SymbolList &symbol_list_arg, 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 checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings);
virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const;
virtual void writeJsonOutput(ostream &output) const; virtual void writeJsonOutput(ostream &output) const;
@ -705,7 +707,7 @@ public:
SvarIdentificationStatement(const svar_identification_restrictions_t &restrictions_arg, SvarIdentificationStatement(const svar_identification_restrictions_t &restrictions_arg,
const bool &upper_cholesky_present_arg, const bool &upper_cholesky_present_arg,
const bool &lower_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); const SymbolTable &symbol_table_arg);
virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings); virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings);
virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const; virtual void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const;
@ -819,11 +821,11 @@ public:
virtual void writeJsonOutput(ostream &output) const; virtual void writeJsonOutput(ostream &output) const;
}; };
class BasicPriorStatement : public Statement class BasicPriorStatement : public Statement
{ {
public: public:
virtual ~BasicPriorStatement(); virtual
~BasicPriorStatement();
protected: protected:
const string name; const string name;
const string subsample_name; const string subsample_name;
@ -932,7 +934,8 @@ public:
class BasicOptionsStatement : public Statement class BasicOptionsStatement : public Statement
{ {
public: public:
virtual ~BasicOptionsStatement(); virtual
~BasicOptionsStatement();
protected: protected:
const string name; const string name;
const string subsample_name; const string subsample_name;

View File

@ -102,7 +102,7 @@ ConfigFile::getConfigFileInfo(const string &config_file)
if (config_file.empty()) if (config_file.empty())
{ {
string defaultConfigFile (""); string defaultConfigFile("");
// Test OS and try to open default file // Test OS and try to open default file
#if defined(_WIN32) || defined(__CYGWIN32__) #if defined(_WIN32) || defined(__CYGWIN32__)
if (getenv("APPDATA") == NULL) if (getenv("APPDATA") == NULL)
@ -122,42 +122,41 @@ ConfigFile::getConfigFileInfo(const string &config_file)
defaultConfigFile += "\\dynare.ini"; defaultConfigFile += "\\dynare.ini";
} }
#else #else
if (getenv("HOME") == NULL) 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 (parallel || parallel_test) if (parallel || parallel_test)
{ cerr << "ERROR: ";
cerr << "ERROR: Could not open the default config file (" << defaultConfigFile << ")" << endl;
exit(EXIT_FAILURE);
}
else else
return; cerr << "WARNING: ";
} cerr << "HOME environment variable not found." << endl;
else if (parallel || parallel_test)
{ exit(EXIT_FAILURE);
configFile = new ifstream(config_file.c_str(), fstream::in); }
if (!configFile->is_open()) 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); 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, string name, computerName, port, userName, password, remoteDrive,
remoteDirectory, dynarePath, matlabOctavePath, operatingSystem, remoteDirectory, dynarePath, matlabOctavePath, operatingSystem,
@ -271,7 +270,7 @@ ConfigFile::getConfigFileInfo(const string &config_file)
vector<string> tokenizedPath; vector<string> tokenizedPath;
split(tokenizedPath, tokenizedLine.back(), is_any_of(":"), token_compress_on); split(tokenizedPath, tokenizedLine.back(), is_any_of(":"), token_compress_on);
for (vector<string>::iterator it = tokenizedPath.begin(); for (vector<string>::iterator it = tokenizedPath.begin();
it != tokenizedPath.end(); it++ ) it != tokenizedPath.end(); it++)
if (!it->empty()) if (!it->empty())
{ {
trim(*it); trim(*it);
@ -375,7 +374,7 @@ ConfigFile::getConfigFileInfo(const string &config_file)
for (tokenizer<char_separator<char> >::iterator it = tokens.begin(); for (tokenizer<char_separator<char> >::iterator it = tokens.begin();
it != tokens.end(); it++) it != tokens.end(); it++)
{ {
string token (*it); string token(*it);
if (token.compare("(") == 0) if (token.compare("(") == 0)
{ {
begin_weight = true; begin_weight = true;
@ -525,10 +524,10 @@ void
ConfigFile::checkPass(WarningConsolidation &warnings) const ConfigFile::checkPass(WarningConsolidation &warnings) const
{ {
bool global_init_file_declared = false; 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(); 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 (mapit->first.compare("global_init_file") == 0)
if (global_init_file_declared == true) if (global_init_file_declared == true)
{ {
@ -686,10 +685,10 @@ vector<string>
ConfigFile::getIncludePaths() const ConfigFile::getIncludePaths() const
{ {
vector<string> include_paths; 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(); 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++) for (vector<string>::const_iterator vecit = mapit->second.begin(); vecit != mapit->second.end(); vecit++)
include_paths.push_back(*vecit); include_paths.push_back(*vecit);
} }
@ -699,10 +698,10 @@ ConfigFile::getIncludePaths() const
void void
ConfigFile::writeHooks(ostream &output) const 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(); 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; output << "options_." << mapit->first << " = '" << mapit->second << "';" << endl;
} }
} }

View File

@ -37,18 +37,26 @@ public:
private: private:
map<string, string> hooks; map<string, string> hooks;
public: public:
inline map<string, string>get_hooks() { return hooks; }; inline map<string, string>
get_hooks()
{
return hooks;
};
}; };
class Path class Path
{ {
public: public:
Path(vector<string> &includepath_arg); Path(vector<string> &includepath_arg);
~Path(); ~Path();
private: private:
map<string, vector<string> > paths; map<string, vector<string> > paths;
public: public:
inline map<string, vector<string> >get_paths() { return paths; }; inline map<string, vector<string> >
get_paths()
{
return paths;
};
}; };
class SlaveNode class SlaveNode

View File

@ -104,7 +104,8 @@ private:
public: public:
DataTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg, ExternalFunctionsTable &external_functions_table_arg); DataTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg, ExternalFunctionsTable &external_functions_table_arg);
virtual ~DataTree(); virtual
~DataTree();
//! Some predefined constants //! Some predefined constants
expr_t Zero, One, Two, MinusOne, NaN, Infinity, MinusInfinity, Pi; expr_t Zero, One, Two, MinusOne, NaN, Infinity, MinusInfinity, Pi;

View File

@ -1140,7 +1140,7 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin
for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++) for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++)
{ {
count_col_det_exo++; 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); exo_det.push_back(*it1);
} }
@ -1150,7 +1150,7 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin
for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++) for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++)
{ {
count_col_exo++; 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); exo.push_back(*it1);
} }
@ -1160,8 +1160,8 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin
for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++) for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++)
{ {
count_col_other_endo++; count_col_other_endo++;
if (find (other_endo.begin(), other_endo.end(), *it1) == other_endo.end()) if (find(other_endo.begin(), other_endo.end(), *it1) == other_endo.end())
other_endo.push_back(*it1); other_endo.push_back(*it1);
} }
FBEGINBLOCK_ fbeginblock(block_mfs, FBEGINBLOCK_ fbeginblock(block_mfs,
@ -1202,10 +1202,10 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin
if (dynamic_cast<AbstractExternalFunctionNode *>(*it) != NULL) if (dynamic_cast<AbstractExternalFunctionNode *>(*it) != NULL)
(*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt2, map_idx, true, false, tef_terms); (*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); fnumexpr.write(code_file, instruction_number);
(*it)->compile(code_file, instruction_number, false, tt2, map_idx, true, false, tef_terms); (*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); fstpt.write(code_file, instruction_number);
// Insert current node into tt2 // Insert current node into tt2
tt2.insert(*it); tt2.insert(*it);
@ -1543,7 +1543,7 @@ DynamicModel::writeDynamicMFile(const string &dynamic_basename) const
<< "% Outputs:" << endl << "% Outputs:" << endl
<< "% residual [M_.endo_nbr by 1] double vector of residuals of the dynamic model equations in order of " << 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 << "% 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 << "% g1 [M_.endo_nbr by #dynamic variables] double Jacobian matrix of the dynamic model equations;" << endl
<< "% rows: equations in order of declaration" << 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 << "% columns: variables in order stored in M_.lead_lag_incidence followed by the ones in M_.exo_names" << endl
@ -1959,11 +1959,11 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
<< " else" << endl << " else" << endl
<< " mthd='UNKNOWN';" << endl << " mthd='UNKNOWN';" << endl
<< " end;" << endl << " end;" << endl
<< " if options_.verbosity" << endl << " if options_.verbosity" << endl
<< " printline(41)" << endl << " printline(41)" << endl
<< " disp(sprintf('MODEL SIMULATION (method=%s):',mthd))" << endl << " disp(sprintf('MODEL SIMULATION (method=%s):',mthd))" << endl
<< " skipline()" << endl << " skipline()" << endl
<< " end" << endl << " end" << endl
<< " periods=options_.periods;" << endl << " periods=options_.periods;" << endl
<< " maxit_=options_.simul.maxit;" << endl << " maxit_=options_.simul.maxit;" << endl
<< " solve_tolf=options_.solve_tolf;" << 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 << " g1=[];g2=[];g3=[];\n";
mDynamicModelFile << " y=" << dynamic_basename << "_" << block + 1 << "(y, x, params, steady_state, 0, y_kmin, periods);\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 << " 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 << " disp(['Inf or Nan value during the evaluation of block " << block <<"']);\n";
mDynamicModelFile << " oo_.deterministic_simulation.error = 100;\n"; mDynamicModelFile << " oo_.deterministic_simulation.error = 100;\n";
mDynamicModelFile << " varargout{1} = oo_;\n"; mDynamicModelFile << " varargout{1} = oo_;\n";
@ -2370,7 +2370,7 @@ DynamicModel::writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia
<< jacobian_output.str() << jacobian_output.str()
<< endl << endl
// Initialize g2 matrix // Initialize g2 matrix
<< "if nargout >= 3," << endl << "if nargout >= 3," << endl
<< " %" << endl << " %" << endl
<< " % Hessian matrix" << endl << " % Hessian matrix" << endl
@ -2561,16 +2561,16 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
output << modstruct << "lead_lag_incidence = ["; output << modstruct << "lead_lag_incidence = [";
// Loop on endogenous variables // Loop on endogenous variables
int nstatic = 0, int nstatic = 0,
nfwrd = 0, nfwrd = 0,
npred = 0, npred = 0,
nboth = 0; nboth = 0;
for (int endoID = 0; endoID < symbol_table.endo_nbr(); endoID++) for (int endoID = 0; endoID < symbol_table.endo_nbr(); endoID++)
{ {
output << endl; output << endl;
int sstatic = 1, int sstatic = 1,
sfwrd = 0, sfwrd = 0,
spred = 0, spred = 0,
sboth = 0; sboth = 0;
// Loop on periods // Loop on periods
for (int lag = -max_endo_lag; lag <= max_endo_lead; lag++) for (int lag = -max_endo_lag; lag <= max_endo_lead; lag++)
{ {
@ -2772,7 +2772,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
int count_other_endogenous = 1; 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 (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"; //cout << "block = " << block+1 << " state_var = " << *it << " it_other_endogenous=" << *it_other_endogenous + 1 << "\n";
if (*it == *it_other_endogenous + 1) if (*it == *it_other_endogenous + 1)
@ -2781,8 +2781,8 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
<< count_other_endogenous << ", " << count_other_endogenous << ", "
<< it - state_var.begin()+1 << ") = 1;\n"; << it - state_var.begin()+1 << ") = 1;\n";
/*output << "block_structure.block(" << block+1 << ").tm1(" /*output << "block_structure.block(" << block+1 << ").tm1("
<< it - state_var.begin()+1 << ", " << it - state_var.begin()+1 << ", "
<< count_other_endogenous << ") = 1;\n";*/ << count_other_endogenous << ") = 1;\n";*/
//cout << "=>\n"; //cout << "=>\n";
} }
} }
@ -2815,10 +2815,10 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
} }
else if (lag == 0) 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); local_stat_var.push_back(getBlockVariableID(block, it->first.second.first)+1);
n_static++; n_static++;
} }
} }
else else
@ -2830,7 +2830,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
} }
else 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_static--;
n_forward++; n_forward++;
} }
@ -2850,13 +2850,13 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
tmp_s.str(""); tmp_s.str("");
} }
vector<int> inter_state_var; 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_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 = state_var.begin(); it != state_var.end(); it++)
if (*it == *it_l) if (*it == *it_l)
inter_state_var.push_back(it - state_var.begin()+1); inter_state_var.push_back(it - state_var.begin()+1);
output << "block_structure.block(" << block+1 << ").sorted_col_dr_ghx = ["; 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++) for (vector<int>::const_iterator it = inter_state_var.begin(); it != inter_state_var.end(); it++)
output << *it << " "; output << *it << " ";
output << "];\n"; output << "];\n";
count_lead_lag_incidence = 0; count_lead_lag_incidence = 0;
output << "block_structure.block(" << block+1 << ").lead_lag_incidence_other = [];\n"; output << "block_structure.block(" << block+1 << ").lead_lag_incidence_other = [];\n";
@ -2901,10 +2901,10 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
output << "];\n"; output << "];\n";
vector<int> variable_inv_reordered(nb_endo); 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; 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); state_equ.push_back(equation_reordered[variable_inv_reordered[*it - 1]]+1);
map<pair< int, pair<int, int> >, int> lag_row_incidence; map<pair< int, pair<int, int> >, int> lag_row_incidence;
@ -2957,7 +2957,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
i_nz_state_var[i] = n; i_nz_state_var[i] = n;
unsigned int lp = n_obs; 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 block_size = getBlockSize(block);
int nze = 0; int nze = 0;
@ -2982,20 +2982,19 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
row_state_var_incidence.insert(make_pair(it_state_equ - state_equ.begin(), it_state_var - state_var.begin())); 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; /*tmp_block_endo_derivative[make_pair(it->second.first, make_pair(it->first.second, it->first.first))] = it->second.second;
if (block == 0) if (block == 0)
{ {
vector<int>::const_iterator it_state_equ = find(state_equ.begin(), state_equ.end(), getBlockEquationID(block, i)+1); 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()) 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"; 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())); 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(); set<pair<int, int> >::const_iterator row_state_var_incidence_it = row_state_var_incidence.begin();
bool diag = true; bool diag = true;
int nb_diag_r = 0; int nb_diag_r = 0;
while (row_state_var_incidence_it != row_state_var_incidence.end() && diag) while (row_state_var_incidence_it != row_state_var_incidence.end() && diag)
@ -3010,10 +3009,10 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
} }
} }
set<pair<int,int> > col_state_var_incidence; 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++) 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)); 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; diag = true;
int nb_diag_c = 0; int nb_diag_c = 0;
while (col_state_var_incidence_it != col_state_var_incidence.end() && diag) while (col_state_var_incidence_it != col_state_var_incidence.end() && diag)
@ -3027,7 +3026,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
nb_diag_c++; 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(); row_state_var_incidence.clear();
col_state_var_incidence.clear(); col_state_var_incidence.clear();
} }
@ -3042,7 +3041,6 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
output << modstruct << "n_diag = " << nb_diag << ";" << endl; output << modstruct << "n_diag = " << nb_diag << ";" << endl;
KF_index_file.write(reinterpret_cast<char *>(&nb_diag), sizeof(nb_diag)); KF_index_file.write(reinterpret_cast<char *>(&nb_diag), sizeof(nb_diag));
typedef pair<int, pair<int, int > > index_KF; typedef pair<int, pair<int, int > > index_KF;
vector<index_KF> v_index_KF; vector<index_KF> v_index_KF;
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
@ -3050,7 +3048,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
for (int j = n_obs; j < n; j++) for (int j = n_obs; j < n; j++)
{ {
int j1 = j - n_obs; 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)) if ((i < n_obs) || (i >= nb_diag + n_obs) || (j1 >= nb_diag))
for (int k = n_obs; k < i_nz_state_var[i]; k++) for (int k = n_obs; k < i_nz_state_var[i]; k++)
{ {
@ -3066,7 +3064,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
vector<index_KF> v_index_KF_2; vector<index_KF> v_index_KF_2;
int n_n_obs = n * n_obs; int n_n_obs = n * n_obs;
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
//i = 0; //i = 0;
for (int j = i; j < n; j++) for (int j = i; j < n; j++)
{ {
if ((i < n_obs) || (i >= nb_diag + n_obs) || (j < n_obs) || (j >= nb_diag + n_obs)) if ((i < n_obs) || (i >= nb_diag + n_obs) || (j < n_obs) || (j >= nb_diag + n_obs))
@ -3083,11 +3081,11 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
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(); 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++) for (vector<int>::const_iterator it = state_var.begin(); it != state_var.end(); it++)
output << *it << " "; output << *it << " ";
output << "];" << endl; output << "];" << endl;
} }
// Writing initialization for some other variables // Writing initialization for some other variables
@ -3101,21 +3099,21 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
output << modstruct << "maximum_endo_lag = " << max_endo_lag << ";" << endl output << modstruct << "maximum_endo_lag = " << max_endo_lag << ";" << endl
<< modstruct << "maximum_endo_lead = " << max_endo_lead << ";" << 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 output << modstruct << "maximum_exo_lag = " << max_exo_lag << ";" << endl
<< modstruct << "maximum_exo_lead = " << max_exo_lead << ";" << 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()) if (symbol_table.exo_det_nbr())
{ {
output << modstruct << "maximum_exo_det_lag = " << max_exo_det_lag << ";" << endl output << modstruct << "maximum_exo_det_lag = " << max_exo_det_lag << ";" << endl
<< modstruct << "maximum_exo_det_lead = " << max_exo_det_lead << ";" << 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(") output << modstruct << "params = " << (julia ? "fill(NaN, " : "NaN(")
<< symbol_table.param_nbr() << (julia ? ")" : ", 1);" ) << endl; << symbol_table.param_nbr() << (julia ? ")" : ", 1);") << endl;
if (compute_xrefs) if (compute_xrefs)
writeXrefs(output); writeXrefs(output);
@ -3123,7 +3121,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
// Write number of non-zero derivatives // Write number of non-zero derivatives
// Use -1 if the derivatives have not been computed // Use -1 if the derivatives have not been computed
output << modstruct << (julia ? "nnzderivatives" : "NNZDerivatives") output << modstruct << (julia ? "nnzderivatives" : "NNZDerivatives")
<< " = [" << NNZDerivatives[0] << "; "; << " = [" << NNZDerivatives[0] << "; ";
if (order > 1) if (order > 1)
output << NNZDerivatives[1] << "; "; output << NNZDerivatives[1] << "; ";
else else
@ -3532,7 +3530,7 @@ DynamicModel::collect_block_first_order_derivatives()
int var = symbol_table.getTypeSpecificID(getSymbIDByDerivID(it2->first.second)); int var = symbol_table.getTypeSpecificID(getSymbIDByDerivID(it2->first.second));
int lag = getLagByDerivID(it2->first.second); int lag = getLagByDerivID(it2->first.second);
int block_eq = equation_2_block[eq]; int block_eq = equation_2_block[eq];
int block_var=0; int block_var = 0;
derivative_t tmp_derivative; derivative_t tmp_derivative;
lag_var_t lag_var; lag_var_t lag_var;
switch (getTypeByDerivID(it2->first.second)) switch (getTypeByDerivID(it2->first.second))
@ -4478,7 +4476,6 @@ DynamicModel::substituteLeadLagInternal(aux_var_t type, bool deterministic_model
equations[i] = substeq; equations[i] = substeq;
} }
// Substitute in aux_equations // Substitute in aux_equations
// Without this loop, the auxiliary equations in equations // Without this loop, the auxiliary equations in equations
// will diverge from those in aux_equations // will diverge from those in aux_equations
@ -4678,7 +4675,7 @@ DynamicModel::fillEvalContext(eval_context_t &eval_context) const
vector <int> trendVars = symbol_table.getTrendVarIds(); vector <int> trendVars = symbol_table.getTrendVarIds();
for (vector <int>::const_iterator it = trendVars.begin(); for (vector <int>::const_iterator it = trendVars.begin();
it != trendVars.end(); it++) 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 bool
@ -4724,7 +4721,7 @@ DynamicModel::dynamicOnlyEquationsNbr() const
} }
#ifndef PRIVATE_BUFFER_SIZE #ifndef PRIVATE_BUFFER_SIZE
#define PRIVATE_BUFFER_SIZE 1024 # define PRIVATE_BUFFER_SIZE 1024
#endif #endif
bool bool
@ -4785,10 +4782,10 @@ DynamicModel::isChecksumMatching(const string &basename) const
} }
char private_buffer[PRIVATE_BUFFER_SIZE]; char private_buffer[PRIVATE_BUFFER_SIZE];
while(buffer) while (buffer)
{ {
buffer.get(private_buffer,PRIVATE_BUFFER_SIZE); buffer.get(private_buffer, PRIVATE_BUFFER_SIZE);
result.process_bytes(private_buffer,strlen(private_buffer)); result.process_bytes(private_buffer, strlen(private_buffer));
} }
bool basename_dir_exists = false; bool basename_dir_exists = false;
@ -4800,8 +4797,8 @@ DynamicModel::isChecksumMatching(const string &basename) const
if (r < 0) if (r < 0)
if (errno != EEXIST) if (errno != EEXIST)
{ {
perror("ERROR"); perror("ERROR");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
else else
basename_dir_exists = true; basename_dir_exists = true;
@ -4816,24 +4813,24 @@ DynamicModel::isChecksumMatching(const string &basename) const
{ {
checksum_file.open(filename.c_str(), ios::in | ios::binary); checksum_file.open(filename.c_str(), ios::in | ios::binary);
if (checksum_file.is_open()) if (checksum_file.is_open())
{ {
checksum_file >> old_checksum; checksum_file >> old_checksum;
checksum_file.close(); checksum_file.close();
} }
} }
// write new checksum file if none or different from old checksum // write new checksum file if none or different from old checksum
if (old_checksum != result.checksum()) if (old_checksum != result.checksum())
{ {
checksum_file.open(filename.c_str(), ios::out | ios::binary); checksum_file.open(filename.c_str(), ios::out | ios::binary);
if (!checksum_file.is_open()) if (!checksum_file.is_open())
{ {
cerr << "ERROR: Can't open file " << filename << endl; cerr << "ERROR: Can't open file " << filename << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
checksum_file << result.checksum(); checksum_file << result.checksum();
checksum_file.close(); checksum_file.close();
return false; return false;
} }
return true; return true;
} }
@ -4848,26 +4845,26 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d
{ {
// Loop on periods // Loop on periods
for (int lag = 0; lag <= 2; lag++) for (int lag = 0; lag <= 2; lag++)
{ {
lag_presence[lag] = 1; lag_presence[lag] = 1;
try try
{ {
getDerivID(symbol_table.getID(eEndogenous, endoID), lag-1); getDerivID(symbol_table.getID(eEndogenous, endoID), lag-1);
} }
catch (UnknownDerivIDException &e) catch (UnknownDerivIDException &e)
{ {
lag_presence[lag] = 0; lag_presence[lag] = 0;
} }
} }
if (lag_presence[0] == 1) if (lag_presence[0] == 1)
if (lag_presence[2] == 1) if (lag_presence[2] == 1)
zeta_mixed.push_back(endoID); zeta_mixed.push_back(endoID);
else else
zeta_back.push_back(endoID); zeta_back.push_back(endoID);
else if (lag_presence[2] == 1) else if (lag_presence[2] == 1)
zeta_fwrd.push_back(endoID); zeta_fwrd.push_back(endoID);
else else
zeta_static.push_back(endoID); zeta_static.push_back(endoID);
} }
output << "size_t nstatic = " << zeta_static.size() << ";" << endl output << "size_t nstatic = " << zeta_static.size() << ";" << endl
@ -4877,8 +4874,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d
output << "size_t zeta_static[" << zeta_static.size() << "] = {"; output << "size_t zeta_static[" << zeta_static.size() << "] = {";
for (vector<int>::iterator i = zeta_static.begin(); i != zeta_static.end(); ++i) for (vector<int>::iterator i = zeta_static.begin(); i != zeta_static.end(); ++i)
{ {
if ( i != zeta_static.begin() ) if (i != zeta_static.begin())
output << ","; output << ",";
output << *i; output << *i;
} }
output << "};" << endl; output << "};" << endl;
@ -4886,8 +4883,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d
output << "size_t zeta_back[" << zeta_back.size() << "] = {"; output << "size_t zeta_back[" << zeta_back.size() << "] = {";
for (vector<int>::iterator i = zeta_back.begin(); i != zeta_back.end(); ++i) for (vector<int>::iterator i = zeta_back.begin(); i != zeta_back.end(); ++i)
{ {
if ( i != zeta_back.begin() ) if (i != zeta_back.begin())
output << ","; output << ",";
output << *i; output << *i;
} }
output << "};" << endl; output << "};" << endl;
@ -4895,8 +4892,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d
output << "size_t zeta_fwrd[" << zeta_fwrd.size() << "] = {"; output << "size_t zeta_fwrd[" << zeta_fwrd.size() << "] = {";
for (vector<int>::iterator i = zeta_fwrd.begin(); i != zeta_fwrd.end(); ++i) for (vector<int>::iterator i = zeta_fwrd.begin(); i != zeta_fwrd.end(); ++i)
{ {
if ( i != zeta_fwrd.begin() ) if (i != zeta_fwrd.begin())
output << ","; output << ",";
output << *i; output << *i;
} }
output << "};" << endl; output << "};" << endl;
@ -4904,8 +4901,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d
output << "size_t zeta_mixed[" << zeta_mixed.size() << "] = {"; output << "size_t zeta_mixed[" << zeta_mixed.size() << "] = {";
for (vector<int>::iterator i = zeta_mixed.begin(); i != zeta_mixed.end(); ++i) for (vector<int>::iterator i = zeta_mixed.begin(); i != zeta_mixed.end(); ++i)
{ {
if ( i != zeta_mixed.begin() ) if (i != zeta_mixed.begin())
output << ","; output << ",";
output << *i; output << *i;
} }
output << "};" << endl; output << "};" << endl;
@ -4925,8 +4922,8 @@ DynamicModel::writeCOutput(ostream &output, const string &basename, bool block_d
output << NNZDerivatives[0] << "," << NNZDerivatives[1] << "," << NNZDerivatives[2] << "};" << endl; output << NNZDerivatives[0] << "," << NNZDerivatives[1] << "," << NNZDerivatives[2] << "};" << endl;
break; break;
default: default:
cerr << "Order larger than 3 not implemented" << endl; cerr << "Order larger than 3 not implemented" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
@ -4978,7 +4975,7 @@ DynamicModel::writeResidualsC(const string &basename, bool cuda) const
<< endl << endl
<< " /* Residual equations */" << endl << " /* Residual equations */" << endl
<< model_output.str() << model_output.str()
<< "}" << endl; << "}" << endl;
writePowerDeriv(mDynamicModelFile); writePowerDeriv(mDynamicModelFile);
writeNormcdf(mDynamicModelFile); writeNormcdf(mDynamicModelFile);
@ -5090,7 +5087,6 @@ DynamicModel::writeFirstDerivativesC_csr(const string &basename, bool cuda) cons
// this is always empty here, but needed by d1->writeOutput // this is always empty here, but needed by d1->writeOutput
deriv_node_temp_terms_t tef_terms; deriv_node_temp_terms_t tef_terms;
// Indexing derivatives in column order // Indexing derivatives in column order
vector<derivative> D; vector<derivative> D;
for (first_derivatives_t::const_iterator it = first_derivatives.begin(); for (first_derivatives_t::const_iterator it = first_derivatives.begin();
@ -5103,35 +5099,35 @@ DynamicModel::writeFirstDerivativesC_csr(const string &basename, bool cuda) cons
SymbolType type = getTypeByDerivID(dynvar); SymbolType type = getTypeByDerivID(dynvar);
int tsid = symbol_table.getTypeSpecificID(symb_id); int tsid = symbol_table.getTypeSpecificID(symb_id);
int col_id; int col_id;
switch(type) switch (type)
{ {
case eEndogenous: case eEndogenous:
col_id = tsid+(lag+1)*symbol_table.endo_nbr(); col_id = tsid+(lag+1)*symbol_table.endo_nbr();
break; break;
case eExogenous: case eExogenous:
col_id = tsid+3*symbol_table.endo_nbr(); col_id = tsid+3*symbol_table.endo_nbr();
break; break;
case eExogenousDet: case eExogenousDet:
col_id = tsid+3*symbol_table.endo_nbr()+symbol_table.exo_nbr(); col_id = tsid+3*symbol_table.endo_nbr()+symbol_table.exo_nbr();
break; break;
default: default:
std::cerr << "This case shouldn't happen" << std::endl; std::cerr << "This case shouldn't happen" << std::endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
derivative deriv(col_id + eq*cols_nbr,col_id,eq,it->second); derivative deriv(col_id + eq *cols_nbr, col_id, eq, it->second);
D.push_back(deriv); D.push_back(deriv);
} }
sort(D.begin(), D.end(), derivative_less_than() ); sort(D.begin(), D.end(), derivative_less_than());
// writing sparse Jacobian // writing sparse Jacobian
vector<int> row_ptr(equations.size()); 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; 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]++; row_ptr[it->row_nbr]++;
mDynamicModelFile << "col_ptr[" << k << "] " mDynamicModelFile << "col_ptr[" << k << "] "
<< "=" << it->col_nbr << ";" << endl; << "=" << it->col_nbr << ";" << endl;
mDynamicModelFile << "value[" << k << "] = "; mDynamicModelFile << "value[" << k << "] = ";
// oCstaticModel makes reference to the static variables // oCstaticModel makes reference to the static variables
it->value->writeOutput(mDynamicModelFile, oCDynamic2Model, temporary_terms, tef_terms); it->value->writeOutput(mDynamicModelFile, oCDynamic2Model, temporary_terms, tef_terms);
@ -5142,20 +5138,20 @@ DynamicModel::writeFirstDerivativesC_csr(const string &basename, bool cuda) cons
// row_ptr must point to the relative address of the first element of the row // row_ptr must point to the relative address of the first element of the row
int cumsum = 0; int cumsum = 0;
mDynamicModelFile << "int row_ptr_data[" << row_ptr.size() + 1 << "] = { 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; cumsum += *it;
mDynamicModelFile << ", " << cumsum; mDynamicModelFile << ", " << cumsum;
} }
mDynamicModelFile << "};" << endl mDynamicModelFile << "};" << endl
<< "int i;" << endl << "int i;" << endl
<< "for (i=0; i < " << row_ptr.size() + 1 << "; i++) row_ptr[i] = row_ptr_data[i];" << endl; << "for (i=0; i < " << row_ptr.size() + 1 << "; i++) row_ptr[i] = row_ptr_data[i];" << endl;
mDynamicModelFile << "}" << endl; mDynamicModelFile << "}" << endl;
mDynamicModelFile.close(); mDynamicModelFile.close();
} }
void void
DynamicModel::writeSecondDerivativesC_csr(const string &basename, bool cuda) const DynamicModel::writeSecondDerivativesC_csr(const string &basename, bool cuda) const
{ {
@ -5211,26 +5207,26 @@ DynamicModel::writeSecondDerivativesC_csr(const string &basename, bool cuda) con
int col_nb = id1 * dynJacobianColsNbr + id2; 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); D.push_back(deriv);
if (id1 != id2) if (id1 != id2)
{ {
col_nb = id2 * dynJacobianColsNbr + id1; col_nb = id2 * dynJacobianColsNbr + id1;
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); D.push_back(deriv);
} }
} }
sort(D.begin(), D.end(), derivative_less_than() ); sort(D.begin(), D.end(), derivative_less_than());
// Writing Hessian // Writing Hessian
vector<int> row_ptr(equations.size()); 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; 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]++; row_ptr[it->row_nbr]++;
mDynamicModelFile << "col_ptr[" << k << "] " mDynamicModelFile << "col_ptr[" << k << "] "
<< "=" << it->col_nbr << ";" << endl; << "=" << it->col_nbr << ";" << endl;
mDynamicModelFile << "value[" << k << "] = "; mDynamicModelFile << "value[" << k << "] = ";
// oCstaticModel makes reference to the static variables // oCstaticModel makes reference to the static variables
it->value->writeOutput(mDynamicModelFile, oCStaticModel, temporary_terms, tef_terms); it->value->writeOutput(mDynamicModelFile, oCStaticModel, temporary_terms, tef_terms);
@ -5241,7 +5237,7 @@ DynamicModel::writeSecondDerivativesC_csr(const string &basename, bool cuda) con
// row_ptr must point to the relative address of the first element of the row // row_ptr must point to the relative address of the first element of the row
int cumsum = 0; int cumsum = 0;
mDynamicModelFile << "row_ptr = [ 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; cumsum += *it;
mDynamicModelFile << ", " << cumsum; mDynamicModelFile << ", " << cumsum;
@ -5314,55 +5310,55 @@ DynamicModel::writeThirdDerivativesC_csr(const string &basename, bool cuda) cons
vector<long unsigned int> cols; vector<long unsigned int> cols;
long unsigned int col_nb = id1 * hessianColsNbr + id2 * dynJacobianColsNbr + id3; long unsigned int col_nb = id1 * hessianColsNbr + id2 * dynJacobianColsNbr + id3;
int thirdDColsNbr = hessianColsNbr*dynJacobianColsNbr; 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); D.push_back(deriv);
cols.push_back(col_nb); cols.push_back(col_nb);
col_nb = id1 * hessianColsNbr + id3 * dynJacobianColsNbr + id2; col_nb = id1 * hessianColsNbr + id3 * dynJacobianColsNbr + id2;
if (find(cols.begin(),cols.end(),col_nb) == cols.end()) if (find(cols.begin(), cols.end(), col_nb) == cols.end())
{ {
derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second);
D.push_back(deriv); D.push_back(deriv);
cols.push_back(col_nb); cols.push_back(col_nb);
} }
col_nb = id2 * hessianColsNbr + id1 * dynJacobianColsNbr + id3; col_nb = id2 * hessianColsNbr + id1 * dynJacobianColsNbr + id3;
if (find(cols.begin(),cols.end(),col_nb) == cols.end()) if (find(cols.begin(), cols.end(), col_nb) == cols.end())
{ {
derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second);
D.push_back(deriv); D.push_back(deriv);
cols.push_back(col_nb); cols.push_back(col_nb);
} }
col_nb = id2 * hessianColsNbr + id3 * dynJacobianColsNbr + id1; col_nb = id2 * hessianColsNbr + id3 * dynJacobianColsNbr + id1;
if (find(cols.begin(),cols.end(),col_nb) == cols.end()) if (find(cols.begin(), cols.end(), col_nb) == cols.end())
{ {
derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second);
D.push_back(deriv); D.push_back(deriv);
cols.push_back(col_nb); cols.push_back(col_nb);
} }
col_nb = id3 * hessianColsNbr + id1 * dynJacobianColsNbr + id2; col_nb = id3 * hessianColsNbr + id1 * dynJacobianColsNbr + id2;
if (find(cols.begin(),cols.end(),col_nb) == cols.end()) if (find(cols.begin(), cols.end(), col_nb) == cols.end())
{ {
derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second);
D.push_back(deriv); D.push_back(deriv);
cols.push_back(col_nb); cols.push_back(col_nb);
} }
col_nb = id3 * hessianColsNbr + id2 * dynJacobianColsNbr + id1; col_nb = id3 * hessianColsNbr + id2 * dynJacobianColsNbr + id1;
if (find(cols.begin(),cols.end(),col_nb) == cols.end()) if (find(cols.begin(), cols.end(), col_nb) == cols.end())
{ {
derivative deriv(col_nb + eq*thirdDerivativesColsNbr,col_nb,eq,it->second); derivative deriv(col_nb + eq *thirdDerivativesColsNbr, col_nb, eq, it->second);
D.push_back(deriv); 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()); 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; 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]++; row_ptr[it->row_nbr]++;
mDynamicModelFile << "col_ptr[" << k << "] " mDynamicModelFile << "col_ptr[" << k << "] "
<< "=" << it->col_nbr << ";" << endl; << "=" << it->col_nbr << ";" << endl;
mDynamicModelFile << "value[" << k << "] = "; mDynamicModelFile << "value[" << k << "] = ";
// oCstaticModel makes reference to the static variables // oCstaticModel makes reference to the static variables
it->value->writeOutput(mDynamicModelFile, oCStaticModel, temporary_terms, tef_terms); it->value->writeOutput(mDynamicModelFile, oCStaticModel, temporary_terms, tef_terms);
@ -5373,7 +5369,7 @@ DynamicModel::writeThirdDerivativesC_csr(const string &basename, bool cuda) cons
// row_ptr must point to the relative address of the first element of the row // row_ptr must point to the relative address of the first element of the row
int cumsum = 0; int cumsum = 0;
mDynamicModelFile << "row_ptr = [ 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; cumsum += *it;
mDynamicModelFile << ", " << cumsum; mDynamicModelFile << ", " << cumsum;
@ -5397,26 +5393,26 @@ DynamicModel::writeCCOutput(ostream &output, const string &basename, bool block_
{ {
// Loop on periods // Loop on periods
for (int lag = 0; lag <= 2; lag++) for (int lag = 0; lag <= 2; lag++)
{ {
lag_presence[lag] = 1; lag_presence[lag] = 1;
try try
{ {
getDerivID(symbol_table.getID(eEndogenous, endoID), lag-1); getDerivID(symbol_table.getID(eEndogenous, endoID), lag-1);
} }
catch (UnknownDerivIDException &e) catch (UnknownDerivIDException &e)
{ {
lag_presence[lag] = 0; lag_presence[lag] = 0;
} }
} }
if (lag_presence[0] == 1) if (lag_presence[0] == 1)
if (lag_presence[2] == 1) if (lag_presence[2] == 1)
output << "zeta_mixed.push_back(" << endoID << ");" << endl; output << "zeta_mixed.push_back(" << endoID << ");" << endl;
else else
output << "zeta_back.push_back(" << endoID << ");" << endl; output << "zeta_back.push_back(" << endoID << ");" << endl;
else if (lag_presence[2] == 1) else if (lag_presence[2] == 1)
output << "zeta_fwrd.push_back(" << endoID << ");" << endl; output << "zeta_fwrd.push_back(" << endoID << ");" << endl;
else else
output << "zeta_static.push_back(" << endoID << ");" << endl; output << "zeta_static.push_back(" << endoID << ");" << endl;
} }
output << "nstatic = zeta_static.size();" << endl output << "nstatic = zeta_static.size();" << endl
@ -5441,7 +5437,6 @@ DynamicModel::writeCCOutput(ostream &output, const string &basename, bool block_
<< "NNZDerivatives.push_back(-1);" << endl; << "NNZDerivatives.push_back(-1);" << endl;
} }
void void
DynamicModel::writeJsonOutput(ostream &output) const DynamicModel::writeJsonOutput(ostream &output) const
{ {

View File

@ -337,7 +337,7 @@ public:
//! Transforms the model by creating aux vars for the diff of forward vars //! 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 /*! 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); void differentiateForwardVars(const vector<string> &subset);
//! Fills eval context with values of model local variables and auxiliary variables //! Fills eval context with values of model local variables and auxiliary variables
@ -543,14 +543,17 @@ public:
long unsigned int col_nbr; long unsigned int col_nbr;
unsigned int row_nbr; unsigned int row_nbr;
expr_t value; expr_t value;
derivative(long unsigned int arg1, long unsigned int arg2, int arg3, expr_t 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) {}; linear_address(arg1), col_nbr(arg2), row_nbr(arg3), value(arg4)
{
};
}; };
class derivative_less_than class derivative_less_than
{ {
public: 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; return d1.linear_address < d2.linear_address;
} }

View File

@ -130,8 +130,8 @@ main(int argc, char **argv)
clear_all = false; clear_all = false;
else if (strlen(argv[arg]) >= 19 && !strncmp(argv[arg], "params_derivs_order", 19)) else if (strlen(argv[arg]) >= 19 && !strncmp(argv[arg], "params_derivs_order", 19))
{ {
if (strlen(argv[arg]) >= 22 || argv[arg][19] != '=' || if (strlen(argv[arg]) >= 22 || argv[arg][19] != '='
!(argv[arg][20] == '0' || argv[arg][20] == '1' || argv[arg][20] == '2')) || !(argv[arg][20] == '0' || argv[arg][20] == '1' || argv[arg][20] == '2'))
{ {
cerr << "Incorrect syntax for params_derivs_order option" << endl; cerr << "Incorrect syntax for params_derivs_order option" << endl;
usage(); usage();
@ -228,12 +228,12 @@ main(int argc, char **argv)
size_t equal_index = string(argv[arg]).find('='); size_t equal_index = string(argv[arg]).find('=');
if (equal_index != string::npos) 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); defines[key] = string(argv[arg]).erase(0, equal_index+1);
} }
else else
{ {
string key = string(argv[arg]).erase(0,2); string key = string(argv[arg]).erase(0, 2);
defines[key] = "1"; defines[key] = "1";
} }
} }
@ -245,36 +245,36 @@ main(int argc, char **argv)
<< "must not be separated from -I by whitespace." << endl; << "must not be separated from -I by whitespace." << endl;
usage(); 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)) else if (strlen(argv[arg]) >= 6 && !strncmp(argv[arg], "output", 6))
{ {
if (strlen(argv[arg]) <= 7 || argv[arg][6] != '=') if (strlen(argv[arg]) <= 7 || argv[arg][6] != '=')
{ {
cerr << "Incorrect syntax for ouput option" << endl; cerr << "Incorrect syntax for ouput option" << endl;
usage(); usage();
} }
if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 7, "dynamic", 7)) if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 7, "dynamic", 7))
output_mode = dynamic; output_mode = dynamic;
else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 7, "first", 5)) else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 7, "first", 5))
output_mode = first; output_mode = first;
else if (strlen(argv[arg]) == 13 && !strncmp(argv[arg] + 7, "second", 6)) else if (strlen(argv[arg]) == 13 && !strncmp(argv[arg] + 7, "second", 6))
output_mode = second; output_mode = second;
else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 7, "third", 5)) else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 7, "third", 5))
output_mode = third; output_mode = third;
else else
{ {
cerr << "Incorrect syntax for ouput option" << endl; cerr << "Incorrect syntax for ouput option" << endl;
usage(); usage();
} }
} }
else if (strlen(argv[arg]) >= 8 && !strncmp(argv[arg], "language", 8)) else if (strlen(argv[arg]) >= 8 && !strncmp(argv[arg], "language", 8))
{ {
if (strlen(argv[arg]) <= 9 || argv[arg][8] != '=') if (strlen(argv[arg]) <= 9 || argv[arg][8] != '=')
{ {
cerr << "Incorrect syntax for language option" << endl; cerr << "Incorrect syntax for language option" << endl;
usage(); usage();
} }
if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 9, "julia", 5)) if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 9, "julia", 5))
language = julia; language = julia;
@ -302,26 +302,26 @@ main(int argc, char **argv)
else if (!strcmp(argv[arg], "onlyjson")) else if (!strcmp(argv[arg], "onlyjson"))
onlyjson = true; onlyjson = true;
else if (!strcmp(argv[arg], "jsonprintderivdetail")) else if (!strcmp(argv[arg], "jsonprintderivdetail"))
jsonprintderivdetail = true; jsonprintderivdetail = true;
else if (strlen(argv[arg]) >= 4 && !strncmp(argv[arg], "json", 4)) else if (strlen(argv[arg]) >= 4 && !strncmp(argv[arg], "json", 4))
{ {
if (strlen(argv[arg]) <= 5 || argv[arg][4] != '=') if (strlen(argv[arg]) <= 5 || argv[arg][4] != '=')
{ {
cerr << "Incorrect syntax for json option" << endl; cerr << "Incorrect syntax for json option" << endl;
usage(); usage();
} }
if (strlen(argv[arg]) == 10 && !strncmp(argv[arg] + 5, "parse", 5)) if (strlen(argv[arg]) == 10 && !strncmp(argv[arg] + 5, "parse", 5))
json = parsing; json = parsing;
else if (strlen(argv[arg]) == 10 && !strncmp(argv[arg] + 5, "check", 5)) else if (strlen(argv[arg]) == 10 && !strncmp(argv[arg] + 5, "check", 5))
json = checkpass; json = checkpass;
else if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 5, "transform", 9)) else if (strlen(argv[arg]) == 14 && !strncmp(argv[arg] + 5, "transform", 9))
json = transformpass; json = transformpass;
else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 5, "compute", 7)) else if (strlen(argv[arg]) == 12 && !strncmp(argv[arg] + 5, "compute", 7))
json = computingpass; json = computingpass;
else else
{ {
cerr << "Incorrect syntax for json option" << endl; cerr << "Incorrect syntax for json option" << endl;
usage(); usage();
} }
} }
else else

View File

@ -69,9 +69,9 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear
mod_file->writeOutputFiles(basename, clear_all, clear_global, no_log, no_warn, console, nograph, mod_file->writeOutputFiles(basename, clear_all, clear_global, no_log, no_warn, console, nograph,
nointeractive, config_file, check_model_changes, minimal_workspace, compute_xrefs nointeractive, config_file, check_model_changes, minimal_workspace, compute_xrefs
#if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__)
, cygwin, msvc, mingw , cygwin, msvc, mingw
#endif #endif
); );
delete mod_file; delete mod_file;

View File

@ -107,7 +107,7 @@ ExprNode::collectVariables(SymbolType type, set<int> &result) const
set<pair<int, int> > symbs_lags; set<pair<int, int> > symbs_lags;
collectDynamicVariables(type, symbs_lags); collectDynamicVariables(type, symbs_lags);
transform(symbs_lags.begin(), symbs_lags.end(), inserter(result, result.begin()), 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 void
@ -537,7 +537,6 @@ NumConstNode::substituteStaticAuxiliaryVariable() const
return const_cast<NumConstNode *>(this); return const_cast<NumConstNode *>(this);
} }
VariableNode::VariableNode(DataTree &datatree_arg, int symb_id_arg, int lag_arg) : VariableNode::VariableNode(DataTree &datatree_arg, int symb_id_arg, int lag_arg) :
ExprNode(datatree_arg), ExprNode(datatree_arg),
symb_id(symb_id_arg), symb_id(symb_id_arg),
@ -1015,15 +1014,15 @@ VariableNode::normalizeEquation(int var_endo, vector<pair<int, pair<expr_t, expr
{ {
/* The equation has to be normalized with respect to the current endogenous variable ascribed to it. /* The equation has to be normalized with respect to the current endogenous variable ascribed to it.
The two input arguments are : The two input arguments are :
- The ID of the endogenous variable associated to the equation. - The ID of the endogenous variable associated to the equation.
- The list of operators and operands needed to normalize the equation* - The list of operators and operands needed to normalize the equation*
The pair returned by NormalizeEquation is composed of The pair returned by NormalizeEquation is composed of
- a flag indicating if the expression returned contains (flag = 1) or not (flag = 0) - a flag indicating if the expression returned contains (flag = 1) or not (flag = 0)
the endogenous variable related to the equation. the endogenous variable related to the equation.
If the expression contains more than one occurence of the associated endogenous variable, If the expression contains more than one occurence of the associated endogenous variable,
the flag is equal to 2. the flag is equal to 2.
- an expression equal to the RHS if flag = 0 and equal to NULL elsewhere - an expression equal to the RHS if flag = 0 and equal to NULL elsewhere
*/ */
if (type == eEndogenous) if (type == eEndogenous)
{ {
@ -2003,7 +2002,7 @@ UnaryOpNode::writeJsonOutput(ostream &output,
break; break;
} }
bool close_parenthesis = false; bool close_parenthesis = false;
/* Enclose argument with parentheses if: /* Enclose argument with parentheses if:
- current opcode is not uminus, or - current opcode is not uminus, or
@ -2660,7 +2659,7 @@ UnaryOpNode::substituteExoLag(subst_table_t &subst_table, vector<BinaryOpNode *>
expr_t expr_t
UnaryOpNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool partial_information_model) const 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)); subst_table_t::iterator it = subst_table.find(const_cast<UnaryOpNode *>(this));
if (it != subst_table.end()) if (it != subst_table.end())
@ -3727,7 +3726,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); expr_t_2 = Compute_RHS(it.second.second, expr_t_2, it.first, 1);
else if (it.second.second && it.second.first) /*Binary operator*/ else if (it.second.second && it.second.first) /*Binary operator*/
expr_t_2 = Compute_RHS(it.second.first, it.second.second, it.first, 1); 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); expr_t_2 = Compute_RHS((UnaryOpNode *) expr_t_2, (UnaryOpNode *) it.second.first, it.first, 0);
} }
} }
@ -4160,7 +4159,6 @@ BinaryOpNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOpN
return buildSimilarBinaryOpNode(arg1subst, arg2subst, datatree); return buildSimilarBinaryOpNode(arg1subst, arg2subst, datatree);
} }
expr_t expr_t
BinaryOpNode::differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const BinaryOpNode::differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const
{ {
@ -4877,7 +4875,6 @@ TrinaryOpNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOp
return buildSimilarTrinaryOpNode(arg1subst, arg2subst, arg3subst, datatree); return buildSimilarTrinaryOpNode(arg1subst, arg2subst, arg3subst, datatree);
} }
expr_t expr_t
TrinaryOpNode::differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const TrinaryOpNode::differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const
{ {

View File

@ -89,16 +89,16 @@ enum ExprNodeOutputType
|| (output_type) == oMatlabDynamicSparseSteadyStateOperator \ || (output_type) == oMatlabDynamicSparseSteadyStateOperator \
|| (output_type) == oSteadyStateFile) || (output_type) == oSteadyStateFile)
#define IS_JULIA(output_type) ((output_type) == oJuliaStaticModel \ #define IS_JULIA(output_type) ((output_type) == oJuliaStaticModel \
|| (output_type) == oJuliaDynamicModel \ || (output_type) == oJuliaDynamicModel \
|| (output_type) == oJuliaDynamicSteadyStateOperator \ || (output_type) == oJuliaDynamicSteadyStateOperator \
|| (output_type) == oJuliaSteadyStateFile) || (output_type) == oJuliaSteadyStateFile)
#define IS_C(output_type) ((output_type) == oCDynamicModel \ #define IS_C(output_type) ((output_type) == oCDynamicModel \
|| (output_type) == oCDynamic2Model \ || (output_type) == oCDynamic2Model \
|| (output_type) == oCStaticModel \ || (output_type) == oCStaticModel \
|| (output_type) == oCDynamicSteadyStateOperator \ || (output_type) == oCDynamicSteadyStateOperator \
|| (output_type) == oCSteadyStateFile) || (output_type) == oCSteadyStateFile)
#define IS_LATEX(output_type) ((output_type) == oLatexStaticModel \ #define IS_LATEX(output_type) ((output_type) == oLatexStaticModel \
|| (output_type) == oLatexDynamicModel \ || (output_type) == oLatexDynamicModel \
@ -122,345 +122,346 @@ enum ExprNodeOutputType
#define MIN_COST(is_matlab) ((is_matlab) ? MIN_COST_MATLAB : MIN_COST_C) #define MIN_COST(is_matlab) ((is_matlab) ? MIN_COST_MATLAB : MIN_COST_C)
//! Base class for expression nodes //! Base class for expression nodes
class ExprNode class ExprNode
{ {
friend class DataTree; friend class DataTree;
friend class DynamicModel; friend class DynamicModel;
friend class StaticModel; friend class StaticModel;
friend class ModelTree; friend class ModelTree;
friend struct ExprNodeLess; friend struct ExprNodeLess;
friend class NumConstNode; friend class NumConstNode;
friend class VariableNode; friend class VariableNode;
friend class UnaryOpNode; friend class UnaryOpNode;
friend class BinaryOpNode; friend class BinaryOpNode;
friend class TrinaryOpNode; friend class TrinaryOpNode;
friend class AbstractExternalFunctionNode; friend class AbstractExternalFunctionNode;
private: private:
//! Computes derivative w.r. to a derivation ID (but doesn't store it in derivatives map) //! 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 */ /*! You shoud use getDerivative() to get the benefit of symbolic a priori and of caching */
virtual expr_t computeDerivative(int deriv_id) = 0; virtual expr_t computeDerivative(int deriv_id) = 0;
protected: protected:
//! Reference to the enclosing DataTree //! Reference to the enclosing DataTree
DataTree &datatree; DataTree &datatree;
//! Index number //! Index number
int idx; int idx;
//! Is the data member non_null_derivatives initialized ? //! Is the data member non_null_derivatives initialized ?
bool preparedForDerivation; bool preparedForDerivation;
//! Set of derivation IDs with respect to which the derivative is potentially non-null //! Set of derivation IDs with respect to which the derivative is potentially non-null
set<int> non_null_derivatives; set<int> non_null_derivatives;
//! Used for caching of first order derivatives (when non-null) //! Used for caching of first order derivatives (when non-null)
map<int, expr_t> derivatives; map<int, expr_t> derivatives;
//! Cost of computing current node //! Cost of computing current node
/*! Nodes included in temporary_terms are considered having a null cost */ /*! Nodes included in temporary_terms are considered having a null cost */
virtual int cost(int cost, bool is_matlab) const; 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 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; virtual int cost(const map<NodeTreeReference, temporary_terms_t> &temp_terms_map, bool is_matlab) const;
//! For creating equation cross references //! For creating equation cross references
struct EquationInfo struct EquationInfo
{ {
set<pair<int, int> > param; set<pair<int, int> > param;
set<pair<int, int> > endo; set<pair<int, int> > endo;
set<pair<int, int> > exo; set<pair<int, int> > exo;
set<pair<int, int> > exo_det; set<pair<int, int> > exo_det;
}; };
public: public:
ExprNode(DataTree &datatree_arg); ExprNode(DataTree &datatree_arg);
virtual ~ExprNode(); virtual
~ExprNode();
//! Initializes data member non_null_derivatives //! Initializes data member non_null_derivatives
virtual void prepareForDerivation() = 0; virtual void prepareForDerivation() = 0;
//! Returns derivative w.r. to derivation ID //! Returns derivative w.r. to derivation ID
/*! Uses a symbolic a priori to pre-detect null derivatives, and caches the result for other derivatives (to avoid computing it several times) /*! 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 */ For an equal node, returns the derivative of lhs minus rhs */
expr_t getDerivative(int deriv_id); expr_t getDerivative(int deriv_id);
//! Computes derivatives by applying the chain rule for some variables //! Computes derivatives by applying the chain rule for some variables
/*! /*!
\param deriv_id The derivation ID with respect to which we are derivating \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 \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; virtual expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables) = 0;
//! Returns precedence of node //! Returns precedence of node
/*! Equals 100 for constants, variables, unary ops, and temporary terms */ /*! Equals 100 for constants, variables, unary ops, and temporary terms */
virtual int precedence(ExprNodeOutputType output_t, const temporary_terms_t &temporary_terms) const; virtual int precedence(ExprNodeOutputType output_t, const temporary_terms_t &temporary_terms) const;
//! Fills temporary_terms set, using reference counts //! 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 */ /*! 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, virtual void computeTemporaryTerms(map<expr_t, pair<int, NodeTreeReference> > &reference_count,
map<NodeTreeReference, temporary_terms_t> &temp_terms_map, map<NodeTreeReference, temporary_terms_t> &temp_terms_map,
bool is_matlab, NodeTreeReference tr) const; 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 //! 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 the output stream
\param[in] output_type the type of output (MATLAB, C, LaTeX...) \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] temporary_terms the nodes that are marked as temporary terms
\param[in,out] tef_terms the set of already written external function nodes \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; 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 //! returns true if the expr node contains an external function
virtual bool containsExternalFunction() const = 0; virtual bool containsExternalFunction() const = 0;
//! Writes output of node (with no temporary terms and with "outside model" output type) //! Writes output of node (with no temporary terms and with "outside model" output type)
void writeOutput(ostream &output) const; void writeOutput(ostream &output) const;
//! Writes output of node (with no temporary terms) //! Writes output of node (with no temporary terms)
void writeOutput(ostream &output, ExprNodeOutputType output_type) const; void writeOutput(ostream &output, ExprNodeOutputType output_type) const;
//! Writes output of node, using a Txxx notation for nodes in temporary_terms //! 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; void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms) const;
//! Writes output of node in JSON syntax //! Writes output of node in JSON syntax
virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0; virtual void writeJsonOutput(ostream &output, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0;
virtual int precedenceJson(const temporary_terms_t &temporary_terms) const; virtual int precedenceJson(const temporary_terms_t &temporary_terms) const;
//! Writes the output for an external function, ensuring that the external function is called as few times as possible using temporary terms //! 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, virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type,
const temporary_terms_t &temporary_terms,
deriv_node_temp_terms_t &tef_terms) const;
//! Write the JSON output of an external function in a string vector
//! Allows the insertion of commas if necessary
virtual void writeJsonExternalFunctionOutput(vector<string> &efout,
const temporary_terms_t &temporary_terms, const temporary_terms_t &temporary_terms,
deriv_node_temp_terms_t &tef_terms) const; deriv_node_temp_terms_t &tef_terms) const;
virtual void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number, //! Write the JSON output of an external function in a string vector
bool lhs_rhs, const temporary_terms_t &temporary_terms, //! Allows the insertion of commas if necessary
const map_idx_t &map_idx, bool dynamic, bool steady_dynamic, virtual void writeJsonExternalFunctionOutput(vector<string> &efout,
deriv_node_temp_terms_t &tef_terms) const; const temporary_terms_t &temporary_terms,
deriv_node_temp_terms_t &tef_terms) const;
//! Computes the set of all variables of a given symbol type in the expression (with information on lags) virtual void compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number,
/*! bool lhs_rhs, const temporary_terms_t &temporary_terms,
Variables are stored as integer pairs of the form (symb_id, lag). const map_idx_t &map_idx, bool dynamic, bool steady_dynamic,
They are added to the set given in argument. deriv_node_temp_terms_t &tef_terms) const;
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) //! Computes the set of all variables of a given symbol type in the expression (with information on lags)
/*! /*!
Variables are stored as symb_id. Variables are stored as integer pairs of the form (symb_id, lag).
They are added to the set given in argument. They are added to the set given in argument.
Note that model local variables are substituted by their expression in the computation Note that model local variables are substituted by their expression in the computation
(and added if type_arg = ModelLocalVariable). (and added if type_arg = ModelLocalVariable).
*/ */
void collectVariables(SymbolType type_arg, set<int> &result) const; virtual void collectDynamicVariables(SymbolType type_arg, set<pair<int, int> > &result) const = 0;
//! Computes the set of endogenous variables in the expression //! Computes the set of all variables of a given symbol type in the expression (without information on lags)
/*! /*!
Endogenous are stored as integer pairs of the form (type_specific_id, lag). Variables are stored as symb_id.
They are added to the set given in argument. They are added to the set given in argument.
Note that model local variables are substituted by their expression in the computation. Note that model local variables are substituted by their expression in the computation
*/ (and added if type_arg = ModelLocalVariable).
virtual void collectEndogenous(set<pair<int, int> > &result) const; */
void collectVariables(SymbolType type_arg, set<int> &result) const;
//! Computes the set of exogenous variables in the expression //! Computes the set of endogenous variables in the expression
/*! /*!
Exogenous are stored as integer pairs of the form (type_specific_id, lag). Endogenous are stored as integer pairs of the form (type_specific_id, lag).
They are added to the set given in argument. They are added to the set given in argument.
Note that model local variables are substituted by their expression in the computation. Note that model local variables are substituted by their expression in the computation.
*/ */
virtual void collectExogenous(set<pair<int, int> > &result) const; virtual void collectEndogenous(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; //! 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 computeTemporaryTerms(map<expr_t, int> &reference_count, virtual void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const = 0;
temporary_terms_t &temporary_terms,
map<expr_t, pair<int, int> > &first_occurence,
int Curr_block,
vector< vector<temporary_terms_t> > &v_temporary_terms,
int equation) const;
class EvalException 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 {
};
{ 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;
/*! virtual double eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException) = 0;
Compute cross references for equations 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;
// virtual void computeXrefs(set<int> &param, set<int> &endo, set<int> &exo, set<int> &exo_det) const = 0; //! Creates a static version of this node
virtual void computeXrefs(EquationInfo &ei) const = 0; /*!
//! Try to normalize an equation linear in its endogenous variable This method duplicates the current node by creating a similar node from which all leads/lags have been stripped,
virtual pair<int, expr_t> normalizeEquation(int symb_id_endo, vector<pair<int, pair<expr_t, expr_t> > > &List_of_Op_RHS) const = 0; adds the result in the static_datatree argument (and not in the original datatree), and returns it.
*/
virtual expr_t toStatic(DataTree &static_datatree) const = 0;
//! Returns the maximum lead of endogenous in this expression /*!
/*! Always returns a non-negative value */ Compute cross references for equations
virtual int maxEndoLead() const = 0; */
// virtual void computeXrefs(set<int> &param, 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 exogenous in this expression //! Returns the maximum lead of endogenous in this expression
/*! Always returns a non-negative value */ /*! Always returns a non-negative value */
virtual int maxExoLead() const = 0; virtual int maxEndoLead() const = 0;
//! Returns the maximum lag of endogenous in this expression //! Returns the maximum lead of exogenous in this expression
/*! Always returns a non-negative value */ /*! Always returns a non-negative value */
virtual int maxEndoLag() const = 0; virtual int maxExoLead() const = 0;
//! Returns the maximum lag of exogenous in this expression //! Returns the maximum lag of endogenous in this expression
/*! Always returns a non-negative value */ /*! Always returns a non-negative value */
virtual int maxExoLag() const = 0; virtual int maxEndoLag() const = 0;
//! Returns the relative period of the most forward term in this expression //! Returns the maximum lag of exogenous in this expression
/*! A negative value means that the expression contains only lagged variables */ /*! Always returns a non-negative value */
virtual int maxLead() const = 0; virtual int maxExoLag() const = 0;
//! Returns a new expression where all the leads/lags have been shifted backwards by the same amount //! Returns the relative period of the most forward term in this expression
/*! /*! A negative value means that the expression contains only lagged variables */
Only acts on endogenous, exogenous, exogenous det virtual int maxLead() const = 0;
\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 //! Returns a new expression where all the leads/lags have been shifted backwards by the same amount
typedef map<const ExprNode *, const VariableNode *> subst_table_t; /*!
Only acts on endogenous, exogenous, exogenous det
\param[in] n The number of lags by which to shift
\return The same expression except that leads/lags have been shifted backwards
*/
virtual expr_t decreaseLeadsLags(int n) const = 0;
//! Creates auxiliary endo lead variables corresponding to this expression //! 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;
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 //! Creates auxiliary endo 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. 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 exogenous lead >= 1 \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[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. \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 \return The new variable node corresponding to the current expression
*/ */
VariableNode *createExoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const; VariableNode *createEndoLeadAuxiliaryVarForMyself(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 //! Creates auxiliary exo lead variables corresponding to this expression
/*! /*!
\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. 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.
\param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables. \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;
If the method detects a sub-expr which needs to be substituted, two cases are possible: //! Constructs a new expression where sub-expressions with max endo lead >= 2 have been replaced by auxiliary variables
- 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 \param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr.
\param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables.
\return A new equivalent expression where sub-expressions with max endo lead >= 2 have been replaced by auxiliary variables 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
virtual expr_t substituteEndoLeadGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const = 0; - if this expr is not in the table, then it will create an auxiliary endogenous variable, add the substitution in the table and return the substituted expression
//! Constructs a new expression where endo variables with max endo lag >= 2 have been replaced by auxiliary variables \return A new equivalent 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. virtual expr_t substituteEndoLeadGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const = 0;
\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 //! 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[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[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; virtual expr_t substituteEndoLagGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) 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 //! 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[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[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 substituteExoLead(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const = 0;
virtual expr_t substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool partial_information_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;
virtual expr_t decreaseLeadsLagsPredeterminedVariables() const = 0; //! Constructs a new expression where the expectation operator has been replaced by auxiliary variables
/*!
\param[in,out] subst_table Map used to store expressions that have already be substituted and their corresponding variable, in order to avoid creating two auxiliary variables for the same sub-expr.
\param[out] neweqs Equations to be added to the model to match the creation of auxiliary variables.
\param[in] partial_information_model Are we substituting in a partial information model?
*/
virtual expr_t substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool partial_information_model) const = 0;
//! Constructs a new expression where forward variables (supposed to be at most in t+1) have been replaced by themselves at t, plus a new aux var representing their (time) differentiate virtual expr_t decreaseLeadsLagsPredeterminedVariables() const = 0;
/*!
\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 //! 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] value of the numerical constante \param[in] subset variables to which to limit the transformation; transform
\param[out] the boolean equal to true if NodeId is a constant equal to value all fwrd vars if empty
*/ \param[in,out] subst_table Map used to store mapping between a given
virtual bool isNumConstNodeEqualTo(double value) const = 0; 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;
//! Returns true if the expression contains one or several endogenous variable //! Return true if the nodeID is a numerical constant equal to value and false otherwise
virtual bool containsEndogenous(void) const = 0; /*!
\param[in] value of the numerical constante
\param[out] the boolean equal to true if NodeId is a constant equal to value
*/
virtual bool isNumConstNodeEqualTo(double value) const = 0;
//! Returns true if the expression contains one or several exogenous variable //! Returns true if the expression contains one or several endogenous variable
virtual bool containsExogenous() const = 0; virtual bool containsEndogenous(void) const = 0;
//! Return true if the nodeID is a variable withe a type equal to type_arg, a specific variable id aqual to varfiable_id and a lag equal to lag_arg and false otherwise //! Returns true if the expression contains one or several exogenous variable
/*! virtual bool containsExogenous() const = 0;
\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 //! 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
virtual expr_t replaceTrendVar() const = 0; /*!
\param[in] the type (type_arg), specifique variable id (variable_id and the lag (lag_arg)
\param[out] the boolean equal to true if NodeId is the variable
*/
virtual bool isVariableNodeEqualTo(SymbolType type_arg, int variable_id, int lag_arg) const = 0;
//! Constructs a new expression where the variable indicated by symb_id has been detrended //! Replaces the Trend var with datatree.One
/*! virtual expr_t replaceTrendVar() const = 0;
\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 //! Constructs a new expression where the variable indicated by symb_id has been detrended
virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const = 0; /*!
\param[in] symb_id indicating the variable to be detrended
\param[in] log_trend indicates if the trend is in log
\param[in] trend indicating the trend
\return the new binary op pointing to a detrended variable
*/
virtual expr_t detrend(int symb_id, bool log_trend, expr_t trend) const = 0;
//! Move a trend variable with lag/lead to time t by dividing/multiplying by its growth factor //! Add ExprNodes to the provided datatree
virtual expr_t removeTrendLeadLag(map<int, expr_t> trend_symbols_map) const = 0; virtual expr_t cloneDynamic(DataTree &dynamic_datatree) const = 0;
//! Returns true if the expression is in static form (no lead, no lag, no expectation, no STEADY_STATE) //! Move a trend variable with lag/lead to time t by dividing/multiplying by its growth factor
virtual bool isInStaticForm() const = 0; virtual expr_t removeTrendLeadLag(map<int, expr_t> trend_symbols_map) const = 0;
//! Substitute auxiliary variables by their expression in static model //! Returns true if the expression is in static form (no lead, no lag, no expectation, no STEADY_STATE)
virtual expr_t substituteStaticAuxiliaryVariable() const = 0; 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) //! Object used to compare two nodes (using their indexes)
struct ExprNodeLess struct ExprNodeLess
@ -563,7 +564,11 @@ public:
{ {
return symb_id; 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 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 expr_t getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables);
virtual int maxEndoLead() const; virtual int maxEndoLead() const;

View File

@ -175,7 +175,7 @@ namespace MFS
if (in_degree(vertex, G) > 0 && out_degree(vertex, G) > 0) 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_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) 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)); Doublet.push_back(source(*it_in, G));
return Doublet; return Doublet;
} }

View File

@ -151,7 +151,7 @@ ModFile::checkPass(bool nostrict)
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.planner_objective_present)
|| (!(mod_file_struct.ramsey_model_present || mod_file_struct.discretionary_policy_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; 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); exit(EXIT_FAILURE);
@ -257,24 +257,24 @@ ModFile::checkPass(bool nostrict)
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (dynamic_model.staticOnlyEquationsNbr() > 0 && if (dynamic_model.staticOnlyEquationsNbr() > 0
(mod_file_struct.ramsey_model_present || mod_file_struct.discretionary_policy_present)) && (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; cerr << "ERROR: marking equations as [static] or [dynamic] is not possible with ramsey_model, ramsey_policy or discretionary_policy" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if (stochastic_statement_present && if (stochastic_statement_present
(dynamic_model.isUnaryOpUsed(oSign) && (dynamic_model.isUnaryOpUsed(oSign)
|| dynamic_model.isUnaryOpUsed(oAbs) || dynamic_model.isUnaryOpUsed(oAbs)
|| dynamic_model.isBinaryOpUsed(oMax) || dynamic_model.isBinaryOpUsed(oMax)
|| dynamic_model.isBinaryOpUsed(oMin) || dynamic_model.isBinaryOpUsed(oMin)
|| dynamic_model.isBinaryOpUsed(oGreater) || dynamic_model.isBinaryOpUsed(oGreater)
|| dynamic_model.isBinaryOpUsed(oLess) || dynamic_model.isBinaryOpUsed(oLess)
|| dynamic_model.isBinaryOpUsed(oGreaterEqual) || dynamic_model.isBinaryOpUsed(oGreaterEqual)
|| dynamic_model.isBinaryOpUsed(oLessEqual) || dynamic_model.isBinaryOpUsed(oLessEqual)
|| dynamic_model.isBinaryOpUsed(oEqualEqual) || dynamic_model.isBinaryOpUsed(oEqualEqual)
|| dynamic_model.isBinaryOpUsed(oDifferent))) || 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; warnings << "WARNING: you are using a function (max, min, abs, sign) or an operator (<, >, <=, >=, ==, !=) which is unsuitable for a stochastic context; see the reference manual, section about \"Expressions\", for more details." << endl;
// Test if some estimated parameters are used within the values of shocks // Test if some estimated parameters are used within the values of shocks
@ -289,7 +289,7 @@ ModFile::checkPass(bool nostrict)
{ {
cerr << "ERROR: some estimated parameters ("; cerr << "ERROR: some estimated parameters (";
for (set<int>::const_iterator it = parameters_intersect.begin(); for (set<int>::const_iterator it = parameters_intersect.begin();
it != parameters_intersect.end(); ) it != parameters_intersect.end();)
{ {
cerr << symbol_table.getName(*it); cerr << symbol_table.getName(*it);
if (++it != parameters_intersect.end()) if (++it != parameters_intersect.end())
@ -363,7 +363,7 @@ ModFile::transformPass(bool nostrict, bool compute_xrefs)
/* /*
clone the model then clone the new equations back to the original because clone the model then clone the new equations back to the original because
we have to call computeDerivIDs (in computeRamseyPolicyFOCs and computingPass) we have to call computeDerivIDs (in computeRamseyPolicyFOCs and computingPass)
*/ */
if (linear) if (linear)
dynamic_model.cloneDynamic(orig_ramsey_dynamic_model); dynamic_model.cloneDynamic(orig_ramsey_dynamic_model);
dynamic_model.cloneDynamic(ramsey_FOC_equations_dynamic_model); dynamic_model.cloneDynamic(ramsey_FOC_equations_dynamic_model);
@ -497,64 +497,64 @@ ModFile::computingPass(bool no_tmp_terms, FileOutputType output, int params_deri
// Compute static model and its derivatives // Compute static model and its derivatives
dynamic_model.toStatic(static_model); dynamic_model.toStatic(static_model);
if (!no_static) if (!no_static)
{ {
if (mod_file_struct.stoch_simul_present if (mod_file_struct.stoch_simul_present
|| mod_file_struct.estimation_present || mod_file_struct.osr_present || mod_file_struct.estimation_present || mod_file_struct.osr_present
|| mod_file_struct.ramsey_model_present || mod_file_struct.identification_present || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present
|| mod_file_struct.calib_smoother_present) || mod_file_struct.calib_smoother_present)
static_model.set_cutoff_to_zero(); static_model.set_cutoff_to_zero();
const bool static_hessian = mod_file_struct.identification_present const bool static_hessian = mod_file_struct.identification_present
|| mod_file_struct.estimation_analytic_derivation; || mod_file_struct.estimation_analytic_derivation;
int paramsDerivsOrder = 0; int paramsDerivsOrder = 0;
if (mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation) if (mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation)
paramsDerivsOrder = params_derivs_order; paramsDerivsOrder = params_derivs_order;
static_model.computingPass(global_eval_context, no_tmp_terms, static_hessian, static_model.computingPass(global_eval_context, no_tmp_terms, static_hessian,
false, paramsDerivsOrder, block, byte_code); false, paramsDerivsOrder, block, byte_code);
} }
// Set things to compute for dynamic model // Set things to compute for dynamic model
if (mod_file_struct.perfect_foresight_solver_present || mod_file_struct.check_present if (mod_file_struct.perfect_foresight_solver_present || mod_file_struct.check_present
|| mod_file_struct.stoch_simul_present || mod_file_struct.stoch_simul_present
|| mod_file_struct.estimation_present || mod_file_struct.osr_present || mod_file_struct.estimation_present || mod_file_struct.osr_present
|| mod_file_struct.ramsey_model_present || mod_file_struct.identification_present || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present
|| mod_file_struct.calib_smoother_present) || mod_file_struct.calib_smoother_present)
{ {
if (mod_file_struct.perfect_foresight_solver_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); dynamic_model.computingPass(true, false, false, none, global_eval_context, no_tmp_terms, block, use_dll, byte_code);
else else
{ {
if (mod_file_struct.stoch_simul_present if (mod_file_struct.stoch_simul_present
|| mod_file_struct.estimation_present || mod_file_struct.osr_present || mod_file_struct.estimation_present || mod_file_struct.osr_present
|| mod_file_struct.ramsey_model_present || mod_file_struct.identification_present || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present
|| mod_file_struct.calib_smoother_present) || mod_file_struct.calib_smoother_present)
dynamic_model.set_cutoff_to_zero(); dynamic_model.set_cutoff_to_zero();
if (mod_file_struct.order_option < 1 || mod_file_struct.order_option > 3) if (mod_file_struct.order_option < 1 || mod_file_struct.order_option > 3)
{ {
cerr << "ERROR: Incorrect order option..." << endl; cerr << "ERROR: Incorrect order option..." << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
bool hessian = mod_file_struct.order_option >= 2 bool hessian = mod_file_struct.order_option >= 2
|| mod_file_struct.identification_present || mod_file_struct.identification_present
|| mod_file_struct.estimation_analytic_derivation || mod_file_struct.estimation_analytic_derivation
|| linear || linear
|| output == second || output == second
|| output == third; || output == third;
bool thirdDerivatives = mod_file_struct.order_option == 3 bool thirdDerivatives = mod_file_struct.order_option == 3
|| mod_file_struct.estimation_analytic_derivation || mod_file_struct.estimation_analytic_derivation
|| output == third; || output == third;
int paramsDerivsOrder = 0; int paramsDerivsOrder = 0;
if (mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation) if (mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation)
paramsDerivsOrder = params_derivs_order; paramsDerivsOrder = params_derivs_order;
dynamic_model.computingPass(true, hessian, thirdDerivatives, paramsDerivsOrder, global_eval_context, no_tmp_terms, block, use_dll, byte_code); 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) 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); 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 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); 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()) || if ((linear && !mod_file_struct.ramsey_model_present && !dynamic_model.checkHessianZero())
(linear && mod_file_struct.ramsey_model_present && !orig_ramsey_dynamic_model.checkHessianZero())) || (linear && mod_file_struct.ramsey_model_present && !orig_ramsey_dynamic_model.checkHessianZero()))
{ {
map<int, string> eqs; map<int, string> eqs;
if (mod_file_struct.ramsey_model_present) if (mod_file_struct.ramsey_model_present)
@ -620,18 +620,18 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo
if (clear_all) if (clear_all)
mOutputFile << "if isoctave || matlab_ver_less_than('8.6')" << endl mOutputFile << "if isoctave || matlab_ver_less_than('8.6')" << endl
<< " clear all" << endl << " clear all" << endl
<< "else" << endl << "else" << endl
<< " clearvars -global" << endl << " clearvars -global" << endl
<< " clear_persistent_variables(fileparts(which('dynare')), false)" << endl << " clear_persistent_variables(fileparts(which('dynare')), false)" << endl
<< "end" << endl; << "end" << endl;
else if (clear_global) else if (clear_global)
mOutputFile << "clear M_ options_ oo_ estim_params_ bayestopt_ dataset_ dataset_info estimation_info ys0_ ex0_;" << endl; mOutputFile << "clear M_ options_ oo_ estim_params_ bayestopt_ dataset_ dataset_info estimation_info ys0_ ex0_;" << endl;
mOutputFile << "tic0 = tic;" << endl mOutputFile << "tic0 = tic;" << endl
<< "% Save empty dates and dseries objects in memory." << endl << "% Save empty dates and dseries objects in memory." << endl
<< "dates('initialize');" << endl << "dates('initialize');" << endl
<< "dseries('initialize');" << endl << "dseries('initialize');" << endl
<< "% Define global variables." << endl << "% Define global variables." << endl
<< "global M_ options_ oo_ estim_params_ bayestopt_ dataset_ dataset_info estimation_info ys0_ ex0_" << endl << "global M_ options_ oo_ estim_params_ bayestopt_ dataset_ dataset_info estimation_info ys0_ ex0_" << endl
<< "options_ = [];" << endl << "options_ = [];" << endl
<< "M_.fname = '" << basename << "';" << endl << "M_.fname = '" << basename << "';" << endl
@ -744,7 +744,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo
} }
#if defined(_WIN32) || defined(__CYGWIN32__) #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 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) if (use_dll && msvc)
{ {
@ -764,7 +764,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
#endif # endif
#endif #endif
// Compile the dynamic MEX file for use_dll option // Compile the dynamic MEX file for use_dll option
@ -774,10 +774,10 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo
#if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__) #if defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__)
if (msvc) if (msvc)
// MATLAB/Windows + Microsoft Visual C++ // 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) else if (cygwin)
// MATLAB/Windows + Cygwin g++ // 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) else if (mingw)
// MATLAB/Windows + MinGW g++ // MATLAB/Windows + MinGW g++
mOutputFile << "dyn_mex('mingw', '" << basename << "', " << !check_model_changes << ")" << endl; mOutputFile << "dyn_mex('mingw', '" << basename << "', " << !check_model_changes << ")" << endl;
@ -855,7 +855,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo
config_file.writeEndParallel(mOutputFile); config_file.writeEndParallel(mOutputFile);
mOutputFile << endl << endl mOutputFile << endl << endl
<< "disp(['Total computing time : ' dynsec2hms(toc(tic0)) ]);" << endl; << "disp(['Total computing time : ' dynsec2hms(toc(tic0)) ]);" << endl;
if (!no_warn) if (!no_warn)
{ {
@ -867,7 +867,6 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo
<< "end" << endl; << "end" << endl;
} }
if (!no_log) if (!no_log)
mOutputFile << "diary off" << endl; mOutputFile << "diary off" << endl;
@ -877,16 +876,16 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo
{ {
// Create static and dynamic files // Create static and dynamic files
if (dynamic_model.equation_number() > 0) if (dynamic_model.equation_number() > 0)
{ {
if (!no_static) if (!no_static)
{ {
static_model.writeStaticFile(basename, block, byte_code, use_dll, false); static_model.writeStaticFile(basename, block, byte_code, use_dll, false);
static_model.writeParamsDerivativesFile(basename, false); static_model.writeParamsDerivativesFile(basename, false);
} }
dynamic_model.writeDynamicFile(basename, block, byte_code, use_dll, mod_file_struct.order_option, false); dynamic_model.writeDynamicFile(basename, block, byte_code, use_dll, mod_file_struct.order_option, false);
dynamic_model.writeParamsDerivativesFile(basename, false); dynamic_model.writeParamsDerivativesFile(basename, false);
} }
// Create steady state file // Create steady state file
steady_state_model.writeSteadyStateFile(basename, mod_file_struct.ramsey_model_present, false); steady_state_model.writeSteadyStateFile(basename, mod_file_struct.ramsey_model_present, false);
@ -898,7 +897,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_glo
void void
ModFile::writeExternalFiles(const string &basename, FileOutputType output, LanguageOutputType language) const ModFile::writeExternalFiles(const string &basename, FileOutputType output, LanguageOutputType language) const
{ {
switch(language) switch (language)
{ {
case c: case c:
writeExternalFilesC(basename, output); writeExternalFilesC(basename, output);
@ -926,7 +925,6 @@ ModFile::writeExternalFilesC(const string &basename, FileOutputType output) cons
if (!no_static) if (!no_static)
static_model.writeStaticFile(basename, false, false, true, false); static_model.writeStaticFile(basename, false, false, true, false);
// static_model.writeStaticCFile(basename, block, byte_code, use_dll); // static_model.writeStaticCFile(basename, block, byte_code, use_dll);
// static_model.writeParamsDerivativesFileC(basename, cuda); // static_model.writeParamsDerivativesFileC(basename, cuda);
// static_model.writeAuxVarInitvalC(mOutputFile, oMatlabOutsideModel, cuda); // static_model.writeAuxVarInitvalC(mOutputFile, oMatlabOutsideModel, cuda);
@ -939,8 +937,8 @@ ModFile::writeExternalFilesC(const string &basename, FileOutputType output) cons
dynamic_model.writeSecondDerivativesC_csr(basename, cuda); dynamic_model.writeSecondDerivativesC_csr(basename, cuda);
else if (output == third) else if (output == third)
{ {
dynamic_model.writeSecondDerivativesC_csr(basename, cuda); dynamic_model.writeSecondDerivativesC_csr(basename, cuda);
dynamic_model.writeThirdDerivativesC_csr(basename, cuda); dynamic_model.writeThirdDerivativesC_csr(basename, cuda);
} }
} }
@ -984,7 +982,7 @@ ModFile::writeModelC(const string &basename) const
// Print statements // Print statements
for (vector<Statement *>::const_iterator it = statements.begin(); for (vector<Statement *>::const_iterator it = statements.begin();
it != statements.end(); it++) it != statements.end(); it++)
(*it)->writeCOutput(mDriverCFile, basename); (*it)->writeCOutput(mDriverCFile, basename);
mDriverCFile << "} DynareInfo;" << endl; mDriverCFile << "} DynareInfo;" << endl;
mDriverCFile.close(); mDriverCFile.close();
@ -1044,8 +1042,8 @@ ModFile::writeExternalFilesCC(const string &basename, FileOutputType output) con
dynamic_model.writeSecondDerivativesC_csr(basename, cuda); dynamic_model.writeSecondDerivativesC_csr(basename, cuda);
else if (output == third) else if (output == third)
{ {
dynamic_model.writeSecondDerivativesC_csr(basename, cuda); dynamic_model.writeSecondDerivativesC_csr(basename, cuda);
dynamic_model.writeThirdDerivativesC_csr(basename, cuda); dynamic_model.writeThirdDerivativesC_csr(basename, cuda);
} }
} }
@ -1089,7 +1087,7 @@ ModFile::writeModelCC(const string &basename) const
// Print statements // Print statements
for (vector<Statement *>::const_iterator it = statements.begin(); for (vector<Statement *>::const_iterator it = statements.begin();
it != statements.end(); it++) it != statements.end(); it++)
(*it)->writeCOutput(mDriverCFile, basename); (*it)->writeCOutput(mDriverCFile, basename);
mDriverCFile << "};" << endl; mDriverCFile << "};" << endl;
mDriverCFile.close(); mDriverCFile.close();
@ -1165,7 +1163,7 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output)
<< "if isfile(\"" << basename << "SteadyState2.jl" "\")" << endl << "if isfile(\"" << basename << "SteadyState2.jl" "\")" << endl
<< " using " << basename << "SteadyState2" << endl << " using " << basename << "SteadyState2" << endl
<< "end" << endl << endl << "end" << endl << endl
<< "export model_, options_, oo_" << endl; << "export model_, options_, oo_" << endl;
// Write Output // Write Output
jlOutputFile << endl jlOutputFile << endl
@ -1223,9 +1221,9 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output)
steady_state_model.writeSteadyStateFile(basename, mod_file_struct.ramsey_model_present, true); steady_state_model.writeSteadyStateFile(basename, mod_file_struct.ramsey_model_present, true);
// Print statements (includes parameter values) // Print statements (includes parameter values)
for (vector<Statement *>::const_iterator it = statements.begin(); for (vector<Statement *>::const_iterator it = statements.begin();
it != statements.end(); it++) it != statements.end(); it++)
(*it)->writeJuliaOutput(jlOutputFile, basename); (*it)->writeJuliaOutput(jlOutputFile, basename);
jlOutputFile << "model_.static = " << basename << "Static.static!" << endl jlOutputFile << "model_.static = " << basename << "Static.static!" << endl
<< "model_.dynamic = " << basename << "Dynamic.dynamic!" << endl << "model_.dynamic = " << basename << "Dynamic.dynamic!" << endl
@ -1245,7 +1243,7 @@ ModFile::writeExternalFilesJulia(const string &basename, FileOutputType output)
<< " using " << basename << "DynamicParamsDerivs" << endl << " using " << basename << "DynamicParamsDerivs" << endl
<< " model_.dynamic_params_derivs = " << basename << "DynamicParamsDerivs.params_derivs" << endl << " model_.dynamic_params_derivs = " << basename << "DynamicParamsDerivs.params_derivs" << endl
<< "end" << endl << "end" << endl
<< "end" << endl; << "end" << endl;
jlOutputFile.close(); jlOutputFile.close();
cout << "done" << endl; cout << "done" << endl;
} }
@ -1331,11 +1329,11 @@ ModFile::writeJsonOutputParsingCheck(const string &basename, JsonFileOutputType
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
else else
{ {
cerr << "ERROR: Missing file name" << endl; cerr << "ERROR: Missing file name" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
jsonOutputFile << output.str(); jsonOutputFile << output.str();
jsonOutputFile.close(); jsonOutputFile.close();

View File

@ -41,7 +41,7 @@ using namespace std;
// for checksum computation // for checksum computation
#ifndef PRIVATE_BUFFER_SIZE #ifndef PRIVATE_BUFFER_SIZE
#define PRIVATE_BUFFER_SIZE 1024 # define PRIVATE_BUFFER_SIZE 1024
#endif #endif
//! The abstract representation of a "mod" file //! The abstract representation of a "mod" file
@ -91,9 +91,9 @@ public:
bool differentiate_forward_vars; bool differentiate_forward_vars;
/*! If the 'differentiate_forward_vars' option is used, contains the set of /*! If the 'differentiate_forward_vars' option is used, contains the set of
endogenous with respect to which to do the transformation; endogenous with respect to which to do the transformation;
if empty, means that the transformation must be applied to all endos if empty, means that the transformation must be applied to all endos
with a lead */ with a lead */
vector<string> differentiate_forward_vars_subset; vector<string> differentiate_forward_vars_subset;
//! Are nonstationary variables present ? //! Are nonstationary variables present ?

View File

@ -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()) 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; 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)) 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; << " 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;
@ -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 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; 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) 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++) 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_g2.clear();
temporary_terms_g3.clear(); temporary_terms_g3.clear();
map<NodeTreeReference, temporary_terms_t> temp_terms_map; map<NodeTreeReference, temporary_terms_t> temp_terms_map;
temp_terms_map[eResiduals]=temporary_terms_res; temp_terms_map[eResiduals] = temporary_terms_res;
temp_terms_map[eFirstDeriv]=temporary_terms_g1; temp_terms_map[eFirstDeriv] = temporary_terms_g1;
temp_terms_map[eSecondDeriv]=temporary_terms_g2; temp_terms_map[eSecondDeriv] = temporary_terms_g2;
temp_terms_map[eThirdDeriv]=temporary_terms_g3; temp_terms_map[eThirdDeriv] = temporary_terms_g3;
for (vector<BinaryOpNode *>::iterator it = equations.begin(); for (vector<BinaryOpNode *>::iterator it = equations.begin();
it != equations.end(); it++) it != equations.end(); it++)
@ -1386,17 +1386,17 @@ ModelTree::compileTemporaryTerms(ostream &code_file, unsigned int &instruction_n
(*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt2, map_idx, dynamic, steady_dynamic, tef_terms); (*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); fnumexpr.write(code_file, instruction_number);
(*it)->compile(code_file, instruction_number, false, tt2, map_idx, dynamic, steady_dynamic, tef_terms); (*it)->compile(code_file, instruction_number, false, tt2, map_idx, dynamic, steady_dynamic, tef_terms);
if (dynamic) 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); fstpt.write(code_file, instruction_number);
} }
else 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); fstpst.write(code_file, instruction_number);
} }
// Insert current node into tt2 // Insert current node into tt2
@ -1871,11 +1871,11 @@ ModelTree::computeParamsDerivativesTemporaryTerms()
map<expr_t, pair<int, NodeTreeReference > > reference_count; map<expr_t, pair<int, NodeTreeReference > > reference_count;
params_derivs_temporary_terms.clear(); params_derivs_temporary_terms.clear();
map<NodeTreeReference, temporary_terms_t> temp_terms_map; map<NodeTreeReference, temporary_terms_t> temp_terms_map;
temp_terms_map[eResidualsParamsDeriv]=params_derivs_temporary_terms_res; temp_terms_map[eResidualsParamsDeriv] = params_derivs_temporary_terms_res;
temp_terms_map[eJacobianParamsDeriv]=params_derivs_temporary_terms_g1; temp_terms_map[eJacobianParamsDeriv] = params_derivs_temporary_terms_g1;
temp_terms_map[eResidualsParamsSecondDeriv]=params_derivs_temporary_terms_res2; temp_terms_map[eResidualsParamsSecondDeriv] = params_derivs_temporary_terms_res2;
temp_terms_map[eJacobianParamsSecondDeriv]=params_derivs_temporary_terms_g12; temp_terms_map[eJacobianParamsSecondDeriv] = params_derivs_temporary_terms_g12;
temp_terms_map[eHessianParamsDeriv]=params_derivs_temporary_terms_g2; temp_terms_map[eHessianParamsDeriv] = params_derivs_temporary_terms_g2;
for (first_derivatives_t::iterator it = residuals_params_derivatives.begin(); for (first_derivatives_t::iterator it = residuals_params_derivatives.begin();
it != residuals_params_derivatives.end(); it++) it != residuals_params_derivatives.end(); it++)
@ -1918,7 +1918,8 @@ ModelTree::computeParamsDerivativesTemporaryTerms()
params_derivs_temporary_terms_g2 = temp_terms_map[eHessianParamsDeriv]; 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) return (nonstationary_symbols_map.find(symb_id)
!= nonstationary_symbols_map.end()); != nonstationary_symbols_map.end());
@ -1928,7 +1929,7 @@ void
ModelTree::writeJsonModelEquations(ostream &output, bool residuals) const ModelTree::writeJsonModelEquations(ostream &output, bool residuals) const
{ {
deriv_node_temp_terms_t tef_terms; deriv_node_temp_terms_t tef_terms;
vector<pair<string,string> > eqtags; vector<pair<string, string> > eqtags;
temporary_terms_t tt_empty; temporary_terms_t tt_empty;
if (residuals) if (residuals)
output << endl << "\"residuals\":[" << endl; output << endl << "\"residuals\":[" << endl;
@ -1986,7 +1987,7 @@ ModelTree::writeJsonModelEquations(ostream &output, bool residuals) const
{ {
output << ", \"tags\": {"; output << ", \"tags\": {";
int i = 0; int i = 0;
for (vector<pair<string, string> >:: const_iterator it = eqtags.begin(); it != eqtags.end(); it++, i++) for (vector<pair<string, string> >::const_iterator it = eqtags.begin(); it != eqtags.end(); it++, i++)
{ {
if (i != 0) if (i != 0)
output << ", "; output << ", ";

View File

@ -128,7 +128,6 @@ protected:
*/ */
third_derivatives_t hessian_params_derivatives; third_derivatives_t hessian_params_derivatives;
//! Temporary terms for the static/dynamic file (those which will be noted Txxxx) //! Temporary terms for the static/dynamic file (those which will be noted Txxxx)
temporary_terms_t temporary_terms; temporary_terms_t temporary_terms;
temporary_terms_t temporary_terms_res; 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_g12;
temporary_terms_t params_derivs_temporary_terms_g2; temporary_terms_t params_derivs_temporary_terms_g2;
//! Trend variables and their growth factors //! Trend variables and their growth factors
map<int, expr_t> trend_symbols_map; map<int, expr_t> trend_symbols_map;
@ -177,7 +175,7 @@ protected:
void computeTemporaryTerms(bool is_matlab); void computeTemporaryTerms(bool is_matlab);
//! Computes temporary terms for the file containing parameters derivatives //! Computes temporary terms for the file containing parameters derivatives
void computeParamsDerivativesTemporaryTerms(); void computeParamsDerivativesTemporaryTerms();
//! Writes temporary terms //! Writes temporary terms
void writeTemporaryTerms(const temporary_terms_t &tt, const temporary_terms_t &ttm1, ostream &output, ExprNodeOutputType output_type, deriv_node_temp_terms_t &tef_terms) const; void writeTemporaryTerms(const temporary_terms_t &tt, const temporary_terms_t &ttm1, ostream &output, ExprNodeOutputType output_type, deriv_node_temp_terms_t &tef_terms) const;
void writeJsonTemporaryTerms(const temporary_terms_t &tt, const temporary_terms_t &ttm1, ostream &output, deriv_node_temp_terms_t &tef_terms, string &concat) const; void writeJsonTemporaryTerms(const temporary_terms_t &tt, const temporary_terms_t &ttm1, ostream &output, deriv_node_temp_terms_t &tef_terms, string &concat) const;
//! Compiles temporary terms //! Compiles temporary terms
@ -274,10 +272,11 @@ protected:
virtual unsigned int getBlockMaxLag(int block_number) const = 0; virtual unsigned int getBlockMaxLag(int block_number) const = 0;
//! Return the maximum lead in a block //! Return the maximum lead in a block
virtual unsigned int getBlockMaxLead(int block_number) const = 0; virtual unsigned int getBlockMaxLead(int block_number) const = 0;
inline void setBlockLeadLag(int block, int max_lag, int max_lead) inline void
{ setBlockLeadLag(int block, int max_lag, int max_lead)
block_lag_lead[block] = make_pair(max_lag, 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 //! Return the type of equation (equation_number) belonging to the block block_number
virtual EquationType getBlockEquationType(int block_number, int equation_number) const = 0; virtual EquationType getBlockEquationType(int block_number, int equation_number) const = 0;

View File

@ -134,7 +134,7 @@ ParsingDriver::create_error_string(const Dynare::parser::location_type &l, const
stream << ", cols " << l.begin.column << "-" << l.end.column - 1; stream << ", cols " << l.begin.column << "-" << l.end.column - 1;
else else
stream << ", col " << l.begin.column << " -" 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; stream << ": " << m << endl;
} }
@ -259,8 +259,8 @@ void
ParsingDriver::declare_statement_local_variable(string *name) ParsingDriver::declare_statement_local_variable(string *name)
{ {
if (mod_file->symbol_table.exists(*name)) if (mod_file->symbol_table.exists(*name))
error("Symbol " + *name + " cannot be assigned within a statement " + error("Symbol " + *name + " cannot be assigned within a statement "
"while being assigned elsewhere in the modfile"); +"while being assigned elsewhere in the modfile");
declare_symbol(name, eStatementDeclaredVariable, NULL, NULL); declare_symbol(name, eStatementDeclaredVariable, NULL, NULL);
delete name; 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, // 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 // 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); undeclared_model_vars.insert(*name);
symb_id = mod_file->symbol_table.getID(*name); symb_id = mod_file->symbol_table.getID(*name);
} }
@ -888,7 +888,7 @@ ParsingDriver::end_svar_identification()
mod_file->addStatement(new SvarIdentificationStatement(svar_ident_restrictions, mod_file->addStatement(new SvarIdentificationStatement(svar_ident_restrictions,
svar_upper_cholesky, svar_upper_cholesky,
svar_lower_cholesky, svar_lower_cholesky,
svar_constants_exclusion, svar_constants_exclusion,
mod_file->symbol_table)); mod_file->symbol_table));
svar_restriction_symbols.clear(); svar_restriction_symbols.clear();
svar_equation_restrictions.clear(); svar_equation_restrictions.clear();
@ -910,18 +910,18 @@ ParsingDriver::combine_lag_and_restriction(string *lag)
for (map<int, vector<int> >::const_iterator it = svar_equation_restrictions.begin(); for (map<int, vector<int> >::const_iterator it = svar_equation_restrictions.begin();
it != svar_equation_restrictions.end(); it++) it != svar_equation_restrictions.end(); it++)
for (vector<int>::const_iterator it1 = it->second.begin(); 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; SvarIdentificationStatement::svar_identification_restriction new_restriction;
new_restriction.equation = it->first; new_restriction.equation = it->first;
if (current_lag > 0) if (current_lag > 0)
new_restriction.restriction_nbr = ++svar_Ri_restriction_nbr[it->first]; new_restriction.restriction_nbr = ++svar_Ri_restriction_nbr[it->first];
else else
new_restriction.restriction_nbr = ++svar_Qi_restriction_nbr[it->first]; new_restriction.restriction_nbr = ++svar_Qi_restriction_nbr[it->first];
new_restriction.lag = current_lag; new_restriction.lag = current_lag;
new_restriction.variable = *it1; new_restriction.variable = *it1;
new_restriction.value = data_tree->One; new_restriction.value = data_tree->One;
svar_ident_restrictions.push_back(new_restriction); svar_ident_restrictions.push_back(new_restriction);
} }
// svar_ident_exclusion_values[make_pair(current_lag, it->first)] = it->second; // svar_ident_exclusion_values[make_pair(current_lag, it->first)] = it->second;
@ -1034,21 +1034,21 @@ ParsingDriver::add_restriction_element(expr_t value, string *variable, string *l
if (svar_restriction_type == ParsingDriver::NOT_SET) if (svar_restriction_type == ParsingDriver::NOT_SET)
{ {
if (current_lag == 0) if (current_lag == 0)
{ {
svar_restriction_type = ParsingDriver::Qi_TYPE; svar_restriction_type = ParsingDriver::Qi_TYPE;
++svar_Qi_restriction_nbr[svar_equation_nbr]; ++svar_Qi_restriction_nbr[svar_equation_nbr];
} }
else else
{ {
svar_restriction_type = ParsingDriver::Ri_TYPE; svar_restriction_type = ParsingDriver::Ri_TYPE;
++svar_Ri_restriction_nbr[svar_equation_nbr]; ++svar_Ri_restriction_nbr[svar_equation_nbr];
} }
} }
else else
{ {
if ((svar_restriction_type == Qi_TYPE && current_lag > 0) if ((svar_restriction_type == Qi_TYPE && current_lag > 0)
|| (svar_restriction_type == Ri_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"); error("SVAR_IDENTIFICATION: a single restrictions must affect either Qi or Ri, but not both");
} }
SvarIdentificationStatement::svar_identification_restriction new_restriction; SvarIdentificationStatement::svar_identification_restriction new_restriction;
new_restriction.equation = svar_equation_nbr; new_restriction.equation = svar_equation_nbr;
@ -1213,7 +1213,7 @@ ParsingDriver::option_symbol_list(const string &name_option)
!= options_list.symbol_list_options.end()) != options_list.symbol_list_options.end())
error("option " + name_option + " declared twice"); 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(); vector<string> shocks = symbol_list.get_symbols();
for (vector<string>::const_iterator it = shocks.begin(); 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); 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(); vector<string> parameters = symbol_list.get_symbols();
for (vector<string>::const_iterator it = parameters.begin(); 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()) if (!from_name2->empty())
check_symbol_existence(*from_name2); 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; string err = *from_name1;
if (!from_name2->empty()) 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->addStatement(new SubsamplesEqualStatement(*to_name1, *to_name2, *from_name1, *from_name2,
mod_file->symbol_table)); mod_file->symbol_table));
subsample_declarations[make_pair(*to_name1, *to_name2)] = subsample_declarations[make_pair(*to_name1, *to_name2)]
subsample_declarations[make_pair(*from_name1, *from_name2)]; = subsample_declarations[make_pair(*from_name1, *from_name2)];
delete to_name1; delete to_name1;
delete to_name2; delete to_name2;
@ -1461,7 +1461,7 @@ ParsingDriver::check_subsample_declaration_exists(string *name1, string *subsamp
if (subsample_name->empty()) if (subsample_name->empty())
return; return;
string *str_empty = new string (""); string *str_empty = new string("");
check_subsample_declaration_exists(name1, str_empty, subsample_name); check_subsample_declaration_exists(name1, str_empty, subsample_name);
delete str_empty; delete str_empty;
} }
@ -1474,13 +1474,13 @@ ParsingDriver::check_subsample_declaration_exists(string *name1, string *name2,
check_symbol_existence(*name1); check_symbol_existence(*name1);
if (!name2->empty()) if (!name2->empty())
check_symbol_existence(*name2); check_symbol_existence(*name2);
subsample_declarations_t::const_iterator it = subsample_declarations.find(make_pair(*name1, *name2)); subsample_declarations_t::const_iterator it = subsample_declarations.find(make_pair(*name1, *name2));
if (it == subsample_declarations.end()) if (it == subsample_declarations.end())
{ {
it = subsample_declarations.find(make_pair(*name2, *name1)); it = subsample_declarations.find(make_pair(*name2, *name1));
if (it== subsample_declarations.end()) if (it == subsample_declarations.end())
{ {
string err = *name1; string err = *name1;
if (!name2->empty()) 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."); error("The subsample name " + *subsample_name + " was not previously declared in a subsample statement.");
} }
void void
ParsingDriver::set_prior(string *name, string *subsample_name) ParsingDriver::set_prior(string *name, string *subsample_name)
{ {
@ -1509,9 +1508,9 @@ ParsingDriver::set_prior(string *name, string *subsample_name)
} }
void 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); add_joint_parameter(*it);
mod_file->addStatement(new JointPriorStatement(joint_parameters, prior_shape, options_list)); mod_file->addStatement(new JointPriorStatement(joint_parameters, prior_shape, options_list));
joint_parameters.clear(); joint_parameters.clear();
@ -1621,7 +1620,7 @@ ParsingDriver::check_symbol_is_endogenous_or_exogenous(string *name)
{ {
check_symbol_existence(*name); check_symbol_existence(*name);
int symb_id = mod_file->symbol_table.getID(*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 eEndogenous:
case eExogenous: case eExogenous:
@ -2034,7 +2033,7 @@ ParsingDriver::ms_compute_probabilities()
void void
ParsingDriver::ms_irf() ParsingDriver::ms_irf()
{ {
mod_file->addStatement(new MSSBVARIrfStatement(symbol_list,options_list)); mod_file->addStatement(new MSSBVARIrfStatement(symbol_list, options_list));
symbol_list.clear(); symbol_list.clear();
options_list.clear(); options_list.clear();
} }
@ -2681,7 +2680,7 @@ ParsingDriver::add_model_var_or_external_function(string *function_name, bool in
if (rv.first) if (rv.first)
{ {
// assume it's a lead/lagged variable // 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); return add_model_variable(mod_file->symbol_table.getID(*function_name), (int) rv.second);
} }
else else
@ -2850,7 +2849,8 @@ ParsingDriver::add_moment_calibration_item(string *endo1, string *endo2, string
moment_calibration_constraints.push_back(c); 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->addStatement(new MomentCalibration(moment_calibration_constraints,
mod_file->symbol_table)); mod_file->symbol_table));
@ -2887,7 +2887,8 @@ ParsingDriver::add_irf_calibration_item(string *endo, string *periods, string *e
irf_calibration_constraints.push_back(c); 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->addStatement(new IrfCalibration(irf_calibration_constraints,
mod_file->symbol_table, mod_file->symbol_table,
@ -2909,7 +2910,6 @@ ParsingDriver::histval_file(string *filename)
delete filename; delete filename;
} }
void void
ParsingDriver::perfect_foresight_setup() ParsingDriver::perfect_foresight_setup()
{ {
@ -2927,7 +2927,7 @@ ParsingDriver::perfect_foresight_solver()
void void
ParsingDriver::prior_posterior_function(bool prior_func) 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(); options_list.clear();
} }
@ -2941,25 +2941,25 @@ ParsingDriver::add_ramsey_constraints_statement()
void void
ParsingDriver::ramsey_constraint_add_less(const string *name, const expr_t rhs) 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 void
ParsingDriver::ramsey_constraint_add_greater(const string *name, const expr_t rhs) 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 void
ParsingDriver::ramsey_constraint_add_less_equal(const string *name, const expr_t rhs) 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 void
ParsingDriver::ramsey_constraint_add_greater_equal(const string *name, const expr_t rhs) 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 void
@ -2996,7 +2996,6 @@ ParsingDriver::add_shock_group_element(string *name)
delete name; delete name;
} }
void void
ParsingDriver::add_shock_group(string *name) ParsingDriver::add_shock_group(string *name)
{ {

View File

@ -182,8 +182,8 @@ private:
//! Temporary storage for left/right handside of a restriction equation within an svar_identificaton block //! Temporary storage for left/right handside of a restriction equation within an svar_identificaton block
bool svar_left_handside; bool svar_left_handside;
//! Temporary storage for current restriction number in svar_identification block //! Temporary storage for current restriction number in svar_identification block
map<int,int> svar_Qi_restriction_nbr; map<int, int> svar_Qi_restriction_nbr;
map<int,int> svar_Ri_restriction_nbr; map<int, int> svar_Ri_restriction_nbr;
//! Stores undeclared model variables //! Stores undeclared model variables
set<string> undeclared_model_vars; set<string> undeclared_model_vars;
//! Temporary storage for restriction type //! Temporary storage for restriction type
@ -239,7 +239,9 @@ private:
ostringstream model_errors; ostringstream model_errors;
public: 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 //! Starts parsing, and constructs the MOD file representation
/*! The returned pointer should be deleted after use */ /*! The returned pointer should be deleted after use */
@ -449,11 +451,11 @@ public:
//! Sets the prior for a parameter //! Sets the prior for a parameter
void set_prior(string *arg1, string *arg2); void set_prior(string *arg1, string *arg2);
//! Sets the joint prior for a set of parameters //! 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 //! Adds a parameters to the list of joint parameters
void add_joint_parameter(string *name); void add_joint_parameter(string *name);
//! Adds the variance option to its temporary holding place //! 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 //! Copies the prior from_name to_name
void copy_prior(string *to_declaration_type, string *to_name1, string *to_name2, string *to_subsample_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); 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); void set_std_options(string *arg1, string *arg2);
//! Sets the prior for estimated correlation //! Sets the prior for estimated correlation
void set_corr_prior(string *arg1, string *arg2, string *arg3); 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); void set_corr_options(string *arg1, string *arg2, string *arg3);
//! Runs estimation process //! Runs estimation process
void run_estimation(); void run_estimation();
@ -534,7 +536,7 @@ public:
void run_load_params_and_steady_state(string *filename); void run_load_params_and_steady_state(string *filename);
void run_save_params_and_steady_state(string *filename); void run_save_params_and_steady_state(string *filename);
void run_identification(); 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(); void run_model_comparison();
//! Begin a planner_objective statement //! Begin a planner_objective statement
void begin_planner_objective(); void begin_planner_objective();

View File

@ -79,17 +79,17 @@ AbstractShocksStatement::writeJsonDetShocks(ostream &output) const
output << ", "; output << ", ";
output << "{\"var\": \"" << symbol_table.getName(it->first) << "\", " output << "{\"var\": \"" << symbol_table.getName(it->first) << "\", "
<< "\"values\": ["; << "\"values\": [";
for (vector<DetShockElement>::const_iterator it1 = it->second.begin(); for (vector<DetShockElement>::const_iterator it1 = it->second.begin();
it1 != it->second.end(); it1++) it1 != it->second.end(); it1++)
{ {
if (it1 != it->second.begin()) if (it1 != it->second.begin())
output << ", "; output << ", ";
output << "{\"period1\": " << it1->period1 << ", " output << "{\"period1\": " << it1->period1 << ", "
<< "\"period2\": " << it1->period2 << ", " << "\"period2\": " << it1->period2 << ", "
<< "\"value\": \""; << "\"value\": \"";
it1->value->writeJsonOutput(output, temporary_terms_t(), tef_terms); it1->value->writeJsonOutput(output, temporary_terms_t(), tef_terms);
output << "\"}"; output << "\"}";
} }
output << "]}"; output << "]}";
} }
output << "]"; output << "]";
@ -122,9 +122,9 @@ ShocksStatement::writeOutput(ostream &output, const string &basename, bool minim
output << "M_.det_shocks = [];" << endl; output << "M_.det_shocks = [];" << endl;
output << "M_.Sigma_e = zeros(" << symbol_table.exo_nbr() << ", " output << "M_.Sigma_e = zeros(" << symbol_table.exo_nbr() << ", "
<< symbol_table.exo_nbr() << ");" << endl << symbol_table.exo_nbr() << ");" << endl
<< "M_.Correlation_matrix = eye(" << symbol_table.exo_nbr() << ", " << "M_.Correlation_matrix = eye(" << symbol_table.exo_nbr() << ", "
<< symbol_table.exo_nbr() << ");" << endl; << symbol_table.exo_nbr() << ");" << endl;
if (has_calibrated_measurement_errors()) if (has_calibrated_measurement_errors())
output << "M_.H = zeros(" << symbol_table.observedVariablesNbr() << ", " output << "M_.H = zeros(" << symbol_table.observedVariablesNbr() << ", "
@ -151,7 +151,6 @@ ShocksStatement::writeOutput(ostream &output, const string &basename, bool minim
output << "M_.sigma_e_is_diagonal = 1;" << endl; output << "M_.sigma_e_is_diagonal = 1;" << endl;
} }
void void
ShocksStatement::writeJsonOutput(ostream &output) const ShocksStatement::writeJsonOutput(ostream &output) const
{ {
@ -606,7 +605,7 @@ ShockGroupsStatement::writeOutput(ostream &output, const string &basename, bool
{ {
int i = 1; int i = 1;
bool unique_label = true; 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++) for (vector<Group>::const_iterator it1 = it+1; it1 != shock_groups.end(); it1++)
if (it->name == it1->name) if (it->name == it1->name)
@ -623,7 +622,7 @@ ShockGroupsStatement::writeOutput(ostream &output, const string &basename, bool
<< ".group" << i << ".label = '" << it->name << "';" << endl << ".group" << i << ".label = '" << it->name << "';" << endl
<< "M_.shock_groups." << name << "M_.shock_groups." << name
<< ".group" << i << ".shocks = {"; << ".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 << " '" << *it1 << "'";
output << "};" << endl; output << "};" << endl;
i++; i++;

View File

@ -78,11 +78,13 @@ Statement::writeCOutput(ostream &output, const string &basename)
{ {
} }
void Statement::writeJuliaOutput(ostream &output, const string &basename) void
Statement::writeJuliaOutput(ostream &output, const string &basename)
{ {
} }
void Statement::writeJsonOutput(ostream &output) const void
Statement::writeJsonOutput(ostream &output) const
{ {
} }
@ -105,7 +107,7 @@ NativeStatement::writeOutput(ostream &output, const string &basename, bool minim
sregex regex_dollar = sregex::compile("(\\$)"+date_regex); sregex regex_dollar = sregex::compile("(\\$)"+date_regex);
string ns = regex_replace(native_statement, regex_lookbehind, "dates('$&')"); 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; output << ns << endl;
} }
@ -182,9 +184,9 @@ OptionsList::writeOutput(ostream &output, const string &option_group) const
{ {
// Initialize option_group as an empty struct iff the field does not exist! // Initialize option_group as an empty struct iff the field does not exist!
unsigned idx = option_group.find_last_of("."); 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 << " " << option_group << " = struct();" << endl;
output << "end" << endl; output << "end" << endl;
} }
@ -241,12 +243,12 @@ OptionsList::writeJsonOutput(ostream &output) const
{ {
output << "\""<< it->first << "\": " << it->second; output << "\""<< it->first << "\": " << it->second;
it++; it++;
if (it != num_options.end() || if (it != num_options.end()
!(paired_num_options.empty() && || !(paired_num_options.empty()
string_options.empty() && && string_options.empty()
date_options.empty() && && date_options.empty()
symbol_list_options.empty() && && symbol_list_options.empty()
vector_int_options.empty())) && vector_int_options.empty()))
output << ", "; output << ", ";
} }
@ -255,11 +257,11 @@ OptionsList::writeJsonOutput(ostream &output) const
{ {
output << "\""<< it->first << "\": [" << it->second.first << " " << it->second.second << "]"; output << "\""<< it->first << "\": [" << it->second.first << " " << it->second.second << "]";
it++; it++;
if (it != paired_num_options.end() || if (it != paired_num_options.end()
!(string_options.empty() && || !(string_options.empty()
date_options.empty() && && date_options.empty()
symbol_list_options.empty() && && symbol_list_options.empty()
vector_int_options.empty())) && vector_int_options.empty()))
output << ", "; output << ", ";
} }
@ -268,10 +270,10 @@ OptionsList::writeJsonOutput(ostream &output) const
{ {
output << "\""<< it->first << "\": \"" << it->second << "\""; output << "\""<< it->first << "\": \"" << it->second << "\"";
it++; it++;
if (it != string_options.end() || if (it != string_options.end()
!(date_options.empty() && || !(date_options.empty()
symbol_list_options.empty() && && symbol_list_options.empty()
vector_int_options.empty())) && vector_int_options.empty()))
output << ", "; output << ", ";
} }
@ -280,9 +282,9 @@ OptionsList::writeJsonOutput(ostream &output) const
{ {
output << "\""<< it->first << "\": \"" << it->second << "\""; output << "\""<< it->first << "\": \"" << it->second << "\"";
it++; it++;
if (it != date_options.end() || if (it != date_options.end()
!(symbol_list_options.empty() && || !(symbol_list_options.empty()
vector_int_options.empty())) && vector_int_options.empty()))
output << ", "; output << ", ";
} }
@ -292,8 +294,8 @@ OptionsList::writeJsonOutput(ostream &output) const
output << "\""<< it->first << "\":"; output << "\""<< it->first << "\":";
it->second.writeJsonOutput(output); it->second.writeJsonOutput(output);
it++; it++;
if (it != symbol_list_options.end() || if (it != symbol_list_options.end()
!vector_int_options.empty()) || !vector_int_options.empty())
output << ", "; output << ", ";
} }

View File

@ -120,7 +120,7 @@ public:
bool occbin_option; bool occbin_option;
//! Stores the original number of equations in the model_block //! Stores the original number of equations in the model_block
int orig_eq_nbr; 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; int ramsey_eq_nbr;
}; };
@ -128,7 +128,8 @@ public:
class Statement class Statement
{ {
public: public:
virtual ~Statement(); virtual
~Statement();
//! Do some internal check, and fill the ModFileStructure class //! Do some internal check, and fill the ModFileStructure class
/*! Don't forget to update ComputingTasks.hh, Shocks.hh and /*! Don't forget to update ComputingTasks.hh, Shocks.hh and
NumericalInitialization.hh if you modify the signature of this NumericalInitialization.hh if you modify the signature of this

View File

@ -661,10 +661,10 @@ StaticModel::writeModelEquationsCode_Block(const string file_name, const string
if (dynamic_cast<AbstractExternalFunctionNode *>(*it) != NULL) if (dynamic_cast<AbstractExternalFunctionNode *>(*it) != NULL)
(*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt2, map_idx, false, false, tef_terms); (*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); fnumexpr.write(code_file, instruction_number);
(*it)->compile(code_file, instruction_number, false, tt2, map_idx, false, false, tef_terms); (*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); fstpst.write(code_file, instruction_number);
// Insert current node into tt2 // Insert current node into tt2
tt2.insert(*it); tt2.insert(*it);
@ -854,12 +854,12 @@ StaticModel::writeModelEquationsCode_Block(const string file_name, const string
if (dynamic_cast<AbstractExternalFunctionNode *>(*it) != NULL) if (dynamic_cast<AbstractExternalFunctionNode *>(*it) != NULL)
(*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt3, map_idx2[block], false, false, tef_terms2); (*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); fnumexpr.write(code_file, instruction_number);
(*it)->compile(code_file, instruction_number, false, tt3, map_idx2[block], false, false, tef_terms); (*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); fstpst.write(code_file, instruction_number);
// Insert current node into tt2 // Insert current node into tt2
tt3.insert(*it); 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))); 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(); expr_t eq_tmp = aux_equations[eq]->substituteStaticAuxiliaryDefinition();
neweqs.push_back(dynamic_cast<BinaryOpNode *>(eq_tmp->toStatic(*this))); neweqs.push_back(dynamic_cast<BinaryOpNode *>(eq_tmp->toStatic(*this)));
} }
equations.clear(); 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 // Compute derivatives w.r. to all endogenous, and possibly exogenous and exogenous deterministic
set<int> vars; set<int> vars;
@ -1338,7 +1338,6 @@ StaticModel::writeStaticModel(ostream &StaticOutput, bool use_dll, bool julia) c
int id2 = getSymbIDByDerivID(var2); int id2 = getSymbIDByDerivID(var2);
int id3 = getSymbIDByDerivID(var3); int id3 = getSymbIDByDerivID(var3);
// Reference column number for the g3 matrix // Reference column number for the g3 matrix
int ref_col = id1 * hessianColsNbr + id2 * JacobianColsNbr + id3; 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 // Initialize g3 matrix
StaticOutput << "if nargout >= 4," << endl StaticOutput << "if nargout >= 4," << endl
<< " %" << endl << " %" << endl
<< " % Third order derivatives" << endl << " % Third order derivatives" << endl
<< " %" << endl << " %" << endl
<< endl; << endl;
int ncols = hessianColsNbr * JacobianColsNbr; int ncols = hessianColsNbr * JacobianColsNbr;
if (third_derivatives.size()) if (third_derivatives.size())
StaticOutput << " v3 = zeros(" << NNZDerivatives[2] << ",3);" << endl StaticOutput << " v3 = zeros(" << NNZDerivatives[2] << ",3);" << endl
<< third_derivatives_output.str() << third_derivatives_output.str()
<< " g3 = sparse(v3(:,1),v3(:,2),v3(:,3)," << nrows << "," << ncols << ");" << endl; << " g3 = sparse(v3(:,1),v3(:,2),v3(:,3)," << nrows << "," << ncols << ");" << endl;
else // Either 3rd derivatives is all zero, or we didn't compute it else // Either 3rd derivatives is all zero, or we didn't compute it
StaticOutput << " g3 = sparse([],[],[]," << nrows << "," << ncols << ");" << endl; StaticOutput << " g3 = sparse([],[],[]," << nrows << "," << ncols << ");" << endl;
StaticOutput << "end" << 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 output << "#define max(a, b) (((a) > (b)) ? (a) : (b))" << endl
<< "#define min(a, b) (((a) > (b)) ? (b) : (a))" << endl; << "#define min(a, b) (((a) > (b)) ? (b) : (a))" << endl;
// Write function definition if oPowerDeriv is used // Write function definition if oPowerDeriv is used
writePowerDerivCHeader(output); writePowerDerivCHeader(output);
writeNormcdfCHeader(output); writeNormcdfCHeader(output);
@ -1754,7 +1752,7 @@ StaticModel::writeStaticFile(const string &basename, bool block, bool bytecode,
chdir(".."); chdir("..");
writeStaticBlockMFSFile(basename); writeStaticBlockMFSFile(basename);
} }
else if(use_dll) else if (use_dll)
writeStaticCFile(basename); writeStaticCFile(basename);
else if (julia) else if (julia)
writeStaticJuliaFile(basename); writeStaticJuliaFile(basename);
@ -2129,7 +2127,8 @@ 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 func_name = basename + "_set_auxiliary_variables";
@ -2311,7 +2310,6 @@ StaticModel::writeParamsDerivativesFile(const string &basename, bool julia) cons
third_derivs1_output << ";" << endl; third_derivs1_output << ";" << endl;
} }
ofstream paramsDerivsFile; ofstream paramsDerivsFile;
string filename = julia ? basename + "StaticParamsDerivs.jl" : basename + "_static_params_derivs.m"; string filename = julia ? basename + "StaticParamsDerivs.jl" : basename + "_static_params_derivs.m";
paramsDerivsFile.open(filename.c_str(), ios::out | ios::binary); paramsDerivsFile.open(filename.c_str(), ios::out | ios::binary);
@ -2582,7 +2580,7 @@ StaticModel::writeJsonComputingPassOutput(ostream &output, bool writeDetails) co
output << "\"static_model_derivative_details\": {"; output << "\"static_model_derivative_details\": {";
else else
output << "\"static_model_derivatives\": {"; output << "\"static_model_derivatives\": {";
output << model_local_vars_output.str() output << model_local_vars_output.str()
<< ", " << model_output.str() << ", " << model_output.str()
<< ", " << jacobian_output.str() << ", " << jacobian_output.str()
<< ", " << hessian_output.str() << ", " << hessian_output.str()

View File

@ -224,12 +224,14 @@ public:
return (block_type_firstequation_size_mfs[block_number].second.first); return (block_type_firstequation_size_mfs[block_number].second.first);
}; };
//! Return the number of exogenous variable in the block block_number //! 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 0;
}; };
//! Return the number of colums in the jacobian matrix for exogenous variable in the block block_number //! 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; return 0;
} }

View File

@ -187,15 +187,15 @@ SteadyStateModel::writeSteadyStateFileC(const string &basename, bool ramsey_mode
output << "#include <math.h>" << endl; output << "#include <math.h>" << endl;
output << "void steadystate(" 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 << "// Steady state file generated by Dynare preprocessor" << endl
<< "{" << endl << "{" << endl
<< " *info = 0;" << endl; << " *info = 0;" << endl;
if (def_table.size() == 0) if (def_table.size() == 0)
{ {
output << " return;" << endl output << " return;" << endl
<< "}" << endl; << "}" << endl;
return; return;
} }
@ -204,11 +204,11 @@ SteadyStateModel::writeSteadyStateFileC(const string &basename, bool ramsey_mode
const vector<int> &symb_ids = def_table[i].first; const vector<int> &symb_ids = def_table[i].first;
output << " "; output << " ";
if (symb_ids.size() > 1) 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)); variable_node_map_t::const_iterator it = variable_node_map.find(make_pair(symb_ids[0], 0));
assert(it != variable_node_map.end()); assert(it != variable_node_map.end());
if (it->second->get_type() == eModFileLocalVariable) if (it->second->get_type() == eModFileLocalVariable)
output << "double "; output << "double ";
dynamic_cast<ExprNode *>(it->second)->writeOutput(output, oCSteadyStateFile); dynamic_cast<ExprNode *>(it->second)->writeOutput(output, oCSteadyStateFile);
output << "="; output << "=";
def_table[i].second->writeOutput(output, oCSteadyStateFile); def_table[i].second->writeOutput(output, oCSteadyStateFile);

View File

@ -44,9 +44,17 @@ public:
//! Clears all content //! Clears all content
void clear(); void clear();
//! Get a copy of the string vector //! Get a copy of the string vector
vector<string> get_symbols() const { return symbols; }; vector<string>
get_symbols() const
{
return symbols;
};
//! Is Empty //! Is Empty
int empty() const { return symbols.empty(); }; int
empty() const
{
return symbols.empty();
};
}; };
#endif #endif

View File

@ -43,7 +43,7 @@ SymbolTable::SymbolTable() : frozen(false), size(0)
} }
int 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) if (frozen)
throw FrozenException(); throw FrozenException();
@ -89,7 +89,7 @@ SymbolTable::addSymbol(const string &name, SymbolType type, const string &tex_na
{ {
map<string, string> pmv; map<string, string> pmv;
for (vector<pair<string *, string *> *>::const_iterator it = partition_value->begin(); 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); pmv[*((*it)->first)] = *((*it)->second);
partition_value_map[id] = pmv; partition_value_map[id] = pmv;
} }
@ -228,7 +228,6 @@ SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException)
<< "M_.exo_names_tex = char(M_.exo_names_tex, '" << getTeXName(exo_ids[id]) << "');" << endl << "M_.exo_names_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; << "M_.exo_names_long = char(M_.exo_names_long, '" << getLongName(exo_ids[id]) << "');" << endl;
map<string, map<int, string> > partitions = getPartitionsForType(eExogenous); map<string, map<int, string> > partitions = getPartitionsForType(eExogenous);
for (map<string, map<int, string> >::const_iterator it = partitions.begin(); for (map<string, map<int, string> >::const_iterator it = partitions.begin();
it != partitions.end(); it++) it != partitions.end(); it++)
@ -304,7 +303,7 @@ SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException)
output << it1->second; output << it1->second;
output << "' "; output << "' ";
} }
output << "};" << endl; output << "};" << endl;
} }
} }
@ -420,7 +419,7 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException)
{ {
output << "char *exo_names[" << exo_nbr() << "];" << endl; output << "char *exo_names[" << exo_nbr() << "];" << endl;
for (int id = 0; id < exo_nbr(); id++) 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 output << endl
@ -429,7 +428,7 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException)
{ {
output << "char *exo_det_names[" << exo_det_nbr() << "];" << endl; output << "char *exo_det_names[" << exo_det_nbr() << "];" << endl;
for (int id = 0; id < exo_det_nbr(); id++) 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 output << endl
@ -438,7 +437,7 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException)
{ {
output << "char *endo_names[" << endo_nbr() << "];" << endl; output << "char *endo_names[" << endo_nbr() << "];" << endl;
for (int id = 0; id < endo_nbr(); id++) 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 output << endl
@ -447,7 +446,7 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException)
{ {
output << "char *param_names[" << param_nbr() << "];" << endl; output << "char *param_names[" << param_nbr() << "];" << endl;
for (int id = 0; id < param_nbr(); id++) 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 // Write the auxiliary variable table
@ -456,24 +455,24 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException)
{ {
output << "struct aux_vars_t *av[" << aux_vars.size() << "];" << endl; output << "struct aux_vars_t *av[" << aux_vars.size() << "];" << endl;
for (int i = 0; i < (int) aux_vars.size(); i++) for (int i = 0; i < (int) aux_vars.size(); i++)
{ {
output << "av[" << i << "].endo_index = " << getTypeSpecificID(aux_vars[i].get_symb_id()) << ";" << endl output << "av[" << i << "].endo_index = " << getTypeSpecificID(aux_vars[i].get_symb_id()) << ";" << endl
<< "av[" << i << "].type = " << aux_vars[i].get_type() << ";" << endl; << "av[" << i << "].type = " << aux_vars[i].get_type() << ";" << endl;
switch (aux_vars[i].get_type()) switch (aux_vars[i].get_type())
{ {
case avEndoLead: case avEndoLead:
case avExoLead: case avExoLead:
case avExpectation: case avExpectation:
case avMultiplier: case avMultiplier:
case avDiffForward: case avDiffForward:
break; break;
case avEndoLag: case avEndoLag:
case avExoLag: case avExoLag:
output << "av[" << i << "].orig_index = " << getTypeSpecificID(aux_vars[i].get_orig_symb_id()) << ";" << endl 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; << "av[" << i << "].orig_lead_lag = " << aux_vars[i].get_orig_lead_lag() << ";" << endl;
break; break;
} }
} }
} }
output << "int predeterminedNbr = " << predeterminedNbr() << ";" << endl; output << "int predeterminedNbr = " << predeterminedNbr() << ";" << endl;
@ -481,12 +480,12 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException)
{ {
output << "int predetermined_variables[" << predeterminedNbr() << "] = {"; output << "int predetermined_variables[" << predeterminedNbr() << "] = {";
for (set<int>::const_iterator it = predetermined_variables.begin(); for (set<int>::const_iterator it = predetermined_variables.begin();
it != predetermined_variables.end(); it++) it != predetermined_variables.end(); it++)
{ {
if ( it != predetermined_variables.begin() ) if (it != predetermined_variables.begin())
output << ","; output << ",";
output << getTypeSpecificID(*it); output << getTypeSpecificID(*it);
} }
output << "};" << endl; output << "};" << endl;
} }
@ -495,13 +494,13 @@ SymbolTable::writeCOutput(ostream &output) const throw (NotYetFrozenException)
{ {
output << "int varobs[" << observedVariablesNbr() << "] = {"; output << "int varobs[" << observedVariablesNbr() << "] = {";
for (vector<int>::const_iterator it = varobs.begin(); for (vector<int>::const_iterator it = varobs.begin();
it != varobs.end(); it++) it != varobs.end(); it++)
{ {
if ( it != varobs.begin() ) if (it != varobs.begin())
output << ","; output << ",";
output << getTypeSpecificID(*it); output << getTypeSpecificID(*it);
} }
output << "};" << endl; output << "};" << endl;
} }
} }
@ -940,27 +939,27 @@ SymbolTable::writeJuliaOutput(ostream &output) const throw (NotYetFrozenExceptio
output << "]" << endl; output << "]" << endl;
} }
if (predeterminedNbr() > 0) if (predeterminedNbr() > 0)
{ {
output << "# Predetermined Variables" << endl output << "# Predetermined Variables" << endl
<< "model_.pred_vars = [ " << endl; << "model_.pred_vars = [ " << endl;
for (set<int>::const_iterator it = predetermined_variables.begin(); for (set<int>::const_iterator it = predetermined_variables.begin();
it != predetermined_variables.end(); it++) it != predetermined_variables.end(); it++)
output << " DynareModel.PredVars(" output << " DynareModel.PredVars("
<< getTypeSpecificID(*it)+1 << ")" << endl; << getTypeSpecificID(*it)+1 << ")" << endl;
output << " ]" << endl; output << " ]" << endl;
} }
if (observedVariablesNbr() > 0) if (observedVariablesNbr() > 0)
{ {
output << "# Observed Variables" << endl output << "# Observed Variables" << endl
<< "options_.obs_vars = [" << endl; << "options_.obs_vars = [" << endl;
for (vector<int>::const_iterator it = varobs.begin(); for (vector<int>::const_iterator it = varobs.begin();
it != varobs.end(); it++) it != varobs.end(); it++)
output << " DynareModel.ObsVars(" output << " DynareModel.ObsVars("
<< getTypeSpecificID(*it)+1 << ")" << endl; << getTypeSpecificID(*it)+1 << ")" << endl;
output << " ]" << endl; output << " ]" << endl;
} }
} }
void void
@ -969,7 +968,7 @@ SymbolTable::writeJsonOutput(ostream &output) const
output << "\"endogenous\": "; output << "\"endogenous\": ";
writeJsonVarVector(output, endo_ids); writeJsonVarVector(output, endo_ids);
output << ", \"exogenous\":" ; output << ", \"exogenous\":";
writeJsonVarVector(output, exo_ids); writeJsonVarVector(output, exo_ids);
output << ", \"exogenous_deterministic\": "; output << ", \"exogenous_deterministic\": ";

View File

@ -58,13 +58,41 @@ private:
expr_t expr_node; //! Auxiliary variable definition expr_t expr_node; //! Auxiliary variable definition
public: 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); 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; }; int
aux_var_t get_type() const { return type; }; get_symb_id() const
int get_orig_symb_id() const { return orig_symb_id; }; {
int get_orig_lead_lag() const { return orig_lead_lag; }; return symb_id;
int get_equation_number_for_multiplier() const { return equation_number_for_multiplier; }; };
int get_information_set() const { return information_set; }; aux_var_t
expr_t get_expr_node() const { return expr_node; } ; 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 //! Stores the symbol table
@ -250,7 +278,11 @@ public:
*/ */
int searchAuxiliaryVars(int orig_symb_id, int orig_lead_lag) const throw (SearchFailedException); int searchAuxiliaryVars(int orig_symb_id, int orig_lead_lag) const throw (SearchFailedException);
//! Returns the number of auxiliary variables //! 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 //! Retruns expr_node for an auxiliary variable
expr_t getAuxiliaryVarsExprNode(int symb_id) const throw (SearchFailedException); expr_t getAuxiliaryVarsExprNode(int symb_id) const throw (SearchFailedException);
//! Tests if symbol already exists //! Tests if symbol already exists

View File

@ -20,8 +20,9 @@
#include "WarningConsolidation.hh" #include "WarningConsolidation.hh"
#include <ostream> #include <ostream>
WarningConsolidation& WarningConsolidation
operator<< (WarningConsolidation& wcc, const string &warning) &
operator<<(WarningConsolidation &wcc, const string &warning)
{ {
if (wcc.no_warn) if (wcc.no_warn)
return wcc; return wcc;
@ -31,8 +32,8 @@ operator<< (WarningConsolidation& wcc, const string &warning)
return wcc; return wcc;
}; };
WarningConsolidation& WarningConsolidation &
operator<< (WarningConsolidation& wcc, const Dynare::location& loc) operator<<(WarningConsolidation &wcc, const Dynare::location &loc)
{ {
if (wcc.no_warn) if (wcc.no_warn)
return wcc; return wcc;
@ -54,8 +55,8 @@ operator<< (WarningConsolidation& wcc, const Dynare::location& loc)
return wcc; return wcc;
}; };
WarningConsolidation& WarningConsolidation &
operator<< (WarningConsolidation& wcc, ostream& (*pf) (ostream&)) operator<<(WarningConsolidation &wcc, ostream & (*pf)(ostream &))
{ {
if (wcc.no_warn) if (wcc.no_warn)
return wcc; return wcc;

View File

@ -34,16 +34,28 @@ private:
bool no_warn; bool no_warn;
public: public:
WarningConsolidation(bool no_warn_arg) : no_warn(no_warn_arg) { }; WarningConsolidation(bool no_warn_arg) : no_warn(no_warn_arg)
~WarningConsolidation() { }; {
};
~WarningConsolidation()
{
};
//! Add A Warning to the StringStream //! Add A Warning to the StringStream
friend WarningConsolidation& operator<< (WarningConsolidation& wcc, const string &warning); friend WarningConsolidation &operator<<(WarningConsolidation &wcc, const string &warning);
friend WarningConsolidation& operator<< (WarningConsolidation& wcc, const Dynare::location &loc); friend WarningConsolidation &operator<<(WarningConsolidation &wcc, const Dynare::location &loc);
friend WarningConsolidation& operator<< (WarningConsolidation& wcc, ostream& (*pf) (ostream&)); friend WarningConsolidation &operator<<(WarningConsolidation &wcc, ostream & (*pf)(ostream &));
inline void addWarning(const string &w) { warnings << w; }; inline void
inline void addWarning(ostream& (*pf) (ostream&)) { warnings << pf; }; addWarning(const string &w)
{
warnings << w;
};
inline void
addWarning(ostream & (*pf)(ostream &))
{
warnings << pf;
};
//! Write Warnings to m file //! Write Warnings to m file
void writeOutput(ostream &output) const; void writeOutput(ostream &output) const;

View File

@ -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. an @#endif or an @#endfor - but no newline - no longer trigger an error.
*/ */
stringstream file_with_endl; stringstream file_with_endl;
for (map<string,string>::iterator it=defines.begin(); for (map<string, string>::iterator it = defines.begin();
it!=defines.end(); it++) it != defines.end(); it++)
try try
{ {
boost::lexical_cast<int>(it->second); boost::lexical_cast<int>(it->second);
file_with_endl << "@#define " << it->first << " = " << it->second << endl; 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; file_with_endl << "@#define " << it->first << " = \"" << it->second << "\"" << endl;
} }

View File

@ -177,12 +177,13 @@ public:
//! Constructor //! Constructor
MacroDriver(); MacroDriver();
//! Destructor //! Destructor
virtual ~MacroDriver(); virtual
~MacroDriver();
//! Starts parsing a file, returns output in out //! Starts parsing a file, returns output in out
/*! \param no_line_macro should we omit the @#line statements ? */ /*! \param no_line_macro should we omit the @#line statements ? */
void parse(const string &f, ostream &out, bool debug, bool no_line_macro, 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 //! Name of main file being parsed
string file; string file;

View File

@ -49,7 +49,8 @@ public:
{ {
}; };
MacroValue(MacroDriver &driver_arg); MacroValue(MacroDriver &driver_arg);
virtual ~MacroValue(); virtual
~MacroValue();
//! Applies + operator //! Applies + operator
virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError) = 0; virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError) = 0;
//! Applies unary + operator //! Applies unary + operator
@ -118,7 +119,8 @@ private:
const int value; const int value;
public: public:
IntMV(MacroDriver &driver, int value_arg); IntMV(MacroDriver &driver, int value_arg);
virtual ~IntMV(); virtual
~IntMV();
//! Computes arithmetic addition //! Computes arithmetic addition
virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError); virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError);
//! Unary plus //! Unary plus
@ -158,7 +160,11 @@ public:
If mv2 < mv1, returns an empty range (for consistency with MATLAB). 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); 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 //! Represents a string value in macro language
@ -170,7 +176,8 @@ private:
const string value; const string value;
public: public:
StringMV(MacroDriver &driver, const string &value_arg); StringMV(MacroDriver &driver, const string &value_arg);
virtual ~StringMV(); virtual
~StringMV();
//! Computes string concatenation //! Computes string concatenation
virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError); virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError);
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; const vector<T> values;
public: public:
ArrayMV(MacroDriver &driver, const vector<T> &values_arg); ArrayMV(MacroDriver &driver, const vector<T> &values_arg);
virtual ~ArrayMV(); virtual
~ArrayMV();
//! Computes array concatenation //! Computes array concatenation
/*! Both array must be of same type */ /*! Both array must be of same type */
virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError); virtual const MacroValue *operator+(const MacroValue &mv) const throw (TypeError);