v4: changing name of preprocessor directory

git-svn-id: https://www.dynare.org/svn/dynare/dynare_v4@1686 ac1d8469-bf42-47a9-8791-bf33cf982152
issue#70
michel 2008-02-03 10:28:36 +00:00
commit 2a69caa17b
54 changed files with 21519 additions and 0 deletions

1190
BlockTriangular.cc Normal file

File diff suppressed because it is too large Load Diff

853
ComputingTasks.cc Normal file
View File

@ -0,0 +1,853 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <sstream>
using namespace std;
#include "ComputingTasks.hh"
#include "Interface.hh"
#include "Statement.hh"
SteadyStatement::SteadyStatement(const OptionsList &options_list_arg) :
options_list(options_list_arg)
{
}
void
SteadyStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
output << "steady;\n";
}
SteadySparseStatement::SteadySparseStatement(const OptionsList &options_list_arg) :
options_list(options_list_arg)
{
}
void
SteadySparseStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
output << basename << "_static;\n";
}
CheckStatement::CheckStatement(const OptionsList &options_list_arg) :
options_list(options_list_arg)
{
}
void
CheckStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
output << "check;\n";
}
void
CheckStatement::checkPass(ModFileStructure &mod_file_struct)
{
mod_file_struct.check_present = true;
}
SimulStatement::SimulStatement(const OptionsList &options_list_arg) :
options_list(options_list_arg)
{
}
void
SimulStatement::checkPass(ModFileStructure &mod_file_struct)
{
mod_file_struct.simul_present = true;
}
void
SimulStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
output << "simul(oo_.dr);\n";
}
SimulSparseStatement::SimulSparseStatement(const OptionsList &options_list_arg,
int compiler_arg, int mode_arg) :
options_list(options_list_arg),
compiler(compiler_arg),
mode(mode_arg)
{
}
void
SimulSparseStatement::checkPass(ModFileStructure &mod_file_struct)
{
mod_file_struct.simul_present = true;
}
void
SimulSparseStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
output << "if (~ options_.initval_file) & (size(oo_.endo_simul,2)<options_.periods)\n";
output << " if ~isfield(options_,'datafile')\n";
output << " make_y_;\n";
output << " make_ex_;\n";
output << " else\n";
output << " read_data_;\n";
output << " end\n";
output << "end\n";
if(mode==eSparseDLLMode)
{
if(compiler!=NO_COMPILE)
{
output << "disp('compiling...');\n";
output << "t0=clock;\n";
if (compiler == 0)
output << "mex " << basename << "_dynamic.c;\n";
else
output << "mex " << basename << "_dynamic.cc;\n";
output << "disp(['compiling time: ' num2str(etime(clock,t0))]);\n";
output << "oo_.endo_simul=" << basename << "_dynamic;\n";
}
else
{
output << "oo_.endo_simul=simulate;\n";
output << "clear simulate.dll;\n";
}
}
else
{
//output << "oo_.endo_simul=" << basename << "_dynamic();\n";
output << basename << "_dynamic;\n";
}
}
StochSimulStatement::StochSimulStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg) :
tmp_symbol_table(tmp_symbol_table_arg),
options_list(options_list_arg)
{
}
void
StochSimulStatement::checkPass(ModFileStructure &mod_file_struct)
{
mod_file_struct.stoch_simul_or_similar_present = true;
// Fill in option_order of mod_file_struct
OptionsList::num_options_type::const_iterator it = options_list.num_options.find("order");
if (it != options_list.num_options.end())
mod_file_struct.order_option = atoi(it->second.c_str());
}
void
StochSimulStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
tmp_symbol_table.writeOutput("var_list_", output);
output << "stoch_simul(var_list_);\n";
}
RamseyPolicyStatement::RamseyPolicyStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg) :
tmp_symbol_table(tmp_symbol_table_arg),
options_list(options_list_arg)
{
}
void
RamseyPolicyStatement::checkPass(ModFileStructure &mod_file_struct)
{
mod_file_struct.stoch_simul_or_similar_present = true;
/* Fill in option_order of mod_file_struct
Since ramsey policy needs one further order of derivation (for example, for 1st order
approximation, it needs 2nd derivatives), we add 1 to the order declared by user */
OptionsList::num_options_type::const_iterator it = options_list.num_options.find("order");
if (it != options_list.num_options.end())
mod_file_struct.order_option = atoi(it->second.c_str()) + 1;
}
void
RamseyPolicyStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
tmp_symbol_table.writeOutput("var_list_", output);
output << "ramsey_policy(var_list_);\n";
}
EstimationStatement::EstimationStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg) :
tmp_symbol_table(tmp_symbol_table_arg),
options_list(options_list_arg)
{
}
void
EstimationStatement::checkPass(ModFileStructure &mod_file_struct)
{
mod_file_struct.stoch_simul_or_similar_present = true;
// Fill in option_order of mod_file_struct
OptionsList::num_options_type::const_iterator it = options_list.num_options.find("order");
if (it != options_list.num_options.end())
mod_file_struct.order_option = atoi(it->second.c_str());
}
void
EstimationStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
tmp_symbol_table.writeOutput("var_list_", output);
output << "dynare_estimation(var_list_);\n";
}
PriorAnalysisStatement::PriorAnalysisStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg) :
tmp_symbol_table(tmp_symbol_table_arg),
options_list(options_list_arg)
{
}
void
PriorAnalysisStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
tmp_symbol_table.writeOutput("var_list_", output);
output << "prior_analysis(var_list_);\n";
}
PosteriorAnalysisStatement::PosteriorAnalysisStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg) :
tmp_symbol_table(tmp_symbol_table_arg),
options_list(options_list_arg)
{
}
void
PosteriorAnalysisStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
tmp_symbol_table.writeOutput("var_list_", output);
output << "posterior_analysis(var_list_);\n";
}
DynareSensitivityStatement::DynareSensitivityStatement(const OptionsList &options_list_arg) :
options_list(options_list_arg)
{
}
void
DynareSensitivityStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
output << "dynare_sensitivity;" << endl;
}
RplotStatement::RplotStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg) :
tmp_symbol_table(tmp_symbol_table_arg),
options_list(options_list_arg)
{
}
void
RplotStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
tmp_symbol_table.writeOutput("var_list_", output);
output << "rplot(var_list_);\n";
}
UnitRootVarsStatement::UnitRootVarsStatement(const TmpSymbolTable &tmp_symbol_table_arg) :
tmp_symbol_table(tmp_symbol_table_arg)
{
}
void
UnitRootVarsStatement::writeOutput(ostream &output, const string &basename) const
{
tmp_symbol_table.writeOutput("options_.unit_root_vars", output);
}
PeriodsStatement::PeriodsStatement(int periods_arg) : periods(periods_arg)
{
}
void
PeriodsStatement::writeOutput(ostream &output, const string &basename) const
{
output << "options_.periods = " << periods << ";" << endl;
output << "options_.simul = 1;" << endl;
}
CutoffStatement::CutoffStatement(double cutoff_arg) : cutoff(cutoff_arg)
{
}
void
CutoffStatement::writeOutput(ostream &output, const string &basename) const
{
output << "options_.cutoff = " << cutoff << ";" << endl;
}
MarkowitzStatement::MarkowitzStatement(double markowitz_arg) : markowitz(markowitz_arg)
{
}
void
MarkowitzStatement::writeOutput(ostream &output, const string &basename) const
{
output << "options_.markowitz = " << markowitz << ";" << endl;
}
DsampleStatement::DsampleStatement(int val1_arg) : val1(val1_arg), val2(-1)
{
}
DsampleStatement::DsampleStatement(int val1_arg, int val2_arg) : val1(val1_arg), val2(val2_arg)
{
}
void
DsampleStatement::writeOutput(ostream &output, const string &basename) const
{
if (val2 < 0)
output << "options_.dsample = " << val1 << ";" << endl;
else
output << "options_.dsample = [" << val1 << "; " << val2 << "];" << endl;
}
VarobsStatement::VarobsStatement(const TmpSymbolTable &tmp_symbol_table_arg) :
tmp_symbol_table(tmp_symbol_table_arg)
{
}
void
VarobsStatement::writeOutput(ostream &output, const string &basename) const
{
tmp_symbol_table.writeOutput("options_.varobs", output);
}
EstimatedParamsStatement::EstimatedParamsStatement(const vector<EstimationParams> &estim_params_list_arg,
const SymbolTable &symbol_table_arg) :
estim_params_list(estim_params_list_arg),
symbol_table(symbol_table_arg)
{
}
void
EstimatedParamsStatement::writeOutput(ostream &output, const string &basename) const
{
output << "global estim_params_\n";
output << "var_list_ = [];\n";
output << "estim_params_.var_exo = [];\n";
output << "estim_params_.var_endo = [];\n";
output << "estim_params_.corrx = [];\n";
output << "estim_params_.corrn = [];\n";
output << "estim_params_.param_names = [];\n";
output << "estim_params_.user_param_names = [];\n";
output << "estim_params_.param_vals = [];\n";
output << "M_.H = 0;\n";
vector<EstimationParams>::const_iterator it;
for(it = estim_params_list.begin(); it != estim_params_list.end(); it++)
{
switch(it->type)
{
case 1:
if (symbol_table.getType(it->name) == eExogenous)
output << "estim_params_.var_exo = [estim_params_.var_exo; ";
else if (symbol_table.getType(it->name) == eEndogenous)
output << "estim_params_.var_endo = [estim_params_.var_endo; ";
output << symbol_table.getID(it->name)+1;
break;
case 2:
output << "estim_params_.param_vals = [estim_params_.param_vals; ";
output << symbol_table.getID(it->name)+1;
break;
case 3:
if (symbol_table.getType(it->name) == eExogenous)
output << "estim_params_.corrx = [estim_params_.corrx; ";
else if (symbol_table.getType(it->name) == eEndogenous)
output << "estim_params_.corrn = [estim_params_.corrn; ";
output << symbol_table.getID(it->name)+1;
output << " " << symbol_table.getID(it->name2)+1;
break;
}
output << " " << it->init_val << " " << it->low_bound
<< " " << it->up_bound << " " << it->prior
<< " " << it->mean << " " << it->std
<< " " << it->p3 << " " << it->p4 << " " << it->jscale << "];\n";
}
}
EstimatedParamsInitStatement::EstimatedParamsInitStatement(const vector<EstimationParams> &estim_params_list_arg,
const SymbolTable &symbol_table_arg) :
estim_params_list(estim_params_list_arg),
symbol_table(symbol_table_arg)
{
}
void
EstimatedParamsInitStatement::writeOutput(ostream &output, const string &basename) const
{
vector<EstimationParams>::const_iterator it;
for(it = estim_params_list.begin(); it != estim_params_list.end(); it++)
{
if (it->type < 3)
{
if (symbol_table.getType(it->name) == eExogenous)
{
output << "tmp1 = find(estim_params_.var_exo(:,1)==" << symbol_table.getID(it->name)+1 << ");\n";
output << "estim_params_.var_exo(tmp1,2) = " << it->init_val << ";\n";
}
else if (symbol_table.getType(it->name) == eEndogenous)
{
output << "tmp1 = find(estim_params_.var_endo(:,1)==" << symbol_table.getID(it->name)+1 << ");\n";
output << "estim_params_.var_endo(tmp1,2) = " << it->init_val << ";\n";
}
else if (symbol_table.getType(it->name) == eParameter)
{
output << "tmp1 = find(estim_params_.param_vals(:,1)==" << symbol_table.getID(it->name)+1 << ");\n";
output << "estim_params_.param_vals(tmp1,2) = " << it->init_val << ";\n";
}
}
else
{
if (symbol_table.getType(it->name) == eExogenous)
{
output << "tmp1 = find((estim_params_.corrx(:,1)==" << symbol_table.getID(it->name)+1 << ")) & (estim_params_.corrx(:,2)==" << symbol_table.getID(it->name2)+1 << ");\n";
output << "estim_params_.corrx(tmp1,3) = " << it->init_val << ";\n";
}
else if (symbol_table.getType(it->name) == eEndogenous)
{
output << "tmp1 = find((estim_params_.corrn(:,1)==" << symbol_table.getID(it->name)+1 << ")) & (estim_params_.corrn(:,2)==" << symbol_table.getID(it->name2)+1 << ";\n";
output << "estim_params_.corrx(tmp1,3) = " << it->init_val << ";\n";
}
}
}
}
EstimatedParamsBoundsStatement::EstimatedParamsBoundsStatement(const vector<EstimationParams> &estim_params_list_arg,
const SymbolTable &symbol_table_arg) :
estim_params_list(estim_params_list_arg),
symbol_table(symbol_table_arg)
{
}
void
EstimatedParamsBoundsStatement::writeOutput(ostream &output, const string &basename) const
{
vector<EstimationParams>::const_iterator it;
for(it = estim_params_list.begin(); it != estim_params_list.end(); it++)
{
if (it->type < 3)
{
if (symbol_table.getType(it->name) == eExogenous)
{
output << "tmp1 = find(estim_params_.var_exo(:,1)==" << symbol_table.getID(it->name)+1 << ");\n";
output << "estim_params_.var_exo(tmp1,3) = " << it->low_bound << ";\n";
output << "estim_params_.var_exo(tmp1,4) = " << it->up_bound << ";\n";
}
else if (symbol_table.getType(it->name) == eEndogenous)
{
output << "tmp1 = find(estim_params_.var_endo(:,1)==" << symbol_table.getID(it->name)+1 << ");\n";
output << "estim_params_.var_endo(tmp1,3) = " << it->low_bound << ";\n";
output << "estim_params_.var_endo(tmp1,4) = " << it->up_bound << ";\n";
}
else if (symbol_table.getType(it->name) == eParameter)
{
output << "tmp1 = find(estim_params_.param_vals(:,1)==" << symbol_table.getID(it->name)+1 << ");\n";
output << "estim_params_.param_vals(tmp1,3) = " << it->low_bound << ";\n";
output << "estim_params_.param_vals(tmp1,4) = " << it->up_bound << ";\n";
}
}
else
{
if (symbol_table.getType(it->name) == eExogenous)
{
output << "tmp1 = find((estim_params_.corrx(:,1)==" << symbol_table.getID(it->name)+1 << ")) & (estim_params_.corrx(:,2)==" << symbol_table.getID(it->name2)+1 << ");\n";
output << "estim_params_.corrx(tmp1,4) = " << it->low_bound << ";\n";
output << "estim_params_.corrx(tmp1,5) = " << it->up_bound << ";\n";
}
else if (symbol_table.getType(it->name) == eEndogenous)
{
output << "tmp1 = find((estim_params_.corrn(:,1)==" << symbol_table.getID(it->name)+1 << ")) & (estim_params_.corrn(:,2)==" << symbol_table.getID(it->name2)+1 << ";\n";
output << "estim_params_.corrx(tmp1,4) = " << it->low_bound << ";\n";
output << "estim_params_.corrx(tmp1,5) = " << it->up_bound << ";\n";
}
}
}
}
ObservationTrendsStatement::ObservationTrendsStatement(const trend_elements_type &trend_elements_arg,
const SymbolTable &symbol_table_arg) :
trend_elements(trend_elements_arg),
symbol_table(symbol_table_arg)
{
}
void
ObservationTrendsStatement::writeOutput(ostream &output, const string &basename) const
{
output << "options_.trend_coeff_ = {};" << endl;
trend_elements_type::const_iterator it;
for(it = trend_elements.begin(); it != trend_elements.end(); it++)
{
Type type = symbol_table.getType(it->first);
if (type == eEndogenous)
{
output << "tmp1 = strmatch('" << it->first << "',options_.varobs,'exact');\n";
output << "options_.trend_coeffs{tmp1} = '";
it->second->writeOutput(output);
output << "';" << endl;
}
else
cout << "Error : Non-variable symbol used in TREND_COEFF: " << it->first << endl;
}
}
CalibVarStatement::CalibVarStatement(const calib_var_type &calib_var_arg,
const calib_covar_type &calib_covar_arg,
const calib_ac_type &calib_ac_arg,
const SymbolTable &symbol_table_arg) :
calib_var(calib_var_arg),
calib_covar(calib_covar_arg),
calib_ac(calib_ac_arg),
symbol_table(symbol_table_arg)
{
}
void
CalibVarStatement::writeOutput(ostream &output, const string &basename) const
{
output << interfaces::comment() << "\n" << interfaces::comment() << "CALIB_VAR \n"
<< interfaces::comment() << "\n";
for(int i = 1; i < 4 ; i++)
{
output << "calib_var_index{" << i << "} = [];\n";
output << "calib_targets{" << i << "} = [];\n";
output << "calib_weights{" << i << "}=[];\n";
}
// Print calibration variances
for(calib_var_type::const_iterator it = calib_var.begin();
it != calib_var.end(); it++)
{
const string &name = it->first;
const string &weight = it->second.first;
const NodeID expression = it->second.second;
int id = symbol_table.getID(name) + 1;
if (symbol_table.getType(name) == eEndogenous)
{
output << "calib_var_index{1} = [calib_var_index{1};" << id << "," << id << "];\n";
output << "calib_weights{1} = [calib_weights{1}; " << weight << "];\n";
output << "calib_targets{1} =[calib_targets{1}; ";
expression->writeOutput(output);
output << "];\n";
}
else if (symbol_table.getType(name) == eExogenous)
{
output << "calib_var_index{3} = [calib_var_index{3};" << id << "," << id << "];\n";
output << "calib_weights{3} = [calib_weights{3}; " << weight << "];\n";
output << "calib_targets{3} =[calib_targets{3}; ";
expression->writeOutput(output);
output << "];\n";
}
}
// Print calibration covariances
for(calib_covar_type::const_iterator it = calib_covar.begin();
it != calib_covar.end(); it++)
{
const string &name1 = it->first.first;
const string &name2 = it->first.second;
const string &weight = it->second.first;
const NodeID expression = it->second.second;
int id1 = symbol_table.getID(name1) + 1;
int id2 = symbol_table.getID(name2) + 1;
if (symbol_table.getType(name1) == eEndogenous)
{
output << "calib_var_index{1} = [calib_var_index{1};" << id1 << "," << id2 << "];\n";
output << "calib_weights{1} = [calib_weights{1}; " << weight << "];\n";
output << "calib_targets{1} =[calib_targets{1}; ";
expression->writeOutput(output);
output << "];\n";
}
else if (symbol_table.getType(name1) == eExogenous)
{
output << "calib_var_index{3} = [calib_var_index{3};" << id1 << "," << id2 << "];\n";
output << "calib_weights{3} = [calib_weights{3}; " << weight << "];\n";
output << "calib_targets{3} =[calib_targets{3}; ";
expression->writeOutput(output);
output << "];\n";
}
}
// Print calibration autocorrelations
int max_iar = 3;
for(calib_ac_type::const_iterator it = calib_ac.begin();
it != calib_ac.end(); it++)
{
const string &name = it->first.first;
int iar = it->first.second + 3;
const string &weight = it->second.first;
const NodeID expression = it->second.second;
int id = symbol_table.getID(name) + 1;
if (iar > max_iar)
{
// Create new variables
for(int i = max_iar + 1; i <= iar; i++)
{
output << "calib_var_index{" << i << "} = [];\n";
output << "calib_targets{" << i << "} = [];\n";
output << "calib_weights{" << i << "}=[];\n";
}
max_iar = iar;
}
output << "calib_var_index{" << iar << "} = [calib_var_index{" << iar << "};" << id << "];\n";
output << "calib_weights{" << iar << "} = [calib_weights{" << iar << "}; " << weight << "];\n";
output << "calib_targets{" << iar << "} =[calib_targets{" << iar << "}; ";
expression->writeOutput(output);
output << "];\n";
}
}
CalibStatement::CalibStatement(int covar_arg) : covar(covar_arg)
{
}
void
CalibStatement::writeOutput(ostream &output, const string &basename) const
{
output << "M_.Sigma_e=calib(calib_var_index,calib_targets,calib_weights," << covar << ",Sigma_e_);\n";
}
OsrParamsStatement::OsrParamsStatement(const TmpSymbolTable &tmp_symbol_table_arg) :
tmp_symbol_table(tmp_symbol_table_arg)
{
}
void
OsrParamsStatement::writeOutput(ostream &output, const string &basename) const
{
tmp_symbol_table.writeOutput("osr_params_", output);
}
OsrStatement::OsrStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg) :
tmp_symbol_table(tmp_symbol_table_arg),
options_list(options_list_arg)
{
}
void
OsrStatement::checkPass(ModFileStructure &mod_file_struct)
{
mod_file_struct.stoch_simul_or_similar_present = true;
// Fill in option_order of mod_file_struct
OptionsList::num_options_type::const_iterator it = options_list.num_options.find("order");
if (it != options_list.num_options.end())
mod_file_struct.order_option = atoi(it->second.c_str());
}
void
OsrStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
tmp_symbol_table.writeOutput("var_list_", output);
output << "osr(var_list_,osr_params_,obj_var_,optim_weights_);\n";
}
OptimWeightsStatement::OptimWeightsStatement(const var_weights_type &var_weights_arg,
const covar_weights_type &covar_weights_arg,
const SymbolTable &symbol_table_arg) :
var_weights(var_weights_arg),
covar_weights(covar_weights_arg),
symbol_table(symbol_table_arg)
{
}
void
OptimWeightsStatement::writeOutput(ostream &output, const string &basename) const
{
output << interfaces::comment() << "OPTIM_WEIGHTS\n\n";
output << "optim_weights_ = sparse(M_.endo_nbr,M_.endo_nbr);\n";
output << "obj_var_ = [];\n\n";
for(var_weights_type::const_iterator it = var_weights.begin();
it != var_weights.end(); it++)
{
const string &name = it->first;
const NodeID value = it->second;
int id = symbol_table.getID(name) + 1;
output << "optim_weights_(" << id << "," << id << ") = ";
value->writeOutput(output);
output << ";" << endl;
output << "obj_var_ = [obj_var_; " << id << "];\n";
}
for(covar_weights_type::const_iterator it = covar_weights.begin();
it != covar_weights.end(); it++)
{
const string &name1 = it->first.first;
const string &name2 = it->first.second;
const NodeID value = it->second;
int id1 = symbol_table.getID(name1) + 1;
int id2 = symbol_table.getID(name2) + 1;
output << "optim_weights_(" << id1 << "," << id2 << ") = ";
value->writeOutput(output);
output << ";" << endl;
output << "obj_var_ = [obj_var_; " << id1 << " " << id2 << "];\n";
}
}
DynaSaveStatement::DynaSaveStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const string &filename_arg, const string &ext_arg) :
tmp_symbol_table(tmp_symbol_table_arg),
filename(filename_arg),
ext(ext_arg)
{
}
void
DynaSaveStatement::writeOutput(ostream &output, const string &basename) const
{
tmp_symbol_table.writeOutput("var_list_", output);
output << "dynasave(" << filename;
if (ext.size() > 0)
output << "," << ext;
output << ",var_list_);\n";
}
DynaTypeStatement::DynaTypeStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const string &filename_arg, const string &ext_arg) :
tmp_symbol_table(tmp_symbol_table_arg),
filename(filename_arg),
ext(ext_arg)
{
}
void
DynaTypeStatement::writeOutput(ostream &output, const string &basename) const
{
tmp_symbol_table.writeOutput("var_list_", output);
output << "dynatype(" << filename;
if (ext.size() > 0)
output << "," << ext;
output << ",var_list_);\n";
}
ModelComparisonStatement::ModelComparisonStatement(const filename_list_type &filename_list_arg,
const OptionsList &options_list_arg) :
filename_list(filename_list_arg),
options_list(options_list_arg)
{
}
void
ModelComparisonStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
output << "ModelNames_ = {};\n";
output << "ModelPriors_ = {};\n";
for(filename_list_type::const_iterator it = filename_list.begin();
it != filename_list.end(); it++)
{
output << "ModelNames_ = { ModelNames_{:} '" << it->first << "};\n";
output << "ModelPriors_ = { ModelPriors_{:} '" << it->second << "};\n";
}
output << "model_comparison(ModelNames_,ModelPriors_);\n";
}
PlannerObjectiveStatement::PlannerObjectiveStatement(ModelTree *model_tree_arg) :
model_tree(model_tree_arg)
{
}
PlannerObjectiveStatement::~PlannerObjectiveStatement()
{
delete model_tree;
}
void
PlannerObjectiveStatement::checkPass(ModFileStructure &mod_file_struct)
{
if (model_tree->equation_number() != 1)
{
cerr << "Error: planer_objective: should have only one equation!" << endl;
exit(-1);
}
}
void
PlannerObjectiveStatement::computingPass()
{
model_tree->computeStaticHessian = true;
model_tree->computingPass(eval_context_type());
}
void
PlannerObjectiveStatement::writeOutput(ostream &output, const string &basename) const
{
model_tree->writeStaticFile(basename + "_objective");
}
BVARDensityStatement::BVARDensityStatement(int maxnlags_arg, const OptionsList &options_list_arg) :
maxnlags(maxnlags_arg),
options_list(options_list_arg)
{
}
void
BVARDensityStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
output << "bvar_density(" << maxnlags << ");" << endl;
}
BVARForecastStatement::BVARForecastStatement(int nlags_arg, const OptionsList &options_list_arg) :
nlags(nlags_arg),
options_list(options_list_arg)
{
}
void
BVARForecastStatement::writeOutput(ostream &output, const string &basename) const
{
options_list.writeOutput(output);
output << "bvar_forecast(" << nlags << ");" << endl;
}

420
DataTree.cc Normal file
View File

