Various simplifications

master
Sébastien Villemot 2022-06-02 10:50:21 +02:00
parent 8b5e33b87a
commit 0b5c88109f
No known key found for this signature in database
GPG Key ID: 2CECE9350ECEBE4A
22 changed files with 351 additions and 493 deletions

View File

@ -104,12 +104,6 @@ ModelInfoStatement::ModelInfoStatement(OptionsList options_list_arg) :
{ {
} }
void
ModelInfoStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
{
//mod_file_struct.model_info_present = true;
}
void void
ModelInfoStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const ModelInfoStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const
{ {
@ -2045,8 +2039,7 @@ OsrParamsStatement::writeOutput(ostream &output, const string &basename, bool mi
output << "M_.osr.param_names = cellstr(M_.osr.param_names);" << endl output << "M_.osr.param_names = cellstr(M_.osr.param_names);" << endl
<< "M_.osr.param_indices = zeros(length(M_.osr.param_names), 1);" << endl; << "M_.osr.param_indices = zeros(length(M_.osr.param_names), 1);" << endl;
int i = 0; int i = 0;
vector<string> symbols = symbol_list.getSymbols(); for (auto &symbol : symbol_list.getSymbols())
for (auto &symbol : symbols)
output << "M_.osr.param_indices(" << ++i <<") = " << symbol_table.getTypeSpecificID(symbol) + 1 << ";" << endl; output << "M_.osr.param_indices(" << ++i <<") = " << symbol_table.getTypeSpecificID(symbol) + 1 << ";" << endl;
} }
@ -2235,28 +2228,28 @@ OptimWeightsStatement::writeJsonOutput(ostream &output) const
{ {
output << R"({"statementName": "optim_weights", )" output << R"({"statementName": "optim_weights", )"
<< R"("weights": [)"; << R"("weights": [)";
for (auto it = var_weights.begin(); it != var_weights.end(); ++it) bool printed_something{false};
for (const auto &[name, value] : var_weights)
{ {
if (it != var_weights.begin()) if (exchange(printed_something, true))
output << ", "; output << ", ";
output << R"({"name": ")" << it->first << R"(")" output << R"({"name": ")" << name << R"(")"
<< R"(, "value": ")"; << R"(, "value": ")";
it->second->writeJsonOutput(output, {}, {}); value->writeJsonOutput(output, {}, {});
output << R"("})"; output << R"("})";
} }
for (auto it = covar_weights.begin(); it != covar_weights.end(); ++it) for (const auto &[names, value] : covar_weights)
{ {
if (it != covar_weights.begin() || !var_weights.empty()) if (exchange(printed_something, true))
output << ", "; output << ", ";
output << R"({"name1": ")" << it->first.first << R"(")" output << R"({"name1": ")" << names.first << R"(")"
<< R"(, "name2": ")" << it->first.second << R"(")" << R"(, "name2": ")" << names.second << R"(")"
<< R"(, "value": ")"; << R"(, "value": ")";
it->second->writeJsonOutput(output, {}, {}); value->writeJsonOutput(output, {}, {});
output << R"("})"; output << R"("})";
} }
output << "]" output << "]}";
<< "}";
} }
DynaSaveStatement::DynaSaveStatement(SymbolList symbol_list_arg, string filename_arg, DynaSaveStatement::DynaSaveStatement(SymbolList symbol_list_arg, string filename_arg,
@ -2357,14 +2350,13 @@ ModelComparisonStatement::writeOutput(ostream &output, const string &basename, b
{ {
options_list.writeOutput(output); options_list.writeOutput(output);
output << "ModelNames_ = {};" << endl; output << "ModelNames_ = {};" << endl
output << "ModelPriors_ = [];" << endl; << "ModelPriors_ = [];" << endl;
for (const auto &[name, prior] : filename_list)
output << "ModelNames_ = { ModelNames_{:} '" << name << "'};" << endl
<< "ModelPriors_ = [ ModelPriors_ ; " << prior << "];" << endl;
for (const auto &it : filename_list)
{
output << "ModelNames_ = { ModelNames_{:} '" << it.first << "'};" << endl;
output << "ModelPriors_ = [ ModelPriors_ ; " << it.second << "];" << endl;
}
output << "oo_ = model_comparison(ModelNames_,ModelPriors_,oo_,options_,M_.fname);" << endl; output << "oo_ = model_comparison(ModelNames_,ModelPriors_,oo_,options_,M_.fname);" << endl;
} }
@ -2433,8 +2425,8 @@ PlannerObjectiveStatement::writeOutput(ostream &output, const string &basename,
output << "M_.NNZDerivatives_objective = ["; output << "M_.NNZDerivatives_objective = [";
for (int i=1; i < static_cast<int>(model_tree.getNNZDerivatives().size()); i++) for (int i=1; i < static_cast<int>(model_tree.getNNZDerivatives().size()); i++)
output << (i > model_tree.getComputedDerivsOrder() ? -1 : model_tree.getNNZDerivatives()[i]) << ";"; output << (i > model_tree.getComputedDerivsOrder() ? -1 : model_tree.getNNZDerivatives()[i]) << ";";
output << "];" << endl; output << "];" << endl
output << "M_.objective_tmp_nbr = ["; << "M_.objective_tmp_nbr = [";
for (const auto &temporary_terms_derivative : model_tree.getTemporaryTermsDerivatives()) for (const auto &temporary_terms_derivative : model_tree.getTemporaryTermsDerivatives())
output << temporary_terms_derivative.size() << "; "; output << temporary_terms_derivative.size() << "; ";
output << "];" << endl; output << "];" << endl;
@ -3334,8 +3326,7 @@ SvarIdentificationStatement::getMaxLag() const
{ {
int max_lag = 0; int max_lag = 0;
for (const auto &restriction : restrictions) for (const auto &restriction : restrictions)
if (restriction.lag > max_lag) max_lag = max(restriction.lag, max_lag);
max_lag = restriction.lag;
return max_lag; return max_lag;
} }
@ -3565,13 +3556,12 @@ MarkovSwitchingStatement::checkPass(ModFileStructure &mod_file_struct, WarningCo
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
else else if (row_trans_prob_sum[i] >= 1.0)
if (row_trans_prob_sum[i] >= 1.0) {
{ cerr << "ERROR: When transition probabilites are not specified for every regime, "
cerr << "ERROR: When transition probabilites are not specified for every regime, " << "their sum must be < 1" << endl;
<< "their sum must be < 1" << endl; exit(EXIT_FAILURE);
exit(EXIT_FAILURE); }
}
if (all_restrictions_in_col[i]) if (all_restrictions_in_col[i])
{ {
@ -3582,13 +3572,12 @@ MarkovSwitchingStatement::checkPass(ModFileStructure &mod_file_struct, WarningCo
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
else else if (col_trans_prob_sum[i] >= 1.0)
if (col_trans_prob_sum[i] >= 1.0) {
{ cerr << "ERROR: When transition probabilites are not specified for every regime, "
cerr << "ERROR: When transition probabilites are not specified for every regime, " << "their sum must be < 1" << endl;
<< "their sum must be < 1" << endl; exit(EXIT_FAILURE);
exit(EXIT_FAILURE); }
}
} }
} }
@ -3636,10 +3625,10 @@ MarkovSwitchingStatement::writeOutput(ostream &output, const string &basename, b
} }
int restrictions_index = 0; int restrictions_index = 0;
for (auto itR = restriction_map.begin(); itR != restriction_map.end(); itR++) for (const auto &[regimes, prob] : restriction_map)
output << "options_.ms.ms_chain(" << itChain->second << ").restrictions(" output << "options_.ms.ms_chain(" << itChain->second << ").restrictions("
<< ++restrictions_index << ") = {[" << itR->first.first << ", " << ++restrictions_index << ") = {[" << regimes.first << ", "
<< itR->first.second << ", " << itR->second << "]};" << endl; << regimes.second << ", " << prob << "]};" << endl;
} }
void void
@ -5115,13 +5104,10 @@ GenerateIRFsStatement::writeOutput(ostream &output, const string &basename, bool
<< generate_irf_names.size() << ");" << endl; << generate_irf_names.size() << ");" << endl;
for (size_t i = 0; i < generate_irf_names.size(); i++) for (size_t i = 0; i < generate_irf_names.size(); i++)
{ for (auto &[exo_name, exo_value] : generate_irf_elements[i])
map<string, double> m = generate_irf_elements[i]; output << "options_.irf_opt.irf_shocks(M_.exo_names == '"
for (auto &it : m) << exo_name << "', " << i + 1 << ") = "
output << "options_.irf_opt.irf_shocks(M_.exo_names == '" << exo_value << ";" << endl;
<< it.first << "', " << i + 1 << ") = "
<< it.second << ";" << endl;
}
} }
void void

View File

@ -123,7 +123,6 @@ private:
const OptionsList options_list; const OptionsList options_list;
public: public:
explicit ModelInfoStatement(OptionsList options_list_arg); explicit ModelInfoStatement(OptionsList options_list_arg);
void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) override;
void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const override; void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream &output) const override; void writeJsonOutput(ostream &output) const override;
}; };

View File