@ -0,0 +1,420 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "DataTree.hh"
DataTree::DataTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg) :
symbol_table(symbol_table_arg),
num_constants(num_constants_arg),
node_counter(0),
variable_table(symbol_table_arg)
{
Zero = AddNumConstant("0");
One = AddNumConstant("1");
MinusOne = AddUMinus(One);
}
DataTree::~DataTree()
{
for (node_list_type::iterator it = node_list.begin(); it != node_list.end(); it++)
delete *it;
}
NodeID
DataTree::AddNumConstant(const string &value)
{
int id = num_constants.AddConstant(value);
num_const_node_map_type::iterator it = num_const_node_map.find(id);
if (it != num_const_node_map.end())
return it->second;
else
return new NumConstNode(*this, id);
}
NodeID
DataTree::AddVariable(const string &name, int lag)
{
int symb_id = symbol_table.getID(name);
Type type = symbol_table.getType(name);
variable_node_map_type::iterator it = variable_node_map.find(make_pair(make_pair(symb_id, type), lag));
if (it != variable_node_map.end())
return it->second;
else
return new VariableNode(*this, symb_id, type, lag);
}
NodeID
DataTree::AddPlus(NodeID iArg1, NodeID iArg2)
{
if (iArg1 != Zero && iArg2 != Zero)
{
// Simplify x+(-y) in x-y
UnaryOpNode *uarg2 = dynamic_cast<UnaryOpNode *>(iArg2);
if (uarg2 != NULL && uarg2->op_code == oUminus)
return AddMinus(iArg1, uarg2->arg);
// To treat commutativity of "+"
// Nodes iArg1 and iArg2 are sorted by index
if (iArg1->idx > iArg2->idx)
{
NodeID tmp = iArg1;
iArg1 = iArg2;
iArg2 = tmp;
}
return AddBinaryOp(iArg1, oPlus, iArg2);
}
else if (iArg1 != Zero)
return iArg1;
else if (iArg2 != Zero)
return iArg2;
else
return Zero;
}
NodeID
DataTree::AddMinus(NodeID iArg1, NodeID iArg2)
{
if (iArg1 != Zero && iArg2 != Zero)
return AddBinaryOp(iArg1, oMinus, iArg2);
else if (iArg1 != Zero)
return iArg1;
else if (iArg2 != Zero)
return AddUMinus(iArg2);
else
return Zero;
}
NodeID
DataTree::AddUMinus(NodeID iArg1)
{
if (iArg1 != Zero)
{
// Simplify -(-x) in x
UnaryOpNode *uarg = dynamic_cast<UnaryOpNode *>(iArg1);
if (uarg != NULL && uarg->op_code == oUminus)
return uarg->arg;
return AddUnaryOp(oUminus, iArg1);
}
else
return Zero;
}
NodeID
DataTree::AddTimes(NodeID iArg1, NodeID iArg2)
{
if (iArg1 == MinusOne)
return AddUMinus(iArg2);
else if (iArg2 == MinusOne)
return AddUMinus(iArg1);
else if (iArg1 != Zero && iArg1 != One && iArg2 != Zero && iArg2 != One)
{
// To treat commutativity of "*"
// Nodes iArg1 and iArg2 are sorted by index
if (iArg1->idx > iArg2->idx)
{
NodeID tmp = iArg1;
iArg1 = iArg2;
iArg2 = tmp;
}
return AddBinaryOp(iArg1, oTimes, iArg2);
}
else if (iArg1 != Zero && iArg1 != One && iArg2 == One)
return iArg1;
else if (iArg2 != Zero && iArg2 != One && iArg1 == One)
return iArg2;
else if (iArg2 == One && iArg1 == One)
return One;
else
return Zero;
}
NodeID
DataTree::AddDivide(NodeID iArg1, NodeID iArg2)
{
if (iArg1 != Zero && iArg2 != Zero && iArg2 != One)
return AddBinaryOp(iArg1, oDivide, iArg2);
else if (iArg2 == One)
return iArg1;
else if (iArg1 == Zero && iArg2 != Zero)
return Zero;
else
{
cerr << "Division by zero!" << endl;
exit(-1);
}
}
NodeID
DataTree::AddLess(NodeID iArg1, NodeID iArg2)
{
return AddBinaryOp(iArg1, oLess, iArg2);
}
NodeID
DataTree::AddGreater(NodeID iArg1, NodeID iArg2)
{
return AddBinaryOp(iArg1, oGreater, iArg2);
}
NodeID
DataTree::AddLessEqual(NodeID iArg1, NodeID iArg2)
{
return AddBinaryOp(iArg1, oLessEqual, iArg2);
}
NodeID
DataTree::AddGreaterEqual(NodeID iArg1, NodeID iArg2)
{
return AddBinaryOp(iArg1, oGreaterEqual, iArg2);
}
NodeID
DataTree::AddEqualEqual(NodeID iArg1, NodeID iArg2)
{
return AddBinaryOp(iArg1, oEqualEqual, iArg2);
}
NodeID
DataTree::AddDifferent(NodeID iArg1, NodeID iArg2)
{
return AddBinaryOp(iArg1, oDifferent, iArg2);
}
NodeID
DataTree::AddPower(NodeID iArg1, NodeID iArg2)
{
if (iArg1 != Zero && iArg2 != Zero && iArg2 != One)
return AddBinaryOp(iArg1, oPower, iArg2);
else if (iArg2 == One)
return iArg1;
else if (iArg2 == Zero)
return One;
else
return Zero;
}
NodeID
DataTree::AddExp(NodeID iArg1)
{
if (iArg1 != Zero)
return AddUnaryOp(oExp, iArg1);
else
return One;
}
NodeID
DataTree::AddLog(NodeID iArg1)
{
if (iArg1 != Zero && iArg1 != One)
return AddUnaryOp(oLog, iArg1);
else if (iArg1 == One)
return Zero;
else
{
cerr << "log(0) isn't available" << endl;
exit(-1);
}
}
NodeID DataTree::AddLog10(NodeID iArg1)
{
if (iArg1 != Zero && iArg1 != One)
return AddUnaryOp(oLog10, iArg1);
else if (iArg1 == One)
return Zero;
else
{
cerr << "log10(0) isn't available" << endl;
exit(-1);
}
}
NodeID
DataTree::AddCos(NodeID iArg1)
{
if (iArg1 != Zero)
return AddUnaryOp(oCos, iArg1);
else
return One;
}
NodeID
DataTree::AddSin(NodeID iArg1)
{
if (iArg1 != Zero)
return AddUnaryOp(oSin, iArg1);
else
return Zero;
}
NodeID
DataTree::AddTan(NodeID iArg1)
{
if (iArg1 != Zero)
return AddUnaryOp(oTan, iArg1);
else
return Zero;
}
NodeID
DataTree::AddACos(NodeID iArg1)
{
if (iArg1 != One)
return AddUnaryOp(oAcos, iArg1);
else
return Zero;
}
NodeID
DataTree::AddASin(NodeID iArg1)
{
if (iArg1 != Zero)
return AddUnaryOp(oAsin, iArg1);
else
return Zero;
}
NodeID
DataTree::AddATan(NodeID iArg1)
{
if (iArg1 != Zero)
return AddUnaryOp(oAtan, iArg1);
else
return Zero;
}
NodeID
DataTree::AddCosH(NodeID iArg1)
{
if (iArg1 != Zero)
return AddUnaryOp(oCosh, iArg1);
else
return One;
}
NodeID
DataTree::AddSinH(NodeID iArg1)
{
if (iArg1 != Zero)
return AddUnaryOp(oSinh, iArg1);
else
return Zero;
}
NodeID
DataTree::AddTanH(NodeID iArg1)
{
if (iArg1 != Zero)
return AddUnaryOp(oTanh, iArg1);
else
return Zero;
}
NodeID
DataTree::AddACosH(NodeID iArg1)
{
if (iArg1 != One)
return AddUnaryOp(oAcosh, iArg1);
else
return Zero;
}
NodeID
DataTree::AddASinH(NodeID iArg1)
{
if (iArg1 != Zero)
return AddUnaryOp(oAsinh, iArg1);
else
return Zero;
}
NodeID
DataTree::AddATanH(NodeID iArg1)
{
if (iArg1 != Zero)
return AddUnaryOp(oAtanh, iArg1);
else
return Zero;
}
NodeID
DataTree::AddSqRt(NodeID iArg1)
{
if (iArg1 != Zero)
return AddUnaryOp(oSqrt, iArg1);
else
return Zero;
}
NodeID
DataTree::AddMaX(NodeID iArg1, NodeID iArg2)
{
return AddBinaryOp(iArg1, oMax, iArg2);
}
NodeID
DataTree::AddMin(NodeID iArg1, NodeID iArg2)
{
return AddBinaryOp(iArg1, oMin, iArg2);
}
NodeID
DataTree::AddNormcdf(NodeID iArg1, NodeID iArg2, NodeID iArg3)
{
return AddTrinaryOp(iArg1, oNormcdf, iArg2, iArg3);
}
NodeID
DataTree::AddEqual(NodeID iArg1, NodeID iArg2)
{
return AddBinaryOp(iArg1, oEqual, iArg2);
}
void
DataTree::AddLocalParameter(const string &name, NodeID value) throw (LocalParameterException)
{
int id = symbol_table.getID(name);
// Throw an exception if symbol already declared
map<int, NodeID>::iterator it = local_variables_table.find(id);
if (it != local_variables_table.end())
throw LocalParameterException(name);
local_variables_table[id] = value;
}
NodeID
DataTree::AddUnknownFunction(const string &function_name, const vector<NodeID> &arguments)
{
if (symbol_table.getType(function_name) != eUnknownFunction)
{
cerr << "Symbol " << function_name << " is not a function name!";
exit(-1);
}
int id = symbol_table.getID(function_name);
return new UnknownFunctionNode(*this, id, arguments);
}

1294
Doxyfile Normal file

File diff suppressed because it is too large Load Diff

1427
DynareBison.yy Normal file

File diff suppressed because it is too large Load Diff

432
DynareFlex.ll Normal file
View File

@ -0,0 +1,432 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
%{
using namespace std;
#include "ParsingDriver.hh"
#include "DynareBison.hh"
// Announce to Flex the prototype we want for lexing function
#define YY_DECL \
Dynare::parser::token_type \
DynareFlex::lex(Dynare::parser::semantic_type *yylval, \
Dynare::parser::location_type *yylloc, \
ParsingDriver &driver)
// Shortcut to access tokens defined by Bison
typedef Dynare::parser::token token;
/* By default yylex returns int, we use token_type.
Unfortunately yyterminate by default returns 0, which is
not of token_type. */
#define yyterminate() return Dynare::parser::token_type (0);
int comment_caller, line_caller;
/* Particular value : when sigma_e command is found
this flag is set to 1, when command finished it is set to 0
*/
int sigma_e = 0;
%}
%option c++
%option prefix="Dynare"
%option case-insensitive noyywrap nounput batch debug never-interactive
%x COMMENT
%x DYNARE_STATEMENT
%x DYNARE_BLOCK
%x NATIVE
%x LINE1
%x LINE2
%x LINE3
%{
// Increments location counter for every token read
#define YY_USER_ACTION yylloc->columns(yyleng);
%}
%%
/* Code put at the beginning of yylex() */
%{
// Reset location before reading token
yylloc->step();
%}
/* Rules for matching @line directives */
<*>^@line\ \" { line_caller = YYSTATE; BEGIN(LINE1); }
<LINE1>[^\"\n]* {
if (yylloc->begin.filename)
delete yylloc->begin.filename;
yylloc->begin.filename = yylloc->end.filename = new string(yytext);
BEGIN(LINE2);
}
<LINE2>\" BEGIN(LINE3);
<LINE3>[0-9]+ {
yylloc->begin.line = yylloc->end.line = atoi(yytext) - 1;
BEGIN(line_caller);
}
/* spaces, tabs and EOL are ignored */
<*>[ \t\r\f]+ { yylloc->step(); }
<*>[\n]+ { yylloc->lines(yyleng); yylloc->step(); }
/* Comments */
<INITIAL,DYNARE_STATEMENT,DYNARE_BLOCK>["%"].*
<INITIAL,DYNARE_STATEMENT,DYNARE_BLOCK>["/"]["/"].*
<INITIAL,DYNARE_STATEMENT,DYNARE_BLOCK>"/*" {comment_caller = YY_START; BEGIN COMMENT;}
<COMMENT>[^*\n]*
<COMMENT>"*"+[^/\n]
<COMMENT>"*"+"/" {BEGIN comment_caller;}
/* Begin of a Dynare statement */
<INITIAL>var {BEGIN DYNARE_STATEMENT; return token::VAR;}
<INITIAL>varexo {BEGIN DYNARE_STATEMENT; return token::VAREXO;}
<INITIAL>varexo_det {BEGIN DYNARE_STATEMENT; return token::VAREXO_DET;}
<INITIAL>parameters {BEGIN DYNARE_STATEMENT; return token::PARAMETERS;}
<INITIAL>periods {BEGIN DYNARE_STATEMENT; return token::PERIODS;}
<INITIAL>cutoff {BEGIN DYNARE_STATEMENT; return token::CUTOFF;}
<INITIAL>markowitz {BEGIN DYNARE_STATEMENT; return token::MARKOWITZ;}
<INITIAL>estimation {BEGIN DYNARE_STATEMENT; return token::ESTIMATION;}
<INITIAL>prior_analysis {BEGIN DYNARE_STATEMENT; return token::PRIOR_ANALYSIS;}
<INITIAL>posterior_analysis {BEGIN DYNARE_STATEMENT; return token::POSTERIOR_ANALYSIS;}
<INITIAL>varobs {BEGIN DYNARE_STATEMENT; return token::VAROBS;}
<INITIAL>unit_root_vars {BEGIN DYNARE_STATEMENT; return token::UNIT_ROOT_VARS;}
<INITIAL>rplot {BEGIN DYNARE_STATEMENT; return token::RPLOT;}
<INITIAL>osr_params {BEGIN DYNARE_STATEMENT; return token::OSR_PARAMS;}
<INITIAL>osr {BEGIN DYNARE_STATEMENT; return token::OSR;}
<INITIAL>dynatype {BEGIN DYNARE_STATEMENT; return token::DYNATYPE;}
<INITIAL>dynasave {BEGIN DYNARE_STATEMENT; return token::DYNASAVE;}
<INITIAL>model_comparison {BEGIN DYNARE_STATEMENT; return token::MODEL_COMPARISON;}
<INITIAL>steady {BEGIN DYNARE_STATEMENT; return token::STEADY;}
<INITIAL>check {BEGIN DYNARE_STATEMENT; return token::CHECK;}
<INITIAL>simul {BEGIN DYNARE_STATEMENT; return token::SIMUL;}
<INITIAL>stoch_simul {BEGIN DYNARE_STATEMENT; return token::STOCH_SIMUL;}
<INITIAL>dsample {BEGIN DYNARE_STATEMENT; return token::DSAMPLE;}
<INITIAL>Sigma_e {BEGIN DYNARE_STATEMENT; sigma_e = 1; return token::SIGMA_E;}
<INITIAL>calib {BEGIN DYNARE_STATEMENT; return token::CALIB;}
<INITIAL>planner_objective {BEGIN DYNARE_STATEMENT; return token::PLANNER_OBJECTIVE;}
<INITIAL>ramsey_policy {BEGIN DYNARE_STATEMENT; return token::RAMSEY_POLICY;}
<INITIAL>bvar_density {BEGIN DYNARE_STATEMENT; return token::BVAR_DENSITY; }
<INITIAL>bvar_forecast {BEGIN DYNARE_STATEMENT; return token::BVAR_FORECAST; }
<INITIAL>dynare_sensitivity {BEGIN DYNARE_STATEMENT; return token::DYNARE_SENSITIVITY;}
/* End of a Dynare statement */
<DYNARE_STATEMENT>; {
if (!sigma_e)
BEGIN INITIAL;
return Dynare::parser::token_type (yytext[0]);
}
/* Begin of a Dynare block */
<INITIAL>model {BEGIN DYNARE_BLOCK; return token::MODEL;}
<INITIAL>initval {BEGIN DYNARE_BLOCK; return token::INITVAL;}
<INITIAL>endval {BEGIN DYNARE_BLOCK; return token::ENDVAL;}
<INITIAL>histval {BEGIN DYNARE_BLOCK; return token::HISTVAL;}
<INITIAL>shocks {BEGIN DYNARE_BLOCK; return token::SHOCKS;}
<INITIAL>estimated_params {BEGIN DYNARE_BLOCK; return token::ESTIMATED_PARAMS;}
/* priors is an alias for estimated_params */
<INITIAL>priors {BEGIN DYNARE_BLOCK;return token::ESTIMATED_PARAMS;}
<INITIAL>estimated_params_init {BEGIN DYNARE_BLOCK; return token::ESTIMATED_PARAMS_INIT;}
<INITIAL>estimated_params_bounds {BEGIN DYNARE_BLOCK; return token::ESTIMATED_PARAMS_BOUNDS;}
<INITIAL>observation_trends {BEGIN DYNARE_BLOCK; return token::OBSERVATION_TRENDS;}
<INITIAL>optim_weights {BEGIN DYNARE_BLOCK; return token::OPTIM_WEIGHTS;}
<INITIAL>calib_var {BEGIN DYNARE_BLOCK; return token::CALIB_VAR;}
<INITIAL>homotopy_setup {BEGIN DYNARE_BLOCK; return token::HOMOTOPY_SETUP;}
/* End of a Dynare block */
<DYNARE_BLOCK>end[ \t\n]*; {BEGIN INITIAL; return token::END;}
/* Inside of a Dynare statement */
<DYNARE_STATEMENT>datafile {return token::DATAFILE;}
<DYNARE_STATEMENT>method {return token::METHOD;}
<DYNARE_STATEMENT>nobs {return token::NOBS;}
<DYNARE_STATEMENT>first_obs {return token::FIRST_OBS;}
<DYNARE_STATEMENT>prefilter {return token::PREFILTER;}
<DYNARE_STATEMENT>presample {return token::PRESAMPLE;}
<DYNARE_STATEMENT>lik_algo {return token::LIK_ALGO;}
<DYNARE_STATEMENT>lik_init {return token::LIK_INIT;}
<DYNARE_STATEMENT>graph {return token::GRAPH;}
<DYNARE_STATEMENT>nograph {return token::NOGRAPH;}
<DYNARE_STATEMENT>print {return token::PRINT;}
<DYNARE_STATEMENT>noprint {return token::NOPRINT;}
<DYNARE_STATEMENT>conf_sig {return token::CONF_SIG;}
<DYNARE_STATEMENT>mh_replic {return token::MH_REPLIC;}
<DYNARE_STATEMENT>mh_drop {return token::MH_DROP;}
<DYNARE_STATEMENT>mh_jscale {return token::MH_JSCALE;}
<DYNARE_STATEMENT>mh_init_scale {return token::MH_INIT_SCALE;}
<DYNARE_STATEMENT>mode_file {return token::MODE_FILE;}
<DYNARE_STATEMENT>mode_compute {return token::MODE_COMPUTE;}
<DYNARE_STATEMENT>mode_check {return token::MODE_CHECK;}
<DYNARE_STATEMENT>prior_trunc {return token::PRIOR_TRUNC;}
<DYNARE_STATEMENT>mh_mode {return token::MH_MODE;}
<DYNARE_STATEMENT>mh_nblocks {return token::MH_NBLOCKS;}
<DYNARE_STATEMENT>load_mh_file {return token::LOAD_MH_FILE;}
<DYNARE_STATEMENT>loglinear {return token::LOGLINEAR;}
<DYNARE_STATEMENT>nodiagnostic {return token::NODIAGNOSTIC;}
<DYNARE_STATEMENT>kalman_algo {return token::KALMAN_ALGO;}
<DYNARE_STATEMENT>kalman_tol {return token::KALMAN_TOL;}
<DYNARE_STATEMENT>forecast {return token::FORECAST;}
<DYNARE_STATEMENT>smoother {return token::SMOOTHER;}
<DYNARE_STATEMENT>bayesian_irf {return token::BAYESIAN_IRF;}
<DYNARE_STATEMENT>moments_varendo {return token::MOMENTS_VARENDO;}
<DYNARE_STATEMENT>filtered_vars {return token::FILTERED_VARS;}
<DYNARE_STATEMENT>filter_step_ahead {return token::FILTER_STEP_AHEAD;}
<DYNARE_STATEMENT>relative_irf {return token::RELATIVE_IRF;}
<DYNARE_STATEMENT>tex {return token::TEX;}
<DYNARE_STATEMENT>nomoments {return token::NOMOMENTS;}
<DYNARE_STATEMENT>corr {return token::CORR;}
<DYNARE_STATEMENT>nocorr {return token::NOCORR;}
<DYNARE_STATEMENT>optim {return token::OPTIM;}
<DYNARE_STATEMENT>periods {return token::PERIODS;}
<DYNARE_STATEMENT>cutoff {return token::CUTOFF;}
<DYNARE_STATEMENT>markowitz {return token::MARKOWITZ;}
<DYNARE_STATEMENT>model_comparison_approximation {return token::MODEL_COMPARISON;}
<DYNARE_STATEMENT>laplace {return token::LAPLACE;}
<DYNARE_STATEMENT>modifiedharmonicmean {return token::MODIFIEDHARMONICMEAN;}
<DYNARE_STATEMENT>constant {return token::CONSTANT;}
<DYNARE_STATEMENT>noconstant {return token::NOCONSTANT;}
<DYNARE_STATEMENT>covar {return token::COVAR;}
<DYNARE_STATEMENT>bvar_prior_tau { return token::BVAR_PRIOR_TAU; }
<DYNARE_STATEMENT>bvar_prior_decay { return token::BVAR_PRIOR_DECAY; }
<DYNARE_STATEMENT>bvar_prior_lambda { return token::BVAR_PRIOR_LAMBDA; }
<DYNARE_STATEMENT>bvar_prior_mu { return token::BVAR_PRIOR_MU; }
<DYNARE_STATEMENT>bvar_prior_omega { return token::BVAR_PRIOR_OMEGA; }
<DYNARE_STATEMENT>bvar_prior_flat { return token::BVAR_PRIOR_FLAT; }
<DYNARE_STATEMENT>bvar_prior_train { return token::BVAR_PRIOR_TRAIN; }
<DYNARE_STATEMENT>bvar_replic { return token::BVAR_REPLIC; }
<DYNARE_STATEMENT>homotopy_mode {return token::HOMOTOPY_MODE; }
<DYNARE_STATEMENT>homotopy_steps {return token::HOMOTOPY_STEPS; }
<DYNARE_STATEMENT>[\$][^$]*[\$] {
strtok(yytext+1, "$");
yylval->string_val = new string(yytext + 1);
return token::TEX_NAME;
}
/* Inside a Dynare block */
<DYNARE_BLOCK>var {return token::VAR;}
<DYNARE_BLOCK>stderr {return token::STDERR;}
<DYNARE_BLOCK>values {return token::VALUES;}
<DYNARE_BLOCK>corr {return token::CORR;}
<DYNARE_BLOCK>periods {return token::PERIODS;}
<DYNARE_BLOCK>cutoff {return token::CUTOFF;}
<DYNARE_BLOCK>markowitz {return token::MARKOWITZ;}
<DYNARE_BLOCK>filename {return token::FILENAME;}
<DYNARE_BLOCK>gamma_pdf {return token::GAMMA_PDF;}
<DYNARE_BLOCK>beta_pdf {return token::BETA_PDF;}
<DYNARE_BLOCK>normal_pdf {return token::NORMAL_PDF;}
<DYNARE_BLOCK>inv_gamma_pdf {return token::INV_GAMMA_PDF;}
<DYNARE_BLOCK>inv_gamma1_pdf {return token::INV_GAMMA_PDF;}
<DYNARE_BLOCK>inv_gamma2_pdf {return token::INV_GAMMA_PDF;}
<DYNARE_BLOCK>uniform_pdf {return token::UNIFORM_PDF;}
<DYNARE_BLOCK>; {return Dynare::parser::token_type (yytext[0]);}
<DYNARE_BLOCK># {return Dynare::parser::token_type (yytext[0]);}
<DYNARE_BLOCK>autocorr {return token::AUTOCORR;}
/* Inside Dynare statement */
<DYNARE_STATEMENT>solve_algo {return token::SOLVE_ALGO;}
<DYNARE_STATEMENT>dr_algo {return token::DR_ALGO;}
<DYNARE_STATEMENT>simul_algo {return token::SIMUL_ALGO;}
<DYNARE_STATEMENT>drop {return token::DROP;}
<DYNARE_STATEMENT>order {return token::ORDER;}
<DYNARE_STATEMENT>replic {return token::REPLIC;}
<DYNARE_STATEMENT>ar {return token::AR;}
<DYNARE_STATEMENT>nofunctions {return token::NOFUNCTIONS;}
<DYNARE_STATEMENT>irf {return token::IRF;}
<DYNARE_STATEMENT>hp_filter {return token::HP_FILTER;}
<DYNARE_STATEMENT>hp_ngrid {return token::HP_NGRID;}
<DYNARE_STATEMENT>simul_seed {return token::SIMUL_SEED;}
<DYNARE_STATEMENT>qz_criterium {return token::QZ_CRITERIUM;}
<DYNARE_STATEMENT>simul {return token::SIMUL;}
<DYNARE_STATEMENT>xls_sheet {return token::XLS_SHEET;}
<DYNARE_STATEMENT>xls_range {return token::XLS_RANGE;}
<DYNARE_STATEMENT>mh_recover {return token::MH_RECOVER;}
<DYNARE_STATEMENT>planner_discount {return token::PLANNER_DISCOUNT;}
<DYNARE_STATEMENT>[\.] {return Dynare::parser::token_type (yytext[0]);}
<DYNARE_STATEMENT>[\\] {return Dynare::parser::token_type (yytext[0]);}
<DYNARE_STATEMENT>[\'] {return Dynare::parser::token_type (yytext[0]);}
<DYNARE_STATEMENT,DYNARE_BLOCK>use_dll {return token::USE_DLL;}
<DYNARE_STATEMENT,DYNARE_BLOCK>lu {return token::LU;}
<DYNARE_STATEMENT,DYNARE_BLOCK>gaussian_elimination {return token::GAUSSIAN_ELIMINATION;}
<DYNARE_STATEMENT,DYNARE_BLOCK>gmres {return token::GMRES;}
<DYNARE_STATEMENT,DYNARE_BLOCK>bicgstab {return token::BICGSTAB;}
<DYNARE_STATEMENT,DYNARE_BLOCK>sparse {return token::SPARSE;}
<DYNARE_STATEMENT,DYNARE_BLOCK>sparse_dll {return token::SPARSE_DLL;}
<DYNARE_STATEMENT,DYNARE_BLOCK>gcc_compiler {return token::GCC_COMPILER;}
<DYNARE_STATEMENT,DYNARE_BLOCK>lcc_compiler {return token::LCC_COMPILER;}
<DYNARE_STATEMENT,DYNARE_BLOCK>no_compiler {return token::NO_COMPILER;}
<DYNARE_STATEMENT,DYNARE_BLOCK>linear {return token::LINEAR;}
<DYNARE_STATEMENT,DYNARE_BLOCK>[,] {return token::COMMA;}
<DYNARE_STATEMENT,DYNARE_BLOCK>[:] {return Dynare::parser::token_type (yytext[0]);}
<DYNARE_STATEMENT,DYNARE_BLOCK>[\(\)] {return Dynare::parser::token_type (yytext[0]);}
<DYNARE_STATEMENT,DYNARE_BLOCK>[\[] {return Dynare::parser::token_type (yytext[0]);}
<DYNARE_STATEMENT,DYNARE_BLOCK>[\]] {
if (sigma_e)
sigma_e = 0;
return Dynare::parser::token_type (yytext[0]);
}
<DYNARE_STATEMENT,DYNARE_BLOCK>[+] {return token::PLUS;}
<DYNARE_STATEMENT,DYNARE_BLOCK>[-] {return token::MINUS;}
<DYNARE_STATEMENT,DYNARE_BLOCK>[*] {return token::TIMES;}
<DYNARE_STATEMENT,DYNARE_BLOCK>[/] {return token::DIVIDE;}
<DYNARE_STATEMENT,DYNARE_BLOCK>[=] {return token::EQUAL;}
<DYNARE_STATEMENT,DYNARE_BLOCK>[<] {return token::LESS;}
<DYNARE_STATEMENT,DYNARE_BLOCK>[>] {return token::GREATER;}
<DYNARE_STATEMENT,DYNARE_BLOCK>">=" {return token::GREATER_EQUAL;}
<DYNARE_STATEMENT,DYNARE_BLOCK>"<=" {return token::LESS_EQUAL;}
<DYNARE_STATEMENT,DYNARE_BLOCK>"==" {return token::EQUAL_EQUAL;}
<DYNARE_STATEMENT,DYNARE_BLOCK>"!=" {return token::EXCLAMATION_EQUAL;}
<DYNARE_STATEMENT,DYNARE_BLOCK>[!] {return token::EXCLAMATION;}
<DYNARE_STATEMENT,DYNARE_BLOCK>[\^] {return token::POWER;}
<DYNARE_STATEMENT,DYNARE_BLOCK>exp {return token::EXP;}
<DYNARE_STATEMENT,DYNARE_BLOCK>log {return token::LOG;}
<DYNARE_STATEMENT,DYNARE_BLOCK>log10 {return token::LOG10;}
<DYNARE_STATEMENT,DYNARE_BLOCK>ln {return token::LN;}
<DYNARE_STATEMENT,DYNARE_BLOCK>sin {return token::SIN;}
<DYNARE_STATEMENT,DYNARE_BLOCK>cos {return token::COS;}
<DYNARE_STATEMENT,DYNARE_BLOCK>tan {return token::TAN;}
<DYNARE_STATEMENT,DYNARE_BLOCK>asin {return token::ASIN;}
<DYNARE_STATEMENT,DYNARE_BLOCK>acos {return token::ACOS;}
<DYNARE_STATEMENT,DYNARE_BLOCK>atan {return token::ATAN;}
<DYNARE_STATEMENT,DYNARE_BLOCK>sinh {return token::SINH;}
<DYNARE_STATEMENT,DYNARE_BLOCK>cosh {return token::COSH;}
<DYNARE_STATEMENT,DYNARE_BLOCK>tanh {return token::TANH;}
<DYNARE_STATEMENT,DYNARE_BLOCK>asinh {return token::ASINH;}
<DYNARE_STATEMENT,DYNARE_BLOCK>acosh {return token::ACOSH;}
<DYNARE_STATEMENT,DYNARE_BLOCK>atanh {return token::ATANH;}
<DYNARE_STATEMENT,DYNARE_BLOCK>sqrt {return token::SQRT;}
<DYNARE_STATEMENT,DYNARE_BLOCK>max {return token::MAX;}
<DYNARE_STATEMENT,DYNARE_BLOCK>min {return token::MIN;}
<DYNARE_STATEMENT,DYNARE_BLOCK>normcdf {return token::NORMCDF;}
/* options for GSA module by Marco Ratto */
<DYNARE_STATEMENT>identification {return token::IDENTIFICATION;}
<DYNARE_STATEMENT>morris {return token::MORRIS;}
<DYNARE_STATEMENT>stab {return token::STAB;}
<DYNARE_STATEMENT>redform {return token::REDFORM;}
<DYNARE_STATEMENT>pprior {return token::PPRIOR;}
<DYNARE_STATEMENT>prior_range {return token::PRIOR_RANGE;}
<DYNARE_STATEMENT>ppost {return token::PPOST;}
<DYNARE_STATEMENT>ilptau {return token::ILPTAU;}
<DYNARE_STATEMENT>glue {return token::GLUE;}
<DYNARE_STATEMENT>morris_nliv {return token::MORRIS_NLIV;}
<DYNARE_STATEMENT>morris_ntra {return token::MORRIS_NTRA;}
<DYNARE_STATEMENT>Nsam {return token::NSAM;}
<DYNARE_STATEMENT>load_redform {return token::LOAD_REDFORM;}
<DYNARE_STATEMENT>load_rmse {return token::LOAD_RMSE;}
<DYNARE_STATEMENT>load_stab {return token::LOAD_STAB;}
<DYNARE_STATEMENT>alpha2_stab {return token::ALPHA2_STAB;}
<DYNARE_STATEMENT>ksstat {return token::KSSTAT;}
<DYNARE_STATEMENT>logtrans_redform {return token::LOGTRANS_REDFORM;}
<DYNARE_STATEMENT>threshold_redform {return token::THRESHOLD_REDFORM;}
<DYNARE_STATEMENT>ksstat_redform {return token::KSSTAT_REDFORM;}
<DYNARE_STATEMENT>alpha2_redform {return token::ALPHA2_REDFORM;}
<DYNARE_STATEMENT>namendo {return token::NAMENDO;}
<DYNARE_STATEMENT>namlagendo {return token::NAMLAGENDO;}
<DYNARE_STATEMENT>namexo {return token::NAMEXO;}
<DYNARE_STATEMENT>rmse {return token::RMSE;}
<DYNARE_STATEMENT>lik_only {return token::LIK_ONLY;}
<DYNARE_STATEMENT>var_rmse {return token::VAR_RMSE;}
<DYNARE_STATEMENT>pfilt_rmse {return token::PFILT_RMSE;}
<DYNARE_STATEMENT>istart_rmse {return token::ISTART_RMSE;}
<DYNARE_STATEMENT>alpha_rmse {return token::ALPHA_RMSE;}
<DYNARE_STATEMENT>alpha2_rmse {return token::ALPHA2_RMSE;}
/* end of GSA options */
<DYNARE_STATEMENT,DYNARE_BLOCK>[A-Za-z_][A-Za-z0-9_]* {
yylval->string_val = new string(yytext);
return token::NAME;
}
<DYNARE_STATEMENT,DYNARE_BLOCK>((([0-9]*\.[0-9]+)|([0-9]+\.))([edED][-+]?[0-9]+)?)|([0-9]+[edED][-+]?[0-9]+) {
yylval->string_val = new string(yytext);
return token::FLOAT_NUMBER;
}
<DYNARE_STATEMENT,DYNARE_BLOCK>[0-9]+ {
yylval->string_val = new string(yytext);
return token::INT_NUMBER;
}
/* an instruction starting with a recognized symbol (which is not a modfile local variable)
is passed as NAME,
otherwise it is a native statement until the end of the line
*/
<INITIAL>[A-Za-z_][A-Za-z0-9_]* {
if (driver.symbol_exists_and_is_not_modfile_local_variable(yytext))
{
BEGIN DYNARE_STATEMENT;
yylval->string_val = new string(yytext);
return token::NAME;
}
else
{
/* Enter a native block */
BEGIN NATIVE;
yyless(0);
}
}
/* Enter a native block */
<INITIAL>. { BEGIN NATIVE; yyless(0); }
/* Add the native statement */
<NATIVE>.* { driver.add_native(yytext); BEGIN INITIAL; }
<*>. { driver.error(*yylloc, "character unrecognized by lexer"); }
%%
DynareFlex::DynareFlex(istream* in, ostream* out)
: DynareFlexLexer(in, out)
{
}
/* This implementation of DynareFlexLexer::yylex() is required to fill the
* vtable of the class DynareFlexLexer. We define the scanner's main yylex
* function via YY_DECL to reside in the DynareFlex class instead. */
#ifdef yylex
# undef yylex
#endif
int
DynareFlexLexer::yylex()
{
cerr << "DynareFlexLexer::yylex() has been called, that should never happen!" << endl;
exit(-1);
}
/*
Local variables:
mode: C++
End:
*/

98
DynareMain.cc Normal file
View File

@ -0,0 +1,98 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
using namespace std;
#include <iostream>
#include <sstream>
#include <fstream>
#include <cctype> // for tolower()
#include <algorithm> // for transform()
#include "macro/MacroDriver.hh"
/* Prototype for second part of main function
Splitting main() in two parts was necessary because ParsingDriver.h and MacroDriver.h can't be
included simultaneously (because of Bison limitations).
*/
void main2(stringstream &in, string &basename, bool trace_scanning, bool trace_parsing,
bool clear_all);
int
main(int argc, char** argv)
{
if (argc < 2)
{
cerr << "Missing model file!" << endl;
cerr << "Dynare usage: dynare mod_file [debug] [noclearall] [savemacro]" << endl;
exit(-1);
}
bool clear_all = true;
bool save_macro = false;
bool trace_scanning = false;
bool trace_parsing = false;
// Parse options
for (int arg = 2; arg < argc; arg++)
{
if (string(argv[arg]) == string("debug"))
{
trace_scanning = true;
trace_parsing = true;
}
else if (string(argv[arg]) == string("noclearall"))
clear_all = false;
else if (string(argv[arg]) == string("savemacro"))
save_macro = true;
}
cout << "Starting Dynare ..." << endl;
cout << "Parsing your model file ..." << endl;
// Construct basename (check file extension is correct then remove it)
string basename = argv[1];
string ext = basename.substr(basename.size() - 4);
transform(ext.begin(), ext.end(), ext.begin(), (int(*)(int)) tolower); // Convert ext to lowercase
if (ext != string(".mod") && ext != string(".dyn"))
{
cerr << "mod_file extension must be .mod or .dyn!" << endl;
exit(-1);
}
basename.erase(basename.size() - 4, 4);
// Do macro processing
MacroDriver m;
m.trace_scanning = trace_scanning;
m.trace_parsing = trace_parsing;
stringstream macro_output;
m.parse(argv[1], macro_output);
if (save_macro)
{
ofstream macro_output_file((basename + "-macroexp.mod").c_str());
macro_output_file << macro_output.str();
macro_output_file.close();
}
// Do the rest
main2(macro_output, basename, trace_scanning, trace_parsing, clear_all);
return 0;
}

50
DynareMain2.cc Normal file
View File

@ -0,0 +1,50 @@
/*
* Copyright (C) 2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
using namespace std;
#include <iostream>
#include "ParsingDriver.hh"
#include "ModFile.hh"
void
main2(stringstream &in, string &basename, bool trace_scanning, bool trace_parsing, bool clear_all)
{
ParsingDriver p;
p.trace_scanning = trace_scanning;
p.trace_parsing = trace_parsing;
// Do parsing and construct internal representation of mod file
ModFile *mod_file = p.parse(in);
// Run checking pass
mod_file->checkPass();
// Do computations
mod_file->computingPass();
// Write outputs
mod_file->writeOutputFiles(basename, clear_all);
delete mod_file;
cout << "Parsing done" << endl;
cout << "Starting Matlab computing ..." << endl;
}

1680
ExprNode.cc Normal file

File diff suppressed because it is too large Load Diff

65
InterfaceMatlab.cc Normal file
View File

@ -0,0 +1,65 @@
/*
* Copyright (C) 2006-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include "Interface.hh"
namespace interfaces
{
string comment()
{
return "% ";
}
string delete_file(string s)
{
return "delete " + s;
}
string file_exist(string s)
{
return "exist('" + s + "')";
}
string compile(string s)
{
return "mex -O " + s + "\n";
}
string function_close()
{
return "";
}
string function_file_extension()
{
return ".m";
}
string strvcat(string s1, string s2)
{
return "strvcat(" + s1 + "," + s2 + ")";
}
string load_model_function_files(string filename)
{
return "";
}
}

65
InterfaceScilab.cc Normal file
View File

@ -0,0 +1,65 @@
/*
* Copyright (C) 2006-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include "Interface.hh"
namespace interfaces
{
string comment()
{
return "// ";
}
string delete_file(string s)
{
return "mdelete " + s;
}
string file_exist(string s)
{
return "file_exist(" + s + ")";
}
string compile(string s)
{
return "";
}
string function_close()
{
return "endfunction\n";
}
string function_file_extension()
{
return ".sci";
}
string strvcat(string s1, string s2)
{
return "[" + s1 + ";" + s2 + "]";
}
string load_model_function_files(string filename)
{
return "getf('" + filename + "_static.sci');\ngetf('" + filename + "_dynamic.sci');\n";
}
}

92
Makefile Normal file
View File

@ -0,0 +1,92 @@
include Makefile.include
ifeq ($(shell uname -o), Cygwin)
DYNARE_M = dynare_m.exe
DYNARE_S = dynare_s.exe
else
DYNARE_M = dynare_m
DYNARE_S = dynare_s
endif
ifeq ($(CROSS_WIN32), yes)
DYNARE_M = dynare_m.exe
DYNARE_S = dynare_s.exe
endif
COMMON_OBJ = \
DynareFlex.o \
DynareBison.o \
ComputingTasks.o \
ModelTree.o \
NumericalConstants.o \
NumericalInitialization.o \
Shocks.o \
SigmaeInitialization.o \
SymbolTable.o \
TmpSymbolTable.o \
VariableTable.o \
ParsingDriver.o \
DataTree.o \
ModFile.o \
Statement.o \
ExprNode.o \
ModelNormalization.o \
ModelBlocks.o \
BlockTriangular.o \
Model_Graph.o \
SymbolGaussElim.o \
DynareMain.o \
DynareMain2.o
MATLAB_OBJ = InterfaceMatlab.o
SCILAB_OBJ = InterfaceScilab.o
# Build rules
all: all-recursive $(DYNARE_M) $(DYNARE_S)
all-recursive:
make -C macro
$(DYNARE_M): $(COMMON_OBJ) $(MATLAB_OBJ) macro/libmacro.a
$(CPP) $(CPPFLAGS) -o $(DYNARE_M) $(COMMON_OBJ) $(MATLAB_OBJ) -Lmacro -lmacro
cp $(DYNARE_M) ../matlab/
$(DYNARE_S): $(COMMON_OBJ) $(SCILAB_OBJ) macro/libmacro.a
$(CPP) $(CPPFLAGS) -o $(DYNARE_S) $(COMMON_OBJ) $(SCILAB_OBJ) -Lmacro -lmacro
cp $(DYNARE_S) ../scilab/
# Dependencies
-include $(COMMON_OBJ:.o=.P) $(MATLAB_OBJ:.o=.P) $(SCILAB_OBJ:.o=.P)
DynareFlex.cc: DynareFlex.ll include/DynareBison.hh include/ParsingDriver.hh
flex -oDynareFlex.cc DynareFlex.ll
DynareBison.cc include/DynareBison.hh: DynareBison.yy include/ParsingDriver.hh
bison --verbose -o DynareBison.cc DynareBison.yy
mv DynareBison.hh location.hh stack.hh position.hh include/
# Clean
clean: clean-recursive
rm -f *.o *.P \
*~ include/*~ \
DynareFlex.cc \
DynareBison.output \
DynareBison.cc \
include/position.hh \
include/stack.hh \
include/location.hh \
include/DynareBison.hh \
$(DYNARE_M) \
$(DYNARE_S)
clean-recursive:
make -C macro clean
.PHONY: all all-recursive clean clean-recursive

37
Makefile.include Normal file
View File

@ -0,0 +1,37 @@
CPP = g++
CPPFLAGS = -Wall
ifeq ($(shell uname -o), Cygwin)
# Detection of uninitialized variables is buggy in Cygwin and generates spurious warnings
CPPFLAGS += -Wno-uninitialized
CPPFLAGS += -mno-cygwin
endif
ifeq ($(CROSS_WIN32), yes)
CPP = i586-mingw32msvc-g++
# Detection of uninitialized variables is buggy in MinGW and generates spurious warnings
CPPFLAGS += -Wno-uninitialized
endif
ifeq ($(DEBUG),yes)
CPPFLAGS += -ggdb
else
CPPFLAGS += -O3
endif
ifeq ($(VALGRIND), yes)
CPPFLAGS = -Wall -O -g -fno-inline
endif
# General rule for compilation
%.o : %.cc
$(CPP) $(CPPFLAGS) -MD -I include -c $<
@cp $*.d $*.P; \
sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
-e '/^$$/ d' -e 's/$$/ :/' < $*.d >> $*.P; \
rm -f $*.d
# Local variables:
# mode: makefile
# End:

196
ModFile.cc Normal file
View File

@ -0,0 +1,196 @@
/*
* Copyright (C) 2006-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <fstream>
#include "ModFile.hh"
#include "Interface.hh"
ModFile::ModFile() : expressions_tree(symbol_table, num_constants),
model_tree(symbol_table, num_constants),
linear(false)
{
}
ModFile::~ModFile()
{
for(vector<Statement *>::iterator it = statements.begin();
it != statements.end(); it++)
delete (*it);
}
void
ModFile::addStatement(Statement *st)
{
statements.push_back(st);
}
void
ModFile::checkPass()
{
for(vector<Statement *>::iterator it = statements.begin();
it != statements.end(); it++)
(*it)->checkPass(mod_file_struct);
// Allow empty model only when doing a standalone BVAR estimation
if (model_tree.equation_number() == 0
&& (mod_file_struct.check_present
|| mod_file_struct.simul_present
|| mod_file_struct.stoch_simul_or_similar_present))
{
cerr << "Error: you must declare at least one model equation!" << endl;
exit(-1);
}
if (mod_file_struct.simul_present
&& mod_file_struct.stoch_simul_or_similar_present)
{
cerr << "Error: a mod file cannot contain both a simul command and one of {stoch_simul, estimation, osr, ramsey_policy}" << endl;
exit(-1);
}
}
void
ModFile::computingPass()
{
// Mod file may have no equation (for example in a standalone BVAR estimation)
if (model_tree.equation_number() > 0)
{
// Set things to compute
if (mod_file_struct.simul_present)
model_tree.computeJacobian = true;
else
{
if (mod_file_struct.order_option < 1 || mod_file_struct.order_option > 3)
{
cerr << "Incorrect order option..." << endl;
exit(-1);
}
model_tree.computeJacobianExo = true;
if (mod_file_struct.order_option >= 2)
model_tree.computeHessian = true;
if (mod_file_struct.order_option == 3)
model_tree.computeThirdDerivatives = true;
}
model_tree.computingPass(global_eval_context);
}
for(vector<Statement *>::iterator it = statements.begin();
it != statements.end(); it++)
(*it)->computingPass();
}
void
ModFile::writeOutputFiles(const string &basename, bool clear_all) const
{
ofstream mOutputFile;
if (basename.size())
{
string fname(basename);
fname += interfaces::function_file_extension();
mOutputFile.open(fname.c_str(), ios::out | ios::binary);
if (!mOutputFile.is_open())
{
cerr << "Error: Can't open file " << fname
<< " for writing" << endl;
exit(-1);
}
}
else
{
cerr << "Error: Missing file name" << endl;
exit(-1);
}
mOutputFile << interfaces::comment() << endl;
mOutputFile << interfaces::comment() << "Status : main Dynare file " << endl;
mOutputFile << interfaces::comment() << endl;
mOutputFile << interfaces::comment() << "Warning : this file is generated automatically by Dynare" << endl;
mOutputFile << interfaces::comment() << " from model file (.mod)" << endl << endl;
if (clear_all)
mOutputFile << "clear all" << endl;
mOutputFile << "tic;" << endl;
mOutputFile << "global M_ oo_ exedet_ exdet_ recur_ recurs_ " << endl;
mOutputFile << "global options_ endval_" << endl;
mOutputFile << "global ys0_ recurs0_ ex0_ ct_" << endl;
mOutputFile << "options_ = [];" << endl;
mOutputFile << "M_.fname = '" << basename << "';" << endl;
mOutputFile << interfaces::comment() << endl;
mOutputFile << interfaces::comment() << "Some global variables initialisation" << endl;
mOutputFile << interfaces::comment() << endl;
mOutputFile << "global_initialization;" << endl;
mOutputFile << "diary off;" << endl << "warning off;" << endl << endl;
mOutputFile << interfaces::delete_file(basename + ".log") << ";" << endl;
mOutputFile << "warning on;" << endl << "warning backtrace;" << endl;
mOutputFile << "logname_ = '" << basename << ".log';" << endl;
mOutputFile << "diary '" << basename << ".log';" << endl;
if (model_tree.equation_number() > 0)
{
if (model_tree.mode == eDLLMode)
{
mOutputFile << "if ";
mOutputFile << interfaces::file_exist(basename + "_static.c") << endl;
mOutputFile << " clear " << basename << "_static" << endl;
mOutputFile << " " << interfaces::compile(basename +"_static.c") << endl;
mOutputFile << "end" << endl;
mOutputFile << "if ";
mOutputFile << interfaces::file_exist(basename + "_dynamic.c") << endl;
mOutputFile << " clear " << basename << "_dynamic" << endl;
mOutputFile << " " + interfaces::compile(basename+"_dynamic.c") << endl;
mOutputFile << "end" << endl;
}
else
{
mOutputFile << "erase_compiled_function('" + basename +"_static');" << endl;
mOutputFile << "erase_compiled_function('" + basename +"_dynamic');" << endl;
mOutputFile << interfaces::load_model_function_files(basename);
}
}
cout << "Processing outputs ..." << endl;
symbol_table.writeOutput(mOutputFile);
if (linear == 1)
mOutputFile << "options_.linear = 1;" << endl;
if (model_tree.equation_number() > 0)
{
model_tree.writeOutput(mOutputFile);
model_tree.writeStaticFile(basename);
model_tree.writeDynamicFile(basename);
}
// Print statements
for(vector<Statement *>::const_iterator it = statements.begin();
it != statements.end(); it++)
(*it)->writeOutput(mOutputFile, basename);
mOutputFile << "save('" << basename << "_results', 'oo_');" << endl;
mOutputFile << "diary off" << endl;
mOutputFile << endl << "disp(['Total computing time : ' sec2hms(round(toc)) ]);" << endl;
mOutputFile.close();
}

351
ModelBlocks.cc Normal file
View File

@ -0,0 +1,351 @@
/*
* Copyright (C) 2007-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include "ModelBlocks.hh"
using namespace std;
#define UNDEFINED -1
Blocks::Blocks()
{
//Empty
}
Blocks::~Blocks()
{
//Empty
}
int n_sc_set=0;
void
Blocks::block_depth_search(int v)
// block_depth_search()
// find the strong components of the graph using a recursive depth first search
// The results are stored in the global variables block_vertices, sets_s, sets_f.
{
Edge *edge_ptr;
int w;
// Add the vertex v to the visited vertex and store it in the result (low_link_nos)
// and increase the number of visited vertex
low_link_nos[v] = visit_nos[v] = n_visited;
n_visited++;
// Put v in the stack.
block_stack[tos] = v;
sp[v] = tos;
tos++;
// Going to visite the edges from vertex v starting
// from the First edge of vetexe v
edge_ptr = vertices[v].First_Edge;
// While there is edge
while(edge_ptr)
{
w = edge_ptr->Vertex_Index;
// if the vertex w hasen't been visited
if(visit_nos[w] == UNDEFINED)
{
// visits the vertex w
block_depth_search(w);
// Update low_link no.
if(low_link_nos[w] < low_link_nos[v])
low_link_nos[v] = low_link_nos[w];
}
else if(visit_nos[w] < visit_nos[v] && sp[w] != UNDEFINED)
{
// Update low_link no. */
if(visit_nos[w] < low_link_nos[v])
if(visit_nos[w]>=0)
low_link_nos[v] = visit_nos[w];
else
{
// Check for hierarchic structure accross strong connex components
if(pos_sc[-(visit_nos[w]+2)]<pos_sc[n_sets])
{
int j=pos_sc[-(visit_nos[w]+2)];
pos_sc[-(visit_nos[w]+2)]=pos_sc[n_sets];
pos_sc[n_sets]=j;
}
}
}
edge_ptr = edge_ptr->next;
}
// If all vertices in v's SC component have been found.
if(low_link_nos[v] == visit_nos[v])
{
int vpos = sp[v];
int i;
sets_s[n_sets] = n_written;
// The SC component vertices are stored from the top of the stack, down
// to v. Write these to the result structure.
for(i = vpos; i < tos; i++)
{
block_vertices[n_written] = block_stack[i];
n_written++;
}
if(n_sc_set>0)
for(i=0;i<n_sc_set;i++)
if(pos_sc[i]<pos_sc[n_sc_set])
{
int j=pos_sc[i];
pos_sc[i]=pos_sc[n_sc_set];
pos_sc[n_sc_set]=j;
for(j=sets_s[i];j<=sets_f[i];j++)
visit_nos[block_vertices[j]] = -(2+pos_sc[i]);
}
n_sc_set++;
for(i = vpos; i < tos; i++)
{
visit_nos[block_stack[i]] = -(2+pos_sc[n_sets]);
}
// Now remove these vertices from the stack.
for(i = vpos; i < tos; i++)
block_stack[i] = UNDEFINED;
tos = vpos;
sets_f[n_sets] = n_written - 1;
n_sets++;
}
// stsz.erase(stsz.length()-1,1);
}
block_result_t*
Blocks::sc(Equation_set *g)
// Generates SC components using Tarjan's algorithm.
// The result is returned as a pointer to a block_result_t structure. The SC
// components are stored as two arrays:
// - sets_s[i] gives the starting position in the vertices[] array of SC
// component i.
// - sets_f[i] gives the finishing position in the vertices[] array of SC
// component i.
// - vertices[] is used for storing the vertex numbers of vertices in the
// SC components.
// For example if there are three SC components the vertices in each are stored
// as follows:
// - SC0: vertices[sets_s[0]] ... vertices[sets_f[0]].
// - SC1: vertices[sets_s[1]] ... vertices[sets_f[1]].
// - SC2: vertices[sets_s[2]] ... vertices[sets_f[2]].
// Note that array entries sets[3] onwards are set to UNDEFINED.
{
int i, v, n;
block_result_t *result;
n = g->size;
// accessed by block_depth_search()
vertices = g->Number;
// Allocate space for arrays to represent the search result.
result = (block_result*)malloc(sizeof(block_result_t));
block_vertices = result->vertices = (int*)malloc(n * sizeof(int));
sets_s = result->sets_s = (int*)malloc(n *sizeof(int));
sets_f = result->sets_f = (int*)malloc(n *sizeof(int));
pos_sc = result->order = (int*)malloc(n * sizeof(int));
result->ordered = (int*)malloc(n * sizeof(int));
// Allocate space for arrays used while generating the result.
block_stack = (int*)malloc(n * sizeof(int));
sp = (int*)malloc(n * sizeof(int));
visit_nos = (int*)malloc(n * sizeof(int));
low_link_nos = (int*)malloc(n * sizeof(int));
// Initialise necessary array entries to UNDEFINED.
// - sets_s[] and sets_f[] array entries are UNDEFINED, until data is
// written into them.
// - visit_nos[] array entries are UNDEFINED, until a vertex has been
// visited,
// - sp[v] is UNDEFINED unless v is in the stack.
for(i = 0; i < n; i++)
{
sets_s[i] = sets_f[i] = visit_nos[i] = sp[i] = UNDEFINED;
pos_sc[i] = i;
}
// Array sizes in the result structure.
result->size = n;
// Tarjan's algorithm proceeds as a recursive depth first search. Note
// that the block_depth_search() function accesses the current graph through the
// global variable `vertices'. If parts of the graph were not reached
// block_depth_search() will be called again, until all vertices have been
// reached.
tos = 0;
n_written = n_visited = 0;
n_sets = 0;
for(v = 0; v < n; v++)
{
n_sc_set=0;
if(visit_nos[v] == UNDEFINED)
block_depth_search(v);
}
result->n_sets = n_sets;
for(i = 0; i < n_sets; i++)
result->ordered[result->order[i]]=i;
// free space taken up by arrays used while generating the result.
free(block_stack);
free(sp);
free(visit_nos);
free(low_link_nos);
return result;
}
void
Blocks::block_result_free(block_result_t *r)
{
free(r->vertices);
free(r->sets_s);
free(r->sets_f);
free(r->order);
free(r->ordered);
free(r);
}
void
Blocks::block_result_print(block_result_t *r)
{
int i, j, n_sets;
n_sets = r->n_sets;
cout << n_sets << " SC components:\n\n";
for(i = 0; i < n_sets; i++)
{
cout << "SC" << r->order[i] << " = ";
for(j = r->sets_s[i]; j <= r->sets_f[i]; j++)
{
cout << r->vertices[j] << " ";
}
cout << "\n";
}
for(i = 0; i < n_sets; i++)
{
cout << "SC" << i << " = ";
for(j = r->sets_s[r->ordered[i]]; j <= r->sets_f[r->ordered[i]]; j++)
{
cout << r->vertices[j] << " ";
}
cout << "\n";
}
}
void
Blocks::block_result_to_IM(block_result_t *r,bool* IM,int prologue, int n,simple* Index_Equ_IM,simple* Index_Var_IM)
{
int i, j, k, l;
bool* SIM=(bool*)malloc(n*n*sizeof(*SIM));
simple* Index_Equ_IM_tmp=(simple*)malloc(n*sizeof(*Index_Equ_IM_tmp));
simple* Index_Var_IM_tmp=(simple*)malloc(n*sizeof(*Index_Var_IM_tmp));
for(i=0;i<n*n;i++)
SIM[i]=IM[i];
for(i=0;i<n;i++)
{
Index_Equ_IM_tmp[i].index=Index_Equ_IM[i].index;
Index_Var_IM_tmp[i].index=Index_Var_IM[i].index;
}
l=prologue;
for(i = 0; i < r->n_sets; i++)
{
for(j = r->sets_s[r->ordered[i]]; j <= r->sets_f[r->ordered[i]]; j++)
{
Index_Equ_IM[l].index=Index_Equ_IM_tmp[r->vertices[j]+prologue].index;
for(k=0;k<n;k++)
SIM[l*n+k]=IM[(r->vertices[j]+prologue)*n+k];
l++;
}
}
for(i=0;i<n*n;i++)
IM[i]=SIM[i];
l=prologue;
for(i = 0; i < r->n_sets; i++)
{
for(j = r->sets_s[r->ordered[i]]; j <= r->sets_f[r->ordered[i]]; j++)
{
Index_Var_IM[l].index=Index_Var_IM_tmp[r->vertices[j]+prologue].index;
for(k=0;k<n;k++)
IM[k*n+l]=SIM[(k*n+r->vertices[j]+prologue)];
l++;
}
}
free(Index_Equ_IM_tmp);
free(Index_Var_IM_tmp);
free(SIM);
}
Equation_set*
Blocks::Equation_gr_IM( int n , bool* IM)
{
Equation_set *g;
Equation_vertex *vertices;
Edge *edge_ptr;
int i,j;
g = (Equation_set*)malloc(sizeof(Equation_set));
vertices = g->Number = (Equation_vertex*)malloc(n*sizeof(Equation_vertex));
g->size = n;
for(i = 0; i < n; i++)
{
vertices[i].First_Edge = NULL;
for(j=0; j<n;j++)
{
if (IM[j*n+i])
{
if (vertices[i].First_Edge==NULL)
{
vertices[i].First_Edge=(Edge*)malloc(sizeof(Edge));
edge_ptr=vertices[i].First_Edge;
edge_ptr->Vertex_Index=j;
edge_ptr->next= NULL;
}
else
{
edge_ptr=(Edge*)malloc(sizeof(Edge));
edge_ptr->Vertex_Index=j;
edge_ptr->next= NULL;
}
}
}
}
return g;
}
void
Blocks::Print_Equation_gr(Equation_set* Equation)
{
int i;
Edge *e1, *e2;
cout << "The oriented graph of the model (earth blocks only) \n";
cout << "equation | links\n";
for(i=0;i<Equation->size;i++)
{
cout << " " << i << " ";
e1=Equation->Number[i].First_Edge;
while(e1!=NULL)
{
e2=e1->next;
cout << e1->Vertex_Index << " ";
e1=e2;
}
cout << "\n";
}
}

570
ModelNormalization.cc Normal file
View File