@ -2098,31 +2098,29 @@ DynamicModel::writeDynamicModel(const string &basename, ostream &DynamicOutput,
writeDynamicMatlabCompatLayer(basename); writeDynamicMatlabCompatLayer(basename);
} }
else if (output_type == ExprNodeOutputType::CDynamicModel) else if (output_type == ExprNodeOutputType::CDynamicModel)
{ for (size_t i = 0; i < d_output.size(); i++)
for (size_t i = 0; i < d_output.size(); i++) {
{ string funcname = i == 0 ? "resid" : "g" + to_string(i);
string funcname = i == 0 ? "resid" : "g" + to_string(i); DynamicOutput << "void dynamic_" << funcname << "_tt(const double *restrict y, const double *restrict x, int nb_row_x, const double *restrict params, const double *restrict steady_state, int it_, double *restrict T)" << endl
DynamicOutput << "void dynamic_" << funcname << "_tt(const double *restrict y, const double *restrict x, int nb_row_x, const double *restrict params, const double *restrict steady_state, int it_, double *restrict T)" << endl << "{" << endl
<< "{" << endl << tt_output[i].str()
<< tt_output[i].str() << "}" << endl
<< "}" << endl << endl
<< endl << "void dynamic_" << funcname << "(const double *restrict y, const double *restrict x, int nb_row_x, const double *restrict params, const double *restrict steady_state, int it_, const double *restrict T, ";
<< "void dynamic_" << funcname << "(const double *restrict y, const double *restrict x, int nb_row_x, const double *restrict params, const double *restrict steady_state, int it_, const double *restrict T, "; if (i == 0)
if (i == 0) DynamicOutput << "double *restrict residual";
DynamicOutput << "double *restrict residual"; else if (i == 1)
else if (i == 1) DynamicOutput << "double *restrict g1";
DynamicOutput << "double *restrict g1"; else
else DynamicOutput << "double *restrict " << funcname << "_i, double *restrict " << funcname << "_j, double *restrict " << funcname << "_v";
DynamicOutput << "double *restrict " << funcname << "_i, double *restrict " << funcname << "_j, double *restrict " << funcname << "_v"; DynamicOutput << ")" << endl
DynamicOutput << ")" << endl << "{" << endl;
<< "{" << endl; if (i == 0)
if (i == 0) DynamicOutput << " double lhs, rhs;" << endl;
DynamicOutput << " double lhs, rhs;" << endl; DynamicOutput << d_output[i].str()
DynamicOutput << d_output[i].str() << "}" << endl
<< "}" << endl << endl;
<< endl; }
}
}
else else
{ {
stringstream output; stringstream output;
@ -2516,23 +2514,21 @@ DynamicModel::removeEquationsHelper(set<pair<string, string>> &listed_eqs_by_tag
if (eqs_to_delete_by_number.contains(i)) if (eqs_to_delete_by_number.contains(i))
{ {
if (excluded_vars_change_type) if (excluded_vars_change_type)
{ if (auto tmp = all_equation_tags.getTagValueByEqnAndKey(i, "endogenous"); !tmp.empty())
if (auto tmp = all_equation_tags.getTagValueByEqnAndKey(i, "endogenous"); !tmp.empty()) excluded_vars.push_back(symbol_table.getID(tmp));
excluded_vars.push_back(symbol_table.getID(tmp)); else
else {
{ set<int> result;
set<int> result; all_equations[i]->arg1->collectVariables(SymbolType::endogenous, result);
all_equations[i]->arg1->collectVariables(SymbolType::endogenous, result); if (result.size() == 1)
if (result.size() == 1) excluded_vars.push_back(*result.begin());
excluded_vars.push_back(*result.begin()); else
else {
{ cerr << "ERROR: Equation " << i+1
cerr << "ERROR: Equation " << i+1 << " has been excluded but it does not have a single variable on its left-hand side or an `endogenous` tag" << endl;
<< " has been excluded but it does not have a single variable on its left-hand side or an `endogenous` tag" << endl; exit(EXIT_FAILURE);
exit(EXIT_FAILURE); }
} }
}
}
} }
else else
{ {
@ -2976,16 +2972,15 @@ DynamicModel::writeDriverOutput(ostream &output, const string &basename, bool bl
nboth += sboth; nboth += sboth;
output << ";"; output << ";";
} }
output << "]';" << endl; output << "]';" << endl
output << "M_.nstatic = " << nstatic << ";" << endl << "M_.nstatic = " << nstatic << ";" << endl
<< "M_.nfwrd = " << nfwrd << ";" << endl << "M_.nfwrd = " << nfwrd << ";" << endl
<< "M_.npred = " << npred << ";" << endl << "M_.npred = " << npred << ";" << endl
<< "M_.nboth = " << nboth << ";" << endl << "M_.nboth = " << nboth << ";" << endl
<< "M_.nsfwrd = " << nfwrd+nboth << ";" << endl << "M_.nsfwrd = " << nfwrd+nboth << ";" << endl
<< "M_.nspred = " << npred+nboth << ";" << endl << "M_.nspred = " << npred+nboth << ";" << endl
<< "M_.ndynamic = " << npred+nboth+nfwrd << ";" << endl; << "M_.ndynamic = " << npred+nboth+nfwrd << ";" << endl
<< "M_.dynamic_tmp_nbr = [";
output << "M_.dynamic_tmp_nbr = [";
for (size_t i = 0; i < temporary_terms_derivatives.size(); i++) for (size_t i = 0; i < temporary_terms_derivatives.size(); i++)
output << temporary_terms_derivatives[i].size() + (i == 0 ? temporary_terms_mlv.size() : 0) << "; "; output << temporary_terms_derivatives[i].size() + (i == 0 ? temporary_terms_mlv.size() : 0) << "; ";
output << "];" << endl; output << "];" << endl;
@ -3719,10 +3714,7 @@ DynamicModel::getUndiffLHSForPac(const string &aux_model_name,
for (auto eqn : nontrend_eqnums) for (auto eqn : nontrend_eqnums)
{ {
int i = 0; auto i = distance(eqnumber.begin(), find(eqnumber.begin(), eqnumber.end(), eqn));
for (auto it1 = eqnumber.begin(); it1 != eqnumber.end(); ++it1, i++)
if (*it1 == eqn)
break;
if (eqnumber[i] != eqn) if (eqnumber[i] != eqn)
{ {
@ -4554,7 +4546,7 @@ DynamicModel::writeDynamicFile(const string &basename, bool block, bool use_dll,
{ {
writeDynamicPerBlockCFiles(basename); writeDynamicPerBlockCFiles(basename);
writeDynamicBlockCFile(basename); writeDynamicBlockCFile(basename);
vector<filesystem::path> src_files{blocks.size() + 1}; vector<filesystem::path> src_files(blocks.size() + 1);
for (int blk = 0; blk < static_cast<int>(blocks.size()); blk++) for (int blk = 0; blk < static_cast<int>(blocks.size()); blk++)
src_files[blk] = model_dir / "src" / ("dynamic_" + to_string(blk+1) + ".c"); src_files[blk] = model_dir / "src" / ("dynamic_" + to_string(blk+1) + ".c");
src_files[blocks.size()] = model_dir / "src" / "dynamic.c"; src_files[blocks.size()] = model_dir / "src" / "dynamic.c";
@ -4684,10 +4676,8 @@ DynamicModel::computeRamseyPolicyFOCs(const StaticModel &static_model)
for (const auto &[symb_id, lag] : dynvars) for (const auto &[symb_id, lag] : dynvars)
{ {
if (max_eq_lead < lag) max_eq_lead = max(lag, max_eq_lead);
max_eq_lead = lag; max_eq_lag = max(-lag, max_eq_lag);
else if (-max_eq_lag > lag)
max_eq_lag = -lag;
} }
// Get Discount Factor // Get Discount Factor
@ -4741,11 +4731,7 @@ DynamicModel::computeRamseyPolicyFOCs(const StaticModel &static_model)
{ {
// This is a derivative w.r.t. a Lagrange multiplier // This is a derivative w.r.t. a Lagrange multiplier
neweqs_lineno.push_back(old_equations_lineno[*i]); neweqs_lineno.push_back(old_equations_lineno[*i]);
map<string, string> tags; neweqs_tags[neweqs.size()-1] = old_equation_tags.getTagsByEqn(*i);
auto tmp = old_equation_tags.getTagsByEqn(*i);
for (const auto &[key, value] : tmp)
tags[key] = value;
neweqs_tags[neweqs.size()-1] = tags;
} }
else else
neweqs_lineno.push_back(nullopt); neweqs_lineno.push_back(nullopt);
@ -4845,10 +4831,9 @@ DynamicModel::setLeadsLagsOrig()
max_lag_with_diffs_expanded_orig); max_lag_with_diffs_expanded_orig);
} }
for (const auto &dynvar : dynvars) for (const auto &[symb_id, lag] : dynvars)
{ {
int lag = dynvar.second; SymbolType type = symbol_table.getType(symb_id);
SymbolType type = symbol_table.getType(dynvar.first);
max_lead_orig = max(lag, max_lead_orig); max_lead_orig = max(lag, max_lead_orig);
max_lag_orig = max(-lag, max_lag_orig); max_lag_orig = max(-lag, max_lag_orig);
@ -4892,10 +4877,9 @@ DynamicModel::computeDerivIDs()
equation->collectDynamicVariables(SymbolType::logTrend, dynvars); equation->collectDynamicVariables(SymbolType::logTrend, dynvars);
} }
for (const auto &dynvar : dynvars) for (const auto &[symb_id, lag] : dynvars)
{ {
int lag = dynvar.second; SymbolType type = symbol_table.getType(symb_id);
SymbolType type = symbol_table.getType(dynvar.first);
/* Setting maximum and minimum lags. /* Setting maximum and minimum lags.
@ -4929,8 +4913,8 @@ DynamicModel::computeDerivIDs()
// Create a new deriv_id // Create a new deriv_id
int deriv_id = deriv_id_table.size(); int deriv_id = deriv_id_table.size();
deriv_id_table[dynvar] = deriv_id; deriv_id_table[{symb_id, lag}] = deriv_id;
inv_deriv_id_table.push_back(dynvar); inv_deriv_id_table.emplace_back(symb_id, lag);
} }
} }
@ -4961,8 +4945,8 @@ DynamicModel::getSymbIDByDerivID(int deriv_id) const noexcept(false)
int int
DynamicModel::getDerivID(int symb_id, int lag) const noexcept(false) DynamicModel::getDerivID(int symb_id, int lag) const noexcept(false)
{ {
auto it = deriv_id_table.find({ symb_id, lag }); if (auto it = deriv_id_table.find({ symb_id, lag });
if (it == deriv_id_table.end()) it == deriv_id_table.end())
throw UnknownDerivIDException(); throw UnknownDerivIDException();
else else
return it->second; return it->second;
@ -4983,11 +4967,9 @@ DynamicModel::computeDynJacobianCols(bool jacobianExo)
and fill the dynamic columns for exogenous and exogenous deterministic */ and fill the dynamic columns for exogenous and exogenous deterministic */
map<pair<int, int>, int> ordered_dyn_endo; map<pair<int, int>, int> ordered_dyn_endo;
for (auto &it : deriv_id_table) for (auto &[symb_lag, deriv_id] : deriv_id_table)
{ {
int symb_id = it.first.first; auto &[symb_id, lag] = symb_lag;
int lag = it.first.second;
int deriv_id = it.second;
SymbolType type = symbol_table.getType(symb_id); SymbolType type = symbol_table.getType(symb_id);
int tsid = symbol_table.getTypeSpecificID(symb_id); int tsid = symbol_table.getTypeSpecificID(symb_id);
@ -5041,9 +5023,10 @@ DynamicModel::getDynJacobianCol(int deriv_id) const noexcept(false)
void void
DynamicModel::testTrendDerivativesEqualToZero(const eval_context_t &eval_context) DynamicModel::testTrendDerivativesEqualToZero(const eval_context_t &eval_context)
{ {
for (auto &it : deriv_id_table) for (auto &[symb_lag1, deriv_id1] : deriv_id_table)
if (symbol_table.getType(it.first.first) == SymbolType::trend if (auto &[symb_id1, lag1] = symb_lag1;
|| symbol_table.getType(it.first.first) == SymbolType::logTrend) symbol_table.getType(symb_id1) == SymbolType::trend
|| symbol_table.getType(symb_id1) == SymbolType::logTrend)
for (int eq = 0; eq < static_cast<int>(equations.size()); eq++) for (int eq = 0; eq < static_cast<int>(equations.size()); eq++)
{ {
expr_t homogeneq = AddMinus(equations[eq]->arg1, expr_t homogeneq = AddMinus(equations[eq]->arg1,
@ -5053,19 +5036,20 @@ DynamicModel::testTrendDerivativesEqualToZero(const eval_context_t &eval_context
if (fabs(homogeneq->eval(eval_context)) > zero_band) if (fabs(homogeneq->eval(eval_context)) > zero_band)
{ {
expr_t testeq = AddLog(homogeneq); // F = log(lhs-rhs) expr_t testeq = AddLog(homogeneq); // F = log(lhs-rhs)
testeq = testeq->getDerivative(it.second); // d F / d Trend testeq = testeq->getDerivative(deriv_id1); // d F / d Trend
for (auto &endogit : deriv_id_table) for (auto &[symb_lag2, deriv_id2] : deriv_id_table)
if (symbol_table.getType(endogit.first.first) == SymbolType::endogenous) if (auto &[symb_id2, lag2] = symb_lag2;
symbol_table.getType(symb_id2) == SymbolType::endogenous)
{ {
double nearZero = testeq->getDerivative(endogit.second)->eval(eval_context); // eval d F / d Trend d Endog double nearZero = testeq->getDerivative(deriv_id2)->eval(eval_context); // eval d F / d Trend d Endog
if (fabs(nearZero) > balanced_growth_test_tol) if (fabs(nearZero) > balanced_growth_test_tol)
{ {
cerr << "ERROR: trends not compatible with balanced growth path; the second-order cross partial of equation " << eq + 1; cerr << "ERROR: trends not compatible with balanced growth path; the second-order cross partial of equation " << eq + 1;
if (equations_lineno[eq]) if (equations_lineno[eq])
cerr << " (line " << *equations_lineno[eq] << ")"; cerr << " (line " << *equations_lineno[eq] << ")";
cerr << "w.r.t. trend variable " cerr << "w.r.t. trend variable "
<< symbol_table.getName(it.first.first) << " and endogenous variable " << symbol_table.getName(symb_id1) << " and endogenous variable "
<< symbol_table.getName(endogit.first.first) << " is not null (abs. value = " << symbol_table.getName(symb_id2) << " is not null (abs. value = "
<< fabs(nearZero) << "). If you are confident that your trends are correctly specified, you can raise the value of option 'balanced_growth_test_tol' in the 'model' block." << endl; << fabs(nearZero) << "). If you are confident that your trends are correctly specified, you can raise the value of option 'balanced_growth_test_tol' in the 'model' block." << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -5677,22 +5661,22 @@ DynamicModel::substituteDiff(VarExpectationModelTable &var_expectation_model_tab
// Mark diff operators to be substituted in model local variables // Mark diff operators to be substituted in model local variables
set<int> used_local_vars; set<int> used_local_vars;
for (const auto &equation : equations) for (auto equation : equations)
equation->collectVariables(SymbolType::modelLocalVariable, used_local_vars); equation->collectVariables(SymbolType::modelLocalVariable, used_local_vars);
for (auto &it : local_variables_table) for (auto &[symb_id, expr] : local_variables_table)
if (used_local_vars.contains(it.first)) if (used_local_vars.contains(symb_id))
it.second->findDiffNodes(diff_nodes); expr->findDiffNodes(diff_nodes);
// Mark diff operators to be substituted in equations // Mark diff operators to be substituted in equations
for (const auto &equation : equations) for (auto equation : equations)
equation->findDiffNodes(diff_nodes); equation->findDiffNodes(diff_nodes);
pac_model_table.findDiffNodesInGrowth(diff_nodes); pac_model_table.findDiffNodesInGrowth(diff_nodes);
// Substitute in model local variables // Substitute in model local variables
vector<BinaryOpNode *> neweqs; vector<BinaryOpNode *> neweqs;
for (auto &it : local_variables_table) for (auto &[symb_id, expr] : local_variables_table)
it.second = it.second->substituteDiff(diff_nodes, diff_subst_table, neweqs); expr = expr->substituteDiff(diff_nodes, diff_subst_table, neweqs);
// Substitute in equations // Substitute in equations
for (auto &equation : equations) for (auto &equation : equations)
@ -5707,7 +5691,7 @@ DynamicModel::substituteDiff(VarExpectationModelTable &var_expectation_model_tab
pac_model_table.substituteDiffNodesInGrowth(diff_nodes, diff_subst_table, neweqs); pac_model_table.substituteDiffNodesInGrowth(diff_nodes, diff_subst_table, neweqs);
// Add new equations // Add new equations
for (auto &neweq : neweqs) for (auto neweq : neweqs)
{ {
addEquation(neweq, nullopt); addEquation(neweq, nullopt);
aux_equations.push_back(neweq); aux_equations.push_back(neweq);
@ -5726,8 +5710,8 @@ DynamicModel::substituteExpectation(bool partial_information_model)
vector<BinaryOpNode *> neweqs; vector<BinaryOpNode *> neweqs;
// Substitute in model local variables // Substitute in model local variables
for (auto &it : local_variables_table) for (auto &[symb_id, expr] : local_variables_table)
it.second = it.second->substituteExpectation(subst_table, neweqs, partial_information_model); expr = expr->substituteExpectation(subst_table, neweqs, partial_information_model);
// Substitute in equations // Substitute in equations
for (auto &equation : equations) for (auto &equation : equations)
@ -5740,7 +5724,7 @@ DynamicModel::substituteExpectation(bool partial_information_model)
operators in [static] equations are forbidden at the parsing level. */ operators in [static] equations are forbidden at the parsing level. */
// Add new equations // Add new equations
for (auto &neweq : neweqs) for (auto neweq : neweqs)
{ {
addEquation(neweq, nullopt); addEquation(neweq, nullopt);
aux_equations.push_back(neweq); aux_equations.push_back(neweq);
@ -5902,13 +5886,12 @@ DynamicModel::fillEvalContext(eval_context_t &eval_context) const
} }
// Second, model local variables // Second, model local variables
for (auto it : local_variables_table) for (auto &[symb_id, expression] : local_variables_table)
{ {
try try
{ {
const expr_t expression = it.second;
double val = expression->eval(eval_context); double val = expression->eval(eval_context);
eval_context[it.first] = val; eval_context[symb_id] = val;
} }
catch (ExprNode::EvalException &e) catch (ExprNode::EvalException &e)
{ {

View File

@ -631,7 +631,7 @@ public:
auto auto
getStaticOnlyEquationsInfo() const getStaticOnlyEquationsInfo() const
{ {
return tuple(static_only_equations, static_only_equations_lineno, static_only_equations_equation_tags); return tuple{static_only_equations, static_only_equations_lineno, static_only_equations_equation_tags};
}; };
//! Returns true if a parameter was used in the model block with a lead or lag //! Returns true if a parameter was used in the model block with a lead or lag

View File

@ -3286,25 +3286,16 @@ UnaryOpNode::substituteAdl() const
expr_t arg1subst = arg->substituteAdl(); expr_t arg1subst = arg->substituteAdl();
expr_t retval = nullptr; expr_t retval = nullptr;
ostringstream inttostr;
for (auto it = adl_lags.begin(); it != adl_lags.end(); ++it) for (auto it = adl_lags.begin(); it != adl_lags.end(); ++it)
if (it == adl_lags.begin()) {
{ expr_t e = datatree.AddTimes(datatree.AddVariable(datatree.symbol_table.getID(adl_param_name + "_lag_" + to_string(*it)), 0),
inttostr << *it;
retval = datatree.AddTimes(datatree.AddVariable(datatree.symbol_table.getID(adl_param_name + "_lag_" + inttostr.str()), 0),
arg1subst->decreaseLeadsLags(*it)); arg1subst->decreaseLeadsLags(*it));
} if (it == adl_lags.begin())
else retval = e;
{ else
inttostr.clear(); retval = datatree.AddPlus(retval, e);
inttostr.str(""); }
inttostr << *it;
retval = datatree.AddPlus(retval,
datatree.AddTimes(datatree.AddVariable(datatree.symbol_table.getID(adl_param_name + "_lag_"
+ inttostr.str()), 0),
arg1subst->decreaseLeadsLags(*it)));
}
return retval; return retval;
} }

View File

@ -218,7 +218,7 @@ protected:
inline static int inline static int
min_cost(bool is_matlab) min_cost(bool is_matlab)
{ {
return (is_matlab ? min_cost_matlab : min_cost_c); return is_matlab ? min_cost_matlab : min_cost_c;
}; };
//! Cost of computing current node //! Cost of computing current node
@ -230,10 +230,7 @@ protected:
//! For creating equation cross references //! For creating equation cross references
struct EquationInfo struct EquationInfo
{ {
set<pair<int, int>> param; set<pair<int, int>> param, endo, exo, exo_det;
set<pair<int, int>> endo;
set<pair<int, int>> exo;
set<pair<int, int>> exo_det;
}; };
//! If this node is a temporary term, writes its temporary term representation //! If this node is a temporary term, writes its temporary term representation

View File

@ -24,6 +24,7 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include <map> #include <map>
#include <algorithm>
using namespace std; using namespace std;
@ -112,12 +113,8 @@ ExternalFunctionsTable::getSecondDerivSymbID(int symb_id) const noexcept(false)
inline int inline int
ExternalFunctionsTable::get_total_number_of_unique_model_block_external_functions() const ExternalFunctionsTable::get_total_number_of_unique_model_block_external_functions() const
{ {
int number_of_unique_model_block_external_functions = 0; return count_if(externalFunctionTable.begin(), externalFunctionTable.end(),
for (const auto &it : externalFunctionTable) [](const auto &kv) { return kv.second.nargs > 0; });
if (it.second.nargs > 0)
number_of_unique_model_block_external_functions++;
return number_of_unique_model_block_external_functions;
} }
#endif #endif

View File

@ -743,11 +743,9 @@ ModFile::computingPass(bool no_tmp_terms, OutputType output, int params_derivs_o
foresight model, because the Hessian is not computed in that case. */ foresight model, because the Hessian is not computed in that case. */
if (linear) if (linear)
{ {
set<int> eqs; set<int> eqs = mod_file_struct.ramsey_model_present ?
if (mod_file_struct.ramsey_model_present) orig_ramsey_dynamic_model.getNonZeroHessianEquations() :
eqs = orig_ramsey_dynamic_model.getNonZeroHessianEquations(); dynamic_model.getNonZeroHessianEquations();
else
eqs = dynamic_model.getNonZeroHessianEquations();
if (!eqs.empty()) if (!eqs.empty())
{ {

View File

@ -64,8 +64,7 @@ SteadyStateModel::addDefinition(int symb_id, expr_t expr)
|| symbol_table.getType(symb_id) == SymbolType::parameter); || symbol_table.getType(symb_id) == SymbolType::parameter);
// Add the variable // Add the variable
vector<int> v; vector<int> v{symb_id};
v.push_back(symb_id);
def_table.emplace_back(v, expr); def_table.emplace_back(v, expr);
} }
@ -89,28 +88,23 @@ SteadyStateModel::checkPass(ModFileStructure &mod_file_struct, WarningConsolidat
return; return;
mod_file_struct.steady_state_model_present = true; mod_file_struct.steady_state_model_present = true;
vector<int> so_far_defined; set<int> so_far_defined;
for (const auto &i : def_table) for (const auto &[symb_ids, expr] : def_table)
{ {
const vector<int> &symb_ids = i.first;
// Check that symbols are not already defined // Check that symbols are not already defined
for (int symb_id : symb_ids) for (int symb_id : symb_ids)
if (find(so_far_defined.begin(), so_far_defined.end(), symb_id) if (so_far_defined.contains(symb_id))
!= so_far_defined.end())
warnings << "WARNING: in the 'steady_state_model' block, variable '" << symbol_table.getName(symb_id) << "' is declared twice" << endl; warnings << "WARNING: in the 'steady_state_model' block, variable '" << symbol_table.getName(symb_id) << "' is declared twice" << endl;
// Check that expression has no undefined symbol // Check that expression has no undefined symbol
if (!mod_file_struct.ramsey_model_present) if (!mod_file_struct.ramsey_model_present)
{ {
set<int> used_symbols; set<int> used_symbols;
const expr_t &expr = i.second;
expr->collectVariables(SymbolType::endogenous, used_symbols); expr->collectVariables(SymbolType::endogenous, used_symbols);
expr->collectVariables(SymbolType::modFileLocalVariable, used_symbols); expr->collectVariables(SymbolType::modFileLocalVariable, used_symbols);
for (int used_symbol : used_symbols) for (int used_symbol : used_symbols)
if (find(so_far_defined.begin(), so_far_defined.end(), used_symbol) if (!so_far_defined.contains(used_symbol))
== so_far_defined.end())
{ {
cerr << "ERROR: in the 'steady_state_model' block, variable '" << symbol_table.getName(used_symbol) cerr << "ERROR: in the 'steady_state_model' block, variable '" << symbol_table.getName(used_symbol)
<< "' is undefined in the declaration of variable '" << symbol_table.getName(symb_ids[0]) << "'" << endl; << "' is undefined in the declaration of variable '" << symbol_table.getName(symb_ids[0]) << "'" << endl;
@ -118,7 +112,7 @@ SteadyStateModel::checkPass(ModFileStructure &mod_file_struct, WarningConsolidat
} }
} }
copy(symb_ids.begin(), symb_ids.end(), back_inserter(so_far_defined)); so_far_defined.insert(symb_ids.begin(), symb_ids.end());
} }
/* Check that all original endogous are defined (except the instruments of a /* Check that all original endogous are defined (except the instruments of a
@ -129,11 +123,8 @@ SteadyStateModel::checkPass(ModFileStructure &mod_file_struct, WarningConsolidat
for (const auto &s : mod_file_struct.instruments.getSymbols()) for (const auto &s : mod_file_struct.instruments.getSymbols())
should_be_defined.erase(symbol_table.getID(s)); should_be_defined.erase(symbol_table.getID(s));
for (int v : should_be_defined) for (int v : should_be_defined)
{ if (!so_far_defined.contains(v))
if (find(so_far_defined.begin(), so_far_defined.end(), v) warnings << "WARNING: in the 'steady_state_model' block, variable '" << symbol_table.getName(v) << "' is not assigned a value" << endl;
== so_far_defined.end())
warnings << "WARNING: in the 'steady_state_model' block, variable '" << symbol_table.getName(v) << "' is not assigned a value" << endl;
}
} }
void void
@ -327,23 +318,23 @@ Epilogue::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &war
return; return;
} }
vector<int> so_far_defined; set<int> so_far_defined;
for (const auto &it : dynamic_def_table) for (const auto &[symb_id, expr] : dynamic_def_table)
if (find(so_far_defined.begin(), so_far_defined.end(), it.first) != so_far_defined.end()) if (so_far_defined.contains(symb_id))
{ {
cerr << "WARNING: in the 'epilogue' block, variable '" << symbol_table.getName(it.first) cerr << "WARNING: in the 'epilogue' block, variable '" << symbol_table.getName(symb_id)
<< "' is declared twice" << endl; << "' is declared twice" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
else else
so_far_defined.push_back(it.first); so_far_defined.insert(symb_id);
} }
void void
Epilogue::toStatic() Epilogue::toStatic()
{ {
for (const auto & [symb_id, expr] : dynamic_def_table) for (const auto & [symb_id, expr] : dynamic_def_table)
static_def_table.emplace_back(make_pair(symb_id, expr->toStatic(*this))); static_def_table.emplace_back(symb_id, expr->toStatic(*this));
} }
void void

View File

@ -1209,9 +1209,7 @@ ModelTree::fixNestedParenthesis(ostringstream &output, map<string, string> &tmp_
if (auto it = tmp_paren_vars.find(val); if (auto it = tmp_paren_vars.find(val);
it == tmp_paren_vars.end()) it == tmp_paren_vars.end())
{ {
ostringstream ptvstr; varname = "paren32_tmp_var_" + to_string(i1++);
ptvstr << i1++;
varname = "paren32_tmp_var_" + ptvstr.str();
repstr = repstr + varname + " = " + val + ";\n"; repstr = repstr + varname + " = " + val + ";\n";
tmp_paren_vars[val] = varname; tmp_paren_vars[val] = varname;
} }
@ -1225,9 +1223,7 @@ ModelTree::fixNestedParenthesis(ostringstream &output, map<string, string> &tmp_
if (auto it = tmp_paren_vars.find(str1); if (auto it = tmp_paren_vars.find(str1);
it == tmp_paren_vars.end()) it == tmp_paren_vars.end())
{ {
ostringstream ptvstr; varname = "paren32_tmp_var_" + to_string(i1++);
ptvstr << i1++;
varname = "paren32_tmp_var_" + ptvstr.str();
repstr = repstr + varname + " = " + str1 + ";\n"; repstr = repstr + varname + " = " + str1 + ";\n";
} }
else else

View File

@ -1,5 +1,5 @@
/* /*
* Copyright © 2003-2019 Dynare Team * Copyright © 2003-2022 Dynare Team
* *
* This file is part of Dynare. * This file is part of Dynare.
* *
@ -57,5 +57,5 @@ double
NumericalConstants::getDouble(int ID) const NumericalConstants::getDouble(int ID) const
{ {
assert(ID >= 0 && ID < static_cast<int>(double_vals.size())); assert(ID >= 0 && ID < static_cast<int>(double_vals.size()));
return (double_vals[ID]); return double_vals[ID];
} }

View File

@ -90,16 +90,14 @@ void
InitOrEndValStatement::fillEvalContext(eval_context_t &eval_context) const InitOrEndValStatement::fillEvalContext(eval_context_t &eval_context) const
{ {
for (auto [symb_id, value] : init_values) for (auto [symb_id, value] : init_values)
{ try
try {
{ eval_context[symb_id] = value->eval(eval_context);
eval_context[symb_id] = value->eval(eval_context); }
} catch (ExprNode::EvalException &e)
catch (ExprNode::EvalException &e) {
{ // Do nothing
// Do nothing }
}
}
} }
set<int> set<int>

View File

@ -536,12 +536,11 @@ ParsingDriver::init_param(const string &name, expr_t rhs)
void void
ParsingDriver::init_val(const string &name, expr_t rhs) ParsingDriver::init_val(const string &name, expr_t rhs)
{ {
if (nostrict) if (nostrict && !mod_file->symbol_table.exists(name))
if (!mod_file->symbol_table.exists(name)) {
{ warning("discarding '" + name + "' as it was not recognized in the initval statement");
warning("discarding '" + name + "' as it was not recognized in the initval statement"); return;
return; }
}
check_symbol_is_endogenous_or_exogenous(name, true); check_symbol_is_endogenous_or_exogenous(name, true);
int symb_id = mod_file->symbol_table.getID(name); int symb_id = mod_file->symbol_table.getID(name);
@ -558,12 +557,11 @@ ParsingDriver::initval_file()
void void
ParsingDriver::end_val(EndValLearntInStatement::LearntEndValType type, const string &name, expr_t rhs) ParsingDriver::end_val(EndValLearntInStatement::LearntEndValType type, const string &name, expr_t rhs)
{ {
if (nostrict) if (nostrict && !mod_file->symbol_table.exists(name))
if (!mod_file->symbol_table.exists(name)) {
{ warning("discarding '" + name + "' as it was not recognized in the endval statement");
warning("discarding '" + name + "' as it was not recognized in the endval statement"); return;
return; }
}
check_symbol_is_endogenous_or_exogenous(name, false); check_symbol_is_endogenous_or_exogenous(name, false);
int symb_id = mod_file->symbol_table.getID(name); int symb_id = mod_file->symbol_table.getID(name);
@ -573,12 +571,11 @@ ParsingDriver::end_val(EndValLearntInStatement::LearntEndValType type, const str
void void
ParsingDriver::hist_val(const string &name, const string &lag, expr_t rhs) ParsingDriver::hist_val(const string &name, const string &lag, expr_t rhs)
{ {
if (nostrict) if (nostrict && !mod_file->symbol_table.exists(name))
if (!mod_file->symbol_table.exists(name)) {
{ warning("discarding '" + name + "' as it was not recognized in the histval block");
warning("discarding '" + name + "' as it was not recognized in the histval block"); return;
return; }
}
check_symbol_is_endogenous_or_exogenous(name, true); check_symbol_is_endogenous_or_exogenous(name, true);
int symb_id = mod_file->symbol_table.getID(name); int symb_id = mod_file->symbol_table.getID(name);
@ -1030,12 +1027,11 @@ ParsingDriver::add_heteroskedastic_shock(const string &var, const vector<pair<in
void void
ParsingDriver::add_stderr_shock(const string &var, expr_t value) ParsingDriver::add_stderr_shock(const string &var, expr_t value)
{ {
if (nostrict) if (nostrict && !mod_file->symbol_table.exists(var))
if (!mod_file->symbol_table.exists(var)) {
{ warning("discarding shocks block declaration of the standard error of '" + var + "' as it was not declared");
warning("discarding shocks block declaration of the standard error of '" + var + "' as it was not declared"); return;
return; }
}
check_symbol_existence(var); check_symbol_existence(var);
int symb_id = mod_file->symbol_table.getID(var); int symb_id = mod_file->symbol_table.getID(var);
@ -1049,12 +1045,11 @@ ParsingDriver::add_stderr_shock(const string &var, expr_t value)
void void
ParsingDriver::add_var_shock(const string &var, expr_t value) ParsingDriver::add_var_shock(const string &var, expr_t value)
{ {
if (nostrict) if (nostrict && !mod_file->symbol_table.exists(var))
if (!mod_file->symbol_table.exists(var)) {
{ warning("discarding shocks block declaration of the variance of '" + var + "' as it was not declared");
warning("discarding shocks block declaration of the variance of '" + var + "' as it was not declared"); return;
return; }
}
check_symbol_existence(var); check_symbol_existence(var);
int symb_id = mod_file->symbol_table.getID(var); int symb_id = mod_file->symbol_table.getID(var);
@ -1068,12 +1063,12 @@ ParsingDriver::add_var_shock(const string &var, expr_t value)
void void
ParsingDriver::add_covar_shock(const string &var1, const string &var2, expr_t value) ParsingDriver::add_covar_shock(const string &var1, const string &var2, expr_t value)
{ {
if (nostrict) if (nostrict &&
if (!mod_file->symbol_table.exists(var1) || !mod_file->symbol_table.exists(var2)) (!mod_file->symbol_table.exists(var1) || !mod_file->symbol_table.exists(var2)))
{ {
warning("discarding shocks block declaration of the covariance of '" + var1 + "' and '" + var2 + "' as at least one was not declared"); warning("discarding shocks block declaration of the covariance of '" + var1 + "' and '" + var2 + "' as at least one was not declared");
return; return;
} }
check_symbol_existence(var1); check_symbol_existence(var1);
check_symbol_existence(var2); check_symbol_existence(var2);
@ -1093,12 +1088,12 @@ ParsingDriver::add_covar_shock(const string &var1, const string &var2, expr_t va
void void
ParsingDriver::add_correl_shock(const string &var1, const string &var2, expr_t value) ParsingDriver::add_correl_shock(const string &var1, const string &var2, expr_t value)
{ {
if (nostrict) if (nostrict &&
if (!mod_file->symbol_table.exists(var1) || !mod_file->symbol_table.exists(var2)) (!mod_file->symbol_table.exists(var1) || !mod_file->symbol_table.exists(var2)))
{ {
warning("discarding shocks block declaration of the correlation of '" + var1 + "' and '" + var2 + "' as at least one was not declared"); warning("discarding shocks block declaration of the correlation of '" + var1 + "' and '" + var2 + "' as at least one was not declared");
return; return;
} }
check_symbol_existence(var1); check_symbol_existence(var1);
check_symbol_existence(var2); check_symbol_existence(var2);
@ -1349,14 +1344,9 @@ ParsingDriver::end_of_row()
void void
ParsingDriver::add_to_row_const(const string &v) ParsingDriver::add_to_row_const(const string &v)
{ {
expr_t id; sigmae_row.push_back(v.at(0) == '-' ?
data_tree->AddUMinus(data_tree->AddNonNegativeConstant(v.substr(1))) :
if (v.at(0) == '-') data_tree->AddNonNegativeConstant(v));
id = data_tree->AddUMinus(data_tree->AddNonNegativeConstant(v.substr(1)));
else
id = data_tree->AddNonNegativeConstant(v);
sigmae_row.push_back(id);
} }
void void
@ -1415,22 +1405,18 @@ ParsingDriver::option_symbol_list(string name_option, vector<string> symbol_list
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)
{ for (auto &shock : symbol_list)
for (auto &shock : symbol_list) {
{ if (!mod_file->symbol_table.exists(shock))
if (!mod_file->symbol_table.exists(shock)) error("Unknown symbol: " + shock);
error("Unknown symbol: " + shock); if (mod_file->symbol_table.getType(shock) != SymbolType::exogenous)
if (mod_file->symbol_table.getType(shock) != SymbolType::exogenous) error("Variables passed to irf_shocks must be exogenous. Caused by: " + shock);
error("Variables passed to irf_shocks must be exogenous. Caused by: " + shock); }
}
}
if (name_option.compare("ms.parameters") == 0) if (name_option.compare("ms.parameters") == 0)
{ for (auto &it : symbol_list)
for (auto &it : symbol_list) if (mod_file->symbol_table.getType(it) != SymbolType::parameter)
if (mod_file->symbol_table.getType(it) != SymbolType::parameter) error("Variables passed to the parameters option of the markov_switching statement must be parameters. Caused by: " + it);
error("Variables passed to the parameters option of the markov_switching statement must be parameters. Caused by: " + it);
}
options_list.symbol_list_options[move(name_option)] = move(symbol_list); options_list.symbol_list_options[move(name_option)] = move(symbol_list);
} }
@ -3097,8 +3083,7 @@ ParsingDriver::external_function()
void void
ParsingDriver::push_external_function_arg_vector_onto_stack() ParsingDriver::push_external_function_arg_vector_onto_stack()
{ {
vector<expr_t> emptyvec; stack_external_function_args.push({});
stack_external_function_args.push(emptyvec);
} }
void void
@ -3283,8 +3268,8 @@ ParsingDriver::add_steady_state_model_equal(const string &varname, expr_t expr)
id = mod_file->symbol_table.addSymbol(varname, SymbolType::modFileLocalVariable); id = mod_file->symbol_table.addSymbol(varname, SymbolType::modFileLocalVariable);
} }
SymbolType type = mod_file->symbol_table.getType(id); if (SymbolType type = mod_file->symbol_table.getType(id);
if (type != SymbolType::endogenous && type != SymbolType::modFileLocalVariable && type != SymbolType::parameter) type != SymbolType::endogenous && type != SymbolType::modFileLocalVariable && type != SymbolType::parameter)
error(varname + " has incorrect type"); error(varname + " has incorrect type");
mod_file->steady_state_model.addDefinition(id, expr); mod_file->steady_state_model.addDefinition(id, expr);
@ -3307,8 +3292,8 @@ ParsingDriver::add_steady_state_model_equal_multiple(const vector<string> &symbo
// Unknown symbol, declare it as a ModFileLocalVariable // Unknown symbol, declare it as a ModFileLocalVariable
id = mod_file->symbol_table.addSymbol(symb, SymbolType::modFileLocalVariable); id = mod_file->symbol_table.addSymbol(symb, SymbolType::modFileLocalVariable);
} }
SymbolType type = mod_file->symbol_table.getType(id); if (SymbolType type = mod_file->symbol_table.getType(id);
if (type != SymbolType::endogenous && type != SymbolType::modFileLocalVariable && type != SymbolType::parameter) type != SymbolType::endogenous && type != SymbolType::modFileLocalVariable && type != SymbolType::parameter)
error(symb + " has incorrect type"); error(symb + " has incorrect type");
ids.push_back(id); ids.push_back(id);
} }
@ -3517,9 +3502,8 @@ ParsingDriver::add_shock_group_element(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);
SymbolType type = mod_file->symbol_table.getType(symb_id);
if (type != SymbolType::exogenous) if (mod_file->symbol_table.getType(symb_id) != SymbolType::exogenous)
error("shock_groups: " + name + " should be an exogenous variable"); error("shock_groups: " + name + " should be an exogenous variable");
shock_group.push_back(move(name)); shock_group.push_back(move(name));
@ -3636,7 +3620,7 @@ ParsingDriver::end_matched_moments(const vector<expr_t> &moments)
{ {
vector<int> symb_ids, lags, powers; vector<int> symb_ids, lags, powers;
m->matchMatchedMoment(symb_ids, lags, powers); m->matchMatchedMoment(symb_ids, lags, powers);
parsed_moments.emplace_back(symb_ids, lags, powers); parsed_moments.emplace_back(move(symb_ids), move(lags), move(powers));
} }
catch (ExprNode::MatchFailureException &e) catch (ExprNode::MatchFailureException &e)
{ {

View File

@ -207,28 +207,28 @@ ShocksStatement::writeJsonOutput(ostream &output) const
} }
void void
ShocksStatement::writeVarOrStdShock(ostream &output, var_and_std_shocks_t::const_iterator &it, ShocksStatement::writeVarOrStdShock(ostream &output, const pair<int, expr_t> &it,
bool stddev) const bool stddev) const
{ {
SymbolType type = symbol_table.getType(it->first); SymbolType type = symbol_table.getType(it.first);
assert(type == SymbolType::exogenous || symbol_table.isObservedVariable(it->first)); assert(type == SymbolType::exogenous || symbol_table.isObservedVariable(it.first));
int id; int id;
if (type == SymbolType::exogenous) if (type == SymbolType::exogenous)
{ {
output << "M_.Sigma_e("; output << "M_.Sigma_e(";
id = symbol_table.getTypeSpecificID(it->first) + 1; id = symbol_table.getTypeSpecificID(it.first) + 1;
} }
else else
{ {
output << "M_.H("; output << "M_.H(";
id = symbol_table.getObservedVariableIndex(it->first) + 1; id = symbol_table.getObservedVariableIndex(it.first) + 1;
} }
output << id << ", " << id << ") = "; output << id << ", " << id << ") = ";
if (stddev) if (stddev)
output << "("; output << "(";
it->second->writeOutput(output); it.second->writeOutput(output);
if (stddev) if (stddev)
output << ")^2"; output << ")^2";
output << ";" << endl; output << ";" << endl;
@ -237,40 +237,40 @@ ShocksStatement::writeVarOrStdShock(ostream &output, var_and_std_shocks_t::const
void void
ShocksStatement::writeVarAndStdShocks(ostream &output) const ShocksStatement::writeVarAndStdShocks(ostream &output) const
{ {
for (auto it = var_shocks.begin(); it != var_shocks.end(); ++it) for (const auto &it : var_shocks)
writeVarOrStdShock(output, it, false); writeVarOrStdShock(output, it, false);
for (auto it = std_shocks.begin(); it != std_shocks.end(); ++it) for (const auto &it : std_shocks)
writeVarOrStdShock(output, it, true); writeVarOrStdShock(output, it, true);
} }
void void
ShocksStatement::writeCovarOrCorrShock(ostream &output, covar_and_corr_shocks_t::const_iterator &it, ShocksStatement::writeCovarOrCorrShock(ostream &output, const pair<pair<int, int>, expr_t> &it,
bool corr) const bool corr) const
{ {
SymbolType type1 = symbol_table.getType(it->first.first); SymbolType type1 = symbol_table.getType(it.first.first);
SymbolType type2 = symbol_table.getType(it->first.second); SymbolType type2 = symbol_table.getType(it.first.second);
assert((type1 == SymbolType::exogenous && type2 == SymbolType::exogenous) assert((type1 == SymbolType::exogenous && type2 == SymbolType::exogenous)
|| (symbol_table.isObservedVariable(it->first.first) && symbol_table.isObservedVariable(it->first.second))); || (symbol_table.isObservedVariable(it.first.first) && symbol_table.isObservedVariable(it.first.second)));
string matrix, corr_matrix; string matrix, corr_matrix;
int id1, id2; int id1, id2;
if (type1 == SymbolType::exogenous) if (type1 == SymbolType::exogenous)
{ {
matrix = "M_.Sigma_e"; matrix = "M_.Sigma_e";
corr_matrix = "M_.Correlation_matrix"; corr_matrix = "M_.Correlation_matrix";
id1 = symbol_table.getTypeSpecificID(it->first.first) + 1; id1 = symbol_table.getTypeSpecificID(it.first.first) + 1;
id2 = symbol_table.getTypeSpecificID(it->first.second) + 1; id2 = symbol_table.getTypeSpecificID(it.first.second) + 1;
} }
else else
{ {
matrix = "M_.H"; matrix = "M_.H";
corr_matrix = "M_.Correlation_matrix_ME"; corr_matrix = "M_.Correlation_matrix_ME";
id1 = symbol_table.getObservedVariableIndex(it->first.first) + 1; id1 = symbol_table.getObservedVariableIndex(it.first.first) + 1;
id2 = symbol_table.getObservedVariableIndex(it->first.second) + 1; id2 = symbol_table.getObservedVariableIndex(it.first.second) + 1;
} }
output << matrix << "(" << id1 << ", " << id2 << ") = "; output << matrix << "(" << id1 << ", " << id2 << ") = ";
it->second->writeOutput(output); it.second->writeOutput(output);
if (corr) if (corr)
output << "*sqrt(" << matrix << "(" << id1 << ", " << id1 << ")*" output << "*sqrt(" << matrix << "(" << id1 << ", " << id1 << ")*"
<< matrix << "(" << id2 << ", " << id2 << "))"; << matrix << "(" << id2 << ", " << id2 << "))";
@ -281,7 +281,7 @@ ShocksStatement::writeCovarOrCorrShock(ostream &output, covar_and_corr_shocks_t:
if (corr) if (corr)
{ {
output << corr_matrix << "(" << id1 << ", " << id2 << ") = "; output << corr_matrix << "(" << id1 << ", " << id2 << ") = ";
it->second->writeOutput(output); it.second->writeOutput(output);
output << ";" << endl output << ";" << endl
<< corr_matrix << "(" << id2 << ", " << id1 << ") = " << corr_matrix << "(" << id2 << ", " << id1 << ") = "
<< corr_matrix << "(" << id1 << ", " << id2 << ");" << endl; << corr_matrix << "(" << id1 << ", " << id2 << ");" << endl;
@ -291,10 +291,10 @@ ShocksStatement::writeCovarOrCorrShock(ostream &output, covar_and_corr_shocks_t:
void void
ShocksStatement::writeCovarAndCorrShocks(ostream &output) const ShocksStatement::writeCovarAndCorrShocks(ostream &output) const
{ {
for (auto it = covar_shocks.begin(); it != covar_shocks.end(); ++it) for (const auto &it : covar_shocks)
writeCovarOrCorrShock(output, it, false); writeCovarOrCorrShock(output, it, false);
for (auto it = corr_shocks.begin(); it != corr_shocks.end(); ++it) for (const auto &it : corr_shocks)
writeCovarOrCorrShock(output, it, true); writeCovarOrCorrShock(output, it, true);
} }
@ -328,7 +328,7 @@ ShocksStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidati
for (const auto & [ids, val] : covar_shocks) for (const auto & [ids, val] : covar_shocks)
{ {
int symb_id1 = ids.first, symb_id2 = ids.second; auto &[symb_id1, symb_id2] = ids;
if (!((symbol_table.getType(symb_id1) == SymbolType::exogenous if (!((symbol_table.getType(symb_id1) == SymbolType::exogenous
&& symbol_table.getType(symb_id2) == SymbolType::exogenous) && symbol_table.getType(symb_id2) == SymbolType::exogenous)
@ -344,7 +344,7 @@ ShocksStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidati
for (const auto & [ids, val] : corr_shocks) for (const auto & [ids, val] : corr_shocks)
{ {
int symb_id1 = ids.first, symb_id2 = ids.second; auto &[symb_id1, symb_id2] = ids;
if (!((symbol_table.getType(symb_id1) == SymbolType::exogenous if (!((symbol_table.getType(symb_id1) == SymbolType::exogenous
&& symbol_table.getType(symb_id2) == SymbolType::exogenous) && symbol_table.getType(symb_id2) == SymbolType::exogenous)
@ -451,16 +451,14 @@ ShocksSurpriseStatement::writeOutput(ostream &output, const string &basename, bo
else else
output << "M_.surprise_shocks = [ M_.surprise_shocks;" << endl; output << "M_.surprise_shocks = [ M_.surprise_shocks;" << endl;
for (const auto &[id, shock_vec] : surprise_shocks) for (const auto &[id, shock_vec] : surprise_shocks)
{ for (const auto &[period1, period2, value] : shock_vec)
for (const auto &[period1, period2, value] : shock_vec) {
{ output << "struct('exo_id'," << symbol_table.getTypeSpecificID(id)+1
output << "struct('exo_id'," << symbol_table.getTypeSpecificID(id)+1 << ",'periods'," << period1 << ":" << period2
<< ",'periods'," << period1 << ":" << period2 << ",'value',";
<< ",'value',"; value->writeOutput(output);
value->writeOutput(output); output << ");" << endl;
output << ");" << endl; }
}
}
output << "];" << endl; output << "];" << endl;
} }
@ -531,18 +529,16 @@ ShocksLearntInStatement::writeOutput(ostream &output, const string &basename, bo
output << "M_.learnt_shocks = [ M_.learnt_shocks;" << endl; output << "M_.learnt_shocks = [ M_.learnt_shocks;" << endl;
for (const auto &[id, shock_vec] : learnt_shocks) for (const auto &[id, shock_vec] : learnt_shocks)
{ for (const auto &[type, period1, period2, value] : shock_vec)
for (const auto &[type, period1, period2, value] : shock_vec) {
{ output << "struct('learnt_in'," << learnt_in_period
output << "struct('learnt_in'," << learnt_in_period << ",'exo_id'," << symbol_table.getTypeSpecificID(id)+1
<< ",'exo_id'," << symbol_table.getTypeSpecificID(id)+1 << ",'periods'," << period1 << ":" << period2
<< ",'periods'," << period1 << ":" << period2 << ",'type','" << typeToString(type) << "'"
<< ",'type','" << typeToString(type) << "'" << ",'value',";
<< ",'value',"; value->writeOutput(output);
value->writeOutput(output); output << ");" << endl;
output << ");" << endl; }
}
}
output << "];" << endl; output << "];" << endl;
} }
@ -579,21 +575,20 @@ ShocksLearntInStatement::writeJsonOutput(ostream &output) const
ConditionalForecastPathsStatement::ConditionalForecastPathsStatement(AbstractShocksStatement::det_shocks_t paths_arg, ConditionalForecastPathsStatement::ConditionalForecastPathsStatement(AbstractShocksStatement::det_shocks_t paths_arg,
const SymbolTable &symbol_table_arg) : const SymbolTable &symbol_table_arg) :
paths{move(paths_arg)}, paths{move(paths_arg)},
symbol_table{symbol_table_arg} symbol_table{symbol_table_arg},
path_length{computePathLength(paths)}
{ {
} }
void int
ConditionalForecastPathsStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) ConditionalForecastPathsStatement::computePathLength(const AbstractShocksStatement::det_shocks_t &paths)
{ {
int length{0};
for (const auto &[ignore, elems] : paths) for (const auto &[ignore, elems] : paths)
{ for (auto &[period1, period2, value] : elems)
int this_path_length = 0; // Period1 < Period2, as enforced in ParsingDriver::add_period()
for (auto [period1, period2, value] : elems) length = max(length, period2);
// Period1 < Period2, as enforced in ParsingDriver::add_period() return length;
this_path_length = max(this_path_length, period2);
path_length = max(this_path_length, path_length);
}
} }
void void
@ -763,9 +758,9 @@ void
ShockGroupsStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const ShockGroupsStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const
{ {
int i = 1; int i = 1;
bool unique_label = true; for (auto it = shock_groups.begin(); it != shock_groups.end(); ++it)
for (auto it = shock_groups.begin(); it != shock_groups.end(); ++it, unique_label = true)
{ {
bool unique_label{true};
for (auto it1 = it+1; it1 != shock_groups.end(); ++it1) for (auto it1 = it+1; it1 != shock_groups.end(); ++it1)
if (it->name == it1->name) if (it->name == it1->name)
{ {
@ -793,10 +788,10 @@ void
ShockGroupsStatement::writeJsonOutput(ostream &output) const ShockGroupsStatement::writeJsonOutput(ostream &output) const
{ {
output << R"({"statementName": "shock_groups", "name": ")" << name << R"(", "groups": [)"; output << R"({"statementName": "shock_groups", "name": ")" << name << R"(", "groups": [)";
bool unique_label = true; bool printed_something{false};
bool printed_group = false; for (auto it = shock_groups.begin(); it != shock_groups.end(); ++it)
for (auto it = shock_groups.begin(); it != shock_groups.end(); ++it, unique_label = true)
{ {
bool unique_label{true};
for (auto it1 = it+1; it1 != shock_groups.end(); ++it1) for (auto it1 = it+1; it1 != shock_groups.end(); ++it1)
if (it->name == it1->name) if (it->name == it1->name)
{ {
@ -806,10 +801,8 @@ ShockGroupsStatement::writeJsonOutput(ostream &output) const
if (unique_label) if (unique_label)
{ {
if (printed_group) if (exchange(printed_something, true))
output << ", "; output << ", ";
else
printed_group = true;
output << R"({"group_name": ")" << it->name << R"(",)" output << R"({"group_name": ")" << it->name << R"(",)"
<< R"("shocks": [)"; << R"("shocks": [)";
for (auto it1 = it->list.begin(); it1 != it->list.end(); ++it1) for (auto it1 = it->list.begin(); it1 != it->list.end(); ++it1)
@ -848,8 +841,8 @@ void
Init2shocksStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const Init2shocksStatement::writeOutput(ostream &output, const string &basename, bool minimal_workspace) const
{ {
output << "M_.init2shocks." << name << " = {" << endl; output << "M_.init2shocks." << name << " = {" << endl;
for (auto &it : init2shocks) for (const auto &[id1, id2] : init2shocks)
output << "{'" << symbol_table.getName(it.first) << "', '" << symbol_table.getName(it.second) << "'};" << endl; output << "{'" << symbol_table.getName(id1) << "', '" << symbol_table.getName(id2) << "'};" << endl;
output << "};" << endl; output << "};" << endl;
} }

View File

@ -58,9 +58,9 @@ public:
private: private:
const var_and_std_shocks_t var_shocks, std_shocks; const var_and_std_shocks_t var_shocks, std_shocks;
const covar_and_corr_shocks_t covar_shocks, corr_shocks; const covar_and_corr_shocks_t covar_shocks, corr_shocks;
void writeVarOrStdShock(ostream &output, var_and_std_shocks_t::const_iterator &it, bool stddev) const; void writeVarOrStdShock(ostream &output, const pair<int, expr_t> &it, bool stddev) const;
void writeVarAndStdShocks(ostream &output) const; void writeVarAndStdShocks(ostream &output) const;
void writeCovarOrCorrShock(ostream &output, covar_and_corr_shocks_t::const_iterator &it, bool corr) const; void writeCovarOrCorrShock(ostream &output, const pair<pair<int, int>, expr_t> &it, bool corr) const;
void writeCovarAndCorrShocks(ostream &output) const; void writeCovarAndCorrShocks(ostream &output) const;
bool has_calibrated_measurement_errors() const; bool has_calibrated_measurement_errors() const;
public: public:
@ -141,13 +141,13 @@ class ConditionalForecastPathsStatement : public Statement
private: private:
const AbstractShocksStatement::det_shocks_t paths; const AbstractShocksStatement::det_shocks_t paths;
const SymbolTable &symbol_table; const SymbolTable &symbol_table;
int path_length{-1}; const int path_length;
public: public:
ConditionalForecastPathsStatement(AbstractShocksStatement::det_shocks_t paths_arg, ConditionalForecastPathsStatement(AbstractShocksStatement::det_shocks_t paths_arg,
const SymbolTable &symbol_table_arg); const SymbolTable &symbol_table_arg);
void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) override;
void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const override; void writeOutput(ostream &output, const string &basename, bool minimal_workspace) const override;
void writeJsonOutput(ostream &output) const override; void writeJsonOutput(ostream &output) const override;
static int computePathLength(const AbstractShocksStatement::det_shocks_t &paths);
}; };
class MomentCalibration : public Statement class MomentCalibration : public Statement

View File

@ -757,44 +757,42 @@ StaticModel::writeStaticBlockBytecode(const string &basename) const
} }
} }
for (i = 0; i < block_size; i++) for (i = 0; i < block_size; i++)
{ if (i >= block_recursive)
if (i >= block_recursive) {
{ FLDR_ fldr(i-block_recursive);
FLDR_ fldr(i-block_recursive); fldr.write(code_file, instruction_number);
fldr.write(code_file, instruction_number);
FLDZ_ fldz; FLDZ_ fldz;
fldz.write(code_file, instruction_number); fldz.write(code_file, instruction_number);
v = getBlockEquationID(block, i); v = getBlockEquationID(block, i);
for (Uf[v].Ufl = Uf[v].Ufl_First; Uf[v].Ufl; Uf[v].Ufl = Uf[v].Ufl->pNext) for (Uf[v].Ufl = Uf[v].Ufl_First; Uf[v].Ufl; Uf[v].Ufl = Uf[v].Ufl->pNext)
{ {
FLDSU_ fldsu(Uf[v].Ufl->u); FLDSU_ fldsu(Uf[v].Ufl->u);
fldsu.write(code_file, instruction_number); fldsu.write(code_file, instruction_number);
FLDSV_ fldsv{static_cast<int>(SymbolType::endogenous), static_cast<unsigned int>(Uf[v].Ufl->var)}; FLDSV_ fldsv{static_cast<int>(SymbolType::endogenous), static_cast<unsigned int>(Uf[v].Ufl->var)};
fldsv.write(code_file, instruction_number); fldsv.write(code_file, instruction_number);
FBINARY_ fbinary{static_cast<int>(BinaryOpcode::times)}; FBINARY_ fbinary{static_cast<int>(BinaryOpcode::times)};
fbinary.write(code_file, instruction_number); fbinary.write(code_file, instruction_number);
FCUML_ fcuml; FCUML_ fcuml;
fcuml.write(code_file, instruction_number); fcuml.write(code_file, instruction_number);
} }
Uf[v].Ufl = Uf[v].Ufl_First; Uf[v].Ufl = Uf[v].Ufl_First;
while (Uf[v].Ufl) while (Uf[v].Ufl)
{ {
Uf[v].Ufl_First = Uf[v].Ufl->pNext; Uf[v].Ufl_First = Uf[v].Ufl->pNext;
free(Uf[v].Ufl); free(Uf[v].Ufl);
Uf[v].Ufl = Uf[v].Ufl_First; Uf[v].Ufl = Uf[v].Ufl_First;
} }
FBINARY_ fbinary{static_cast<int>(BinaryOpcode::minus)}; FBINARY_ fbinary{static_cast<int>(BinaryOpcode::minus)};
fbinary.write(code_file, instruction_number); fbinary.write(code_file, instruction_number);
FSTPSU_ fstpsu(i - block_recursive); FSTPSU_ fstpsu(i - block_recursive);
fstpsu.write(code_file, instruction_number); fstpsu.write(code_file, instruction_number);
} }
}
break; break;
default: default:
break; break;
@ -1023,7 +1021,6 @@ StaticModel::computingPass(int derivsOrder, int paramsDerivsOrder, const eval_co
for (int i = 0; i < symbol_table.endo_nbr(); i++) for (int i = 0; i < symbol_table.endo_nbr(); i++)
{ {
int id = symbol_table.getID(SymbolType::endogenous, i); int id = symbol_table.getID(SymbolType::endogenous, i);
// if (!symbol_table.isAuxiliaryVariableButNotMultiplier(id))
vars.insert(getDerivID(id, 0)); vars.insert(getDerivID(id, 0));
} }
@ -1803,7 +1800,7 @@ StaticModel::writeStaticFile(const string &basename, bool block, bool use_dll, c
{ {
writeStaticPerBlockCFiles(basename); writeStaticPerBlockCFiles(basename);
writeStaticBlockCFile(basename); writeStaticBlockCFile(basename);
vector<filesystem::path> src_files{blocks.size() + 1}; vector<filesystem::path> src_files(blocks.size() + 1);
for (int blk = 0; blk < static_cast<int>(blocks.size()); blk++) for (int blk = 0; blk < static_cast<int>(blocks.size()); blk++)
src_files[blk] = model_dir / "src" / ("static_" + to_string(blk+1) + ".c"); src_files[blk] = model_dir / "src" / ("static_" + to_string(blk+1) + ".c");
src_files[blocks.size()] = model_dir / "src" / "static.c"; src_files[blocks.size()] = model_dir / "src" / "static.c";

View File

@ -325,18 +325,7 @@ TrendComponentModelTable::writeOutput(const string &basename, ostream &output) c
vector<string> eqtags_vec = eqtags.at(name); vector<string> eqtags_vec = eqtags.at(name);
output << "M_.trend_component." << name << ".target_eqn = ["; output << "M_.trend_component." << name << ".target_eqn = [";
for (auto it : target_eqtags_vec) for (auto it : target_eqtags_vec)
{ output << distance(eqtags_vec.begin(), find(eqtags_vec.begin(), eqtags_vec.end(), it)) + 1 << " ";
int i = 0;
for (auto it1 : eqtags_vec)
{
i++;
if (it == it1)
{
output << i << " ";
break;
}
}
}
output << "];" << endl; output << "];" << endl;
vector<int> target_lhs_vec = getTargetLhs(name); vector<int> target_lhs_vec = getTargetLhs(name);

View File

@ -57,14 +57,8 @@ SymbolList::checkPass(WarningConsolidation &warnings, const vector<SymbolType> &
throw SymbolListException{"Variable " + symbol + " was not declared."}; throw SymbolListException{"Variable " + symbol + " was not declared."};
} }
bool type_found = false; if (none_of(types.begin(), types.end(),
for (auto type : types) [&](SymbolType type) { return symbol_table.getType(symbol) == type; }))
if (symbol_table.getType(symbol) == type)
{
type_found = true;
break;
}
if (!type_found)
{ {
string valid_types; string valid_types;
for (auto type : types) for (auto type : types)

View File

@ -61,7 +61,7 @@ public:
//! Write JSON output //! Write JSON output
void writeJsonOutput(ostream &output) const; void writeJsonOutput(ostream &output) const;
//! Is Empty //! Is Empty
int bool
empty() const empty() const
{ {
return symbols.empty(); return symbols.empty();

View File

@ -217,8 +217,7 @@ SymbolTable::writeOutput(ostream &output) const noexcept(false)
output << "M_.exo_names(" << id+1 << ") = {'" << getName(exo_ids[id]) << "'};" << endl output << "M_.exo_names(" << id+1 << ") = {'" << getName(exo_ids[id]) << "'};" << endl
<< "M_.exo_names_tex(" << id+1 << ") = {'" << getTeXName(exo_ids[id]) << "'};" << endl << "M_.exo_names_tex(" << id+1 << ") = {'" << getTeXName(exo_ids[id]) << "'};" << endl
<< "M_.exo_names_long(" << id+1 << ") = {'" << getLongName(exo_ids[id]) << "'};" << endl; << "M_.exo_names_long(" << id+1 << ") = {'" << getLongName(exo_ids[id]) << "'};" << endl;
map<string, map<int, string>> partitions = getPartitionsForType(SymbolType::exogenous); for (auto &partition : getPartitionsForType(SymbolType::exogenous))
for (auto &partition : partitions)
if (partition.first != "long_name") if (partition.first != "long_name")
{ {
output << "M_.exo_partitions." << partition.first << " = { "; output << "M_.exo_partitions." << partition.first << " = { ";
@ -254,8 +253,7 @@ SymbolTable::writeOutput(ostream &output) const noexcept(false)
<< "M_.exo_det_names_tex(" << id+1 << ") = {'" << getTeXName(exo_det_ids[id]) << "'};" << endl << "M_.exo_det_names_tex(" << id+1 << ") = {'" << getTeXName(exo_det_ids[id]) << "'};" << endl
<< "M_.exo_det_names_long(" << id+1 << ") = {'" << getLongName(exo_det_ids[id]) << "'};" << endl; << "M_.exo_det_names_long(" << id+1 << ") = {'" << getLongName(exo_det_ids[id]) << "'};" << endl;
output << "M_.exo_det_partitions = struct();" << endl; output << "M_.exo_det_partitions = struct();" << endl;
map<string, map<int, string>> partitions = getPartitionsForType(SymbolType::exogenousDet); for (auto &partition : getPartitionsForType(SymbolType::exogenousDet))
for (auto &partition : partitions)
if (partition.first != "long_name") if (partition.first != "long_name")
{ {
output << "M_.exo_det_partitions." << partition.first << " = { "; output << "M_.exo_det_partitions." << partition.first << " = { ";
@ -281,8 +279,7 @@ SymbolTable::writeOutput(ostream &output) const noexcept(false)
<< "M_.endo_names_tex(" << id+1 << ") = {'" << getTeXName(endo_ids[id]) << "'};" << endl << "M_.endo_names_tex(" << id+1 << ") = {'" << getTeXName(endo_ids[id]) << "'};" << endl
<< "M_.endo_names_long(" << id+1 << ") = {'" << getLongName(endo_ids[id]) << "'};" << endl; << "M_.endo_names_long(" << id+1 << ") = {'" << getLongName(endo_ids[id]) << "'};" << endl;
output << "M_.endo_partitions = struct();" << endl; output << "M_.endo_partitions = struct();" << endl;
map<string, map<int, string>> partitions = getPartitionsForType(SymbolType::endogenous); for (auto &partition : getPartitionsForType(SymbolType::endogenous))
for (auto &partition : partitions)
if (partition.first != "long_name") if (partition.first != "long_name")
{ {
output << "M_.endo_partitions." << partition.first << " = { "; output << "M_.endo_partitions." << partition.first << " = { ";
@ -312,8 +309,7 @@ SymbolTable::writeOutput(ostream &output) const noexcept(false)
output << "options_.dsge_var = 1;" << endl; output << "options_.dsge_var = 1;" << endl;
} }
output << "M_.param_partitions = struct();" << endl; output << "M_.param_partitions = struct();" << endl;
map<string, map<int, string>> partitions = getPartitionsForType(SymbolType::parameter); for (auto &partition : getPartitionsForType(SymbolType::parameter))
for (auto &partition : partitions)
if (partition.first != "long_name") if (partition.first != "long_name")
{ {
output << "M_.param_partitions." << partition.first << " = { "; output << "M_.param_partitions." << partition.first << " = { ";
@ -426,20 +422,15 @@ SymbolTable::writeOutput(ostream &output) const noexcept(false)
int int
SymbolTable::addLeadAuxiliaryVarInternal(bool endo, int index, expr_t expr_arg) noexcept(false) SymbolTable::addLeadAuxiliaryVarInternal(bool endo, int index, expr_t expr_arg) noexcept(false)
{ {
ostringstream varname; string varname{(endo ? "AUX_ENDO_LEAD_" : "AUX_EXO_LEAD_") + to_string(index)};
if (endo)
varname << "AUX_ENDO_LEAD_";
else
varname << "AUX_EXO_LEAD_";
varname << index;
int symb_id; int symb_id;
try try
{ {
symb_id = addSymbol(varname.str(), SymbolType::endogenous); symb_id = addSymbol(varname, SymbolType::endogenous);
} }
catch (AlreadyDeclaredException &e) catch (AlreadyDeclaredException &e)
{ {
cerr << "ERROR: you should rename your variable called " << varname.str() << ", this name is internally used by Dynare" << endl; cerr << "ERROR: you should rename your variable called " << varname << ", this name is internally used by Dynare" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -451,21 +442,15 @@ SymbolTable::addLeadAuxiliaryVarInternal(bool endo, int index, expr_t expr_arg)
int int
SymbolTable::addLagAuxiliaryVarInternal(bool endo, int orig_symb_id, int orig_lead_lag, expr_t expr_arg) noexcept(false) SymbolTable::addLagAuxiliaryVarInternal(bool endo, int orig_symb_id, int orig_lead_lag, expr_t expr_arg) noexcept(false)
{ {
ostringstream varname; string varname{(endo ? "AUX_ENDO_LAG_" : "AUX_EXO_LAG_") + to_string(orig_symb_id) + "_" + to_string(-orig_lead_lag)};
if (endo)
varname << "AUX_ENDO_LAG_";
else
varname << "AUX_EXO_LAG_";
varname << orig_symb_id << "_" << -orig_lead_lag;
int symb_id; int symb_id;
try try
{ {
symb_id = addSymbol(varname.str(), SymbolType::endogenous); symb_id = addSymbol(varname, SymbolType::endogenous);
} }
catch (AlreadyDeclaredException &e) catch (AlreadyDeclaredException &e)
{ {
cerr << "ERROR: you should rename your variable called " << varname.str() << ", this name is internally used by Dynare" << endl; cerr << "ERROR: you should rename your variable called " << varname << ", this name is internally used by Dynare" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -501,19 +486,16 @@ SymbolTable::addExoLagAuxiliaryVar(int orig_symb_id, int orig_lead_lag, expr_t e
int int
SymbolTable::addExpectationAuxiliaryVar(int information_set, int index, expr_t expr_arg) noexcept(false) SymbolTable::addExpectationAuxiliaryVar(int information_set, int index, expr_t expr_arg) noexcept(false)
{ {
ostringstream varname; string varname{string{"AUX_EXPECT_"} + (information_set < 0 ? "LAG" : "LEAD") + "_"
+ to_string(abs(information_set)) + "_" + to_string(index)};
int symb_id; int symb_id;
varname << "AUX_EXPECT_" << (information_set < 0 ? "LAG" : "LEAD") << "_"
<< abs(information_set) << "_" << index;
try try
{ {
symb_id = addSymbol(varname.str(), SymbolType::endogenous); symb_id = addSymbol(varname, SymbolType::endogenous);
} }
catch (AlreadyDeclaredException &e) catch (AlreadyDeclaredException &e)
{ {
cerr << "ERROR: you should rename your variable called " << varname.str() << ", this name is internally used by Dynare" << endl; cerr << "ERROR: you should rename your variable called " << varname << ", this name is internally used by Dynare" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -545,18 +527,15 @@ SymbolTable::addLogTransformAuxiliaryVar(int orig_symb_id, int orig_lead_lag, ex
int int
SymbolTable::addDiffLagAuxiliaryVar(int index, expr_t expr_arg, int orig_symb_id, int orig_lag) noexcept(false) SymbolTable::addDiffLagAuxiliaryVar(int index, expr_t expr_arg, int orig_symb_id, int orig_lag) noexcept(false)
{ {
ostringstream varname; string varname{"AUX_DIFF_LAG_" + to_string(index)};
int symb_id; int symb_id;
varname << "AUX_DIFF_LAG_" << index;
try try
{ {
symb_id = addSymbol(varname.str(), SymbolType::endogenous); symb_id = addSymbol(varname, SymbolType::endogenous);
} }
catch (AlreadyDeclaredException &e) catch (AlreadyDeclaredException &e)
{ {
cerr << "ERROR: you should rename your variable called " << varname.str() << ", this name is internally used by Dynare" << endl; cerr << "ERROR: you should rename your variable called " << varname << ", this name is internally used by Dynare" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -568,18 +547,15 @@ SymbolTable::addDiffLagAuxiliaryVar(int index, expr_t expr_arg, int orig_symb_id
int int
SymbolTable::addDiffLeadAuxiliaryVar(int index, expr_t expr_arg, int orig_symb_id, int orig_lead) noexcept(false) SymbolTable::addDiffLeadAuxiliaryVar(int index, expr_t expr_arg, int orig_symb_id, int orig_lead) noexcept(false)
{ {
ostringstream varname; string varname{"AUX_DIFF_LEAD_" + to_string(index)};
int symb_id; int symb_id;
varname << "AUX_DIFF_LEAD_" << index;
try try
{ {
symb_id = addSymbol(varname.str(), SymbolType::endogenous); symb_id = addSymbol(varname, SymbolType::endogenous);
} }
catch (AlreadyDeclaredException &e) catch (AlreadyDeclaredException &e)
{ {
cerr << "ERROR: you should rename your variable called " << varname.str() << ", this name is internally used by Dynare" << endl; cerr << "ERROR: you should rename your variable called " << varname << ", this name is internally used by Dynare" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -591,18 +567,15 @@ SymbolTable::addDiffLeadAuxiliaryVar(int index, expr_t expr_arg, int orig_symb_i
int int
SymbolTable::addDiffAuxiliaryVar(int index, expr_t expr_arg, optional<int> orig_symb_id, optional<int> orig_lag) noexcept(false) SymbolTable::addDiffAuxiliaryVar(int index, expr_t expr_arg, optional<int> orig_symb_id, optional<int> orig_lag) noexcept(false)
{ {
ostringstream varname; string varname{"AUX_DIFF_" + to_string(index)};
int symb_id; int symb_id;
varname << "AUX_DIFF_" << index;
try try
{ {
symb_id = addSymbol(varname.str(), SymbolType::endogenous); symb_id = addSymbol(varname, SymbolType::endogenous);
} }
catch (AlreadyDeclaredException &e) catch (AlreadyDeclaredException &e)
{ {
cerr << "ERROR: you should rename your variable called " << varname.str() << ", this name is internally used by Dynare" << endl; cerr << "ERROR: you should rename your variable called " << varname << ", this name is internally used by Dynare" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -614,17 +587,15 @@ SymbolTable::addDiffAuxiliaryVar(int index, expr_t expr_arg, optional<int> orig_
int int
SymbolTable::addUnaryOpAuxiliaryVar(int index, expr_t expr_arg, string unary_op, optional<int> orig_symb_id, optional<int> orig_lag) noexcept(false) SymbolTable::addUnaryOpAuxiliaryVar(int index, expr_t expr_arg, string unary_op, optional<int> orig_symb_id, optional<int> orig_lag) noexcept(false)
{ {
ostringstream varname; string varname{"AUX_UOP_" + to_string(index)};
int symb_id; int symb_id;
varname << "AUX_UOP_" << index;
try try
{ {
symb_id = addSymbol(varname.str(), SymbolType::endogenous); symb_id = addSymbol(varname, SymbolType::endogenous);
} }
catch (AlreadyDeclaredException &e) catch (AlreadyDeclaredException &e)
{ {
cerr << "ERROR: you should rename your variable called " << varname.str() << ", this name is internally used by Dynare" << endl; cerr << "ERROR: you should rename your variable called " << varname << ", this name is internally used by Dynare" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -636,17 +607,15 @@ SymbolTable::addUnaryOpAuxiliaryVar(int index, expr_t expr_arg, string unary_op,
int int
SymbolTable::addMultiplierAuxiliaryVar(int index) noexcept(false) SymbolTable::addMultiplierAuxiliaryVar(int index) noexcept(false)
{ {
ostringstream varname; string varname{"MULT_" + to_string(index+1)};
int symb_id; int symb_id;
varname << "MULT_" << index+1;
try try
{ {
symb_id = addSymbol(varname.str(), SymbolType::endogenous); symb_id = addSymbol(varname, SymbolType::endogenous);
} }
catch (AlreadyDeclaredException &e) catch (AlreadyDeclaredException &e)
{ {
cerr << "ERROR: you should rename your variable called " << varname.str() << ", this name is internally used by Dynare" << endl; cerr << "ERROR: you should rename your variable called " << varname << ", this name is internally used by Dynare" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -657,17 +626,15 @@ SymbolTable::addMultiplierAuxiliaryVar(int index) noexcept(false)
int int
SymbolTable::addDiffForwardAuxiliaryVar(int orig_symb_id, int orig_lead_lag, expr_t expr_arg) noexcept(false) SymbolTable::addDiffForwardAuxiliaryVar(int orig_symb_id, int orig_lead_lag, expr_t expr_arg) noexcept(false)
{ {
ostringstream varname; string varname{"AUX_DIFF_FWRD_" + to_string(orig_symb_id+1)};
int symb_id; int symb_id;
varname << "AUX_DIFF_FWRD_" << orig_symb_id+1;
try try
{ {
symb_id = addSymbol(varname.str(), SymbolType::endogenous); symb_id = addSymbol(varname, SymbolType::endogenous);
} }
catch (AlreadyDeclaredException &e) catch (AlreadyDeclaredException &e)
{ {
cerr << "ERROR: you should rename your variable called " << varname.str() << ", this name is internally used by Dynare" << endl; cerr << "ERROR: you should rename your variable called " << varname << ", this name is internally used by Dynare" << endl;
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright © 2012-2017 Dynare Team * Copyright © 2012-2022 Dynare Team
* *
* This file is part of Dynare. * This file is part of Dynare.
* *
@ -20,8 +20,7 @@
#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)

View File

@ -651,9 +651,8 @@ Variable::eval(Environment &env)
if (indices && !indices->empty()) if (indices && !indices->empty())
{ {
ArrayPtr map = dynamic_pointer_cast<Array>(indices->eval(env)); ArrayPtr map = dynamic_pointer_cast<Array>(indices->eval(env));
vector<ExpressionPtr> index = map->getValue();
vector<int> ind; vector<int> ind;
for (const auto &it : index) for (const auto &it : map->getValue())
// Necessary to handle indexes like: y[1:2,2] // Necessary to handle indexes like: y[1:2,2]
// In general this evaluates to [[1:2],2] but when subscripting we want to expand it to [1,2,2] // In general this evaluates to [[1:2],2] but when subscripting we want to expand it to [1,2,2]
if (auto db = dynamic_pointer_cast<Real>(it); db) if (auto db = dynamic_pointer_cast<Real>(it); db)