@ -0,0 +1,570 @@
/*
* Copyright (C) 2007-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
//#define DEBUG
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include "ModelNormalization.hh"
using namespace std;
Normalization::Normalization(const SymbolTable &symbol_table_arg) :
symbol_table(symbol_table_arg)
{
//Empty
fp_verbose=false;
};
Normalization::~Normalization()
{
//Empty
};
void
Normalization::IM_to_Gr(int n0, int prologue, int epilogue, bool* IM, Equation_set *Equation, Variable_set *Variable )
// Create a non-oriented graph of the model from the incidence matrix
{
int i, j, edges, n;
Edge *e1;
#ifdef DEBUG
cout << "in IM_to_Gr\n";
#endif
//Normalize only the earth block (the prologue and the epilogue are still normalized)
n = n0 - prologue - epilogue;
Equation->size = n;
Variable->size = n;
Equation->Number = (Equation_vertex*)malloc(n * sizeof(Equation_vertex));
Variable->Number = (Variable_vertex*)malloc(n * sizeof(Variable_vertex));
edges = 0;
for(i = 0;i < n;i++)
{
Equation->Number[i].First_Edge = NULL;
Equation->Number[i].matched = -1;
Variable->Number[i].matched = -1;
for(j = 0;j < n;j++)
{
if(IM[(j + prologue)*n0 + (i + prologue)])
{
edges++;
e1 = (Edge *) malloc(sizeof(Edge));
e1->next = Equation->Number[i].First_Edge;
Equation->Number[i].First_Edge = e1;
e1->Vertex_Index = j;
}
}
}
//The maximum number of vertex in each equation is set to the total amount of edges in the model
Equation->edges = edges;
#ifdef DEBUG
cout << "end of IM_to_Gr\n";
#endif
}
void
Normalization::Inits(Equation_set *Equation)
{
int i;
#ifdef DEBUG
cout << "in Inits\n";
#endif
eq = eex = 0;
IndexUnmatched = Equation->edges * 2;
Local_Heap = (t_Heap*)malloc(IndexUnmatched * sizeof(t_Heap));
for(i = 0; i < Equation->size; i++)
{
Equation->Number[i].Next_Edge = Equation->Number[i].First_Edge;
visited[i] = 0;
// we put all unmatched vertices from Equation at the other end of the Local_Heap
if(Equation->Number[i].matched == -1)
{
Local_Heap[--IndexUnmatched].u = i;
#ifdef DEBUG
cout << i << " is unmatched\n";
#endif
}
}
#ifdef DEBUG
cout << "end of Inits\n";
#endif
}
void
Normalization::UpdatePath(Equation_set *Equation, Variable_set *Variable, int i1, int i2)
{
int i, j;
#ifdef DEBUG
cout << "in UpdatePath \n";
#endif
while(i2 >= 0)
{
i = Local_Heap[i2].u;
j = Local_Heap[i1].v;
Variable->Number[j].matched = i;
Equation->Number[i].matched = j;
i1 = i2;
i2 = Local_Heap[i2].i_parent;
eex++;
}
#ifdef DEBUG
cout << "end of UpdatePath \n";
#endif
}
void
Normalization::FindAugmentingPaths(Equation_set *Equation, Variable_set *Variable)
{
// augmenting paths using breadth-first search.
int Bottom;
int Top;
int u, i;
Edge *e, *e2;
#ifdef DEBUG
cout << "in FindAugmentingPaths\n";
#endif
// external loop gets unmatched u vertices from far end of array Local_Heap
while(IndexUnmatched < Equation->edges*2)
{
Top = Bottom = 0;
Local_Heap[Top].u = Local_Heap[IndexUnmatched++].u;
Local_Heap[Top].i_parent = -1; /* root of BFS tree */
#ifdef DEBUG
cout << "unmatched u" << Local_Heap[Top].u << " will be processed\n";
#endif
// Local_Heap processing
while(Bottom >= Top)
{
u = Local_Heap[Top++].u;
e = Equation->Number[u].First_Edge;
eq++;
// adjacency list scanning
while(e != NULL)
{
if (!visited[Variable->Number[e->Vertex_Index].matched])
{
// extend tree
Local_Heap[++Bottom].u = u = Variable->Number[e->Vertex_Index].matched;
Local_Heap[Bottom].i_parent = Top - 1;
Local_Heap[Bottom].v = e->Vertex_Index;
visited[u] = 1;
e2 = Equation->Number[u].Next_Edge;
eq++;
while ((e2 != NULL) && (Variable->Number[e2->Vertex_Index].matched != -1))
{
e2 = e2->next;
eq++;
}
Equation->Number[u].Next_Edge = e2;
if(e2 != NULL)
{
#ifdef DEBUG
cout << "augmenting path found\n";
#endif
// u in the Local_Heap but not the edge to v
Variable->Number[e2->Vertex_Index].matched = u;
Equation->Number[u].matched = e2->Vertex_Index;
// now for the rest of the path
UpdatePath(Equation, Variable, Bottom, Top - 1);
// temporary cut is emptied
for(i = 0; i <= Bottom; i++)
visited[Local_Heap[i].u] = 0;
Bottom = Top - 1;
// to get off from Local_Heap loop
// to get off from adj list scan loop
break;
}
}
e = e->next;
eq++;
}
}
}
#ifdef DEBUG
cout << "end of FindAugmentingPaths\n";
#endif
}
void
Normalization::CheapMatching(Equation_set *Equation, Variable_set *Variable)
{
int i;
Edge *e;
int count = 0;
#ifdef DEBUG
cout << "in CheapMatching Equation->size : " << Equation->size << "\n";
#endif
for(i = 0; i < Equation->size; i++)
{
e = Equation->Number[i].First_Edge;
while(e != (Edge *) NULL)
{
if(Variable->Number[e->Vertex_Index].matched == -1)
{
Variable->Number[e->Vertex_Index].matched = i;
Equation->Number[i].matched = e->Vertex_Index;
#ifdef DEBUG
cout << i << " matched to " << e->Vertex_Index << "\n";
#endif
count++;
break;
}
e = e->next;
}
}
if(fp_verbose)
cout << count << " vertices in Equation were initially matched (" << (float) 100*count / Equation->size << "%)\n";
#ifdef DEBUG
cout << "end of CheapMatching\n";
#endif
}
void
Normalization::MaximumMatching(Equation_set *Equation, Variable_set *Variable)
{
#ifdef DEBUG
cout << "in MaximumMatching\n";
#endif
CheapMatching(Equation, Variable);
Inits(Equation);
FindAugmentingPaths(Equation, Variable);
#ifdef DEBUG
cout << "end of MaximumMatching\n";
#endif
}
int
Normalization::MeasureMatching(Equation_set *Equation)
{
int size = 0, i;
for(i = 0; i < Equation->size; i++)
if(Equation->Number[i].matched != -1)
size++;
return size;
}
void
Normalization::OutputMatching(Equation_set* Equation)
{
int i;
Edge* e1;
cout << "Maximum Matching Results for |Equation|=" << Equation->size << " |Edges|=" << Equation->edges << "\n";
for(i = 0; i < Equation->size; i++)
{
if(Equation->Number[i].matched != -1)
cout << "equation " << i << " matched to variable " << Equation->Number[i].matched;
else
cout << "equation " << i << " not matched \n";
e1 = Equation->Number[i].First_Edge;
while(e1 != NULL)
{
cout << " " << e1->Vertex_Index;
e1 = e1->next;
}
cout << "\n";
}
}
void
Normalization::Gr_to_IM_basic(int n0, int prologue, int epilogue, bool* IM, Equation_set *Equation, bool transpose)
{
int i, j, edges, n;
Edge *e1;
n = n0 - prologue - epilogue;
Equation->size = n;
Equation->Number = (Equation_vertex*)malloc(n * sizeof(Equation_vertex));
edges = 0;
if(transpose)
{
for(i = 0;i < n;i++)
{
Equation->Number[i].First_Edge = NULL;
Equation->Number[i].matched = -1;
for(j = 0;j < n;j++)
{
if ((IM[(j + prologue)*n0 + (i + prologue)]) && (i != j))
{
edges++;
e1 = (Edge *) malloc(sizeof(Edge));
e1->next = Equation->Number[i].First_Edge;
Equation->Number[i].First_Edge = e1;
e1->Vertex_Index = j;
}
}
}
}
else
{
for(i = 0;i < n;i++)
{
Equation->Number[i].First_Edge = NULL;
Equation->Number[i].matched = -1;
for(j = 0;j < n;j++)
{
if ((IM[(i + prologue)*n0 + (j + prologue)]) && (i != j))
{
edges++;
e1 = (Edge *) malloc(sizeof(Edge));
e1->next = Equation->Number[i].First_Edge;
Equation->Number[i].First_Edge = e1;
e1->Vertex_Index = j;
}
}
}
}
//The maximum number of vertex in each equation is set to the total amount of edges in the model
Equation->edges = edges;
#ifdef DEBUG
cout << "end of IM_to_Gr\n";
#endif
}
void
Normalization::Gr_to_IM(int n0, int prologue, int epilogue, bool* IM, simple* Index_Equ_IM, Equation_set *Equation, bool mixing, bool* IM_s)
{
int i, j, n, l;
Edge *e1, *e2;
Equation_set* Equation_p;
simple* Index_Equ_IM_tmp = (simple*)malloc(n0 * sizeof(*Index_Equ_IM_tmp));
bool* SIM = (bool*)malloc(n0 * n0 * sizeof(bool));
#ifdef DEBUG
cout << "in Gr_to_IM\n";
#endif
n = n0 - prologue - epilogue;
if(mixing)
{
for(i = 0;i < n0*n0;i++)
SIM[i] = IM_s[i];
for(i = 0;i < n0;i++)
Index_Equ_IM_tmp[i].index = Index_Equ_IM[i].index;
for(i = 0;i < n;i++)
{
/*Index_Var_IM[j+prologue].index=Index_Var_IM_tmp[Equation->Number[j].matched+prologue].index;*/
if(fp_verbose)
cout << "Equation->Number[" << i << "].matched=" << Equation->Number[i].matched << "\n";
Index_Equ_IM[i + prologue].index = Index_Equ_IM_tmp[Equation->Number[i].matched + prologue].index;
for(j = 0;j < n0;j++)
SIM[(i + prologue)*n0 + j] = IM_s[(Equation->Number[i].matched + prologue) * n0 + j];
}
for(i = 0;i < n0*n0;i++)
IM[i] = SIM[i];
}
else
{
for(i = 0;i < n0*n0;i++)
SIM[i] = IM[i];
for(i = 0;i < n0;i++)
Index_Equ_IM_tmp[i].index = Index_Equ_IM[i].index;
for(j = 0;j < n;j++)
{
if(fp_verbose)
cout << "Equation->Number[" << j << "].matched=" << Equation->Number[j].matched << "\n";
Index_Equ_IM[j + prologue].index = Index_Equ_IM_tmp[Equation->Number[j].matched + prologue].index;
for(i = 0;i < n0;i++)
SIM[(i)*n0 + j + prologue] = IM[(i) * n0 + Equation->Number[j].matched + prologue];
}
for(i = 0;i < n0*n0;i++)
IM[i] = SIM[i];
}
free(SIM);
free(Index_Equ_IM_tmp);
if(mixing)
Gr_to_IM_basic(n0, prologue, epilogue, IM, Equation, true);
else
{
// In this step we :
// 1) get ride of the edge from the equation to its explain variable
// 2) resort the equation in the order of the matched variable
// 3) transpose the graph
// in order to get the oriented graph needed to find strong connex components
Equation_p = (Equation_set*)malloc(sizeof(Equation_set));
Equation_p->size = Equation->size;
Equation_p->edges = Equation->edges;
Equation_p->Number = (Equation_vertex*)malloc(n * sizeof(Equation_vertex));
for(i = 0;i < n;i++)
{
Equation_p->Number[i].First_Edge = NULL;
Equation_p->Number[i].Next_Edge = NULL;
}
for(i = 0;i < n;i++)
{
l = Equation->Number[i].matched;
e1 = Equation->Number[l].First_Edge;
while(e1 != NULL)
{
if(e1->Vertex_Index != i)
{
j = e1->Vertex_Index;
if(Equation_p->Number[j].First_Edge != NULL)
{
Equation_p->Number[j].Next_Edge->next = (Edge*)malloc(sizeof(Edge*));
Equation_p->Number[j].Next_Edge = Equation_p->Number[j].Next_Edge->next;
}
else
{
Equation_p->Number[j].First_Edge = (Edge*)malloc(sizeof(Edge*));
Equation_p->Number[j].Next_Edge = Equation_p->Number[j].First_Edge;
}
Equation_p->Number[j].Next_Edge->next = NULL;
Equation_p->Number[j].Next_Edge->Vertex_Index = i;
}
e2 = e1->next;
free(e1);
e1 = e2;
}
}
for(i = 0;i < n;i++)
{
Equation->Number[i].matched = Equation_p->Number[i].matched;
Equation->Number[i].First_Edge = Equation_p->Number[i].First_Edge;
Equation->Number[i].Next_Edge = Equation_p->Number[i].Next_Edge;
}
free(Equation_p->Number);
free(Equation_p);
}
#ifdef DEBUG
cout << "end of Gr_to_IM\n";
#endif
}
void
Normalization::Free_Equation(int n, Equation_set* Equation)
{
//free unused space
Edge *e1, *e2;
int i;
for(i = 0;i < n;i++)
{
e1 = Equation->Number[i].First_Edge;
while(e1 != NULL)
{
e2 = e1->next;
e1 = e2;
}
}
free(Equation->Number);
free(Equation);
}
void
Normalization::Free_Other(Variable_set* Variable)
{
//free unused space
free(Local_Heap);
free(Variable->Number);
free(Variable);
free(visited);
}
void
Normalization::Free_All(int n, Equation_set* Equation, Variable_set* Variable)
{
Free_Equation(n, Equation);
Free_Other(Variable);
}
void
Normalization::ErrorHandling(int n, bool* IM, simple* Index_Equ_IM)
{
int i, j, k, k1, k2;
for(i = 0;i < n;i++)
{
k = 0;
for(j = 0;j < n;j++)
k += (int)IM[j * n + Index_Equ_IM[i].index];
if(k == 0)
cout << " the variable " << getnamebyID(eEndogenous, Index_Equ_IM[i].index) << " does not appear in any equation \n";
for(j = i + 1;j < n;j++)
{
k1 = k2 = 0;
for(k = 0;k < n;k++)
{
k1 = k1 + (int)(IM[Index_Equ_IM[i].index * n + k] != IM[Index_Equ_IM[j].index * n + k]);
k2 = k2 + (int)IM[Index_Equ_IM[i].index * n + k];
}
if ((k1 == 0)&(k2 == 1))
cout << " the variable " << getnamebyID(eEndogenous, Index_Equ_IM[i].index) << " is the only endogenous variable in equations " << Index_Equ_IM[i].index + 1 << " and " << Index_Equ_IM[j].index + 1 << "\n";
}
}
}
void
Normalization::Set_fp_verbose(bool ok)
{
fp_verbose=ok;
}
bool
Normalization::Normalize(int n, int prologue, int epilogue, bool* IM, simple* Index_Equ_IM, Equation_set* Equation, bool mixing, bool* IM_s)
{
int matchingSize, effective_n;
int save_fp_verbose=fp_verbose;
fp_verbose = 0;
Variable_set* Variable = (Variable_set*) malloc(sizeof(Variable_set));
#ifdef DEBUG
cout << "in Normalize\n";
#endif
visited = (bool*)malloc(n * sizeof(*visited));
IM_to_Gr(n, prologue, epilogue, IM, Equation, Variable);
MaximumMatching(Equation, Variable);
matchingSize = MeasureMatching(Equation);
effective_n = n - prologue - epilogue;
fp_verbose=save_fp_verbose;
if(matchingSize < effective_n && fp_verbose)
{
cout << "Error: dynare could not normalize the model.\n The following equations:\n - ";
int i;
for(i = 0; i < Equation->size; i++)
if(Equation->Number[i].matched == -1)
cout << i << " ";
cout << "\n and the following variables:\n - ";
for(i = 0; i < Variable->size; i++)
if(Variable->Number[i].matched == -1)
cout << symbol_table.getNameByID(eEndogenous, Index_Equ_IM[i].index) << " ";
cout << "\n could not be normalized\n";
//ErrorHandling(n, IM, Index_Equ_IM);
//system("PAUSE");
exit( -1);
}
if(matchingSize >= effective_n )
{
Gr_to_IM(n, prologue, epilogue, IM, Index_Equ_IM, Equation, mixing, IM_s);
if(fp_verbose)
{
OutputMatching(Equation);
for(int i = 0;i < n;i++)
cout << "Index_Equ_IM[" << i << "]=" << Index_Equ_IM[i].index /*<< " == " "Index_Var_IM[" << i << "]=" << Index_Var_IM[i].index*/ << "\n";
}
}
Free_Other(Variable);
#ifdef DEBUG
cout << "end of Normalize\n";
#endif
if(matchingSize < effective_n )
return(0);
else
return(1);
}

3778
ModelTree.cc Normal file

File diff suppressed because it is too large Load Diff

1080
Model_Graph.cc Normal file

File diff suppressed because it is too large Load Diff

66
NumericalConstants.cc Normal file
View File

@ -0,0 +1,66 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "NumericalConstants.hh"
NumericalConstants::NumericalConstants()
{
AddConstant("0");
AddConstant("1");
}
int
NumericalConstants::AddConstant(const string &iConst)
{
map<string, int>::iterator iter = numConstantsIndex.find(iConst);
//cout << "iConst=" << iConst << "\n" ;
if (iter != numConstantsIndex.end())
return iter->second;
if (atof(iConst.c_str()) < 0)
{
cerr << "Can't handle a negative constant..!" << endl;
exit(-1);
}
int id = (int) mNumericalConstants.size();
mNumericalConstants.push_back(iConst);
numConstantsIndex[iConst] = id;
return id;
}
string
NumericalConstants::get(int ID) const
{
if (ID < (int) mNumericalConstants.size())
return mNumericalConstants[ID];
else
{
cerr << "Unknown constant" << endl;
exit(-1);
}
}
double
NumericalConstants::getDouble(int iID) const
{
return(atof(get(iID).c_str()));
}

199
NumericalInitialization.cc Normal file
View File

@ -0,0 +1,199 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include "NumericalInitialization.hh"
#include "Interface.hh"
InitParamStatement::InitParamStatement(const string &param_name_arg,
const NodeID param_value_arg,
const SymbolTable &symbol_table_arg) :
param_name(param_name_arg),
param_value(param_value_arg),
symbol_table(symbol_table_arg)
{
}
void
InitParamStatement::writeOutput(ostream &output, const string &basename) const
{
int id = symbol_table.getID(param_name) + 1;
output << "M_.params( " << id << " ) = ";
param_value->writeOutput(output);
output << ";" << endl;
output << param_name << " = M_.params( " << id << " );\n";
}
InitOrEndValStatement::InitOrEndValStatement(const init_values_type &init_values_arg,
const SymbolTable &symbol_table_arg) :
init_values(init_values_arg),
symbol_table(symbol_table_arg)
{
}
void
InitOrEndValStatement::writeInitValues(ostream &output) const
{
for(init_values_type::const_iterator it = init_values.begin();
it != init_values.end(); it++)
{
const string &name = it->first;
const NodeID expression = it->second;
Type type = symbol_table.getType(name);
int id = symbol_table.getID(name) + 1;
if (type == eEndogenous)
output << "oo_.steady_state";
else if (type == eExogenous)
output << "oo_.exo_steady_state";
else if (type == eExogenousDet)
output << "oo_.exo_det_steady_state";
output << "( " << id << " ) = ";
expression->writeOutput(output);
output << ";" << endl;
}
}
InitValStatement::InitValStatement(const init_values_type &init_values_arg,
const SymbolTable &symbol_table_arg) :
InitOrEndValStatement(init_values_arg, symbol_table_arg)
{
}
void
InitValStatement::writeOutput(ostream &output, const string &basename) const
{
output << interfaces::comment() << "\n" << interfaces::comment() << "INITVAL instructions \n"
<< interfaces::comment() << "\n";
// Writing initval block to set initial values for variables
output << "options_.initval_file = 0;\nendval_=0;\n";
if (symbol_table.recur_nbr > 0)
output << "recurs_ = zeros(" << symbol_table.recur_nbr << ", 1);\n";
writeInitValues(output);
output << "oo_.y_simul=[oo_.steady_state*ones(1,M_.maximum_lag)];\n";
output << "if M_.exo_nbr > 0;\n";
output << "\too_.exo_simul = [ones(M_.maximum_lag,1)*oo_.exo_steady_state'];\n";
output <<"end;\n";
output << "if M_.exo_det_nbr > 0;\n";
output << "\too_.exo_det_simul = [ones(M_.maximum_lag,1)*oo_.exo_det_steady_state'];\n";
output <<"end;\n";
}
EndValStatement::EndValStatement(const init_values_type &init_values_arg,
const SymbolTable &symbol_table_arg) :
InitOrEndValStatement(init_values_arg, symbol_table_arg)
{
}
void
EndValStatement::writeOutput(ostream &output, const string &basename) const
{
output << interfaces::comment() << "\n" << interfaces::comment() << "ENDVAL instructions\n"
<< interfaces::comment() << "\n";
// Writing endval block to set terminal values for variables
output << "ys0_= oo_.steady_state;\nex0_ = oo_.exo_steady_state;\nrecurs0_ = recurs_;\nendval_ = 1;\n";
writeInitValues(output);
}
HistValStatement::HistValStatement(const hist_values_type &hist_values_arg,
const SymbolTable &symbol_table_arg) :
hist_values(hist_values_arg),
symbol_table(symbol_table_arg)
{
}
void
HistValStatement::writeOutput(ostream &output, const string &basename) const
{
output << interfaces::comment() << "\n" << interfaces::comment() << "HISTVAL instructions\n"
<< interfaces::comment() << "\n";
for(hist_values_type::const_iterator it = hist_values.begin();
it != hist_values.end(); it++)
{
const string &name = it->first.first;
const int &lag = it->first.second;
const NodeID expression = it->second;
Type type = symbol_table.getType(name);
int id = symbol_table.getID(name) + 1;
if (type == eEndogenous)
output << "oo_.endo_simul( " << id << ", M_.maximum_lag + " << lag << ") = ";
else if (type == eExogenous)
output << "oo_.exo_simul( M_.maximum_lag + " << lag << ", " << id << " ) = ";
else if (type != eExogenousDet)
output << "oo_.exo_det_simul( M_.maximum_lag + " << lag << ", " << id << " ) = ";
expression->writeOutput(output);
output << ";" << endl;
}
}
HomotopyStatement::HomotopyStatement(const homotopy_values_type &homotopy_values_arg,
const SymbolTable &symbol_table_arg) :
homotopy_values(homotopy_values_arg),
symbol_table(symbol_table_arg)
{
}
void
HomotopyStatement::writeOutput(ostream &output, const string &basename) const
{
output << interfaces::comment() << "\n" << interfaces::comment() << "HOMOTOPY_SETUP instructions\n"
<< interfaces::comment() << "\n";
output << "homotopy_param = {};" << endl;
output << "homotopy_exo = {};" << endl;
output << "homotopy_exodet = {};" << endl;
for(homotopy_values_type::const_iterator it = homotopy_values.begin();
it != homotopy_values.end(); it++)
{
const string &name = it->first;
const NodeID expression1 = it->second.first;
const NodeID expression2 = it->second.second;
Type type = symbol_table.getType(name);
if (type == eParameter)
output << "homotopy_param = vertcat(homotopy_param,{ '" << name << "', ";
else if (type == eExogenous)
output << "homotopy_exo = vertcat(homotopy_exo,{ '" << name << "', ";
else if (type != eExogenousDet)
output << "homotopy_exodet = vertcat(homotopy_exodet,{ '" << name << "', ";
expression1->writeOutput(output);
output << ", ";
expression2->writeOutput(output);
output << "});" << endl;
}
output << "options_.homotopy_param = homotopy_param;" << endl;
output << "options_.homotopy_exo = homotopy_exo;" << endl;
output << "options_.homotopy_exodet = homotopy_exodet;" << endl;
}

1311
ParsingDriver.cc Normal file

File diff suppressed because it is too large Load Diff

188
Shocks.cc Normal file
View File

@ -0,0 +1,188 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
using namespace std;
#include <iostream>
#include "Shocks.hh"
#include "Interface.hh"
AbstractShocksStatement::AbstractShocksStatement(bool mshocks_arg,
const det_shocks_type &det_shocks_arg,
const var_and_std_shocks_type &var_shocks_arg,
const var_and_std_shocks_type &std_shocks_arg,
const covar_and_corr_shocks_type &covar_shocks_arg,
const covar_and_corr_shocks_type &corr_shocks_arg,
const SymbolTable &symbol_table_arg) :
mshocks(mshocks_arg),
det_shocks(det_shocks_arg),
var_shocks(var_shocks_arg),
std_shocks(std_shocks_arg),
covar_shocks(covar_shocks_arg),
corr_shocks(corr_shocks_arg),
symbol_table(symbol_table_arg)
{
}
void
AbstractShocksStatement::writeDetShocks(ostream &output) const
{
int exo_det_length = 0;
for(det_shocks_type::const_iterator it = det_shocks.begin();
it != det_shocks.end(); it++)
{
int id = symbol_table.getID(it->first) + 1;
bool exo_det = (symbol_table.getType(it->first) == eExogenousDet);
int set_shocks_index = ((int) mshocks) + 2 * ((int) exo_det);
for (unsigned int i = 0; i < it->second.size(); i++)
{
const int &period1 = it->second[i].period1;
const int &period2 = it->second[i].period2;
const NodeID value = it->second[i].value;
if (period1 == period2)
{
output << "set_shocks(" << set_shocks_index << "," << period1
<< ", " << id << ", ";
value->writeOutput(output);
output << ");" << endl;
}
else
{
output << "set_shocks(" << set_shocks_index << "," << period1
<< ":" << period2 << ", " << id << ", ";
value->writeOutput(output);
output << ");" << endl;
}
if (exo_det && (period2 > exo_det_length))
exo_det_length = period2;
}
}
output << "M_.exo_det_length = " << exo_det_length << ";\n";
}
void
AbstractShocksStatement::writeVarAndStdShocks(ostream &output) const
{
var_and_std_shocks_type::const_iterator it;
for(it = var_shocks.begin(); it != var_shocks.end(); it++)
{
int id = symbol_table.getID(it->first) + 1;
const NodeID value = it->second;
output << "M_.Sigma_e(" << id << ", " << id << ") = ";
value->writeOutput(output);
output << ";" << endl;
}
for(it = std_shocks.begin(); it != std_shocks.end(); it++)
{
int id = symbol_table.getID(it->first) + 1;
const NodeID value = it->second;
output << "M_.Sigma_e(" << id << ", " << id << ") = (";
value->writeOutput(output);
output << ")^2;" << endl;
}
}
void
AbstractShocksStatement::writeCovarAndCorrShocks(ostream &output) const
{
covar_and_corr_shocks_type::const_iterator it;
for(it = covar_shocks.begin(); it != covar_shocks.end(); it++)
{
int id1 = symbol_table.getID(it->first.first) + 1;
int id2 = symbol_table.getID(it->first.second) + 1;
const NodeID value = it->second;
output << "M_.Sigma_e(" << id1 << ", " << id2 << ") = ";
value->writeOutput(output);
output << "; M_.Sigma_e(" << id2 << ", " << id1 << ") = M_.Sigma_e("
<< id1 << ", " << id2 << ");\n";
}
for(it = corr_shocks.begin(); it != corr_shocks.end(); it++)
{
int id1 = symbol_table.getID(it->first.first) + 1;
int id2 = symbol_table.getID(it->first.second) + 1;
const NodeID value = it->second;
output << "M_.Sigma_e(" << id1 << ", " << id2 << ") = ";
value->writeOutput(output);
output << "*sqrt(M_.Sigma_e(" << id1 << ", " << id1 << ")*M_.Sigma_e("
<< id2 << ", " << id2 << "); M_.Sigma_e(" << id2 << ", "
<< id1 << ") = M_.Sigma_e(" << id1 << ", " << id2 << ");\n";
}
}
ShocksStatement::ShocksStatement(const det_shocks_type &det_shocks_arg,
const var_and_std_shocks_type &var_shocks_arg,
const var_and_std_shocks_type &std_shocks_arg,
const covar_and_corr_shocks_type &covar_shocks_arg,
const covar_and_corr_shocks_type &corr_shocks_arg,
const SymbolTable &symbol_table_arg) :
AbstractShocksStatement(false, det_shocks_arg, var_shocks_arg, std_shocks_arg,
covar_shocks_arg, corr_shocks_arg, symbol_table_arg)
{
}
void
ShocksStatement::writeOutput(ostream &output, const string &basename) const
{
output << interfaces::comment() << endl << interfaces::comment();
output << "SHOCKS instructions \n";
output << interfaces::comment() << "\n";
// Write instruction that initializes a shock
output << "make_ex_;\n";
writeDetShocks(output);
writeVarAndStdShocks(output);
writeCovarAndCorrShocks(output);
}
MShocksStatement::MShocksStatement(const det_shocks_type &det_shocks_arg,
const var_and_std_shocks_type &var_shocks_arg,
const var_and_std_shocks_type &std_shocks_arg,
const covar_and_corr_shocks_type &covar_shocks_arg,
const covar_and_corr_shocks_type &corr_shocks_arg,
const SymbolTable &symbol_table_arg) :
AbstractShocksStatement(true, det_shocks_arg, var_shocks_arg, std_shocks_arg,
covar_shocks_arg, corr_shocks_arg, symbol_table_arg)
{
}
void
MShocksStatement::writeOutput(ostream &output, const string &basename) const
{
output << interfaces::comment() << endl << interfaces::comment();
output << "SHOCKS instructions \n";
output << interfaces::comment() << "\n";
// Write instruction that initializes a shock
output << "make_ex_;\n";
writeDetShocks(output);
writeVarAndStdShocks(output);
writeCovarAndCorrShocks(output);
}

100
SigmaeInitialization.cc Normal file
View File

@ -0,0 +1,100 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SigmaeInitialization.hh"
SigmaeStatement::SigmaeStatement(const matrix_type &matrix_arg) throw (MatrixFormException) :
matrix(matrix_arg),
matrix_form(determineMatrixForm(matrix))
{
}
SigmaeStatement::matrix_form_type
SigmaeStatement::determineMatrixForm(const matrix_type &matrix) throw (MatrixFormException)
{
unsigned int nbe;
int inc;
matrix_form_type type;
// Checking if first or last row has one element.
if (matrix.front().size() == 1)
{
inc = 1;
nbe = 2;
type = eLower;
}
else if (matrix.back().size() == 1)
{
inc = -1;
nbe = matrix.front().size()-1;
type = eUpper;
}
else
throw MatrixFormException();
// Checking if matrix is triangular (upper or lower):
// each row has one element more or less than the previous one
// and first or last one has one element.
matrix_type::const_iterator ir;
for (ir = matrix.begin(), ir++; ir != matrix.end(); ir++, nbe += inc )
if (ir->size() != nbe)
throw MatrixFormException();
return type;
}
void
SigmaeStatement::writeOutput(ostream &output, const string &basename) const
{
unsigned int ic, ic1;
unsigned int ir, ir1;
output << "M_.Sigma_e = [...\n";
for (ir = 0; ir < matrix.size(); ir++)
{
output << "\t";
for (ic = 0; ic < matrix.size(); ic++)
{
if (ic >= ir && matrix_form == eUpper)
{
ic1 = ic-ir;
ir1 = ir;
}
else if (ic < ir && matrix_form == eUpper)
{
ic1 = ir-ic;
ir1 = ic;
}
else if (ic > ir && matrix_form == eLower)
{
ic1 = ir;
ir1 = ic;
}
else if (ic <= ir && matrix_form == eLower)
{
ic1 = ic;
ir1 = ir;
}
matrix[ir1][ic1]->writeOutput(output);
output << " ";
}
output << ";...\n";
}
output << "\t];...\n";
}

78
Statement.cc Normal file
View File

@ -0,0 +1,78 @@
/*
* Copyright (C) 2006-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Statement.hh"
ModFileStructure::ModFileStructure() :
check_present(false),
simul_present(false),
stoch_simul_or_similar_present(false),
order_option(2)
{
}
Statement::~Statement()
{
}
void
Statement::checkPass(ModFileStructure &mod_file_struct)
{
}
void
Statement::computingPass()
{
}
NativeStatement::NativeStatement(const string &native_statement_arg) :
native_statement(native_statement_arg)
{
}
void
NativeStatement::writeOutput(ostream &output, const string &basename) const
{
output << native_statement << endl;
}
void
OptionsList::writeOutput(ostream &output) const
{
for(num_options_type::const_iterator it = num_options.begin();
it != num_options.end(); it++)
output << "options_." << it->first << " = " << it->second << ";" << endl;
for(paired_num_options_type::const_iterator it = paired_num_options.begin();
it != paired_num_options.end(); it++)
output << "options_." << it->first << " = [" << it->second.first << "; "
<< it->second.second << "];" << endl;
for(string_options_type::const_iterator it = string_options.begin();
it != string_options.end(); it++)
output << "options_." << it->first << " = '" << it->second << "';" << endl;
}
void
OptionsList::clear()
{
num_options.clear();
paired_num_options.clear();
string_options.clear();
}

1957
SymbolGaussElim.cc Normal file

File diff suppressed because it is too large Load Diff

138
SymbolTable.cc Normal file
View File

@ -0,0 +1,138 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <sstream>
#include "SymbolTable.hh"
#include "Interface.hh"
SymbolTable::SymbolTable() : endo_nbr(0), exo_nbr(0), exo_det_nbr(0), recur_nbr(0),
parameter_nbr(0), model_local_variable_nbr(0),
modfile_local_variable_nbr(0), unknown_function_nbr(0)
{
}
void
SymbolTable::addSymbol(const string &name, Type type, const string &tex_name) throw (AlreadyDeclaredException)
{
if (exists(name))
if (symbol_table[name].first == type)
throw AlreadyDeclaredException(name, true);
else
throw AlreadyDeclaredException(name, false);
int id;
switch (type)
{
case eExogenous:
id = exo_nbr++;
break;
case eExogenousDet:
id = exo_det_nbr++;
break;
case eEndogenous:
id = endo_nbr++;
break;
case eParameter:
id = parameter_nbr++;
break;
case eRecursiveVariable:
id = recur_nbr++;
break;
case eModelLocalVariable:
id = model_local_variable_nbr++;
break;
case eModFileLocalVariable:
id = modfile_local_variable_nbr++;
break;
case eUnknownFunction:
id = unknown_function_nbr++;
break;
}
symbol_type symbol(type, id);
symbol_table[name] = symbol;
name_table[symbol] = name;
tex_name_table[symbol] = tex_name;
}
void
SymbolTable::writeOutput(ostream &output) const
{
if (exo_nbr > 0)
{
output << "M_.exo_names = '" << getNameByID(eExogenous, 0) << "';" << endl;
output << "M_.exo_names_tex = '" << getTeXNameByID(eExogenous, 0) << "';" << endl;
for (int id = 1; id < exo_nbr; id++)
{
output << "M_.exo_names = " << interfaces::strvcat("M_.exo_names","'"+getNameByID(eExogenous, id)+"'") << ";" << endl;
output << "M_.exo_names_tex = " << interfaces::strvcat("M_.exo_names_tex","'"+getTeXNameByID(eExogenous, id)+"'") << ";" << endl;
}
}
if (exo_det_nbr > 0)
{
output << "lgxdet_ = '" << getNameByID(eExogenousDet, 0) << "';" << endl;
output << "lgxdet_tex_ = '" << getTeXNameByID(eExogenousDet, 0) << "';" << endl;
for (int id = 1; id < exo_det_nbr; id++)
{
output << "lgxdet_ = " << interfaces::strvcat("lgxdet_","'"+getNameByID(eExogenousDet, id)+"'") << ";" << endl;
output << "lgxdet_tex_ = " << interfaces::strvcat("lgxdet_tex_","'"+getTeXNameByID(eExogenousDet, id)+"'") << ";" << endl;
}
}
if (endo_nbr > 0)
{
output << "M_.endo_names = '" << getNameByID(eEndogenous, 0) << "';" << endl;
output << "M_.endo_names_tex = '" << getTeXNameByID(eEndogenous, 0) << "';" << endl;
for (int id = 1; id < endo_nbr; id++)
{
output << "M_.endo_names = " << interfaces::strvcat("M_.endo_names","'"+getNameByID(eEndogenous, id)+"'") << ";" << endl;
output << "M_.endo_names_tex = " << interfaces::strvcat("M_.endo_names_tex","'"+getTeXNameByID(eEndogenous, id)+"'") << ";" << endl;
}
}
if (recur_nbr > 0)
{
output << "M_.recur_names = '" << getNameByID(eRecursiveVariable, 0) << "';" << endl;
output << "M_.recur_names_tex = '" << getTeXNameByID(eRecursiveVariable, 0) << "';" << endl;
for (int id = 1; id < recur_nbr; id++)
{
output << "M_.recur_names = " << interfaces::strvcat("M_.recur_names","'"+getNameByID(eRecursiveVariable, id)+"'") << ";" << endl;
output << "M_.recur_names_tex = " << interfaces::strvcat("M_.recur_names_tex","'"+getTeXNameByID(eRecursiveVariable, id)+"'") << ";" << endl;
}
}
if (parameter_nbr > 0)
{
output << "M_.param_names = '" << getNameByID(eParameter, 0) << "';" << endl;
output << "M_.param_names_tex = '" << getTeXNameByID(eParameter, 0) << "';" << endl;
for (int id = 1; id < parameter_nbr; id++)
{
output << "M_.param_names = " << interfaces::strvcat("M_.param_names","'"+getNameByID(eParameter, id)+"'") << ";" << endl;
output << "M_.param_names_tex = " << interfaces::strvcat("M_.param_names_tex","'"+getTeXNameByID(eParameter, id)+"'") << ";" << endl;
}
}
output << "M_.exo_det_nbr = " << exo_det_nbr << ";" << endl
<< "M_.exo_nbr = " << exo_nbr << ";" << endl
<< "M_.endo_nbr = " << endo_nbr << ";" << endl
<< "M_.recur_nbr = " << recur_nbr << ";" << endl
<< "M_.param_nbr = " << parameter_nbr << ";" << endl;
output << "M_.Sigma_e = zeros(" << exo_nbr << ", " << exo_nbr << ");" << endl;
}

69
TmpSymbolTable.cc Normal file
View File

@ -0,0 +1,69 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
using namespace std;
#include "SymbolTable.hh"
#include "TmpSymbolTable.hh"
#include "Interface.hh"
TmpSymbolTable::TmpSymbolTable(const SymbolTable &symbol_table_arg) :
symbol_table(symbol_table_arg)
{
}
TmpSymbolTable::~TmpSymbolTable()
{
}
void
TmpSymbolTable::AddTempSymbol(const string &symbol)
{
// FIXME: add check to verify that symbol exists in symbol_table
// FIXME: add check to verify that symbol doesn't yet exist in the present table
tmpsymboltable.push_back(symbol);
}
void
TmpSymbolTable::AddTempSymbol(const string &symbol1, const string &symbol2)
{
// FIXME: add checks to verify that symbol1 and symbol2 exist in symbol_table
// FIXME: add check to verify that symbol1 doesn't yet exist in the present table
tmpsymboltable.push_back(symbol1);
nameTable.push_back(symbol2);
}
void
TmpSymbolTable::writeOutput(const string &varname, ostream &output) const
{
output << varname << "=[];" << endl;
for (vector<string>::const_iterator it = tmpsymboltable.begin();
it != tmpsymboltable.end(); it++)
{
output << varname << " = ";
output << interfaces::strvcat(varname, "'" + *it + "'") << ";" << endl;
}
}
void
TmpSymbolTable::clear()
{
tmpsymboltable.clear();
nameTable.clear();
}

108
VariableTable.cc Normal file
View File

@ -0,0 +1,108 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include "VariableTable.hh"
VariableTable::VariableTable(const SymbolTable &symbol_table_arg) :
symbol_table(symbol_table_arg),
var_endo_nbr(0), var_exo_nbr(0), var_exo_det_nbr(0),
max_lag(0), max_lead(0),
max_endo_lag(0), max_endo_lead(0),
max_exo_lag(0), max_exo_lead(0),
max_exo_det_lag(0), max_exo_det_lead(0),
max_recur_lag(0), max_recur_lead(0)
{
}
int
VariableTable::addVariable(Type type, int symb_id, int lag) throw (AlreadySortedException)
{
if (sorted_ids_table.size() != 0)
throw AlreadySortedException();
var_key_type key = make_pair(make_pair(type, lag), symb_id);
// Testing if variable already exists
variable_table_type::const_iterator it = variable_table.find(key);
if (it != variable_table.end())
return it->second;
int var_id = size();
variable_table[key] = var_id;
inv_variable_table[var_id] = key;
if (type == eEndogenous)
var_endo_nbr++;
if (type == eExogenous)
var_exo_nbr++;
if (type == eExogenousDet)
var_exo_det_nbr++;
// Setting maximum and minimum lags
if (max_lead < lag)
max_lead = lag;
else if (-max_lag > lag)
max_lag = -lag;
switch(type)
{
case eEndogenous:
if (max_endo_lead < lag)
max_endo_lead = lag;
else if (-max_endo_lag > lag)
max_endo_lag = -lag;
break;
case eExogenous:
if (max_exo_lead < lag)
max_exo_lead = lag;
else if (-max_exo_lag > lag)
max_exo_lag = -lag;
break;
case eExogenousDet:
if (max_exo_det_lead < lag)
max_exo_det_lead = lag;
else if (-max_exo_det_lag > lag)
max_exo_det_lag = -lag;
break;
case eRecursiveVariable:
if (max_recur_lead < lag)
max_recur_lead = lag;
else if (-max_recur_lag > lag)
max_recur_lag = -lag;
break;
default:
;
}
return var_id;
}
void
VariableTable::sort() throw (AlreadySortedException)
{
if (sorted_ids_table.size() != 0)
throw AlreadySortedException();
int sorted_id = 0;
sorted_ids_table.resize(size());
for(variable_table_type::const_iterator it = variable_table.begin();
it != variable_table.end(); it++)
sorted_ids_table[it->second] = sorted_id++;
}

192
include/BlockTriangular.hh Normal file
View File

@ -0,0 +1,192 @@
/*
* Copyright (C) 2007-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef BLOCKTRIANGULAR_H
#define BLOCKTRIANGULAR_H
#include <string>
#include "ExprNode.hh"
#include "SymbolTable.hh"
#include "ModelNormalization.hh"
#include "ModelBlocks.hh"
/*!
\class BlockTriangular
\brief Creat the incidence matrice and reorder the model's equations.
*/
#include "ExprNode.hh"
typedef struct List_IM
{
List_IM* pNext;
int lead_lag;
bool* IM;
};
typedef struct vari
{
int Size;
int* arc;
int used_arc;
int available;
};
typedef map<pair<int ,int >,double> jacob_map;
class BlockTriangular
{
public:
BlockTriangular(const SymbolTable &symbol_table_arg);
~BlockTriangular();
/*! The incidence matrix for each lead and lags */
const SymbolTable &symbol_table;
Blocks blocks;
Normalization normalization;
List_IM* Build_IM(int lead_lag);
List_IM* Get_IM(int lead_lag);
bool* bGet_IM(int lead_lag);
bool* bGet_IM(int lead_lag) const;
void fill_IM(int equation, int variable_endo, int lead_lag);
void unfill_IM(int equation, int variable_endo, int lead_lag);
void incidence_matrix() const;
void init_incidence_matrix(int nb_endo);
void Print_IM(int n) const;
void Free_IM(List_IM* First_IM);
void Print_SIM(bool* IM, int n) const;
void Normalize_and_BlockDecompose_Static_Model();
void Normalize_and_BlockDecompose_Static_0_Model(const jacob_map &j_m);
bool Normalize_and_BlockDecompose(bool* IM, Model_Block* ModelBlock, int n, int* prologue, int* epilogue, simple* Index_Var_IM, simple* Index_Equ_IM, bool Do_Normalization, bool mixing, bool* IM_0 );
bool Normalize_and_BlockDecompose(bool* IM, Model_Block* ModelBlock, int n, int* prologue, int* epilogue, simple* Index_Var_IM, simple* Index_Equ_IM, bool Do_Normalization, bool mixing, bool* IM_0 , jacob_map j_m);
void Normalize_and_BlockDecompose_0();
void Normalize_and_BlockDecompose_Inside_Earth();
void Prologue_Epilogue(bool* IM, int* prologue, int* epilogue, int n, simple* Index_Var_IM, simple* Index_Equ_IM);
void Sort_By_Cols(bool* IM, int d, int f);
void getMax_Lead_Lag(int var, int equ, int *lead, int *lag);
void getMax_Lead_Lag_B(int size, int* Equation, int *Variable, int *lead, int *lag);
void swap_IM_c(bool *SIM, int pos1, int pos2, int pos3, simple* Index_Var_IM, simple* Index_Equ_IM, int n);
void Allocate_Block(int size, int *count_Equ, int *count_Block, int type, Model_Block * ModelBlock);
void Free_Block(Model_Block* ModelBlock);
string getnamebyID(Type type, int id);
List_IM *First_IM ;
List_IM *Last_IM ;
simple *Index_Equ_IM;
simple *Index_Var_IM;
int prologue, epilogue;
int Model_Max_Lead, Model_Max_Lag, periods;
bool bt_verbose;
int endo_nbr;
Model_Block* ModelBlock;
inline static std::string BlockType0(int type)
{
switch (type)
{
case 0:
return ("SIMULTANEOUS TIME SEPARABLE ");
break;
case 1:
return ("PROLOGUE ");
break;
case 2:
return ("EPILOGUE ");
break;
case 3:
return ("SIMULTANEOUS TIME UNSEPARABLE");
break;
default:
return ("UNKNOWN ");
break;
}
};
inline static std::string BlockSim(int type)
{
switch (type)
{
case EVALUATE_FOREWARD:
case EVALUATE_FOREWARD_R:
return ("EVALUATE FOREWARD ");
break;
case EVALUATE_BACKWARD:
case EVALUATE_BACKWARD_R:
return ("EVALUATE BACKWARD ");
break;
case SOLVE_FOREWARD_SIMPLE:
return ("SOLVE FOREWARD SIMPLE ");
break;
case SOLVE_BACKWARD_SIMPLE:
return ("SOLVE BACKWARD SIMPLE ");
break;
case SOLVE_TWO_BOUNDARIES_SIMPLE:
return ("SOLVE TWO BOUNDARIES SIMPLE ");
break;
case SOLVE_FOREWARD_COMPLETE:
return ("SOLVE FOREWARD COMPLETE ");
break;
case SOLVE_BACKWARD_COMPLETE:
return ("SOLVE BACKWARD COMPLETE ");
break;
case SOLVE_TWO_BOUNDARIES_COMPLETE:
return ("SOLVE TWO BOUNDARIES COMPLETE");
break;
default:
return ("UNKNOWN ");
break;
}
};
inline static std::string BlockSim_d(int type)
{
switch (type)
{
case EVALUATE_FOREWARD:
case EVALUATE_FOREWARD_R:
return ("EVALUATE_FOREWARD ");
break;
case EVALUATE_BACKWARD:
case EVALUATE_BACKWARD_R:
return ("EVALUATE_BACKWARD ");
break;
case SOLVE_FOREWARD_SIMPLE:
return ("SOLVE_FOREWARD_SIMPLE ");
break;
case SOLVE_BACKWARD_SIMPLE:
return ("SOLVE_BACKWARD_SIMPLE ");
break;
case SOLVE_TWO_BOUNDARIES_SIMPLE:
return ("SOLVE_TWO_BOUNDARIES_SIMPLE ");
break;
case SOLVE_FOREWARD_COMPLETE:
return ("SOLVE_FOREWARD_COMPLETE ");
break;
case SOLVE_BACKWARD_COMPLETE:
return ("SOLVE_BACKWARD_COMPLETE ");
break;
case SOLVE_TWO_BOUNDARIES_COMPLETE:
return ("SOLVE_TWO_BOUNDARIES_COMPLETE");
break;
default:
return ("UNKNOWN ");
break;
}
};
};
//------------------------------------------------------------------------------
#endif

115
include/CodeInterpreter.hh Normal file
View File

@ -0,0 +1,115 @@
/*
* Copyright (C) 2007-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CODEINTERPRETER
#define CODEINTERPRETER
const char FLDZ=0;
const char FLDT=1;
const char FLDU=2;
const char FLDV=3;
const char FLDR=4;
const char FLDC=5;
const char FSTPT=6;
const char FSTPV=7;
const char FSTPR=8;
const char FSTPU=9;
const char FSTPG=10;
const char FUNARY=11;
const char FBINARY=12;
const char FCUML=13;
const char FBEGINBLOCK=14;
const char FENDBLOCK=15;
const char FDIMT=16;
const char FEND=17;
const char FOK=18;
const char FENDEQU=19;
const int SIMULTANS=0;
const int PROLOGUE=1;
const int EPILOGUE=2;
const int SIMULTAN=3;
const int UNKNOWN=-1;
const int EVALUATE_FOREWARD=0;
const int EVALUATE_BACKWARD=1;
const int SOLVE_FOREWARD_SIMPLE=2;
const int SOLVE_BACKWARD_SIMPLE=3;
const int SOLVE_TWO_BOUNDARIES_SIMPLE=4;
const int SOLVE_FOREWARD_COMPLETE=5;
const int SOLVE_BACKWARD_COMPLETE=6;
const int SOLVE_TWO_BOUNDARIES_COMPLETE=7;
const int EVALUATE_FOREWARD_R=8;
const int EVALUATE_BACKWARD_R=9;
//! Enumeration of possible symbol types
/*! Warning: do not to change the order of the enumeration, it matters for VariableTable (at least ensure that eEndogenous is the first one) */
enum Type
{
eEndogenous = 0, //!< Endogenous
eExogenous = 1, //!< Exogenous
eExogenousDet = 2, //!< Exogenous deterministic
eRecursiveVariable = 3, //!< Recursive variable (reserved for future use)
eParameter = 4, //!< Parameter
eModelLocalVariable = 10, //!< Local variable whose scope is model (pound expression)
eModFileLocalVariable = 11, //!< Local variable whose scope is mod file (model excluded)
eUnknownFunction = 12 //!< Function unknown to the preprocessor
};
enum UnaryOpcode
{
oUminus,
oExp,
oLog,
oLog10,
oCos,
oSin,
oTan,
oAcos,
oAsin,
oAtan,
oCosh,
oSinh,
oTanh,
oAcosh,
oAsinh,
oAtanh,
oSqrt
};
enum BinaryOpcode
{
oPlus,
oMinus,
oTimes,
oDivide,
oPower,
oEqual,
oMax,
oMin,
oLess,
oGreater,
oLessEqual,
oGreaterEqual,
oEqualEqual,
oDifferent
};
#endif

442
include/ComputingTasks.hh Normal file
View File

@ -0,0 +1,442 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _COMPUTINGTASKS_HH
#define _COMPUTINGTASKS_HH
#include <ostream>
#include "TmpSymbolTable.hh"
#include "SymbolTable.hh"
#include "Statement.hh"
#include "ModelTree.hh"
class SteadyStatement : public Statement
{
private:
const OptionsList options_list;
public:
SteadyStatement(const OptionsList &options_list_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class SteadySparseStatement : public Statement
{
private:
const OptionsList options_list;
public:
SteadySparseStatement(const OptionsList &options_list_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class CheckStatement : public Statement
{
private:
const OptionsList options_list;
public:
CheckStatement(const OptionsList &options_list_arg);
virtual void checkPass(ModFileStructure &mod_file_struct);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class SimulStatement : public Statement
{
private:
const OptionsList options_list;
public:
SimulStatement(const OptionsList &options_list_arg);
virtual void checkPass(ModFileStructure &mod_file_struct);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class SimulSparseStatement : public Statement
{
private:
const OptionsList options_list;
const int compiler, mode;
public:
SimulSparseStatement(const OptionsList &options_list_arg, int compiler_arg, int mode_arg);
virtual void checkPass(ModFileStructure &mod_file_struct);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class StochSimulStatement : public Statement
{
private:
const TmpSymbolTable tmp_symbol_table;
const OptionsList options_list;
public:
StochSimulStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg);
virtual void checkPass(ModFileStructure &mod_file_struct);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class RamseyPolicyStatement : public Statement
{
private:
const TmpSymbolTable tmp_symbol_table;
const OptionsList options_list;
public:
RamseyPolicyStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg);
virtual void checkPass(ModFileStructure &mod_file_struct);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class RplotStatement : public Statement
{
private:
const TmpSymbolTable tmp_symbol_table;
const OptionsList options_list;
public:
RplotStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class UnitRootVarsStatement : public Statement
{
private:
const TmpSymbolTable tmp_symbol_table;
public:
UnitRootVarsStatement(const TmpSymbolTable &tmp_symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class PeriodsStatement : public Statement
{
private:
const int periods;
public:
PeriodsStatement(int periods_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class CutoffStatement : public Statement
{
private:
const double cutoff;
public:
CutoffStatement(double cutoff_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class MarkowitzStatement : public Statement
{
private:
const double markowitz;
public:
MarkowitzStatement(double markowitz_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class DsampleStatement : public Statement
{
private:
const int val1, val2;
public:
DsampleStatement(int val1_arg);
DsampleStatement(int val1_arg, int val2_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class EstimationStatement : public Statement
{
private:
const TmpSymbolTable tmp_symbol_table;
const OptionsList options_list;
public:
EstimationStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg);
virtual void checkPass(ModFileStructure &mod_file_struct);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class PriorAnalysisStatement : public Statement
{
private:
const TmpSymbolTable tmp_symbol_table;
const OptionsList options_list;
public:
PriorAnalysisStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class PosteriorAnalysisStatement : public Statement
{
private:
const TmpSymbolTable tmp_symbol_table;
const OptionsList options_list;
public:
PosteriorAnalysisStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class DynareSensitivityStatement : public Statement
{
private:
const OptionsList options_list;
public:
DynareSensitivityStatement(const OptionsList &options_list_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class VarobsStatement : public Statement
{
private:
const TmpSymbolTable tmp_symbol_table;
public:
VarobsStatement(const TmpSymbolTable &tmp_symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class ObservationTrendsStatement : public Statement
{
public:
typedef map<string, NodeID> trend_elements_type;
private:
const trend_elements_type trend_elements;
const SymbolTable &symbol_table;
public:
ObservationTrendsStatement(const trend_elements_type &trend_elements_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class OsrParamsStatement : public Statement
{
private:
const TmpSymbolTable tmp_symbol_table;
public:
OsrParamsStatement(const TmpSymbolTable &tmp_symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class OsrStatement : public Statement
{
private:
const TmpSymbolTable tmp_symbol_table;
const OptionsList options_list;
public:
OsrStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg);
virtual void checkPass(ModFileStructure &mod_file_struct);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class DynaTypeStatement : public Statement
{
private:
const TmpSymbolTable tmp_symbol_table;
const string filename;
const string ext;
public:
DynaTypeStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const string &filename_arg, const string &ext_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class DynaSaveStatement : public Statement
{
private:
const TmpSymbolTable tmp_symbol_table;
const string filename;
const string ext;
public:
DynaSaveStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const string &filename_arg, const string &ext_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class ModelComparisonStatement : public Statement
{
public:
typedef map<string, string, less<string> > filename_list_type;
private:
filename_list_type filename_list;
OptionsList options_list;
public:
ModelComparisonStatement(const filename_list_type &filename_list_arg,
const OptionsList &options_list_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
/*!
\class EstimationParams
\brief EstimationParams
*/
struct EstimationParams
{
int type;
std::string name;
std::string name2;
std::string init_val;
std::string prior;
std::string low_bound;
std::string up_bound;
std::string mean;
std::string std;
std::string p3;
std::string p4;
std::string jscale;
EstimationParams()
{
clear();
}
void clear()
{
type = 0;
name = "";
name2 = "";
init_val = "NaN";
prior = "NaN";
low_bound = "-Inf";
up_bound = "Inf";
mean = "NaN";
std = "NaN";
p3 = "NaN";
p4 = "NaN";
jscale = "NaN";
}
};
class EstimatedParamsStatement : public Statement
{
private:
const vector<EstimationParams> estim_params_list;
const SymbolTable &symbol_table;
public:
EstimatedParamsStatement(const vector<EstimationParams> &estim_params_list_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class EstimatedParamsInitStatement : public Statement
{
private:
const vector<EstimationParams> estim_params_list;
const SymbolTable &symbol_table;
public:
EstimatedParamsInitStatement(const vector<EstimationParams> &estim_params_list_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class EstimatedParamsBoundsStatement : public Statement
{
private:
const vector<EstimationParams> estim_params_list;
const SymbolTable &symbol_table;
public:
EstimatedParamsBoundsStatement(const vector<EstimationParams> &estim_params_list_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class OptimWeightsStatement : public Statement
{
public:
typedef map<string, NodeID> var_weights_type;
typedef map<pair<string, string>, NodeID> covar_weights_type;
private:
const var_weights_type var_weights;
const covar_weights_type covar_weights;
const SymbolTable &symbol_table;
public:
OptimWeightsStatement(const var_weights_type &var_weights_arg,
const covar_weights_type &covar_weights_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class CalibStatement : public Statement
{
private:
const int covar;
public:
CalibStatement(int covar_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class CalibVarStatement : public Statement
{
public:
//! Maps a variable to a pair (weight, expression)
typedef map<string, pair<string, NodeID> > calib_var_type;
//! Maps a pair of variables to a pair (weight, expression)
typedef map<pair<string, string>, pair<string, NodeID> > calib_covar_type;
//! Maps a pair (variable, autocorr) to a pair (weight, expression)
typedef map<pair<string, int>, pair<string, NodeID> > calib_ac_type;
private:
const calib_var_type calib_var;
const calib_covar_type calib_covar;
const calib_ac_type calib_ac;
const SymbolTable &symbol_table;
public:
CalibVarStatement(const calib_var_type &calib_var_arg,
const calib_covar_type &calib_covar_arg,
const calib_ac_type &calib_ac_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
/*! \todo Make model_tree a member instead of a pointer */
class PlannerObjectiveStatement : public Statement
{
private:
ModelTree *model_tree;
public:
//! Constructor
/*! \param model_tree_arg the model tree used to store the objective function.
It is owned by the PlannerObjectiveStatement, and will be deleted by its destructor */
PlannerObjectiveStatement(ModelTree *model_tree_arg);
virtual ~PlannerObjectiveStatement();
/*! \todo check there are only endogenous variables at the current period in the objective
(no exogenous, no lead/lag) */
virtual void checkPass(ModFileStructure &mod_file_struct);
virtual void computingPass();
virtual void writeOutput(ostream &output, const string &basename) const;
};
class BVARDensityStatement : public Statement
{
private:
const int maxnlags;
const OptionsList options_list;
public:
BVARDensityStatement(int maxnlags_arg, const OptionsList &options_list_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class BVARForecastStatement : public Statement
{
private:
const int nlags;
const OptionsList options_list;
public:
BVARForecastStatement(int nlags_arg, const OptionsList &options_list_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
#endif

254
include/DataTree.hh Normal file
View File

@ -0,0 +1,254 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _DATATREE_HH
#define _DATATREE_HH
using namespace std;
#include <string>
#include <map>
#include <list>
#include <sstream>
#include <iomanip>
#include "SymbolTable.hh"
#include "NumericalConstants.hh"
#include "VariableTable.hh"
#include "ExprNode.hh"
#define CONSTANTS_PRECISION 16
class DataTree
{
friend class ExprNode;
friend class NumConstNode;
friend class VariableNode;
friend class UnaryOpNode;
friend class BinaryOpNode;
friend class TrinaryOpNode;
friend class UnknownFunctionNode;
protected:
//! A reference to the symbol table
SymbolTable &symbol_table;
//! Reference to numerical constants table
NumericalConstants &num_constants;
typedef list<NodeID> node_list_type;
//! The list of nodes
node_list_type node_list;
//! A counter for filling ExprNode's idx field
int node_counter;
//! Stores local variables value
map<int, NodeID> local_variables_table;
typedef map<int, NodeID> num_const_node_map_type;
num_const_node_map_type num_const_node_map;
//! Type (symbol_id, type, lag) used as key
typedef map<pair<pair<int, Type>, int>, NodeID> variable_node_map_type;
variable_node_map_type variable_node_map;
typedef map<pair<NodeID, int>, NodeID> unary_op_node_map_type;
unary_op_node_map_type unary_op_node_map;
typedef map<pair<pair<NodeID, NodeID>, int>, NodeID> binary_op_node_map_type;
binary_op_node_map_type binary_op_node_map;
typedef map<pair<pair<pair<NodeID, NodeID>,NodeID>, int>, NodeID> trinary_op_node_map_type;
trinary_op_node_map_type trinary_op_node_map;
inline NodeID AddPossiblyNegativeConstant(double val);
inline NodeID AddUnaryOp(UnaryOpcode op_code, NodeID arg);
inline NodeID AddBinaryOp(NodeID arg1, BinaryOpcode op_code, NodeID arg2);
inline NodeID AddTrinaryOp(NodeID arg1, TrinaryOpcode op_code, NodeID arg2, NodeID arg3);
public:
DataTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg);
virtual ~DataTree();
//! The variable table
VariableTable variable_table;
NodeID Zero, One, MinusOne;
//! Raised when a local parameter is declared twice
class LocalParameterException
{
public:
string name;
LocalParameterException(const string &name_arg) : name(name_arg) {}
};
NodeID AddNumConstant(const string &value);
NodeID AddVariable(const string &name, int lag = 0);
//! Adds "arg1+arg2" to model tree
NodeID AddPlus(NodeID iArg1, NodeID iArg2);
//! Adds "arg1-arg2" to model tree
NodeID AddMinus(NodeID iArg1, NodeID iArg2);
//! Adds "-arg" to model tree
NodeID AddUMinus(NodeID iArg1);
//! Adds "arg1*arg2" to model tree
NodeID AddTimes(NodeID iArg1, NodeID iArg2);
//! Adds "arg1/arg2" to model tree
NodeID AddDivide(NodeID iArg1, NodeID iArg2);
//! Adds "arg1<arg2" to model tree
NodeID AddLess(NodeID iArg1, NodeID iArg2);
//! Adds "arg1>arg2" to model tree
NodeID AddGreater(NodeID iArg1, NodeID iArg2);
//! Adds "arg1<=arg2" to model tree
NodeID AddLessEqual(NodeID iArg1, NodeID iArg2);
//! Adds "arg1>=arg2" to model tree
NodeID AddGreaterEqual(NodeID iArg1, NodeID iArg2);
//! Adds "arg1==arg2" to model tree
NodeID AddEqualEqual(NodeID iArg1, NodeID iArg2);
//! Adds "arg1!=arg2" to model tree
NodeID AddDifferent(NodeID iArg1, NodeID iArg2);
//! Adds "arg1^arg2" to model tree
NodeID AddPower(NodeID iArg1, NodeID iArg2);
//! Adds "exp(arg)" to model tree
NodeID AddExp(NodeID iArg1);
//! Adds "log(arg)" to model tree
NodeID AddLog(NodeID iArg1);
//! Adds "log10(arg)" to model tree
NodeID AddLog10(NodeID iArg1);
//! Adds "cos(arg)" to model tree
NodeID AddCos(NodeID iArg1);
//! Adds "sin(arg)" to model tree
NodeID AddSin(NodeID iArg1);
//! Adds "tan(arg)" to model tree
NodeID AddTan(NodeID iArg1);
//! Adds "acos(arg)" to model tree
NodeID AddACos(NodeID iArg1);
//! Adds "asin(arg)" to model tree
NodeID AddASin(NodeID iArg1);
//! Adds "atan(arg)" to model tree
NodeID AddATan(NodeID iArg1);
//! Adds "cosh(arg)" to model tree
NodeID AddCosH(NodeID iArg1);
//! Adds "sinh(arg)" to model tree
NodeID AddSinH(NodeID iArg1);
//! Adds "tanh(arg)" to model tree
NodeID AddTanH(NodeID iArg1);
//! Adds "acosh(arg)" to model tree
NodeID AddACosH(NodeID iArg1);
//! Adds "asinh(arg)" to model tree
NodeID AddASinH(NodeID iArg1);
//! Adds "atanh(args)" to model tree
NodeID AddATanH(NodeID iArg1);
//! Adds "sqrt(arg)" to model tree
NodeID AddSqRt(NodeID iArg1);
//! Adds "max(arg1,arg2)" to model tree
NodeID AddMaX(NodeID iArg1, NodeID iArg2);
//! Adds "min(arg1,arg2)" to model tree
NodeID AddMin(NodeID iArg1, NodeID iArg2);
//! Adds "normcdf(arg1,arg2,arg3)" to model tree
NodeID AddNormcdf(NodeID iArg1, NodeID iArg2, NodeID iArg3);
//! Adds "arg1=arg2" to model tree
NodeID AddEqual(NodeID iArg1, NodeID iArg2);
void AddLocalParameter(const string &name, NodeID value) throw (LocalParameterException);
//! Adds an unknown function node
/*! \todo Use a map to share identical nodes */
NodeID AddUnknownFunction(const string &function_name, const vector<NodeID> &arguments);
};
inline NodeID
DataTree::AddPossiblyNegativeConstant(double v)
{
bool neg = false;
if (v < 0)
{
v = -v;
neg = true;
}
ostringstream ost;
ost << setprecision(CONSTANTS_PRECISION) << v;
NodeID cnode = AddNumConstant(ost.str());
if (neg)
return AddUMinus(cnode);
else
return cnode;
}
inline NodeID
DataTree::AddUnaryOp(UnaryOpcode op_code, NodeID arg)
{
// If the node already exists in tree, share it
unary_op_node_map_type::iterator it = unary_op_node_map.find(make_pair(arg, op_code));
if (it != unary_op_node_map.end())
return it->second;
// Try to reduce to a constant
// Case where arg is a constant and op_code == oUminus (i.e. we're adding a negative constant) is skipped
NumConstNode *carg = dynamic_cast<NumConstNode *>(arg);
if (op_code != oUminus || carg == NULL)
{
try
{
double argval = arg->eval(eval_context_type());
double val = UnaryOpNode::eval_opcode(op_code, argval);
return AddPossiblyNegativeConstant(val);
}
catch(ExprNode::EvalException &e)
{
}
}
return new UnaryOpNode(*this, op_code, arg);
}
inline NodeID
DataTree::AddBinaryOp(NodeID arg1, BinaryOpcode op_code, NodeID arg2)
{
binary_op_node_map_type::iterator it = binary_op_node_map.find(make_pair(make_pair(arg1, arg2), op_code));
if (it != binary_op_node_map.end())
return it->second;
// Try to reduce to a constant
try
{
double argval1 = arg1->eval(eval_context_type());
double argval2 = arg2->eval(eval_context_type());
double val = BinaryOpNode::eval_opcode(argval1, op_code, argval2);
return AddPossiblyNegativeConstant(val);
}
catch(ExprNode::EvalException &e)
{
}
return new BinaryOpNode(*this, arg1, op_code, arg2);
}
inline NodeID
DataTree::AddTrinaryOp(NodeID arg1, TrinaryOpcode op_code, NodeID arg2, NodeID arg3)
{
trinary_op_node_map_type::iterator it = trinary_op_node_map.find(make_pair(make_pair(make_pair(arg1, arg2), arg3), op_code));
if (it != trinary_op_node_map.end())
return it->second;
// Try to reduce to a constant
try
{
double argval1 = arg1->eval(eval_context_type());
double argval2 = arg2->eval(eval_context_type());
double argval3 = arg3->eval(eval_context_type());
double val = TrinaryOpNode::eval_opcode(argval1, op_code, argval2, argval3);
return AddPossiblyNegativeConstant(val);
}
catch(ExprNode::EvalException &e)
{
}
return new TrinaryOpNode(*this, arg1, op_code, arg2, arg3);
}
#endif

343
include/ExprNode.hh Normal file
View File

@ -0,0 +1,343 @@
/*
* Copyright (C) 2007-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _EXPR_NODE_HH
#define _EXPR_NODE_HH
using namespace std;
#include <set>
#include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include "SymbolTable.hh"
#include "CodeInterpreter.hh"
class DataTree;
typedef class ExprNode *NodeID;
typedef struct Model_Block;
struct ExprNodeLess;
//! Type for set of temporary terms
/*! They are ordered by index number thanks to ExprNodeLess */
typedef set<NodeID, ExprNodeLess> temporary_terms_type;
typedef map<int,int> map_idx_type;
//! Possible types of output when writing ExprNode(s)
enum ExprNodeOutputType
{
oMatlabStaticModel, //!< Matlab code, static model declarations
oMatlabDynamicModel, //!< Matlab code, dynamic model declarations
oMatlabStaticModelSparse, //!< Matlab code, static block decomposed mode declaration
oMatlabDynamicModelSparse, //!< Matlab code, dynamic block decomposed mode declaration
oCStaticModel, //!< C code, static model declarations
oCDynamicModel, //!< C code, dynamic model declarations
oCDynamicModelSparseDLL, //!< C code, dynamic model declarations in SparseDLL module
oMatlabOutsideModel //!< Matlab code, outside model block (for example in initval)
};
//! Type for evaluation contexts
/*! The key is a pair (symbol id, symbol type)
Lags are assumed to be null */
typedef map<pair<int, Type>, double> eval_context_type;
/* Equal to 1 for Matlab langage, or to 0 for C language
In Matlab, array indexes begin at 1, while they begin at 0 in C */
#define OFFSET(output_type) ((output_type == oMatlabStaticModel) \
|| (output_type == oMatlabDynamicModel) \
|| (output_type == oMatlabOutsideModel) \
|| (output_type == oMatlabStaticModelSparse) \
|| (output_type == oMatlabDynamicModelSparse))
// Left parenthesis: '(' for Matlab, '[' for C
#define LPAR(output_type) (OFFSET(output_type) ? '(' : '[')
// Right parenthesis: ')' for Matlab, ']' for C
#define RPAR(output_type) (OFFSET(output_type) ? ')' : ']')
// Computing cost above which a node can be declared a temporary term
#define MIN_COST_MATLAB (40*90)
#define MIN_COST_C (40*4)
#define MIN_COST(is_matlab) (is_matlab ? MIN_COST_MATLAB : MIN_COST_C)
//! Base class for expression nodes
class ExprNode
{
friend class DataTree;
friend class ModelTree;
friend class ExprNodeLess;
friend class NumConstNode;
friend class VariableNode;
friend class UnaryOpNode;
friend class BinaryOpNode;
friend class TrinaryOpNode;
private:
//! Computes derivative w.r. to variable varID (but doesn't store it in derivatives map)
/*! You shoud use getDerivative() to get the benefit of symbolic a priori and of caching */
virtual NodeID computeDerivative(int varID) = 0;
protected:
//! Reference to the enclosing DataTree
DataTree &datatree;
//! Index number
int idx;
//! Set of variable IDs with respect to which the derivative is potentially non-null
set<int> non_null_derivatives;
//! Used for caching of first order derivatives (when non-null)
map<int, NodeID> derivatives;
//! Cost of computing current node
/*! Nodes included in temporary_terms are considered having a null cost */
virtual int cost(const temporary_terms_type &temporary_terms, bool is_matlab) const;
//! set of endogenous variables in the current expression
//! <symbolID, lag>
set< pair<int,int> > present_endogenous;
public:
ExprNode(DataTree &datatree_arg);
virtual ~ExprNode();
//! Returns derivative w.r. to variable varID
/*! 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 */
NodeID getDerivative(int varID);
//! Returns precedence of node
/*! Equals 100 for constants, variables, unary ops, and temporary terms */
virtual int precedence(ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const;
//! Fills temporary_terms set, using reference counts
/*! A node will be marked as a temporary term if it is referenced at least two times (i.e. has at least two parents), and has a computing cost (multiplied by reference count) greater to datatree.min_cost */
virtual void computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms, bool is_matlab) const;
//! Writes output of node, using a Txxx notation for nodes in temporary_terms
virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const = 0;
//! Writes output of node (with no temporary terms and with "outside model" output type)
void writeOutput(ostream &output);
//! Collects the Endogenous in a expression
virtual void collectEndogenous(NodeID &Id) = 0;
virtual void computeTemporaryTerms(map<NodeID, int> &reference_count,
temporary_terms_type &temporary_terms,
map<NodeID, int> &first_occurence,
int Curr_block,
Model_Block *ModelBlock,
map_idx_type &map_idx) const;
int present_endogenous_size() const;
int present_endogenous_find(int var, int lag) const;
class EvalException
{
};
virtual double eval(const eval_context_type &eval_context) const throw (EvalException) = 0;
virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const = 0;
};
//! Object used to compare two nodes (using their indexes)
struct ExprNodeLess
{
bool operator()(NodeID arg1, NodeID arg2) const
{
return arg1->idx < arg2->idx;
}
};
//! Numerical constant node
/*! The constant is necessarily non-negative (this is enforced at the NumericalConstants class level) */
class NumConstNode : public ExprNode
{
private:
//! Id from numerical constants table
const int id;
virtual NodeID computeDerivative(int varID);
public:
NumConstNode(DataTree &datatree_arg, int id_arg);
virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const;
virtual void collectEndogenous(NodeID &Id);
virtual double eval(const eval_context_type &eval_context) const throw (EvalException);
virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const;
};
//! Symbol or variable node
class VariableNode : public ExprNode
{
private:
//! Id from the symbol table
const int symb_id;
const Type type;
const int lag;
//! Id from the variable table (-1 if not a endogenous/exogenous/recursive)
int var_id;
virtual NodeID computeDerivative(int varID);
public:
VariableNode(DataTree &datatree_arg, int symb_id_arg, Type type_arg, int lag_arg);
virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms = temporary_terms_type()) const;
virtual void collectEndogenous(NodeID &Id);
virtual double eval(const eval_context_type &eval_context) const throw (EvalException);
virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const;
};
//! Unary operator node
class UnaryOpNode : public ExprNode
{
friend class DataTree;
private:
const NodeID arg;
const UnaryOpcode op_code;
virtual NodeID computeDerivative(int varID);
virtual int cost(const temporary_terms_type &temporary_terms, bool is_matlab) const;
public:
UnaryOpNode(DataTree &datatree_arg, UnaryOpcode op_code_arg, const NodeID arg_arg);
virtual void computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms, bool is_matlab) const;
virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const;
virtual void computeTemporaryTerms(map<NodeID, int> &reference_count,
temporary_terms_type &temporary_terms,
map<NodeID, int> &first_occurence,
int Curr_block,
Model_Block *ModelBlock,
map_idx_type &map_idx) const;
virtual void collectEndogenous(NodeID &Id);
static double eval_opcode(UnaryOpcode op_code, double v) throw (EvalException);
virtual double eval(const eval_context_type &eval_context) const throw (EvalException);
virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const;
};
//! Binary operator node
class BinaryOpNode : public ExprNode
{
friend class ModelTree;
private:
const NodeID arg1, arg2;
const BinaryOpcode op_code;
virtual NodeID computeDerivative(int varID);
virtual int cost(const temporary_terms_type &temporary_terms, bool is_matlab) const;
public:
BinaryOpNode(DataTree &datatree_arg, const NodeID arg1_arg,
BinaryOpcode op_code_arg, const NodeID arg2_arg);
virtual int precedence(ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const;
virtual void computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms, bool is_matlab) const;
virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const;
virtual void computeTemporaryTerms(map<NodeID, int> &reference_count,
temporary_terms_type &temporary_terms,
map<NodeID, int> &first_occurence,
int Curr_block,
Model_Block *ModelBlock,
map_idx_type &map_idx) const;
virtual void collectEndogenous(NodeID &Id);
static double eval_opcode(double v1, BinaryOpcode op_code, double v2) throw (EvalException);
virtual double eval(const eval_context_type &eval_context) const throw (EvalException);
virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const;
};
enum TrinaryOpcode
{
oNormcdf
};
//! Trinary operator node
class TrinaryOpNode : public ExprNode
{
friend class ModelTree;
private:
const NodeID arg1, arg2, arg3;
const TrinaryOpcode op_code;
virtual NodeID computeDerivative(int varID);
virtual int cost(const temporary_terms_type &temporary_terms, bool is_matlab) const;
public:
TrinaryOpNode(DataTree &datatree_arg, const NodeID arg1_arg,
TrinaryOpcode op_code_arg, const NodeID arg2_arg, const NodeID arg3_arg);
virtual int precedence(ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const;
virtual void computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms, bool is_matlab) const;
virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const;
virtual void computeTemporaryTerms(map<NodeID, int> &reference_count,
temporary_terms_type &temporary_terms,
map<NodeID, int> &first_occurence,
int Curr_block,
Model_Block *ModelBlock,
map_idx_type &map_idx) const;
virtual void collectEndogenous(NodeID &Id);
static double eval_opcode(double v1, TrinaryOpcode op_code, double v2, double v3) throw (EvalException);
virtual double eval(const eval_context_type &eval_context) const throw (EvalException);
virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const;
};
//! Unknown function node
class UnknownFunctionNode : public ExprNode
{
private:
//! Symbol ID (no need to store type: it is necessary eUnknownFunction)
const int symb_id;
const vector<NodeID> arguments;
virtual NodeID computeDerivative(int varID);
public:
UnknownFunctionNode(DataTree &datatree_arg, int symb_id_arg,
const vector<NodeID> &arguments_arg);
virtual void computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms, bool is_matlab) const;
virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const;
virtual void computeTemporaryTerms(map<NodeID, int> &reference_count,
temporary_terms_type &temporary_terms,
map<NodeID, int> &first_occurence,
int Curr_block,
Model_Block *ModelBlock,
map_idx_type &map_idx) const;
virtual void collectEndogenous(NodeID &Id);
virtual double eval(const eval_context_type &eval_context) const throw (EvalException);
virtual void compile(ofstream &CompileCode, bool lhs_rhs, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms, map_idx_type map_idx) const;
};
typedef struct IM_compact
{
int size, u_init, u_finish, nb_endo;
int *u, *us, *Var, *Equ, *Var_Index, *Equ_Index, *Var_dyn_Index;
};
typedef struct Block
{
int Size, Sized, Type, Simulation_Type, Max_Lead, Max_Lag, Nb_Lead_Lag_Endo;
bool is_linear;
int *Equation, *Own_Derivative;
int *Variable, *Variable_Sorted, *dVariable;
int *variable_dyn_index, *variable_dyn_leadlag;
temporary_terms_type *Temporary_terms;
IM_compact *IM_lead_lag;
int Code_Start, Code_Length;
};
typedef struct Model_Block
{
int Size, Periods;
Block* Block_List;
int *in_Block_Equ, *in_Block_Var, *in_Equ_of_Block, *in_Var_of_Block;
};
#endif

36
include/Interface.hh Normal file
View File

@ -0,0 +1,36 @@
/*
* Copyright (C) 2006-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _INTERFACE_HH
#define _INTERFACE_HH
using namespace std;
namespace interfaces
{
string comment();
string delete_file(string s);
string file_exist(string s);
string compile(string s);
string function_close();
string function_file_extension();
string strvcat(string s1, string s2);
string load_model_function_files(string filename);
}
#endif

74
include/ModFile.hh Normal file
View File

@ -0,0 +1,74 @@
/*
* Copyright (C) 2006-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _MOD_FILE_HH
#define _MOD_FILE_HH
using namespace std;
#include <ostream>
#include "SymbolTable.hh"
#include "NumericalConstants.hh"
#include "ModelTree.hh"
#include "VariableTable.hh"
#include "Statement.hh"
//! The abstract representation of a "mod" file
class ModFile
{
public:
ModFile();
~ModFile();
//! Symbol table
SymbolTable symbol_table;
//! Numerical constants table
NumericalConstants num_constants;
//! Expressions outside model block
DataTree expressions_tree;
//! Model equations and their derivatives
ModelTree model_tree;
//! Option linear
bool linear;
//! Global evaluation context
/*! Filled using initval blocks and parameters initializations */
eval_context_type global_eval_context;
private:
//! List of statements
vector<Statement *> statements;
//! Structure of the mod file
ModFileStructure mod_file_struct;
public:
//! Add a statement
void addStatement(Statement *st);
//! Do some checking and fills mod_file_struct
void checkPass();
//! Execute computations
void computingPass();
//! Writes Matlab/Scilab output files
/*!
\param basename The base name used for writing output files. Should be the name of the mod file without its extension
\param clear_all Should a "clear all" instruction be written to output ?
*/
void writeOutputFiles(const string &basename, bool clear_all) const;
};
#endif // ! MOD_FILE_HH

56
include/ModelBlocks.hh Normal file
View File

@ -0,0 +1,56 @@
/*
* Copyright (C) 2007-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MODELBLOCKS
#define MODELBLOCKS
#include "ModelNormalization.hh"
typedef struct block_result
{
int size, n_sets;
int *vertices;
int *sets_s, *sets_f;
int *order, *ordered;
}
block_result_t;
class Blocks
{
public:
Blocks();
~Blocks();
void block_depth_search(int v);
block_result_t* sc(Equation_set *g);
void block_result_free(block_result_t *r);
void block_result_print(block_result_t *r);
Equation_set* Equation_gr_IM( int n , bool* IM);
void Print_Equation_gr(Equation_set* Equation);
void block_result_to_IM(block_result_t *r,bool* IM,int prologue, int n,simple* Index_Equ_IM,simple* Index_Var_IM);
Equation_vertex *vertices;
int *block_vertices, *sets_s, *sets_f;
int *block_stack, *sp, tos;
int *visit_nos, *low_link_nos;
int n_visited, n_written, n_sets;
int *pos_sc;
};
#endif

View File

@ -0,0 +1,100 @@
/*
* Copyright (C) 2007-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MODELNORMALIZATION
#define MODELNORMALIZATION
#include "SymbolTable.hh"
#include "CodeInterpreter.hh"
typedef struct Edge
{
Edge *next;
int Vertex_Index;
};
typedef struct Equation_vertex
{
Edge *First_Edge;
Edge *Next_Edge;
int matched,index;
};
typedef struct Equation_set
{
Equation_vertex *Number;
int size;
int edges;
};
typedef struct simple
{
int index, block;
bool available;
};
typedef std::string (*t_getNameByID)(Type type, int id);
class Normalization
{
private:
typedef struct Variable_vertex
{
int matched;
};
typedef struct Variable_set
{
Variable_vertex *Number;
int size;
};
typedef struct t_Heap
{
int u; /* vertex */
int i_parent; /* index in t_Heap of parent vertex in tree of u */
int v; /* current matched of u */
};
public:
Normalization(const SymbolTable &symbol_table_arg);
~Normalization();
bool Normalize(int n, int prologue, int epilogue, bool* IM, simple* Index_Var_IM, Equation_set* Equation,bool mixing, bool* IM_s);
void Gr_to_IM_basic(int n0, int prologue, int epilogue, bool* IM, Equation_set *Equation,bool transpose);
t_getNameByID getnamebyID;
const SymbolTable &symbol_table;
void Set_fp_verbose(bool ok);
private:
void IM_to_Gr(int n0, int prologue, int epilogue, bool* IM, Equation_set *Equation, Variable_set *Variable );
void Inits(Equation_set *Equation);
void UpdatePath(Equation_set *Equation, Variable_set *Variable, int i1, int i2);
void FindAugmentingPaths(Equation_set *Equation, Variable_set *Variable);
void CheapMatching(Equation_set *Equation, Variable_set *Variable);
void MaximumMatching(Equation_set *Equation, Variable_set *Variable);
int MeasureMatching(Equation_set *Equation);
void OutputMatching(Equation_set* Equation);
void Gr_to_IM(int n0, int prologue, int epilogue, bool* IM, simple* Index_Var_IM, Equation_set *Equation,bool mixing, bool* IM_s);
void Free_Equation(int n, Equation_set* Equation);
void Free_Other(Variable_set* Variable);
void Free_All(int n, Equation_set* Equation, Variable_set* Variable);
void ErrorHandling(int n, bool* IM, simple* Index_Equ_IM);
int eq, eex;
int IndexUnmatched;
bool fp_verbose;
bool* visited;
t_Heap* Local_Heap;
};
#endif

188
include/ModelTree.hh Normal file
View File

@ -0,0 +1,188 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _MODELTREE_HH
#define _MODELTREE_HH
using namespace std;
#include <string>
#include <vector>
#include <map>
#include <ostream>
#include "SymbolTable.hh"
#include "NumericalConstants.hh"
#include "DataTree.hh"
#include "BlockTriangular.hh"
#include "SymbolGaussElim.hh"
#define LCC_COMPILE 0
#define GCC_COMPILE 1
#define NO_COMPILE 2
//#define CONDITION
//! The three in which ModelTree can work
enum ModelTreeMode
{
eStandardMode, //!< Standard mode (static and dynamic files in Matlab)
eSparseMode, //!< Sparse mode (static file in Matlab, dynamic file in Matlab with block decomposition)
eDLLMode, //!< DLL mode (static and dynamic files in C)
eSparseDLLMode //!< Sparse DLL mode (static file in Matlab, dynamic file in C with block decomposition plus a binary file)
};
//! Stores a model's equations and derivatives
class ModelTree : public DataTree
{
private:
//! Stores declared equations
vector<BinaryOpNode *> equations;
typedef map<pair<int, int>, NodeID> first_derivatives_type;
//! First order derivatives
/*! First index is equation number, second is variable w.r. to which is computed the derivative.
Only non-null derivatives are stored in the map.
Variable indexes used are those of the variable_table, before sorting.
*/
first_derivatives_type first_derivatives;
typedef map<pair<int, pair<int, int> >, NodeID> second_derivatives_type;
//! Second order derivatives
/*! First index is equation number, second and third are variables w.r. to which is computed the derivative.
Only non-null derivatives are stored in the map.
Contains only second order derivatives where var1 >= var2 (for obvious symmetry reasons).
Variable indexes used are those of the variable_table, before sorting.
*/
second_derivatives_type second_derivatives;
typedef map<pair<int, pair<int, pair<int, int> > >, NodeID> third_derivatives_type;
//! Third order derivatives
/*! First index is equation number, second, third and fourth are variables w.r. to which is computed the derivative.
Only non-null derivatives are stored in the map.
Contains only third order derivatives where var1 >= var2 >= var3 (for obvious symmetry reasons).
Variable indexes used are those of the variable_table, before sorting.
*/
third_derivatives_type third_derivatives;
//! Temporary terms (those which will be noted Txxxx)
temporary_terms_type temporary_terms;
map_idx_type map_idx;
//! Computes derivatives of ModelTree
void derive(int order);
//! Write derivative of an equation w.r. to a variable
void writeDerivative(ostream &output, int eq, int symb_id, int lag, ExprNodeOutputType output_type, const temporary_terms_type &temporary_terms) const;
//! Write derivative code of an equation w.r. to a variable
void compileDerivative(ofstream &code_file, int eq, int symb_id, int lag, ExprNodeOutputType output_type, map_idx_type map_idx) const;
//! Computes temporary terms
void computeTemporaryTerms(int order);
void computeTemporaryTermsOrdered(int order, Model_Block *ModelBlock);
//! Writes temporary terms
void writeTemporaryTerms(ostream &output, ExprNodeOutputType output_type) const;
//! Writes model local variables
/*! No temporary term is used in the output, so that local parameters declarations can be safely put before temporary terms declaration in the output files */
void writeModelLocalVariables(ostream &output, ExprNodeOutputType output_type) const;
//! Writes model equations
void writeModelEquations(ostream &output, ExprNodeOutputType output_type) const;
//! Writes the static model equations and its derivatives
/*! \todo handle hessian in C output */
void writeStaticModel(ostream &StaticOutput) const;
//! Writes the dynamic model equations and its derivatives
/*! \todo add third derivatives handling in C output */
void writeDynamicModel(ostream &DynamicOutput) const;
//! Writes the Block reordred structure of the model in C output
void writeModelEquationsOrdered_C(ostream &output, Model_Block *ModelBlock) const;
//! Writes the Block reordred structure of the model in M output
void writeModelEquationsOrdered_M(ostream &output, Model_Block *ModelBlock, const string &dynamic_basename) const;
//! Writes the Block reordred structure of the static model in M output
void writeModelStaticEquationsOrdered_M(ostream &output, Model_Block *ModelBlock, const string &static_basename) const;
//! Writes the code of the Block reordred structure of the model in C output
void writeModelEquationsCodeOrdered(const string file_name, const Model_Block *ModelBlock, const string bin_basename, ExprNodeOutputType output_type) const;
//! Writes static model file (Matlab version)
void writeStaticMFile(const string &static_basename) const;
//! Writes static model file (C version)
void writeStaticCFile(const string &static_basename) const;
//! Writes static model file when Sparse option is on (Matlab version)
void writeSparseStaticMFile(const string &static_basename, const string &bin_basename, const int mode) const;
//! Writes dynamic model file (Matlab version)
void writeDynamicMFile(const string &dynamic_basename) const;
//! Writes dynamic model file (C version)
/*! \todo add third derivatives handling */
void writeDynamicCFile(const string &dynamic_basename) const;
//! Writes dynamic model header file when SparseDLL option is on
void writeSparseDLLDynamicHFile(const string &dynamic_basename) const;
//! Writes dynamic model file when SparseDLL option is on
void writeSparseDynamicFileAndBinFile(const string &dynamic_basename, const string &bin_basename, ExprNodeOutputType output_type, const int mode) const;
//! Computes jacobian and prepares for equation normalization
/*! Using values from initval/endval blocks and parameter initializations:
- computes the jacobian for the model w.r. to contemporaneous variables
- removes edges of the incidence matrix when derivative w.r. to the corresponding variable is too close to zero (below the cutoff)
*/
void evaluateJacobian(const eval_context_type &eval_context, jacob_map *j_m);
void BlockLinear(Model_Block *ModelBlock);
string reform(string name) const;
//! Writes either (i+1,j+1) or [i+j*n_i] whether we are in Matlab or C mode
void matrixHelper(ostream &output, int eq_nb, int col_nb, ExprNodeOutputType output_type) const;
public:
ModelTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants);
//! Mode in which the ModelTree is supposed to work (Matlab, DLL or SparseDLL)
ModelTreeMode mode;
//! Type of compiler used in matlab for SPARSE_DLL option: 0 = LCC or 1 = GCC or 2 = NO
int compiler;
//! Absolute value under which a number is considered to be zero
double cutoff;
//! The weight of the Markowitz criteria to determine the pivot in the linear solver (simul_NG1 from simulate.cc)
double markowitz;
//! Use a graphical and symbolic version of the symbolic gaussian elimination (new_SGE = false) or use direct gaussian elimination (new_SGE = true)
bool new_SGE;
//! the file containing the model and the derivatives code
ofstream code_file;
//! Declare a node as an equation of the model
void addEquation(NodeID eq);
//! Whether dynamic Jacobian (w.r. to endogenous) should be written
bool computeJacobian;
//! Whether dynamic Jacobian (w.r. to endogenous and exogenous) should be written
bool computeJacobianExo;
//! Whether dynamic Hessian (w.r. to endogenous and exogenous) should be written
bool computeHessian;
//! Whether static Hessian (w.r. to endogenous only) should be written
bool computeStaticHessian;
//! Whether dynamic third order derivatives (w.r. to endogenous and exogenous) should be written
bool computeThirdDerivatives;
//! Execute computations (variable sorting + derivation)
/*! You must set computeJacobian, computeJacobianExo, computeHessian, computeStaticHessian and computeThirdDerivatives to correct values before calling this function */
void computingPass(const eval_context_type &eval_context);
//! Writes model initialization and lead/lag incidence matrix to output
void writeOutput(ostream &output) const;
//! Writes static model file
void writeStaticFile(const string &basename) const;
//! Writes dynamic model file
void writeDynamicFile(const string &basename) const;
//! Complete set to block decompose the model
BlockTriangular block_triangular;
//! Adds informations for simulation in a binary file
void Write_Inf_To_Bin_File(const string &dynamic_basename, const string &bin_basename,
const int &num, int &u_count_int, bool &file_open) const;
int equation_number() const;
};
#endif

83
include/Model_Graph.hh Normal file
View File

@ -0,0 +1,83 @@
/*
* Copyright (C) 2007-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MODEL_GRAPH
#define MODEL_GRAPH
#define DIRECT_COMPUTE
#define SORTED
#define SIMPLIFY
#define SIMPLIFYS
#define SAVE
#define COMPUTE
//#define PRINT_OUT_OUT
//#define PRINT_OUT_1
#define DIRECT_SAVE
#include "ModelTree.hh"
#include "BlockTriangular.hh"
typedef struct t_edge
{
int index, u_count;
};
typedef struct t_vertex
{
t_edge *out_degree_edge, *in_degree_edge;
int nb_out_degree_edges, nb_in_degree_edges;
int max_nb_out_degree_edges, max_nb_in_degree_edges;
int index, lag_lead;
};
typedef struct t_model_graph
{
int nb_vertices;
t_vertex* vertex;
};
typedef struct t_pList
{
int* Lag_in, * Lag_out;
int CurrNb_in, CurrNb_out;
};
void free_model_graph(t_model_graph* model_graph);
void print_Graph(t_model_graph* model_graph);
void Check_Graph(t_model_graph* model_graph);
void copy_model_graph(t_model_graph* model_graph, t_model_graph* saved_model_graph, int nb_endo, int y_kmax);
int ModelBlock_Graph(Model_Block *ModelBlock, int Blck_num,bool dynamic, t_model_graph* model_graph, int nb_endo, int *block_u_count, int *starting_vertex, int* periods, int *nb_table_y, int *mean_var_in_equ);
void IM_to_model_graph(List_IM* First_IM,int Time, int endo, int* y_kmin, int* y_kmax, t_model_graph* model_graph, int* nb_endo, int *stacked_time, double** u1, int* u_count
#ifdef VERIF
, Matrix *B, Matrix *D
#endif
);
void IM_to_model_graph_new(List_IM* First_IM,int Time, int endo, int* y_kmin, int* y_kmax, t_model_graph* model_graph, int* nb_endo, int *stacked_time, double** u1, int* u_count
#ifdef VERIF
, Matrix *B, Matrix *D
#endif
);
void IM_to_model_graph_new_new(List_IM* First_IM,int Time, int endo, int* y_kmin, int* y_kmax, t_model_graph* model_graph, int* nb_endo, int *stacked_time, double** u1, int* u_count
#ifdef VERIF
, Matrix *B, Matrix *D
#endif
);
void reduce_model_graph(t_model_graph* model_graph,int pos);
#endif

View File

@ -0,0 +1,47 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _NUMERICALCONSTANTS_HH
#define _NUMERICALCONSTANTS_HH
using namespace std;
#include <string>
#include <vector>
#include <map>
//! Handles numerical constants
class NumericalConstants
{
private:
//! Vector of numerical constants
vector<string> mNumericalConstants;
//! Map matching constants to their id
map<string, int> numConstantsIndex;
public:
NumericalConstants();
//! Adds a constant and returns its ID
int AddConstant(const string &iConst);
//! Get a constant in string form
string get(int iID) const;
//! Get a constant in double form
double getDouble(int iID) const;
};
#endif

View File

@ -0,0 +1,111 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _NUMERICALINITIALIZATION_HH
#define _NUMERICALINITIALIZATION_HH
using namespace std;
#include <string>
#include <map>
#include "SymbolTable.hh"
#include "ExprNode.hh"
#include "Statement.hh"
class InitParamStatement : public Statement
{
private:
const string param_name;
const NodeID param_value;
const SymbolTable &symbol_table;
public:
InitParamStatement(const string &param_name_arg, const NodeID param_value_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class InitOrEndValStatement : public Statement
{
public:
/*!
We use a vector instead of a map, since the order of declaration matters:
an initialization can depend on a previously initialized variable inside the block
*/
typedef vector<pair<string, NodeID> > init_values_type;
protected:
const init_values_type init_values;
const SymbolTable &symbol_table;
public:
InitOrEndValStatement(const init_values_type &init_values_arg,
const SymbolTable &symbol_table_arg);
protected:
void writeInitValues(ostream &output) const;
};
class InitValStatement : public InitOrEndValStatement
{
public:
InitValStatement(const init_values_type &init_values_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class EndValStatement : public InitOrEndValStatement
{
public:
EndValStatement(const init_values_type &init_values_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class HistValStatement : public Statement
{
public:
/*!
Contrary to Initval and Endval, we use a map, since it is impossible to reuse
a given initialization value in a second initialization inside the block.
*/
typedef map<pair<string, int>, NodeID> hist_values_type;
private:
const hist_values_type hist_values;
const SymbolTable &symbol_table;
public:
HistValStatement(const hist_values_type &hist_values_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class HomotopyStatement : public Statement
{
public:
/*!
Contrary to Initval and Endval, we use a map, since it is impossible to reuse
a given initialization value in a second initialization inside the block.
*/
typedef map<string,pair<NodeID,NodeID> > homotopy_values_type;
private:
const homotopy_values_type homotopy_values;
const SymbolTable &symbol_table;
public:
HomotopyStatement(const homotopy_values_type &homotopy_values_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
#endif

418
include/ParsingDriver.hh Normal file
View File

@ -0,0 +1,418 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _PARSING_DRIVER_HH
#define _PARSING_DRIVER_HH
#ifdef _MACRO_DRIVER_HH
# error Impossible to include both ParsingDriver.hh and MacroDriver.hh
#endif
#include <string>
#include <vector>
#include <istream>
#include "ModFile.hh"
#include "TmpSymbolTable.hh"
#include "DynareBison.hh"
#include "ComputingTasks.hh"
#include "Shocks.hh"
#include "SigmaeInitialization.hh"
#include "NumericalInitialization.hh"
#include "ModelTree.hh"
using namespace std;
// Declare DynareFlexLexer class
#ifndef __FLEX_LEXER_H
# define yyFlexLexer DynareFlexLexer
# include <FlexLexer.h>
# undef yyFlexLexer
#endif
//! The lexer class
/*! Actually it was necessary to subclass the DynareFlexLexer class generated by Flex,
since the prototype for DynareFlexLexer::yylex() was not convenient.
*/
class DynareFlex : public DynareFlexLexer
{
public:
DynareFlex(istream* in = 0, ostream* out = 0);
//! The main lexing function
Dynare::parser::token_type lex(Dynare::parser::semantic_type *yylval,
Dynare::parser::location_type *yylloc,
ParsingDriver &driver);
};
//! Drives the scanning and parsing of the .mod file, and constructs its abstract representation
/*! It is built along the guidelines given in Bison 2.3 manual. */
class ParsingDriver
{
private:
//! Checks that a given symbol exists, and stops with an error message if it doesn't
void check_symbol_existence(const string &name);
//! Helper to add a symbol declaration
void declare_symbol(string *name, Type type, string *tex_name);
//! Creates option "optim_opt" in OptionsList if it doesn't exist, else add a comma, and adds the option name
void optim_options_helper(const string &name);
//! Stores temporary symbol table
TmpSymbolTable *tmp_symbol_table;
//! The data tree in which to add expressions currently parsed
DataTree *data_tree;
//! The model tree in which to add expressions currently parsed
/*! It is only a dynamic cast of data_tree pointer, and is therefore null if data_tree is not a ModelTree instance */
ModelTree *model_tree;
//! Sets data_tree and model_tree pointers
void set_current_data_tree(DataTree *data_tree_arg);
//! Stores options lists
OptionsList options_list;
//! Temporary storage for trend elements
ObservationTrendsStatement::trend_elements_type trend_elements;
//! Temporary storage for filename list of ModelComparison
ModelComparisonStatement::filename_list_type filename_list;
//! Temporary storage for list of EstimationParams (from estimated_params* statements)
vector<EstimationParams> estim_params_list;
//! Temporary storage of variances from optim_weights
OptimWeightsStatement::var_weights_type var_weights;
//! Temporary storage of covariances from optim_weights
OptimWeightsStatement::covar_weights_type covar_weights;
//! Temporary storage of variances from calib_var
CalibVarStatement::calib_var_type calib_var;
//! Temporary storage of covariances from calib_var
CalibVarStatement::calib_covar_type calib_covar;
//! Temporary storage of autocorrelations from calib_var
CalibVarStatement::calib_ac_type calib_ac;
//! Temporary storage for deterministic shocks
ShocksStatement::det_shocks_type det_shocks;
//! Temporary storage for periods of deterministic shocks
vector<pair<int, int> > det_shocks_periods;
//! Temporary storage for values of deterministic shocks
vector<NodeID> det_shocks_values;
//! Temporary storage for variances of shocks
ShocksStatement::var_and_std_shocks_type var_shocks;
//! Temporary storage for standard errors of shocks
ShocksStatement::var_and_std_shocks_type std_shocks;
//! Temporary storage for covariances of shocks
ShocksStatement::covar_and_corr_shocks_type covar_shocks;
//! Temporary storage for correlations of shocks
ShocksStatement::covar_and_corr_shocks_type corr_shocks;
//! Temporary storage for Sigma_e rows
SigmaeStatement::row_type sigmae_row;
//! Temporary storage for Sigma_e matrix
SigmaeStatement::matrix_type sigmae_matrix;
//! Temporary storage for initval/endval blocks
InitOrEndValStatement::init_values_type init_values;
//! Temporary storage for histval blocks
HistValStatement::hist_values_type hist_values;
//! Temporary storage for homotopy_setup blocks
HomotopyStatement::homotopy_values_type homotopy_values;
//! Temporary storage for argument list of unknown function
vector<NodeID> unknown_function_args;
//! The mod file representation constructed by this ParsingDriver
ModFile *mod_file;
public:
//! Constructor
ParsingDriver();
//! Destructor
virtual ~ParsingDriver();
//! Starts parsing, and constructs the MOD file representation
/*! The returned pointer should be deleted after use */
ModFile *parse(istream &in);
//! Reference to the lexer
class DynareFlex *lexer;
//! Copy of parsing location, maintained by YYLLOC_DEFAULT macro in DynareBison.yy
Dynare::parser::location_type location;
//! Trace scanning ?
/*! If set to true before calling parse(), the flex scanner will dump a lot of debugging information. Defaults to false.
*/
bool trace_scanning;
//! Trace parsing ?
/*! If set to true before calling parse(), the bison parser will dump debugging information. Defaults to false. */
bool trace_parsing;
//! Estimation parameters
EstimationParams estim_params;
//! Error handler with explicit location
void error(const Dynare::parser::location_type &l, const string &m);
//! Error handler using saved location
void error(const string &m);
//! Warning handler using saved location
void warning(const string &m);
//! Check if a given symbol exists in the parsing context, and is not a mod file local variable
bool symbol_exists_and_is_not_modfile_local_variable(const char *s);
//! Sets mode of ModelTree class to use C output
void use_dll();
//! Sets mode of ModelTree class to block decompose the model and triggers the creation of the incidence matrix in a C context
void sparse_dll();
//! Sets mode of ModelTree class to block decompose the model and triggers the creation of the incidence matrix in Matlab context
void sparse();
//! Sets the compiler type used in conjunction with SPARCE_DLL
void init_compiler(int compiler_type);
//! Sets the FILENAME for the initial value in initval
void init_val_filename(string *filename);
//! Declares an endogenous variable
void declare_endogenous(string *name, string *tex_name = new string);
//! Declares an exogenous variable
void declare_exogenous(string *name, string *tex_name = new string);
//! Declares an exogenous deterministic variable
void declare_exogenous_det(string *name, string *tex_name = new string);
//! Declares a parameter
void declare_parameter(string *name, string *tex_name = new string);
//! Declares and initializes a local parameter
void declare_and_init_model_local_variable(string *name, NodeID rhs);
//! Adds a constant to DataTree
NodeID add_constant(string *constant);
//! Adds a model variable to ModelTree and VariableTable
NodeID add_model_variable(string *name);
//! Adds a model lagged variable to ModelTree and VariableTable
NodeID add_model_variable(string *name, string *olag);
//! Adds an Expression's variable
NodeID add_expression_variable(string *name);
//! Adds a "periods" statement
void periods(string *periods);
//! Adds a "cutoff" statement
void cutoff(string *cutoff);
//! Adds a weight of the "markowitz" criteria statement
void markowitz(string *markowitz);
//! Adds a "dsample" statement
void dsample(string *arg1);
//! Adds a "dsample" statement
void dsample(string *arg1, string *arg2);
//! Writes parameter intitialisation expression
void init_param(string *name, NodeID rhs);
//! Writes an initval block
void init_val(string *name, NodeID rhs);
//! Writes an histval block
void hist_val(string *name, string *lag, NodeID rhs);
//! Writes an homotopy_setup block
void homotopy_val(string *name, NodeID val1, NodeID val2);
//! Writes end of an initval block
void end_initval();
//! Writes end of an endval block
void end_endval();
//! Writes end of an histval block
void end_histval();
//! Writes end of an homotopy_setup block
void end_homotopy();
//! Begin a model block
void begin_model();
//! Writes a shocks statement
void end_shocks();
//! Writes a mshocks statement
void end_mshocks();
//! Adds a deterministic chock
void add_det_shock(string *var);
//! Adds a std error chock
void add_stderr_shock(string *var, NodeID value);
//! Adds a variance chock
void add_var_shock(string *var, NodeID value);
//! Adds a covariance chock
void add_covar_shock(string *var1, string *var2, NodeID value);
//! Adds a correlated chock
void add_correl_shock(string *var1, string *var2, NodeID value);
//! Adds a shock period range
void add_period(string *p1, string *p2);
//! Adds a shock period
void add_period(string *p1);
//! Adds a deterministic shock value
void add_value(NodeID value);
//! Adds a deterministic shock value
void add_value(string *p1);
//! Writes a Sigma_e block
void do_sigma_e();
//! Ends row of Sigma_e block
void end_of_row();
//! Adds a constant element to current row of Sigma_e
void add_to_row_const(string *s);
//! Adds an expression element to current row of Sigma_e
void add_to_row(NodeID v);
//! Write a steady command
void steady();
//! Sets an option to a numerical value
void option_num(const string &name_option, string *opt);
//! Sets an option to a numerical value
void option_num(const string &name_option, const string &opt);
//! Sets an option to a numerical value
void option_num(const string &name_option, string *opt1, string *opt2);
//! Sets an option to a string value
void option_str(const string &name_option, string *opt);
//! Sets an option to a string value
void option_str(const string &name_option, const string &opt);
//! Indicates that the model is linear
void linear();
//! Adds a variable to temp symbol table and sets its value
void add_tmp_var(string *tmp_var1, string *tmp_var2);
//! Adds a variable to temp symbol table
void add_tmp_var(string *tmp_var);
//! Writes a rplot() command
void rplot();
//! Writes a stock_simul command
void stoch_simul();
//! Determine whether to write simul command or simul_sparse command
void simulate();
//! Writes a simul_sparse command
void simul_sparse();
//! Writes a simul command
void simul();
//! Writes check command
void check();
//! Writes estimated params command
void estimated_params();
//! Writes estimated params init command
void estimated_params_init();
//! Writes estimated params bound command
void estimated_params_bounds();
//! Add a line in an estimated params block
void add_estimated_params_element();
//! Runs estimation process
void run_estimation();
//! Runs prior_analysis();
void run_prior_analysis();
//! Runs posterior_analysis();
void run_posterior_analysis();
//! Runs dynare_sensitivy()
void dynare_sensitivity();
//! Adds an optimization option (string value)
void optim_options_string(string *name, string *value);
//! Adds an optimization option (numeric value)
void optim_options_num(string *name, string *value);
//! Prints varops instructions
void set_varobs();
void set_trends();
void set_trend_element(string *arg1, NodeID arg2);
void set_unit_root_vars();
void optim_weights();
void set_optim_weights(string *name, NodeID value);
void set_optim_weights(string *name1, string *name2, NodeID value);
void set_osr_params();
void run_osr();
void run_calib_var();
void set_calib_var(string *name, string *weight, NodeID expression);
void set_calib_covar(string *name1, string *name2, string *weight, NodeID expression);
void set_calib_ac(string *name, string *ar, string *weight, NodeID expression);
void run_calib(int covar);
void run_dynasave(string *arg1, string *arg2 = new string);
void run_dynatype(string *arg1, string *arg2 = new string);
void add_mc_filename(string *filename, string *prior = new string("1"));
void run_model_comparison();
//! Begin a planner_objective statement
void begin_planner_objective();
//! End a planner objective statement
void end_planner_objective(NodeID expr);
//! ramsey policy statement
void ramsey_policy();
//! BVAR marginal density
void bvar_density(string *maxnlags);
//! BVAR forecast
void bvar_forecast(string *nlags);
//! Writes token "arg1=arg2" to model tree
NodeID add_model_equal(NodeID arg1, NodeID arg2);
//! Writes token "arg=0" to model tree
NodeID add_model_equal_with_zero_rhs(NodeID arg);
//! Writes token "arg1+arg2" to model tree
NodeID add_plus(NodeID arg1, NodeID arg2);
//! Writes token "arg1-arg2" to model tree
NodeID add_minus(NodeID arg1, NodeID arg2);
//! Writes token "-arg1" to model tree
NodeID add_uminus(NodeID arg1);
//! Writes token "arg1*arg2" to model tree
NodeID add_times(NodeID arg1, NodeID arg2);
//! Writes token "arg1/arg2" to model tree
NodeID add_divide(NodeID arg1, NodeID arg2);
//! Writes token "arg1<arg2" to model tree
NodeID add_less(NodeID arg1, NodeID arg2);
//! Writes token "arg1>arg2" to model treeNodeID
NodeID add_greater(NodeID arg1, NodeID arg2);
//! Writes token "arg1<=arg2" to model treeNodeID
NodeID add_less_equal(NodeID arg1, NodeID arg2);
//! Writes token "arg1>=arg2" to model treeNodeID
NodeID add_greater_equal(NodeID arg1, NodeID arg2);
//! Writes token "arg1==arg2" to model treeNodeIDNodeID
NodeID add_equal_equal(NodeID arg1, NodeID arg2);
//! Writes token "arg1!=arg2" to model treeNodeIDNodeID
NodeID add_different(NodeID arg1, NodeID arg2);
//! Writes token "arg1^arg2" to model tree
NodeID add_power(NodeID arg1, NodeID arg2);
//! Writes token "exp(arg1)" to model tree
NodeID add_exp(NodeID arg1);
//! Writes token "log(arg1)" to model tree
NodeID add_log(NodeID arg1);
//! Writes token "log10(arg1)" to model tree
NodeID add_log10(NodeID arg1);
//! Writes token "cos(arg1)" to model tree
NodeID add_cos(NodeID arg1);
//! Writes token "sin(arg1)" to model tree
NodeID add_sin(NodeID arg1);
//! Writes token "tan(arg1)" to model tree
NodeID add_tan(NodeID arg1);
//! Writes token "acos(arg1)" to model tree
NodeID add_acos(NodeID arg1);
//! Writes token "asin(arg1)" to model tree
NodeID add_asin(NodeID arg1);
//! Writes token "atan(arg1)" to model tree
NodeID add_atan(NodeID arg1);
//! Writes token "cosh(arg1)" to model tree
NodeID add_cosh(NodeID arg1);
//! Writes token "sinh(arg1)" to model tree
NodeID add_sinh(NodeID arg1);
//! Writes token "tanh(arg1)" to model tree
NodeID add_tanh(NodeID arg1);
//! Writes token "acosh(arg1)" to model tree
NodeID add_acosh(NodeID arg1);
//! Writes token "asin(arg1)" to model tree
NodeID add_asinh(NodeID arg1);
//! Writes token "atanh(arg1)" to model tree
NodeID add_atanh(NodeID arg1);
//! Writes token "sqrt(arg1)" to model tree
NodeID add_sqrt(NodeID arg1);
//! Writes token "max(arg1,arg2)" to model tree
NodeID add_max(NodeID arg1, NodeID arg2);
//! Writes token "min(arg1,arg2)" to model tree
NodeID add_min(NodeID arg1, NodeID arg2);
//! Writes token "normcdf(arg1,arg2,arg3)" to model tree
NodeID add_normcdf(NodeID arg1, NodeID arg2, NodeID arg3);
//! Adds an unknwon function argument
void add_unknown_function_arg(NodeID arg);
//! Adds an unknown function call node
NodeID add_unknown_function(string *function_name);
//! Adds a native statement
void add_native(const char *s);
//! Resets data_tree and model_tree pointers to default (i.e. mod_file->expressions_tree)
void reset_data_tree();
};
#endif // ! PARSING_DRIVER_HH

89
include/Shocks.hh Normal file
View File

@ -0,0 +1,89 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _SHOCKS_HH
#define _SHOCKS_HH
using namespace std;
#include <string>
#include <vector>
#include <map>
#include "Statement.hh"
#include "SymbolTable.hh"
#include "ExprNode.hh"
class AbstractShocksStatement : public Statement
{
public:
struct DetShockElement
{
int period1;
int period2;
NodeID value;
};
typedef map<string, vector<DetShockElement> > det_shocks_type;
typedef map<string, NodeID> var_and_std_shocks_type;
typedef map<pair<string, string>, NodeID> covar_and_corr_shocks_type;
protected:
//! Is this statement a "mshocks" statement ? (instead of a "shocks" statement)
const bool mshocks;
const det_shocks_type det_shocks;
const var_and_std_shocks_type var_shocks, std_shocks;
const covar_and_corr_shocks_type covar_shocks, corr_shocks;
const SymbolTable &symbol_table;
void writeDetShocks(ostream &output) const;
void writeVarAndStdShocks(ostream &output) const;
void writeCovarAndCorrShocks(ostream &output) const;
AbstractShocksStatement(bool mshocks_arg,
const det_shocks_type &det_shocks_arg,
const var_and_std_shocks_type &var_shocks_arg,
const var_and_std_shocks_type &std_shocks_arg,
const covar_and_corr_shocks_type &covar_shocks_arg,
const covar_and_corr_shocks_type &corr_shocks_arg,
const SymbolTable &symbol_table_arg);
};
class ShocksStatement : public AbstractShocksStatement
{
public:
ShocksStatement(const det_shocks_type &det_shocks_arg,
const var_and_std_shocks_type &var_shocks_arg,
const var_and_std_shocks_type &std_shocks_arg,
const covar_and_corr_shocks_type &covar_shocks_arg,
const covar_and_corr_shocks_type &corr_shocks_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class MShocksStatement : public AbstractShocksStatement
{
public:
MShocksStatement(const det_shocks_type &det_shocks_arg,
const var_and_std_shocks_type &var_shocks_arg,
const var_and_std_shocks_type &std_shocks_arg,
const covar_and_corr_shocks_type &covar_shocks_arg,
const covar_and_corr_shocks_type &corr_shocks_arg,
const SymbolTable &symbol_table_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
#endif

View File

@ -0,0 +1,65 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _SIGMAEINITIALIZATION_HH
#define _SIGMAEINITIALIZATION_HH
using namespace std;
#include <string>
#include <vector>
#include "ExprNode.hh"
#include "Statement.hh"
//! Stores a Sigma_e statement
class SigmaeStatement : public Statement
{
public:
//! Matrix form (lower or upper triangular) enum
enum matrix_form_type
{
eLower = 0, //!< Lower triangular matrix
eUpper = 1 //!< Upper triangular matrix
};
//! Type of a matrix row
typedef vector<NodeID> row_type;
//! Type of a complete matrix
typedef vector<row_type> matrix_type;
//! An exception indicating that a matrix is neither upper triangular nor lower triangular
class MatrixFormException
{
};
private:
//! The matrix
const matrix_type matrix;
//! Matrix form (lower or upper)
const matrix_form_type matrix_form;
//! Returns the type (upper or lower triangular) of a given matrix
/*! Throws an exception if it is neither upper triangular nor lower triangular */
static matrix_form_type determineMatrixForm(const matrix_type &matrix) throw (MatrixFormException);
public :
SigmaeStatement(const matrix_type &matrix_arg) throw (MatrixFormException);
virtual void writeOutput(ostream &output, const string &basename) const;
};
#endif

81
include/Statement.hh Normal file
View File

@ -0,0 +1,81 @@
/*
* Copyright (C) 2006-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _STATEMENT_HH
#define _STATEMENT_HH
using namespace std;
#include <ostream>
#include <string>
#include <map>
class ModFileStructure
{
public:
ModFileStructure();
//! Wheter check is present
bool check_present;
//! Whether a simul statement is present
bool simul_present;
//! Whether a stoch_simul, estimation, osr, ramsey_policy statement is present
bool stoch_simul_or_similar_present;
//! The value of the "order" option of stoch_simul, estimation, osr, ramsey_policy
/*! Defaults to 2 */
int order_option;
};
class Statement
{
public:
virtual ~Statement();
//! Do some internal check, and fill the ModFileStructure class
virtual void checkPass(ModFileStructure &mod_file_struct);
virtual void computingPass();
//! Write Matlab outout code
/*!
\param output is the output stream of the main matlab file
\param basename is the name of the modfile (without extension) which can be used to build auxiliary files
*/
virtual void writeOutput(ostream &output, const string &basename) const = 0;
};
class NativeStatement : public Statement
{
private:
const string native_statement;
public:
NativeStatement(const string &native_statement_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class OptionsList
{
public:
typedef map<string, string> num_options_type;
typedef map<string, pair<string, string> > paired_num_options_type;
typedef map<string, string> string_options_type;
num_options_type num_options;
paired_num_options_type paired_num_options;
string_options_type string_options;
void writeOutput(ostream &output) const;
void clear();
};
#endif // ! _STATEMENT_HH

108
include/SymbolGaussElim.hh Normal file
View File

@ -0,0 +1,108 @@
/*
* Copyright (C) 2007-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SYMBGAUSSELIM
#define SYMBGAUSSELIM
#include <iostream>
#include <fstream>
#include "Model_Graph.hh"
using namespace std;
#define TOL 1e-9
typedef struct t_table_y
{
int index,nb;
int *u_index, *y_index;
};
typedef struct t_table_u
{
t_table_u* pNext;
unsigned char type;
int index;
int op1,op2;
};
class SymbolicGaussElimination
{
public:
int y_kmin, y_kmax, nb_endo, Time, stacked_time, u_count, periods;
double* u1;
int *s_i1, *s_i2, *s_j2;
bool nstacked, save_direct;
int nb_loop_table;
int *loop_table_u_count, *loop_table_vertex_index;
#ifdef DIRECT_COMPUTE
int u_count_init;
double tol;
t_table_y *table_y;
int vertex_count;
t_table_u* table_u;
int nb_table_u;
t_table_u *get_table_u;
t_table_u* First_table_u;
#endif /**DIRECT_COMPUTE**/
int starting_vertex;
t_table_u *first_u_blck, *second_u_blck, *third_u_blck, *stop_table_u, *forth_u_blck;
int first_y_blck, second_y_blck, third_y_blck;
#ifdef SAVE
t_table_u *prologue_save_table_u, *first_save_table_u, *first_save_i_table_u, *middle_save_table_u, *middle_save_i_table_u, *last_save_table_u, *save_table_u, *save_i_table_u;
t_table_y *prologue_save_table_y, *first_save_table_y, *first_save_i_table_y, *middle_save_table_y, *middle_save_i_table_y, *last_save_table_y;
int nb_prologue_save_table_y, nb_first_save_table_y, nb_middle_save_table_y, nb_last_save_table_y;
int nb_prologue_save_table_u, nb_first_save_table_u, nb_middle_save_table_u, nb_last_save_table_u, middle_count_loop;
int pos_nb_first_save_table_u;
std::ofstream SaveCode;
bool file_open;
#endif /**SAVE**/
#ifdef SIMPLIFY
int* free_u_list;
int* free_u_list1;
int MAX_FREE_U_LIST;
int nb_free_u_list,nb_free_u_list1,max_nb_free_u_list1,max_nb_free_u_list;
bool simplification_allowed;
void print_free_u_list();
void set_free_u_list(int index);
int get_free_u_list(bool dynamic);
#endif /**SIMPLIFY**/
SymbolicGaussElimination();
void list_table_u(int pos);
void init_glb();
void write_to_file_table_y( t_table_y *save_table_y, t_table_y *save_i_table_y, int nb_save_table_y, int nb_save_i_table_y);
void write_to_file_table_u(t_table_u *save_table_u,t_table_u *save_i_table_u, int nb_save_table_u);
void write_to_file_table_u_b(t_table_u *save_table_u, t_table_u *last_table_u, int *nb_save_table_u, bool chk);
bool Check_Regularity(t_table_u *first_u_blck, t_table_u *second_u_blck, t_table_u *third_u_blck);
t_table_u* interpolation(t_model_graph* model_graph,t_table_y* table_y, int to_add, bool middle,int per);
bool Loop_Elimination(t_model_graph* model_graph);
bool Vertex_Elimination(t_model_graph* model_graph, int pos,bool* interpolate, int length_markowitz, bool dynamic);
void Gaussian_Elimination(t_model_graph* model_graph
#ifdef SAVE
, string file_name
#endif
, bool dynamic);
int SGE_all(int endo,int Time, List_IM *First_IM);
void SGE_compute(Model_Block *ModelBlock, int blck, bool dynamic, string file_name, int endo_nbr);
void file_is_open();
void file_is_open1();
};
//------------------------------------------------------------------------------
#endif

164
include/SymbolTable.hh Normal file
View File

@ -0,0 +1,164 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _SYMBOLTABLE_HH
#define _SYMBOLTABLE_HH
using namespace std;
#include <map>
#include <string>
#include <vector>
#include <ostream>
#include <iostream>
#include "CodeInterpreter.hh"
//! Stores the symbol table
/*!
A symbol is given by its name, and is internally represented by a pair (type, id).
There is a distinct sequence of ids for each type, so two symbol of different types can have the same id.
Also manages a TeX name for each symbol, which by default is an empty string.
*/
class SymbolTable
{
private:
//! A symbol is represented by a pair (type, id)
typedef pair<Type, int> symbol_type;
typedef map<string, symbol_type> symbol_table_type;
//! Maps strings to pairs (type,id)
symbol_table_type symbol_table;
typedef map<symbol_type, string> inv_symbol_table_type;
//! Maps pairs (type, id) to names
inv_symbol_table_type name_table;
//! Maps pairs (type, id) to TeX names
inv_symbol_table_type tex_name_table;
public:
SymbolTable();
//! Thrown when trying to access an unknown symbol (by name)
class UnknownSymbolNameException
{
public:
//! Symbol name
string name;
UnknownSymbolNameException(const string &name_arg) : name(name_arg) {}
};
//! Thrown when trying to access an unknown symbol (by type+id pair)
class UnknownSymbolIDException
{
public:
//! Symbol type
Type type;
//! Symbol ID
int id;
UnknownSymbolIDException(Type type_arg, int id_arg) : type(type_arg), id(id_arg) {}
};
//! Thrown when trying to declare a symbol twice
class AlreadyDeclaredException
{
public:
//! Symbol name
string name;
//! Was the previous declaration done with the same symbol type ?
bool same_type;
AlreadyDeclaredException(const string &name_arg, bool same_type_arg) : name(name_arg), same_type(same_type_arg) {}
};
//! Number of declared endogenous variables
int endo_nbr;
//! Number of declared exogenous variables
int exo_nbr;
//! Number of declared deterministic exogenous variables
int exo_det_nbr;
//! Number of declared recursive variables
int recur_nbr;
//! Number of declared parameters
int parameter_nbr;
//! Number of model local variables
int model_local_variable_nbr;
//! Number of modfile local variables
int modfile_local_variable_nbr;
//! Number of unknown functions
int unknown_function_nbr;
//! Add a symbol
void addSymbol(const string &name, Type type, const string &tex_name = "") throw (AlreadyDeclaredException);
//! Tests if symbol already exists
inline bool exists(const string &name) const;
//! Get symbol name by type and ID
inline string getNameByID(Type type, int id) const throw (UnknownSymbolIDException);
//! Get TeX name by type and ID
inline string getTeXNameByID(Type type, int id) const throw (UnknownSymbolIDException);
//! Get type by name
inline Type getType(const string &name) const throw (UnknownSymbolNameException);
//! Get ID by name
inline int getID(const string &name) const throw (UnknownSymbolNameException);
//! Write output of this class
void writeOutput(ostream &output) const;
};
inline bool
SymbolTable::exists(const string &name) const
{
symbol_table_type::const_iterator iter = symbol_table.find(name);
return (iter != symbol_table.end());
}
inline string
SymbolTable::getNameByID(Type type, int id) const throw (UnknownSymbolIDException)
{
inv_symbol_table_type::const_iterator iter = name_table.find(make_pair(type, id));
if (iter != name_table.end())
return iter->second;
else
throw UnknownSymbolIDException(type, id);
}
inline string
SymbolTable::getTeXNameByID(Type type, int id) const throw (UnknownSymbolIDException)
{
inv_symbol_table_type::const_iterator iter = tex_name_table.find(make_pair(type, id));
if (iter != tex_name_table.end())
return iter->second;
else
throw UnknownSymbolIDException(type, id);
}
inline Type
SymbolTable::getType(const string &name) const throw (UnknownSymbolNameException)
{
symbol_table_type::const_iterator iter = symbol_table.find(name);
if (iter != symbol_table.end())
return iter->second.first;
else
throw UnknownSymbolNameException(name);
}
inline int
SymbolTable::getID(const string &name) const throw (UnknownSymbolNameException)
{
symbol_table_type::const_iterator iter = symbol_table.find(name);
if (iter != symbol_table.end())
return iter->second.second;
else
throw UnknownSymbolNameException(name);
}
#endif

57
include/TmpSymbolTable.hh Normal file
View File

@ -0,0 +1,57 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _TMPSYMBOLTABLE_HH
#define _TMPSYMBOLTABLE_HH
#include <string>
#include <vector>
#include <ostream>
#include "SymbolTable.hh"
/*!
\class TmpSymbolTable
\brief Defines temparary symbol table used with computing tasks
*/
class TmpSymbolTable
{
private :
/*! list of string TempSymbolTable */
std::vector<std::string> tmpsymboltable;
/*! List of symbol Values */
std::vector<std::string> nameTable;
//! A reference to enclosing symbol table
const SymbolTable &symbol_table;
public :
/*! Constrcutor */
TmpSymbolTable(const SymbolTable &symbol_table_arg);
/*! Destructor*/
~TmpSymbolTable();
/*! Adds a temp symbol */
void AddTempSymbol(const std::string &symbol);
/*! Adds a temp symbol and its value */
void AddTempSymbol(const std::string &symbol1, const std::string &symbol2);
/*! Write TempSymbolTable to output string */
void writeOutput(const std::string &varname, std::ostream &output) const;
//! Clears all content
void clear();
};
//------------------------------------------------------------------------------
#endif

189
include/VariableTable.hh Normal file
View File

@ -0,0 +1,189 @@
/*
* Copyright (C) 2003-2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _VARIABLETABLE_HH
#define _VARIABLETABLE_HH
using namespace std;
#include <map>
#include <vector>
#include "SymbolTable.hh"
//! Used to keep track of variables in the sense of the models, i.e. pairs (symbol, lead/lag)
/*! Warning: some methods access variables through the tuple (type, symbol_id, lag), but internally the class uses a lexicographic order over (type, lag, symbol_id) */
class VariableTable
{
private:
//! A reference to the symbol table
const SymbolTable &symbol_table;
//! A variable is a tuple (type, lag, symbol_id)
/*! Warning: don't change the order of elements in the tuple, since this determines the lexicographic ordering in sort() */
typedef pair<pair<Type, int>, int> var_key_type;
typedef map<var_key_type, int> variable_table_type;
//! Maps a tuple (type, lag, symbol_id) to a variable ID
variable_table_type variable_table;
typedef map<int, var_key_type> inv_variable_table_type;
//! Maps a variable ID to a tuple (type, lag, symbol_id)
inv_variable_table_type inv_variable_table;
//! Contains the sorted IDs (indexed by variable IDs)
vector<int> sorted_ids_table;
public:
VariableTable(const SymbolTable &symbol_table_arg);
//! Number of dynamic endogenous variables inside the model block
int var_endo_nbr;
//! Number of dynamic exogenous variables inside the model block
int var_exo_nbr;
//! Number of dynamic deterministic exogenous variables inside the model block
int var_exo_det_nbr;
//! Maximum lag over all types of variables (positive value)
int max_lag;
//! Maximum lead over all types of variables
int max_lead;
//! Maximum lag over endogenous variables (positive value)
int max_endo_lag;
//! Maximum lead over endogenous variables
int max_endo_lead;
//! Maximum lag over exogenous variables (positive value)
int max_exo_lag;
//! Maximum lead over exogenous variables
int max_exo_lead;
//! Maximum lag over deterministic exogenous variables (positive value)
int max_exo_det_lag;
//! Maximum lead over deterministic exogenous variables
int max_exo_det_lead;
//! Maximum lag over recursive variables (positive value)
int max_recur_lag;
//! Maximum lead over recursive variables
int max_recur_lead;
//! Thrown when trying to access an unknown variable by (type, symb_id, lag)
class UnknownVariableKeyException
{
public:
Type type;
int symb_id, lag;
UnknownVariableKeyException(Type type_arg, int symb_id_arg, int lag_arg) : type(type_arg), symb_id(symb_id_arg), lag(lag_arg) {}
};
//! Thrown when trying to access an unknown variable by var_id
class UnknownVariableIDException
{
public:
//! Variable ID
int id;
UnknownVariableIDException(int id_arg) : id(id_arg) {}
};
//! Thrown when getSortID() called before sort()
class NotYetSortedException
{
};
//! Thrown when sort() or addVariable() called after sort()
class AlreadySortedException
{
};
//! Adds a variable in the table, and returns its (newly allocated) variable ID
/*! Also works if the variable already exists */
int addVariable(Type type, int symb_id, int lag) throw (AlreadySortedException);
//! Return variable ID
inline int getID(Type type, int symb_id, int lag) const throw (UnknownVariableKeyException);
//! Return lag of variable
inline int getLag(int var_id) const throw (UnknownVariableIDException);
//! Return symbol ID of variable
inline int getSymbolID(int var_id) const throw (UnknownVariableIDException);
//! Get variable type
inline Type getType(int var_id) const throw (UnknownVariableIDException);
//! Get number of variables
inline int size() const;
//! Get variable ID of sorted variable table
/*! In practice, only used for endogenous variables */
inline int getSortID(int var_id) const throw (NotYetSortedException, UnknownVariableIDException);
//! Sorts variable table
/*! The order used is a lexicographic order over the tuple (type, lag, symbol_id) */
void sort() throw (AlreadySortedException);
//! Get the number of dynamic variables
inline int get_dyn_var_nbr() const;
};
inline int
VariableTable::getSortID(int var_id) const throw (NotYetSortedException, UnknownVariableIDException)
{
if (sorted_ids_table.size() == 0)
throw NotYetSortedException();
if (var_id < 0 || var_id >= size())
throw UnknownVariableIDException(var_id);
return sorted_ids_table[var_id];
}
inline int
VariableTable::getID(Type type, int symb_id, int lag) const throw (UnknownVariableKeyException)
{
variable_table_type::const_iterator it = variable_table.find(make_pair(make_pair(type, lag), symb_id));
if (it == variable_table.end())
throw UnknownVariableKeyException(type, symb_id, lag);
else
return it->second;
}
inline Type
VariableTable::getType(int var_id) const throw (UnknownVariableIDException)
{
inv_variable_table_type::const_iterator it = inv_variable_table.find(var_id);
if (it != inv_variable_table.end())
return it->second.first.first;
else
throw UnknownVariableIDException(var_id);
}
inline int
VariableTable::getSymbolID(int var_id) const throw (UnknownVariableIDException)
{
inv_variable_table_type::const_iterator it = inv_variable_table.find(var_id);
if (it != inv_variable_table.end())
return it->second.second;
else
throw UnknownVariableIDException(var_id);
}
inline int
VariableTable::getLag(int var_id) const throw (UnknownVariableIDException)
{
inv_variable_table_type::const_iterator it = inv_variable_table.find(var_id);
if (it != inv_variable_table.end())
return it->second.first.second;
else
throw UnknownVariableIDException(var_id);
}
inline int
VariableTable::size() const
{
return variable_table.size();
}
inline int
VariableTable::get_dyn_var_nbr() const
{
return var_endo_nbr + symbol_table.exo_nbr + symbol_table.exo_det_nbr;
}
#endif

85
macro/MacroBison.yy Normal file
View File

@ -0,0 +1,85 @@
/*
* Copyright (C) 2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
%skeleton "lalr1.cc"
%require "2.3"
%defines
%{
using namespace std;
class MacroDriver;
%}
%name-prefix="Macro"
%parse-param { MacroDriver &driver }
%parse-param { ostream &out }
%lex-param { MacroDriver &driver }
%locations
%initial-action
{
// Initialize the location filenames
@$.begin.filename = @$.end.filename = &driver.file;
// Output first @line statement
out << "@line \"" << driver.file << "\" 1" << endl;
};
%debug
%error-verbose
%union
{
string *string_val;
int int_val;
};
%{
#include "MacroDriver.hh"
/* this "connects" the bison parser in the driver to the flex scanner class
* object. it defines the yylex() function call to pull the next token from the
* current lexer object of the driver context. */
#undef yylex
#define yylex driver.lexer->lex
%}
%token <int_val> INT_NUMBER
%token <string_val> NAME
%%
%start statement_list_or_nothing;
statement_list_or_nothing : /* empty */;
%%
void
Macro::parser::error(const Macro::parser::location_type &l,
const string &m)
{
driver.error(l, m);
}
/*
Local variables:
mode: C++
End:
*/

54
macro/MacroDriver.cc Normal file
View File

@ -0,0 +1,54 @@
/*
* Copyright (C) 2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <fstream>
#include "MacroDriver.hh"
MacroDriver::MacroDriver() : trace_scanning(false), trace_parsing(false)
{
}
MacroDriver::~MacroDriver()
{
}
void
MacroDriver::parse(const string &f, ostream &out)
{
file = f;
ifstream in(f.c_str());
lexer = new MacroFlex(&in, &out);
lexer->set_debug(trace_scanning);
Macro::parser parser(*this, out);
parser.parse();
delete lexer;
}
void
MacroDriver::error(const Macro::parser::location_type &l, const string &m)
{
cerr << "ERROR: " << l << ": " << m << endl;
exit(-1);
}

100
macro/MacroDriver.hh Normal file
View File

@ -0,0 +1,100 @@
/*
* Copyright (C) 2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _MACRO_DRIVER_HH
#define _MACRO_DRIVER_HH
#ifdef _PARSING_DRIVER_HH
# error Impossible to include both ParsingDriver.hh and MacroDriver.hh
#endif
#include <string>
#include <iostream>
#include <stack>
#include "MacroBison.hh"
using namespace std;
// Declare MacroFlexLexer class
#ifndef __FLEX_LEXER_H
# define yyFlexLexer MacroFlexLexer
# include <FlexLexer.h>
# undef yyFlexLexer
#endif
//! The lexer class
/*! Actually it was necessary to subclass the MacroFlexLexer class generated by Flex,
since the prototype for MacroFlexLexer::yylex() was not convenient.
*/
class MacroFlex : public MacroFlexLexer
{
private:
//! The stack of scanner states
/*! We could have used instead yypush_buffer_state() and yypop_buffer_state(),
but those functions do not exist in Flex 2.5.4 */
stack<struct yy_buffer_state *> state_stack;
public:
MacroFlex(istream* in = 0, ostream* out = 0);
//! The main lexing function
Macro::parser::token_type lex(Macro::parser::semantic_type *yylval,
Macro::parser::location_type *yylloc,
MacroDriver &driver);
};
//! Implements the macro expansion using a Flex scanner and a Bison parser
class MacroDriver
{
public:
//! Constructor
MacroDriver();
//! Destructor
virtual ~MacroDriver();
//! Starts parsing a file, returns output in out
void parse(const string &f, ostream &out);
//! Pointer to keep track of the input file stream currently scanned
ifstream *ifs;
//! Stack of locations used for (possibly nested) includes
stack<Macro::parser::location_type> loc_stack;
//! Name of main file being parsed
string file;
//! Reference to the lexer
class MacroFlex *lexer;
//! Trace scanning ?
/*! If set to true before calling parse(), the flex scanner will dump a lot of debugging information. Defaults to false.
*/
bool trace_scanning;
//! Trace parsing ?
/*! If set to true before calling parse(), the bison parser will dump debugging information. Defaults to false. */
bool trace_parsing;
//! Error handler
void error(const Macro::parser::location_type &l, const string &m);
};
#endif // ! MACRO_DRIVER_HH

149
macro/MacroFlex.ll Normal file
View File

@ -0,0 +1,149 @@
/*
* Copyright (C) 2008 Dynare Team
*
* This file is part of Dynare.
*
* Dynare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dynare is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Dynare. If not, see <http://www.gnu.org/licenses/>.
*/
%{
using namespace std;
#include <fstream>
#include "MacroDriver.hh"
#include "MacroBison.hh"
// Announce to Flex the prototype we want for lexing function
#define YY_DECL \
Macro::parser::token_type \
MacroFlex::lex(Macro::parser::semantic_type *yylval, \
Macro::parser::location_type *yylloc, \
MacroDriver &driver)
// Shortcut to access tokens defined by Bison
typedef Macro::parser::token token;
/* By default yylex returns int, we use token_type.
Unfortunately yyterminate by default returns 0, which is
not of token_type. */
#define yyterminate() return Macro::parser::token_type (0);
%}
%option c++
%option prefix="Macro"
%option case-insensitive noyywrap nounput batch debug never-interactive
%x INCLUDE
%x END_INCLUDE
%{
// Increments location counter for every token read
#define YY_USER_ACTION yylloc->columns(yyleng);
%}
%%
/* Code put at the beginning of yylex() */
%{
// Reset location before reading token
yylloc->step();
%}
/* Ignore @line declarations, replace them by a blank line */
<INITIAL>^@line[^\n]*\n { yylloc->lines(1); yylloc->step(); *yyout << endl; }
<INITIAL>^@include[ \t]+\" BEGIN(INCLUDE);
<INCLUDE>[^\"\n]* {
driver.ifs = new ifstream(yytext);
if (driver.ifs->fail())
driver.error(*yylloc, "Could not open " + string(yytext));
// Save old location
yylloc->step();
driver.loc_stack.push(*yylloc);
// Reset location
yylloc->begin.filename = yylloc->end.filename = new string(yytext);
yylloc->begin.line = yylloc->end.line = 1;
yylloc->begin.column = yylloc->end.column = 0;
// Display @line
*yyout << "@line \"" << *yylloc->begin.filename << "\" 1" << endl;
// Switch to new buffer
/* We don't use yypush_buffer_state(), since it doesn't exist in
Flex 2.5.4 (see Flex 2.5.33 info file - section 11 - for code
example with yypush_buffer_state()) */
state_stack.push(YY_CURRENT_BUFFER);
yy_switch_to_buffer(yy_create_buffer(driver.ifs, YY_BUF_SIZE));
BEGIN(INITIAL);
}
<END_INCLUDE>\"[^\n]*\n {
yylloc->lines(1);
yylloc->step();
*yyout << "@line \"" << *yylloc->begin.filename << "\" "
<< yylloc->begin.line << endl;
BEGIN(INITIAL);
}
<<EOF>> {
/* We don't use yypop_buffer_state(), since it doesn't exist in
Flex 2.5.4 (see Flex 2.5.33 info file - section 11 - for code
example with yypop_buffer_state()) */
// Quit lexer if end of main file
if (state_stack.empty())
{
yyterminate();
}
// Else restore old flex buffer
yy_delete_buffer(YY_CURRENT_BUFFER);
yy_switch_to_buffer(state_stack.top());
state_stack.pop();
// And restore old location
delete yylloc->begin.filename;
*yylloc = driver.loc_stack.top();
driver.loc_stack.pop();
BEGIN(END_INCLUDE);
}
<INITIAL>[\n]+ { yylloc->lines(yyleng); yylloc->step(); ECHO; }
<INITIAL>. { yylloc->step(); ECHO; }
<*>. { driver.error(*yylloc, "Macro lexer error: '" + string(yytext) + "'"); }
%%
MacroFlex::MacroFlex(istream* in, ostream* out)
: MacroFlexLexer(in, out)
{
}
/* This implementation of MacroFlexLexer::yylex() is required to fill the
* vtable of the class MacroFlexLexer. We define the scanner's main yylex
* function via YY_DECL to reside in the MacroFlex class instead. */
#ifdef yylex
# undef yylex
#endif
int
MacroFlexLexer::yylex()
{
cerr << "MacroFlexLexer::yylex() has been called, that should never happen!" << endl;
exit(-1);
}
/*
Local variables:
mode: C++
End:
*/

27
macro/Makefile Normal file
View File

@ -0,0 +1,27 @@
include ../Makefile.include
OBJ = MacroFlex.o MacroBison.o MacroDriver.o
libmacro.a: $(OBJ)
ar crs libmacro.a $(OBJ)
-include $(OBJ:.o=.P)
MacroFlex.cc: MacroFlex.ll MacroBison.hh MacroDriver.hh
flex -oMacroFlex.cc MacroFlex.ll
MacroBison.cc MacroBison.hh: MacroBison.yy MacroDriver.hh
bison --verbose -o MacroBison.cc MacroBison.yy
clean:
rm -f *.o *.P *~ \
MacroFlex.cc \
MacroBison.output \
MacroBison.cc \
MacroBison.hh \
location.hh \
stack.hh \
position.hh \
libmacro.a
.PHONY: clean