v4 parser: merged Fehrat's changes

git-svn-id: https://www.dynare.org/svn/dynare/dynare_v4@1190 ac1d8469-bf42-47a9-8791-bf33cf982152
time-shift
sebastien 2007-02-21 23:28:16 +00:00
parent 4cf7281291
commit feec20209d
31 changed files with 9375 additions and 2023 deletions

File diff suppressed because it is too large Load Diff

View File

@ -60,6 +60,33 @@ SimulStatement::writeOutput(ostream &output, const string &basename) const
output << "simul(oo_.dr);\n"; output << "simul(oo_.dr);\n";
} }
SimulSparseStatement::SimulSparseStatement(const OptionsList &options_list_arg) :
options_list(options_list_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\n";
output << " make_y_;\n";
output << " make_ex_;\n";
output << "end\n";
output << "disp('compiling...');\n";
if (compiler == 0)
output << "mex " << filename << "_dynamic.c;\n";
else
output << "mex " << filename << "_dynamic.cc;\n";
output << "oo_.endo_simul=" << filename << "_dynamic;\n";
}
StochSimulStatement::StochSimulStatement(const TmpSymbolTable &tmp_symbol_table_arg, StochSimulStatement::StochSimulStatement(const TmpSymbolTable &tmp_symbol_table_arg,
const OptionsList &options_list_arg) : const OptionsList &options_list_arg) :
tmp_symbol_table(tmp_symbol_table_arg), tmp_symbol_table(tmp_symbol_table_arg),
@ -205,6 +232,16 @@ PeriodsStatement::writeOutput(ostream &output, const string &basename) const
output << "options_.simul = 1;" << endl; output << "options_.simul = 1;" << endl;
} }
CutoffStatement::CutoffStatement(int cutoff_arg) : cutoff(cutoff_arg)
{
}
void
CutoffStatement::writeOutput(ostream &output, const string &basename) const
{
output << "options_.cutoff = " << cutoff << ";" << endl;
}
DsampleStatement::DsampleStatement(int val1_arg) : val1(val1_arg), val2(-1) DsampleStatement::DsampleStatement(int val1_arg) : val1(val1_arg), val2(-1)
{ {
} }

View File

@ -5,8 +5,10 @@
DataTree::DataTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg) : DataTree::DataTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg) :
symbol_table(symbol_table_arg), symbol_table(symbol_table_arg),
num_constants(num_constants_arg), num_constants(num_constants_arg),
node_counter(0),
variable_table(symbol_table_arg), variable_table(symbol_table_arg),
offset(1) offset(1),
compiler(LCC_COMPILE)
{ {
Zero = AddNumConstant("0.0"); Zero = AddNumConstant("0.0");
One = AddNumConstant("1.0"); One = AddNumConstant("1.0");

File diff suppressed because it is too large Load Diff

View File

@ -40,19 +40,19 @@ typedef pair<int, Type> ExpObj;
%token AR AUTOCORR %token AR AUTOCORR
%token BAYESIAN_IRF BETA_PDF %token BAYESIAN_IRF BETA_PDF
%token CALIB CALIB_VAR CHECK CONF_SIG CONSTANT CORR COVAR %token CALIB CALIB_VAR CHECK CONF_SIG CONSTANT CORR COVAR CUTOFF
%token DATAFILE DR_ALGO DROP DSAMPLE DYNASAVE DYNATYPE %token DATAFILE DR_ALGO DROP DSAMPLE DYNASAVE DYNATYPE
%token END ENDVAL EQUAL ESTIMATION ESTIMATED_PARAMS ESTIMATED_PARAMS_BOUNDS ESTIMATED_PARAMS_INIT %token END ENDVAL EQUAL ESTIMATION ESTIMATED_PARAMS ESTIMATED_PARAMS_BOUNDS ESTIMATED_PARAMS_INIT
%token FILTER_STEP_AHEAD FILTERED_VARS FIRST_OBS %token FILENAME FILTER_STEP_AHEAD FILTERED_VARS FIRST_OBS
%token <string_val> FLOAT_NUMBER %token <string_val> FLOAT_NUMBER
%token FORECAST %token FORECAST
%token GAMMA_PDF GRAPH %token GAMMA_PDF GCC_COMPILER GRAPH
%token HISTVAL HP_FILTER HP_NGRID %token HISTVAL HP_FILTER HP_NGRID
%token INITVAL %token INITVAL
%token <string_val> INT_NUMBER %token <string_val> INT_NUMBER
%token INV_GAMMA_PDF IRF %token INV_GAMMA_PDF IRF
%token KALMAN_ALGO KALMAN_TOL %token KALMAN_ALGO KALMAN_TOL
%token LAPLACE LIK_ALGO LIK_INIT LINEAR LOAD_MH_FILE LOGLINEAR %token LAPLACE LCC_COMPILER LIK_ALGO LIK_INIT LINEAR LOAD_MH_FILE LOGLINEAR
%token MH_DROP MH_INIT_SCALE MH_JSCALE MH_MODE MH_NBLOCKS MH_REPLIC MH_RECOVER %token MH_DROP MH_INIT_SCALE MH_JSCALE MH_MODE MH_NBLOCKS MH_REPLIC MH_RECOVER
%token MODE_CHECK MODE_COMPUTE MODE_FILE MODEL MODEL_COMPARISON MSHOCKS %token MODE_CHECK MODE_COMPUTE MODE_FILE MODEL MODEL_COMPARISON MSHOCKS
%token MODEL_COMPARISON_APPROXIMATION MODIFIEDHARMONICMEAN MOMENTS_VARENDO %token MODEL_COMPARISON_APPROXIMATION MODIFIEDHARMONICMEAN MOMENTS_VARENDO
@ -62,7 +62,7 @@ typedef pair<int, Type> ExpObj;
%token PARAMETERS PERIODS PLANNER_OBJECTIVE PREFILTER PRESAMPLE PRINT PRIOR_TRUNC PRIOR_ANALYSIS POSTERIOR_ANALYSIS %token PARAMETERS PERIODS PLANNER_OBJECTIVE PREFILTER PRESAMPLE PRINT PRIOR_TRUNC PRIOR_ANALYSIS POSTERIOR_ANALYSIS
%token QZ_CRITERIUM %token QZ_CRITERIUM
%token RELATIVE_IRF REPLIC RPLOT %token RELATIVE_IRF REPLIC RPLOT
%token SHOCKS SIGMA_E SIMUL SIMUL_ALGO SIMUL_SEED SMOOTHER SOLVE_ALGO STDERR STEADY STOCH_SIMUL %token SHOCKS SIGMA_E SIMUL SIMUL_ALGO SIMUL_SEED SMOOTHER SOLVE_ALGO SPARSE_DLL STDERR STEADY STOCH_SIMUL
%token TEX RAMSEY_POLICY PLANNER_DISCOUNT %token TEX RAMSEY_POLICY PLANNER_DISCOUNT
%token <string_val> TEX_NAME %token <string_val> TEX_NAME
%token UNIFORM_PDF UNIT_ROOT_VARS USE_DLL %token UNIFORM_PDF UNIT_ROOT_VARS USE_DLL
@ -93,6 +93,7 @@ typedef pair<int, Type> ExpObj;
statement statement
: declaration : declaration
| periods | periods
| cutoff
| model | model
| initval | initval
| endval | endval
@ -232,6 +233,16 @@ typedef pair<int, Type> ExpObj;
} }
; ;
cutoff
: CUTOFF FLOAT_NUMBER ';'
{
driver.cutoff($2);
}
| CUTOFF EQUAL FLOAT_NUMBER ';'
{
driver.cutoff($3);
}
;
init_param init_param
: NAME EQUAL expression ';' : NAME EQUAL expression ';'
@ -296,7 +307,13 @@ typedef pair<int, Type> ExpObj;
initval initval
: INITVAL ';' initval_list END : INITVAL ';' initval_list END
{driver.end_initval();} {driver.end_initval();}
| INITVAL '(' initval_option ')' ';' initval_list END
{driver.end_initval();}
; ;
initval_option
: FILENAME EQUAL NAME {driver.init_val_filename($3);}
;
endval endval
: ENDVAL ';' initval_list END : ENDVAL ';' initval_list END
@ -327,6 +344,16 @@ typedef pair<int, Type> ExpObj;
: NAME '(' signed_integer ')' EQUAL expression ';' : NAME '(' signed_integer ')' EQUAL expression ';'
{driver.hist_val($1, $3, $6);} {driver.hist_val($1, $3, $6);}
; ;
model_sparse_options_list : model_sparse_options_list COMMA model_sparse_options
| model_sparse_options
;
model_sparse_options :
LCC_COMPILER { driver.init_compiler(0); }
| GCC_COMPILER { driver.init_compiler(1); }
| o_cutoff
;
model model
: MODEL ';' { driver.begin_model(); } equation_list END : MODEL ';' { driver.begin_model(); } equation_list END
@ -334,6 +361,10 @@ typedef pair<int, Type> ExpObj;
equation_list END equation_list END
| MODEL '(' USE_DLL ')' ';' { driver.begin_model(); driver.use_dll(); } | MODEL '(' USE_DLL ')' ';' { driver.begin_model(); driver.use_dll(); }
equation_list END equation_list END
| MODEL '(' SPARSE_DLL COMMA model_sparse_options_list ')' { driver.sparse_dll(); driver.begin_model(); } ';'
equation_list END
| MODEL '(' SPARSE_DLL ')' { driver.sparse_dll(); driver.begin_model(); } ';'
equation_list END
; ;
equation_list equation_list
@ -529,9 +560,9 @@ typedef pair<int, Type> ExpObj;
simul simul
: SIMUL ';' : SIMUL ';'
{driver.simul();} {driver.simulate();}
| SIMUL '(' simul_options_list ')' ';' | SIMUL '(' simul_options_list ')' ';'
{driver.simul();} {driver.simulate();}
; ;
simul_options_list: simul_options_list COMMA simul_options simul_options_list: simul_options_list COMMA simul_options
@ -572,6 +603,7 @@ typedef pair<int, Type> ExpObj;
| o_hp_filter | o_hp_filter
| o_hp_ngrid | o_hp_ngrid
| o_periods | o_periods
| o_cutoff
| o_simul | o_simul
| o_simul_seed | o_simul_seed
| o_qz_criterium | o_qz_criterium
@ -1091,6 +1123,7 @@ typedef pair<int, Type> ExpObj;
o_hp_filter: HP_FILTER EQUAL INT_NUMBER {driver.option_num("hp_filter", $3);}; o_hp_filter: HP_FILTER EQUAL INT_NUMBER {driver.option_num("hp_filter", $3);};
o_hp_ngrid: HP_NGRID EQUAL INT_NUMBER {driver.option_num("hp_ngrid", $3);}; o_hp_ngrid: HP_NGRID EQUAL INT_NUMBER {driver.option_num("hp_ngrid", $3);};
o_periods: PERIODS EQUAL INT_NUMBER {driver.option_num("periods", $3); driver.option_num("simul", "1");}; o_periods: PERIODS EQUAL INT_NUMBER {driver.option_num("periods", $3); driver.option_num("simul", "1");};
o_cutoff: CUTOFF EQUAL FLOAT_NUMBER {driver.option_num("cutoff", $3);}
o_simul: SIMUL {driver.option_num("simul", "1");}; o_simul: SIMUL {driver.option_num("simul", "1");};
o_simul_seed: SIMUL_SEED EQUAL INT_NUMBER { driver.option_num("simul_seed", $3)}; o_simul_seed: SIMUL_SEED EQUAL INT_NUMBER { driver.option_num("simul_seed", $3)};
o_qz_criterium: QZ_CRITERIUM EQUAL INT_NUMBER { driver.option_num("qz_criterium", $3)} o_qz_criterium: QZ_CRITERIUM EQUAL INT_NUMBER { driver.option_num("qz_criterium", $3)}

View File

@ -57,6 +57,7 @@ int sigma_e = 0;
<INITIAL>varexo_det {BEGIN DYNARE_STATEMENT; return token::VAREXO_DET;} <INITIAL>varexo_det {BEGIN DYNARE_STATEMENT; return token::VAREXO_DET;}
<INITIAL>parameters {BEGIN DYNARE_STATEMENT; return token::PARAMETERS;} <INITIAL>parameters {BEGIN DYNARE_STATEMENT; return token::PARAMETERS;}
<INITIAL>periods {BEGIN DYNARE_STATEMENT; return token::PERIODS;} <INITIAL>periods {BEGIN DYNARE_STATEMENT; return token::PERIODS;}
<INITIAL>cutoff {BEGIN DYNARE_STATEMENT; return token::CUTOFF;}
<INITIAL>estimation {BEGIN DYNARE_STATEMENT; return token::ESTIMATION;} <INITIAL>estimation {BEGIN DYNARE_STATEMENT; return token::ESTIMATION;}
<INITIAL>prior_analysis {BEGIN DYNARE_STATEMENT; return token::PRIOR_ANALYSIS;} <INITIAL>prior_analysis {BEGIN DYNARE_STATEMENT; return token::PRIOR_ANALYSIS;}
<INITIAL>posterior_analysis {BEGIN DYNARE_STATEMENT; return token::POSTERIOR_ANALYSIS;} <INITIAL>posterior_analysis {BEGIN DYNARE_STATEMENT; return token::POSTERIOR_ANALYSIS;}
@ -148,6 +149,7 @@ int sigma_e = 0;
<DYNARE_STATEMENT>nocorr {return token::NOCORR;} <DYNARE_STATEMENT>nocorr {return token::NOCORR;}
<DYNARE_STATEMENT>optim {return token::OPTIM;} <DYNARE_STATEMENT>optim {return token::OPTIM;}
<DYNARE_STATEMENT>periods {return token::PERIODS;} <DYNARE_STATEMENT>periods {return token::PERIODS;}
<DYNARE_STATEMENT>cutoff {return token::CUTOFF;}
<DYNARE_STATEMENT>model_comparison_approximation {return token::MODEL_COMPARISON;} <DYNARE_STATEMENT>model_comparison_approximation {return token::MODEL_COMPARISON;}
<DYNARE_STATEMENT>laplace {return token::LAPLACE;} <DYNARE_STATEMENT>laplace {return token::LAPLACE;}
<DYNARE_STATEMENT>modifiedharmonicmean {return token::MODIFIEDHARMONICMEAN;} <DYNARE_STATEMENT>modifiedharmonicmean {return token::MODIFIEDHARMONICMEAN;}
@ -167,7 +169,7 @@ int sigma_e = 0;
<DYNARE_BLOCK>values {return token::VALUES;} <DYNARE_BLOCK>values {return token::VALUES;}
<DYNARE_BLOCK>corr {return token::CORR;} <DYNARE_BLOCK>corr {return token::CORR;}
<DYNARE_BLOCK>periods {return token::PERIODS;} <DYNARE_BLOCK>periods {return token::PERIODS;}
<DYNARE_BLOCK>filename {return token::FILENAME;}
<DYNARE_BLOCK>gamma_pdf {return token::GAMMA_PDF;} <DYNARE_BLOCK>gamma_pdf {return token::GAMMA_PDF;}
<DYNARE_BLOCK>beta_pdf {return token::BETA_PDF;} <DYNARE_BLOCK>beta_pdf {return token::BETA_PDF;}
<DYNARE_BLOCK>normal_pdf {return token::NORMAL_PDF;} <DYNARE_BLOCK>normal_pdf {return token::NORMAL_PDF;}
@ -208,6 +210,9 @@ int sigma_e = 0;
<DYNARE_STATEMENT>[\'] {return yy::parser::token_type (yytext[0]);} <DYNARE_STATEMENT>[\'] {return yy::parser::token_type (yytext[0]);}
<DYNARE_STATEMENT,DYNARE_BLOCK>use_dll {return token::USE_DLL;} <DYNARE_STATEMENT,DYNARE_BLOCK>use_dll {return token::USE_DLL;}
<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>linear {return token::LINEAR;} <DYNARE_STATEMENT,DYNARE_BLOCK>linear {return token::LINEAR;}
<DYNARE_STATEMENT,DYNARE_BLOCK>[,] {return token::COMMA;} <DYNARE_STATEMENT,DYNARE_BLOCK>[,] {return token::COMMA;}
<DYNARE_STATEMENT,DYNARE_BLOCK>[:] {return yy::parser::token_type (yytext[0]);} <DYNARE_STATEMENT,DYNARE_BLOCK>[:] {return yy::parser::token_type (yytext[0]);}

View File

@ -2,6 +2,8 @@
#include <iterator> #include <iterator>
#include <algorithm> #include <algorithm>
#include <math.h>
#include "ExprNode.hh" #include "ExprNode.hh"
#include "DataTree.hh" #include "DataTree.hh"
@ -52,6 +54,18 @@ ExprNode::cost(const temporary_terms_type &temporary_terms) const
return 0; return 0;
} }
int
ExprNode::present_endogenous_size() const
{
return(present_endogenous.size());
}
int
ExprNode::present_endogenous_find(int var, int lag) const
{
return(present_endogenous.find(make_pair(var,lag))!=present_endogenous.end());
}
void void
ExprNode::computeTemporaryTerms(map<NodeID, int> &reference_count, ExprNode::computeTemporaryTerms(map<NodeID, int> &reference_count,
temporary_terms_type &temporary_terms) const temporary_terms_type &temporary_terms) const
@ -59,6 +73,16 @@ ExprNode::computeTemporaryTerms(map<NodeID, int> &reference_count,
// Nothing to do for a terminal node // Nothing to do for a terminal node
} }
void
ExprNode::computeTemporaryTerms(map<NodeID, int> &reference_count,
temporary_terms_type &temporary_terms,
map<NodeID, int> &first_occurence,
int Curr_block,
Model_Block *ModelBlock) const
{
// Nothing to do for a terminal node
}
NumConstNode::NumConstNode(DataTree &datatree_arg, int id_arg) : NumConstNode::NumConstNode(DataTree &datatree_arg, int id_arg) :
ExprNode(datatree_arg), ExprNode(datatree_arg),
id(id_arg) id(id_arg)
@ -77,15 +101,29 @@ NumConstNode::computeDerivative(int varID)
void void
NumConstNode::writeOutput(ostream &output, bool is_dynamic, NumConstNode::writeOutput(ostream &output, bool is_dynamic,
const temporary_terms_type &temporary_terms) const const temporary_terms_type &temporary_terms, int offset) const
{ {
temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<NumConstNode *>(this)); temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<NumConstNode *>(this));
if (it != temporary_terms.end()) if (it != temporary_terms.end())
output << "T" << idx; if (offset != 2)
output << "T" << idx;
else
output << "T" << idx << "[it_]";
else else
output << datatree.num_constants.get(id); output << datatree.num_constants.get(id);
} }
void
NumConstNode::Evaluate() const
{
datatree.interprete_.Stack.push(atof(datatree.num_constants.get(id).c_str()));
}
void
NumConstNode::collectEndogenous(NodeID &Id)
{
}
VariableNode::VariableNode(DataTree &datatree_arg, int id_arg, Type type_arg) : VariableNode::VariableNode(DataTree &datatree_arg, int id_arg, Type type_arg) :
ExprNode(datatree_arg), ExprNode(datatree_arg),
id(id_arg), id(id_arg),
@ -150,13 +188,16 @@ VariableNode::computeDerivative(int varID)
void void
VariableNode::writeOutput(ostream &output, bool is_dynamic, VariableNode::writeOutput(ostream &output, bool is_dynamic,
const temporary_terms_type &temporary_terms) const const temporary_terms_type &temporary_terms, int offset) const
{ {
// If node is a temporary term // If node is a temporary term
temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<VariableNode *>(this)); temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<VariableNode *>(this));
if (it != temporary_terms.end()) if (it != temporary_terms.end())
{ {
output << "T" << idx; if (offset != 2)
output << "T" << idx;
else
output << "T" << idx << "[it_]";
return; return;
} }
@ -167,7 +208,10 @@ VariableNode::writeOutput(ostream &output, bool is_dynamic,
switch(type) switch(type)
{ {
case eParameter: case eParameter:
output << "params" << lpar << id + datatree.offset << rpar; if (datatree.offset < 2)
output << "params" << lpar << id + datatree.offset << rpar;
else
output << "params" << lpar << id << rpar;
break; break;
case eLocalParameter: case eLocalParameter:
output << datatree.symbol_table.getNameByID(eLocalParameter, id); output << datatree.symbol_table.getNameByID(eLocalParameter, id);
@ -175,17 +219,39 @@ VariableNode::writeOutput(ostream &output, bool is_dynamic,
case eEndogenous: case eEndogenous:
if (is_dynamic) if (is_dynamic)
{ {
idx = datatree.variable_table.getPrintIndex(id) + datatree.offset; if (datatree.offset < 2)
output << "y" << lpar << idx << rpar; idx = datatree.variable_table.getPrintIndex(id) + datatree.offset;
else
idx = datatree.variable_table.getSymbolID(id);
if (datatree.offset == 2)
{
int l = datatree.variable_table.getLag((long int) id);
if (l > 0)
output << "y" << lpar << "(it_+" << l << ")*y_size+" << idx << rpar;
else if (l < 0)
output << "y" << lpar << "(it_" << l << ")*y_size+" << idx << rpar;
else
output << "y" << lpar << "Per_y_+" << idx << rpar;
}
else
output << "y" << lpar << idx << rpar;
} }
else else
{ {
idx = datatree.variable_table.getSymbolID(id) + datatree.offset; if (datatree.offset < 2)
idx = datatree.variable_table.getSymbolID(id) + datatree.offset;
else
idx = datatree.variable_table.getSymbolID(id);
output << "y" << lpar << idx << rpar; output << "y" << lpar << idx << rpar;
} }
break; break;
case eExogenous: case eExogenous:
idx = datatree.variable_table.getSymbolID(id) + datatree.offset; if (datatree.offset < 2)
idx = datatree.variable_table.getSymbolID(id) + datatree.offset;
else
idx = datatree.variable_table.getSymbolID(id);
if (is_dynamic) if (is_dynamic)
{ {
int lag = datatree.variable_table.getLag(id); int lag = datatree.variable_table.getLag(id);
@ -195,30 +261,40 @@ VariableNode::writeOutput(ostream &output, bool is_dynamic,
else else
output << "x" << lpar << "it_, " << idx << rpar; output << "x" << lpar << "it_, " << idx << rpar;
else else
if (lag != 0) if (lag == 0)
output << "x" << lpar << "it_+" << idx << "*nb_row_x" << rpar;
else if (lag > 0)
output << "x" << lpar << "it_+" << lag << "+" << idx << "*nb_row_x" << rpar; output << "x" << lpar << "it_+" << lag << "+" << idx << "*nb_row_x" << rpar;
else else
output << "x" << lpar << "it_+" << idx << "*nb_row_x" << rpar; output << "x" << lpar << "it_" << lag << "+" << idx << "*nb_row_x" << rpar;
} }
else else
output << "x" << lpar << idx << rpar; output << "x" << lpar << idx << rpar;
break; break;
case eExogenousDet: case eExogenousDet:
idx = datatree.variable_table.getSymbolID(id) + datatree.symbol_table.exo_nbr if (datatree.offset < 2)
+ datatree.offset; idx = datatree.variable_table.getSymbolID(id) + datatree.symbol_table.exo_nbr
+ datatree.offset;
else
idx = datatree.variable_table.getSymbolID(id) + datatree.symbol_table.exo_nbr;
if (is_dynamic) if (is_dynamic)
{ {
int lag = datatree.variable_table.getLag(id); int lag = datatree.variable_table.getLag(id);
if (datatree.offset == 1) if (datatree.offset == 1)
if (lag != 0) if (lag > 0)
output << "x" << lpar << "it_ + " << lag << ", " << idx << rpar; output << "x" << lpar << "it_ +" << lag << ", " << idx << rpar;
else if (lag < 0)
output << "x" << lpar << "it_ " << lag << ", " << idx << rpar;
else else
output << "x" << lpar << "it_, " << idx << rpar; output << "x" << lpar << "it_, " << idx << rpar;
else else
if (lag != 0) if (lag == 0)
output << "x" << lpar << "it_ + " << lag << "+" << idx << "*nb_row_xd" << rpar;
else
output << "x" << lpar << "it_+" << idx << "*nb_row_xd" << rpar; output << "x" << lpar << "it_+" << idx << "*nb_row_xd" << rpar;
else if (lag < 0)
output << "x" << lpar << "it_ " << lag << "+" << idx << "*nb_row_xd" << rpar;
else
output << "x" << lpar << "it_ +" << lag << "+" << idx << "*nb_row_xd" << rpar;
} }
else else
output << "x" << lpar << idx << rpar; output << "x" << lpar << idx << rpar;
@ -235,6 +311,26 @@ VariableNode::writeOutput(ostream &output, bool is_dynamic,
} }
} }
void
VariableNode::Evaluate() const
{
if (type == eParameter)
datatree.interprete_.Stack.push(datatree.interprete_.GetDataValue(id, type));
else
datatree.interprete_.Stack.push(datatree.interprete_.GetDataValue(datatree.variable_table.getSymbolID(id), type));
}
void
VariableNode::collectEndogenous(NodeID &Id)
{
int idx;
if (type == eEndogenous)
{
idx = datatree.variable_table.getSymbolID(id);
Id->present_endogenous.insert(make_pair(idx, datatree.variable_table.getLag((long int) id)));
}
}
UnaryOpNode::UnaryOpNode(DataTree &datatree_arg, UnaryOpcode op_code_arg, const NodeID arg_arg) : UnaryOpNode::UnaryOpNode(DataTree &datatree_arg, UnaryOpcode op_code_arg, const NodeID arg_arg) :
ExprNode(datatree_arg), ExprNode(datatree_arg),
arg(arg_arg), arg(arg_arg),
@ -327,7 +423,7 @@ UnaryOpNode::cost(const temporary_terms_type &temporary_terms) const
int cost = arg->cost(temporary_terms); int cost = arg->cost(temporary_terms);
if (datatree.offset) if (datatree.offset == 1)
// Cost for Matlab files // Cost for Matlab files
switch(op_code) switch(op_code)
{ {
@ -422,15 +518,44 @@ UnaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count,
} }
} }
void
UnaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count,
temporary_terms_type &temporary_terms,
map<NodeID, int> &first_occurence,
int Curr_block,
Model_Block *ModelBlock) const
{
NodeID this2 = const_cast<UnaryOpNode *>(this);
map<NodeID, int>::iterator it = reference_count.find(this2);
if (it == reference_count.end())
{
reference_count[this2] = 1;
first_occurence[this2] = Curr_block;
arg->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, ModelBlock);
}
else
{
reference_count[this2]++;
if (reference_count[this2] * cost(temporary_terms) > datatree.min_cost)
{
temporary_terms.insert(this2);
ModelBlock->Block_List[first_occurence[this2]].Temporary_terms->insert(this2);
}
}
}
void void
UnaryOpNode::writeOutput(ostream &output, bool is_dynamic, UnaryOpNode::writeOutput(ostream &output, bool is_dynamic,
const temporary_terms_type &temporary_terms) const const temporary_terms_type &temporary_terms, int offset) const
{ {
// If node is a temporary term // If node is a temporary term
temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode *>(this)); temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<UnaryOpNode *>(this));
if (it != temporary_terms.end()) if (it != temporary_terms.end())
{ {
output << "T" << idx; if (offset != 2)
output << "T" << idx;
else
output << "T" << idx << "[it_]";
return; return;
} }
@ -507,7 +632,7 @@ UnaryOpNode::writeOutput(ostream &output, bool is_dynamic,
} }
// Write argument // Write argument
arg->writeOutput(output, is_dynamic, temporary_terms); arg->writeOutput(output, is_dynamic, temporary_terms, offset);
if (close_parenthesis) if (close_parenthesis)
output << ")"; output << ")";
@ -517,6 +642,75 @@ UnaryOpNode::writeOutput(ostream &output, bool is_dynamic,
output << ")"; output << ")";
} }
void
UnaryOpNode::Evaluate() const
{
this->arg->Evaluate();
datatree.interprete_.u2 = datatree.interprete_.Stack.top();
datatree.interprete_.Stack.pop();
switch(op_code)
{
case oUminus:
datatree.interprete_.u1=-datatree.interprete_.u2;
break;
case oExp:
datatree.interprete_.u1=exp(datatree.interprete_.u2);
break;
case oLog:
datatree.interprete_.u1=log(datatree.interprete_.u2);
break;
case oLog10:
datatree.interprete_.u1=log10(datatree.interprete_.u2);
break;
case oCos:
datatree.interprete_.u1=cos(datatree.interprete_.u2);
break;
case oSin:
datatree.interprete_.u1=sin(datatree.interprete_.u2);
break;
case oTan:
datatree.interprete_.u1=tan(datatree.interprete_.u2);
break;
case oAcos:
datatree.interprete_.u1=acos(datatree.interprete_.u2);
break;
case oAsin:
datatree.interprete_.u1=asin(datatree.interprete_.u2);
break;
case oAtan:
datatree.interprete_.u1=atan(datatree.interprete_.u2);
break;
case oCosh:
datatree.interprete_.u1=cosh(datatree.interprete_.u2);
break;
case oSinh:
datatree.interprete_.u1=sinh(datatree.interprete_.u2);
break;
case oTanh:
datatree.interprete_.u1=tanh(datatree.interprete_.u2);
break;
case oAcosh:
datatree.interprete_.u1=acosh(datatree.interprete_.u2);
break;
case oAsinh:
datatree.interprete_.u1=asinh(datatree.interprete_.u2);
break;
case oAtanh:
datatree.interprete_.u1=atanh(datatree.interprete_.u2);
break;
case oSqrt:
datatree.interprete_.u1=sqrt(datatree.interprete_.u2);
break;
}
datatree.interprete_.Stack.push(datatree.interprete_.u1);
}
void
UnaryOpNode::collectEndogenous(NodeID &Id)
{
arg->collectEndogenous(Id);
}
BinaryOpNode::BinaryOpNode(DataTree &datatree_arg, const NodeID arg1_arg, BinaryOpNode::BinaryOpNode(DataTree &datatree_arg, const NodeID arg1_arg,
BinaryOpcode op_code_arg, const NodeID arg2_arg) : BinaryOpcode op_code_arg, const NodeID arg2_arg) :
ExprNode(datatree_arg), ExprNode(datatree_arg),
@ -606,7 +800,7 @@ BinaryOpNode::precedence(const temporary_terms_type &temporary_terms) const
case oDivide: case oDivide:
return 1; return 1;
case oPower: case oPower:
if (datatree.offset) if (datatree.offset == 1)
// In C, power operator is of the form pow(a, b) // In C, power operator is of the form pow(a, b)
return 100; return 100;
else else
@ -627,7 +821,7 @@ BinaryOpNode::cost(const temporary_terms_type &temporary_terms) const
int cost = arg1->cost(temporary_terms); int cost = arg1->cost(temporary_terms);
cost += arg2->cost(temporary_terms); cost += arg2->cost(temporary_terms);
if (datatree.offset) if (datatree.offset == 1)
// Cost for Matlab files // Cost for Matlab files
switch(op_code) switch(op_code)
{ {
@ -685,25 +879,88 @@ BinaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count,
} }
} }
void
BinaryOpNode::computeTemporaryTerms(map<NodeID, int> &reference_count,
temporary_terms_type &temporary_terms,
map<NodeID, int> &first_occurence,
int Curr_block,
Model_Block *ModelBlock) const
{
NodeID this2 = const_cast<BinaryOpNode *>(this);
map<NodeID, int>::iterator it = reference_count.find(this2);
if (it == reference_count.end())
{
reference_count[this2] = 1;
first_occurence[this2] = Curr_block;
arg1->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, ModelBlock);
arg2->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, Curr_block, ModelBlock);
}
else
{
reference_count[this2]++;
if (reference_count[this2] * cost(temporary_terms) > datatree.min_cost)
{
temporary_terms.insert(this2);
ModelBlock->Block_List[first_occurence[this2]].Temporary_terms->insert(this2);
}
}
}
void
BinaryOpNode::Evaluate() const
{
// Write current operator symbol
this->arg1->Evaluate();
this->arg2->Evaluate();
datatree.interprete_.u2 = datatree.interprete_.Stack.top();
datatree.interprete_.Stack.pop();
datatree.interprete_.u1 = datatree.interprete_.Stack.top();
datatree.interprete_.Stack.pop();
switch(op_code)
{
case oPlus:
datatree.interprete_.u1+=datatree.interprete_.u2;
break;
case oMinus:
datatree.interprete_.u1-=datatree.interprete_.u2;
break;
case oTimes:
datatree.interprete_.u1*=datatree.interprete_.u2;
break;
case oDivide:
datatree.interprete_.u1/=datatree.interprete_.u2;
break;
case oPower:
datatree.interprete_.u1=pow(datatree.interprete_.u1,datatree.interprete_.u2);
break;
case oEqual:
break;
}
datatree.interprete_.Stack.push(datatree.interprete_.u1);
}
void void
BinaryOpNode::writeOutput(ostream &output, bool is_dynamic, BinaryOpNode::writeOutput(ostream &output, bool is_dynamic,
const temporary_terms_type &temporary_terms) const const temporary_terms_type &temporary_terms, int offset) const
{ {
// If current node is a temporary term // If current node is a temporary term
temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this)); temporary_terms_type::const_iterator it = temporary_terms.find(const_cast<BinaryOpNode *>(this));
if (it != temporary_terms.end()) if (it != temporary_terms.end())
{ {
output << "T" << idx; if (offset != 2)
output << "T" << idx;
else
output << "T" << idx << "[it_]";
return; return;
} }
// Treat special case of power operator in C // Treat special case of power operator in C
if (op_code == oPower && datatree.offset == 0) if (op_code == oPower && (datatree.offset == 0 || datatree.offset == 2))
{ {
output << "pow("; output << "pow(";
arg1->writeOutput(output, is_dynamic, temporary_terms); arg1->writeOutput(output, is_dynamic, temporary_terms, offset);
output << ","; output << ",";
arg2->writeOutput(output, is_dynamic, temporary_terms); arg2->writeOutput(output, is_dynamic, temporary_terms, offset);
output << ")"; output << ")";
return; return;
} }
@ -722,7 +979,7 @@ BinaryOpNode::writeOutput(ostream &output, bool is_dynamic,
} }
// Write left argument // Write left argument
arg1->writeOutput(output, is_dynamic, temporary_terms); arg1->writeOutput(output, is_dynamic, temporary_terms, offset);
if (close_parenthesis) if (close_parenthesis)
output << ")"; output << ")";
@ -769,8 +1026,15 @@ BinaryOpNode::writeOutput(ostream &output, bool is_dynamic,
} }
// Write right argument // Write right argument
arg2->writeOutput(output, is_dynamic, temporary_terms); arg2->writeOutput(output, is_dynamic, temporary_terms, offset);
if (close_parenthesis) if (close_parenthesis)
output << ")"; output << ")";
} }
void
BinaryOpNode::collectEndogenous(NodeID &Id)
{
arg1->collectEndogenous(Id);
arg2->collectEndogenous(Id);
}

View File

@ -51,7 +51,13 @@ COMMON_OBJ=\
DataTree.o \ DataTree.o \
ModFile.o \ ModFile.o \
Statement.o \ Statement.o \
ExprNode.o ExprNode.o \
ModelNormalization.o \
ModelBlocks.o \
BlockTriangular.o \
Model_Graph.o \
interprete.o \
SymbolGaussElim.o
MATLAB_OBJ = InterfaceMatlab.o MATLAB_OBJ = InterfaceMatlab.o

View File

@ -67,7 +67,7 @@ ModFile::computingPass()
} }
void void
ModFile::writeOutputFiles(const string &basename, bool clear_all) const ModFile::writeOutputFiles(const string &basename, bool clear_all)
{ {
ofstream mOutputFile; ofstream mOutputFile;
@ -142,7 +142,24 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all) const
cout << "Processing outputs ..." << endl; cout << "Processing outputs ..." << endl;
model_tree.block_triangular.file_name = basename;
int true_offset = model_tree.offset;
if (model_tree.offset == 2)
{
model_tree.offset = 1;
model_tree.lpar = '(';
model_tree.rpar = ')';
}
model_tree.writeStaticFile(basename); model_tree.writeStaticFile(basename);
if (true_offset == 2)
{
model_tree.offset = 2;
model_tree.lpar = '[';
model_tree.rpar = ']';
}
model_tree.writeDynamicFile(basename); model_tree.writeDynamicFile(basename);
// Print statements // Print statements

332
parser.src/ModelBlocks.cc Normal file
View File

@ -0,0 +1,332 @@
#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";
}
}

View File

@ -0,0 +1,524 @@
//#define DEBUG
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include "ModelNormalization.hh"
using namespace std;
Normalization::Normalization()
{
//Empty
};
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::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;
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;
if(matchingSize < effective_n)
{
cout << "Error: dynare could not normalize the model\n";
ErrorHandling(n, IM, Index_Equ_IM);
system("PAUSE");
exit( -1);
}
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
}

File diff suppressed because it is too large Load Diff

1056
parser.src/Model_Graph.cc Normal file

File diff suppressed because it is too large Load Diff

View File

@ -110,6 +110,10 @@ ExpObj *
ParsingDriver::add_expression_constant(string *constant) ParsingDriver::add_expression_constant(string *constant)
{ {
int id = mod_file->num_constants.AddConstant(*constant); int id = mod_file->num_constants.AddConstant(*constant);
if(mod_file->model_tree.interprete_.eval)
mod_file->model_tree.interprete_.Stack.push(mod_file->model_tree.interprete_.S_to_Val(constant));
delete constant; delete constant;
return new ExpObj(id, eNumericalConstant); return new ExpObj(id, eNumericalConstant);
} }
@ -127,6 +131,14 @@ ParsingDriver::add_model_variable(string *name)
{ {
check_symbol_existence(*name); check_symbol_existence(*name);
NodeID id = model_tree->AddVariable(*name); NodeID id = model_tree->AddVariable(*name);
Type type = mod_file->symbol_table.getType(*name);
if ((type == eEndogenous) && (mod_file->model_tree.offset == 2))
{
int ID = mod_file->symbol_table.getID(*name);
mod_file->model_tree.block_triangular.fill_IM(model_tree->equation_number(), ID, 0);
}
delete name; delete name;
return id; return id;
} }
@ -145,6 +157,10 @@ ParsingDriver::add_model_variable(string *name, string *olag)
<< " has lag " << lag << endl; << " has lag " << lag << endl;
} }
NodeID id = model_tree->AddVariable(*name, lag); NodeID id = model_tree->AddVariable(*name, lag);
if ((type == eEndogenous) && (mod_file->model_tree.offset == 2))
mod_file->model_tree.block_triangular.fill_IM(model_tree->equation_number(), mod_file->symbol_table.getID(*name), lag);
delete name; delete name;
delete olag; delete olag;
return id; return id;
@ -156,6 +172,10 @@ ParsingDriver::add_expression_variable(string *name)
check_symbol_existence(*name); check_symbol_existence(*name);
int id = mod_file->symbol_table.getID(*name); int id = mod_file->symbol_table.getID(*name);
Type type = mod_file->symbol_table.getType(*name); Type type = mod_file->symbol_table.getType(*name);
if(mod_file->model_tree.interprete_.eval)
mod_file->model_tree.interprete_.Stack.push(mod_file->model_tree.interprete_.get_value(name,0));
delete name; delete name;
return new ExpObj(id, type); return new ExpObj(id, type);
} }
@ -166,6 +186,26 @@ ParsingDriver::add_expression_token(ExpObj *arg1, ExpObj *arg2, int op)
int id = expression.AddToken(arg1->first, arg1->second, int id = expression.AddToken(arg1->first, arg1->second,
arg2->first, arg2->second, arg2->first, arg2->second,
op); op);
if (mod_file->model_tree.interprete_.eval)
{
mod_file->model_tree.interprete_.u2 = mod_file->model_tree.interprete_.Stack.top();
mod_file->model_tree.interprete_.Stack.pop();
mod_file->model_tree.interprete_.u1 = mod_file->model_tree.interprete_.Stack.top();
mod_file->model_tree.interprete_.Stack.pop();
if (op == token::PLUS)
mod_file->model_tree.interprete_.u1+=mod_file->model_tree.interprete_.u2;
else if (op == token::MINUS)
mod_file->model_tree.interprete_.u1-=mod_file->model_tree.interprete_.u2;
else if (op == token::DIVIDE)
mod_file->model_tree.interprete_.u1/=mod_file->model_tree.interprete_.u2;
else if (op == token::TIMES)
mod_file->model_tree.interprete_.u1*=mod_file->model_tree.interprete_.u2;
else if (op == token::POWER)
mod_file->model_tree.interprete_.u1=pow(mod_file->model_tree.interprete_.u1,mod_file->model_tree.interprete_.u2);
mod_file->model_tree.interprete_.Stack.push(mod_file->model_tree.interprete_.u1);
}
delete arg1; delete arg1;
delete arg2; delete arg2;
return new ExpObj(id, eTempResult); return new ExpObj(id, eTempResult);
@ -175,6 +215,36 @@ ExpObj *
ParsingDriver::add_expression_token(ExpObj *arg1, int op) ParsingDriver::add_expression_token(ExpObj *arg1, int op)
{ {
int id = expression.AddToken(arg1->first, arg1->second, op); int id = expression.AddToken(arg1->first, arg1->second, op);
if (mod_file->model_tree.interprete_.eval)
{
mod_file->model_tree.interprete_.u2 = mod_file->model_tree.interprete_.Stack.top();
mod_file->model_tree.interprete_.Stack.pop();
if (op == token::UMINUS)
mod_file->model_tree.interprete_.u1=-mod_file->model_tree.interprete_.u2;
else if (op == token::EXP)
mod_file->model_tree.interprete_.u1=exp(mod_file->model_tree.interprete_.u2);
else if (op == token::LOG)
mod_file->model_tree.interprete_.u1=log(mod_file->model_tree.interprete_.u2);
else if (op == token::LOG10)
mod_file->model_tree.interprete_.u1=log10(mod_file->model_tree.interprete_.u2);
else if (op == token::SIN)
mod_file->model_tree.interprete_.u1=sin(mod_file->model_tree.interprete_.u2);
else if (op == token::COS)
mod_file->model_tree.interprete_.u1=cos(mod_file->model_tree.interprete_.u2);
else if (op == token::TAN)
mod_file->model_tree.interprete_.u1=tan(mod_file->model_tree.interprete_.u2);
else if (op == token::ASIN)
mod_file->model_tree.interprete_.u1=asin(mod_file->model_tree.interprete_.u2);
else if (op == token::ACOS)
mod_file->model_tree.interprete_.u1=acos(mod_file->model_tree.interprete_.u2);
else if (op == token::ATAN)
mod_file->model_tree.interprete_.u1=atan(mod_file->model_tree.interprete_.u2);
else if (op == token::SQRT)
mod_file->model_tree.interprete_.u1=sqrt(mod_file->model_tree.interprete_.u2);
mod_file->model_tree.interprete_.Stack.push(mod_file->model_tree.interprete_.u1);
}
delete arg1; delete arg1;
return new ExpObj(id, eTempResult); return new ExpObj(id, eTempResult);
} }
@ -183,6 +253,15 @@ ExpObj *
ParsingDriver::add_expression_token(ExpObj *arg1, string *op_name) ParsingDriver::add_expression_token(ExpObj *arg1, string *op_name)
{ {
int id = expression.AddToken(arg1->first, arg1->second, *op_name); int id = expression.AddToken(arg1->first, arg1->second, *op_name);
if (mod_file->model_tree.interprete_.eval)
{
mod_file->model_tree.interprete_.u2 = mod_file->model_tree.interprete_.Stack.top();
mod_file->model_tree.interprete_.Stack.pop();
mod_file->model_tree.interprete_.Stack.push(mod_file->model_tree.interprete_.get_value(op_name,mod_file->model_tree.interprete_.u2));
mod_file->model_tree.interprete_.Stack.push(mod_file->model_tree.interprete_.u1);
}
delete arg1; delete arg1;
delete op_name; delete op_name;
return new ExpObj(id, eTempResult); return new ExpObj(id, eTempResult);
@ -196,6 +275,14 @@ ParsingDriver::periods(string *periods)
delete periods; delete periods;
} }
void
ParsingDriver::cutoff(string *cutoff)
{
int cutoff_val = atoi(cutoff->c_str());
mod_file->addStatement(new CutoffStatement(cutoff_val));
delete cutoff;
}
void void
ParsingDriver::dsample(string *arg1) ParsingDriver::dsample(string *arg1)
{ {
@ -222,6 +309,11 @@ ParsingDriver::init_param(string *name, ExpObj *rhs)
error(*name + " is not a parameter"); error(*name + " is not a parameter");
mod_file->addStatement(new InitParamStatement(*name, get_expression(rhs), mod_file->symbol_table)); mod_file->addStatement(new InitParamStatement(*name, get_expression(rhs), mod_file->symbol_table));
mod_file->model_tree.interprete_.u2 = mod_file->model_tree.interprete_.Stack.top();
mod_file->model_tree.interprete_.Stack.pop();
mod_file->model_tree.interprete_.put_value(name,mod_file->symbol_table.getID(*name), eParameter, mod_file->model_tree.interprete_.u2);
delete name; delete name;
delete rhs; delete rhs;
} }
@ -239,10 +331,25 @@ ParsingDriver::init_val(string *name, ExpObj *rhs)
init_values.push_back(make_pair(*name, get_expression(rhs))); init_values.push_back(make_pair(*name, get_expression(rhs)));
if(mod_file->model_tree.interprete_.eval)
{
mod_file->model_tree.interprete_.u2 = mod_file->model_tree.interprete_.Stack.top();
mod_file->model_tree.interprete_.Stack.pop();
mod_file->model_tree.interprete_.put_value(name, mod_file->symbol_table.getID(*name), type, mod_file->model_tree.interprete_.u2);
}
delete name; delete name;
delete rhs; delete rhs;
} }
void
ParsingDriver::init_val_filename(string *filename)
{
options_list.num_options["INITVAL_FILE"] = 1;
options_list.string_options["INITVAL_FILENAME"] = *filename;
delete filename;
}
void void
ParsingDriver::hist_val(string *name, string *lag, ExpObj *rhs) ParsingDriver::hist_val(string *name, string *lag, ExpObj *rhs)
{ {
@ -267,6 +374,14 @@ ParsingDriver::hist_val(string *name, string *lag, ExpObj *rhs)
delete rhs; delete rhs;
} }
void
ParsingDriver::initialize_model(void)
{
//Initialize the incidence matrix
//cout << "mod_file->symbol_table.endo_nbr=" << mod_file->symbol_table.endo_nbr << "\n";
mod_file->model_tree.block_triangular.init_incidence_matrix(mod_file->symbol_table.endo_nbr);
}
void void
ParsingDriver::use_dll() ParsingDriver::use_dll()
{ {
@ -274,6 +389,13 @@ ParsingDriver::use_dll()
mod_file->model_tree.offset = 0; mod_file->model_tree.offset = 0;
} }
void
ParsingDriver::sparse_dll()
{
// Seetting variable momber offset to use C outputs
mod_file->model_tree.offset = 2;
}
void void
ParsingDriver::end_initval() ParsingDriver::end_initval()
{ {
@ -299,6 +421,8 @@ void
ParsingDriver::begin_model() ParsingDriver::begin_model()
{ {
model_tree = &mod_file->model_tree; model_tree = &mod_file->model_tree;
if (mod_file->model_tree.offset == 2)
initialize_model();
} }
void void
@ -529,6 +653,11 @@ ParsingDriver::option_num(const string &name_option, const string &opt)
!= options_list.num_options.end()) != options_list.num_options.end())
error("option " + name_option + " declared twice"); error("option " + name_option + " declared twice");
if ((name_option == "periods") && (mod_file->model_tree.offset == 2))
mod_file->model_tree.block_triangular.periods = atoi(opt.c_str());
else if (name_option == "cutoff")
mod_file->model_tree.interprete_.set_cutoff(atof(opt.c_str()));
options_list.num_options[name_option] = opt; options_list.num_options[name_option] = opt;
} }
@ -587,6 +716,33 @@ void ParsingDriver::stoch_simul()
options_list.clear(); options_list.clear();
} }
void ParsingDriver::simulate()
{
if(mod_file->model_tree.offset==2)
simul_sparse();
else
simul();
}
void
ParsingDriver::simul_sparse()
{
SimulSparseStatement *st=new SimulSparseStatement(options_list);
st->filename=file;
string tmp=st->filename.substr(st->filename.length()-4);
if(tmp==".mod"||tmp==".dyn")
st->filename.erase(st->filename.length()-4);
st->compiler=mod_file->model_tree.compiler;
mod_file->addStatement(st);
options_list.clear();
}
void
ParsingDriver::init_compiler(int compiler_type)
{
mod_file->model_tree.compiler=compiler_type;
}
void void
ParsingDriver::simul() ParsingDriver::simul()
{ {

File diff suppressed because it is too large Load Diff

View File

@ -132,3 +132,45 @@ VariableTable::Sort()
} }
} }
} }
int*
VariableTable::GetVariableTable(int* Size, int* HSize)
{
int* Table;
varKey key;
int variable,id, ind;
(*Size)=0;
for (id=0; id < (int) mVariableIndex.size(); id++)
{
key = mVariableIndex[id];
variable = mVariableTable[key];
if(getType(variable)==eEndogenous)
(*Size)++;
}
(*HSize)=4;
Table=(int*)malloc((*Size)*(*HSize)*sizeof(*Table));
ind=0;
for (id=0; id < (int) mVariableIndex.size(); id++)
{
key = mVariableIndex[id];
variable = mVariableTable[key];
if (getType(variable)==eEndogenous)
{
Table[ind*(*HSize)]= getSymbolID(id);
Table[ind*(*HSize)+1]= key.second;
Table[ind*(*HSize)+2]= mPrintFormatIndex[id];
Table[ind*(*HSize)+3]= mSortedVariableID[id];
ind++;
}
}
return(Table);
}
int
VariableTable::getIDS(int id, int lead_lag) const
{
varKey key;
key=mVariableIndex[id];
map<varKey, int>::const_iterator it = mVariableTable.find(key);
return(it->second);
}

View File

@ -0,0 +1,173 @@
#ifndef BLOCKTRIANGULAR_H
#define BLOCKTRIANGULAR_H
//------------------------------------------------------------------------------
/*! \file
\version 1.0
\date 16/07/2006
\par This file defines the BlockTriangular class.
*/
//------------------------------------------------------------------------------
#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;
};
class BlockTriangular
{
public:
Normalization normalization;
BlockTriangular(const SymbolTable &symbol_table_arg);
~BlockTriangular();
/*! The incidence matrix for each lead and lags */
Blocks blocks;
SymbolTable symbol_table;
List_IM* Build_IM(int lead_lag);
List_IM* Get_IM(int lead_lag);
bool* bGet_IM(int lead_lag);
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);
void Free_IM(List_IM* First_IM);
void Print_SIM(bool* IM, int n);
void Normalize_and_BlockDecompose_Static_Model();
void Normalize_and_BlockDecompose_Static_0_Model();
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 );
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, int* Table, int TableSize);
void Free_Block(Model_Block* ModelBlock);
void SetVariableTable(int *Table,int Size,int HSize);
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, TableSize;
int* Table;
Model_Block* ModelBlock;
string file_name;
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 0:
return ("EVALUATE FOREWARD ");
break;
case 1:
return ("EVALUATE BACKWARD ");
break;
case 2:
return ("SOLVE FOREWARD SIMPLE ");
break;
case 3:
return ("SOLVE BACKWARD SIMPLE ");
break;
case 4:
return ("SOLVE TWO BOUNDARIES SIMPLE ");
break;
case 5:
return ("SOLVE FOREWARD COMPLETE ");
break;
case 6:
return ("SOLVE BACKWARD COMPLETE ");
break;
case 7:
return ("SOLVE TWO BOUNDARIES COMPLETE");
break;
default:
return ("UNKNOWN ");
break;
}
};
inline static std::string BlockSim_d(int type)
{
switch (type)
{
case 0:
return ("EVALUATE_FOREWARD ");
break;
case 1:
return ("EVALUATE_BACKWARD ");
break;
case 2:
return ("SOLVE_FOREWARD_SIMPLE ");
break;
case 3:
return ("SOLVE_BACKWARD_SIMPLE ");
break;
case 4:
return ("SOLVE_TWO_BOUNDARIES_SIMPLE ");
break;
case 5:
return ("SOLVE_FOREWARD_COMPLETE ");
break;
case 6:
return ("SOLVE_BACKWARD_COMPLETE ");
break;
case 7:
return ("SOLVE_TWO_BOUNDARIES_COMPLETE");
break;
default:
return ("UNKNOWN ");
break;
}
};
};
//------------------------------------------------------------------------------
#endif

View File

@ -37,6 +37,18 @@ public:
virtual void writeOutput(ostream &output, const string &basename) const; virtual void writeOutput(ostream &output, const string &basename) const;
}; };
class SimulSparseStatement : public Statement
{
private:
const OptionsList options_list;
public:
string filename;
int compiler;
SimulSparseStatement(const OptionsList &options_list_arg);
virtual void checkPass(ModFileStructure &mod_file_struct);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class StochSimulStatement : public Statement class StochSimulStatement : public Statement
{ {
private: private:
@ -90,6 +102,15 @@ public:
virtual void writeOutput(ostream &output, const string &basename) const; virtual void writeOutput(ostream &output, const string &basename) const;
}; };
class CutoffStatement : public Statement
{
private:
const int cutoff;
public:
CutoffStatement(int cutoff_arg);
virtual void writeOutput(ostream &output, const string &basename) const;
};
class DsampleStatement : public Statement class DsampleStatement : public Statement
{ {
private: private:

View File

@ -12,6 +12,11 @@ using namespace std;
#include "VariableTable.hh" #include "VariableTable.hh"
#include "ExprNode.hh" #include "ExprNode.hh"
#include "interprete.hh"
#define LCC_COMPILE 0
#define GCC_COMPILE 1
class DataTree class DataTree
{ {
friend class ExprNode; friend class ExprNode;
@ -24,8 +29,6 @@ protected:
SymbolTable &symbol_table; SymbolTable &symbol_table;
//! Reference to numerical constants table //! Reference to numerical constants table
NumericalConstants &num_constants; NumericalConstants &num_constants;
//! The variable table
VariableTable variable_table;
typedef list<NodeID> node_list_type; typedef list<NodeID> node_list_type;
//! The list of nodes //! The list of nodes
@ -39,11 +42,6 @@ protected:
//! Computing cost above which a node can be declared a temporary term //! Computing cost above which a node can be declared a temporary term
int min_cost; int min_cost;
//! Left indexing parenthesis
char lpar;
//! Right indexing parenthesis
char rpar;
typedef map<int, NodeID> num_const_node_map_type; typedef map<int, NodeID> num_const_node_map_type;
num_const_node_map_type num_const_node_map; num_const_node_map_type num_const_node_map;
typedef map<pair<int, Type>, NodeID> variable_node_map_type; typedef map<pair<int, Type>, NodeID> variable_node_map_type;
@ -58,9 +56,20 @@ protected:
public: public:
DataTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg); DataTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants_arg);
virtual ~DataTree(); virtual ~DataTree();
//! The variable table
VariableTable variable_table;
NodeID Zero, One, MinusOne; NodeID Zero, One, MinusOne;
//! Type of output 0 for C and 1 for Matlab (default), also used as matrix index offset //! Type of output 0 for C and 1 for Matlab (default), also used as matrix index offset
int offset; int offset;
//! Complete set to interpret the model parameters and variables
interprete interprete_;
//! Left indexing parenthesis
char lpar;
//! Right indexing parenthesis
char rpar;
//! Type of compiler used in matlab : 0 = LCC or 1 = GCC
int compiler;
//! Raised when a local parameter is declared twice //! Raised when a local parameter is declared twice
class LocalParameterException class LocalParameterException

View File

@ -61,7 +61,7 @@ class ParsingDriver;
typedef pair<int, Type> ExpObj; typedef pair<int, Type> ExpObj;
/* Line 303 of lalr1.cc. */ /* Line 35 of lalr1.cc. */
#line 66 "DynareBison.hh" #line 66 "DynareBison.hh"
#include "location.hh" #include "location.hh"
@ -119,7 +119,7 @@ namespace yy
ExpObj *exp_val; ExpObj *exp_val;
NodeID model_val; NodeID model_val;
} }
/* Line 303 of lalr1.cc. */ /* Line 35 of lalr1.cc. */
#line 124 "DynareBison.hh" #line 124 "DynareBison.hh"
; ;
#else #else
@ -143,136 +143,141 @@ namespace yy
CONSTANT = 266, CONSTANT = 266,
CORR = 267, CORR = 267,
COVAR = 268, COVAR = 268,
DATAFILE = 269, CUTOFF = 269,
DR_ALGO = 270, DATAFILE = 270,
DROP = 271, DR_ALGO = 271,
DSAMPLE = 272, DROP = 272,
DYNASAVE = 273, DSAMPLE = 273,
DYNATYPE = 274, DYNASAVE = 274,
END = 275, DYNATYPE = 275,
ENDVAL = 276, END = 276,
EQUAL = 277, ENDVAL = 277,
ESTIMATION = 278, EQUAL = 278,
ESTIMATED_PARAMS = 279, ESTIMATION = 279,
ESTIMATED_PARAMS_BOUNDS = 280, ESTIMATED_PARAMS = 280,
ESTIMATED_PARAMS_INIT = 281, ESTIMATED_PARAMS_BOUNDS = 281,
FILTER_STEP_AHEAD = 282, ESTIMATED_PARAMS_INIT = 282,
FILTERED_VARS = 283, FILENAME = 283,
FIRST_OBS = 284, FILTER_STEP_AHEAD = 284,
FLOAT_NUMBER = 285, FILTERED_VARS = 285,
FORECAST = 286, FIRST_OBS = 286,
GAMMA_PDF = 287, FLOAT_NUMBER = 287,
GRAPH = 288, FORECAST = 288,
HISTVAL = 289, GAMMA_PDF = 289,
HP_FILTER = 290, GCC_COMPILER = 290,
HP_NGRID = 291, GRAPH = 291,
INITVAL = 292, HISTVAL = 292,
INT_NUMBER = 293, HP_FILTER = 293,
INV_GAMMA_PDF = 294, HP_NGRID = 294,
IRF = 295, INITVAL = 295,
KALMAN_ALGO = 296, INT_NUMBER = 296,
KALMAN_TOL = 297, INV_GAMMA_PDF = 297,
LAPLACE = 298, IRF = 298,
LIK_ALGO = 299, KALMAN_ALGO = 299,
LIK_INIT = 300, KALMAN_TOL = 300,
LINEAR = 301, LAPLACE = 301,
LOAD_MH_FILE = 302, LCC_COMPILER = 302,
LOGLINEAR = 303, LIK_ALGO = 303,
MH_DROP = 304, LIK_INIT = 304,
MH_INIT_SCALE = 305, LINEAR = 305,
MH_JSCALE = 306, LOAD_MH_FILE = 306,
MH_MODE = 307, LOGLINEAR = 307,
MH_NBLOCKS = 308, MH_DROP = 308,
MH_REPLIC = 309, MH_INIT_SCALE = 309,
MH_RECOVER = 310, MH_JSCALE = 310,
MODE_CHECK = 311, MH_MODE = 311,
MODE_COMPUTE = 312, MH_NBLOCKS = 312,
MODE_FILE = 313, MH_REPLIC = 313,
MODEL = 314, MH_RECOVER = 314,
MODEL_COMPARISON = 315, MODE_CHECK = 315,
MSHOCKS = 316, MODE_COMPUTE = 316,
MODEL_COMPARISON_APPROXIMATION = 317, MODE_FILE = 317,
MODIFIEDHARMONICMEAN = 318, MODEL = 318,
MOMENTS_VARENDO = 319, MODEL_COMPARISON = 319,
NAME = 320, MSHOCKS = 320,
NOBS = 321, MODEL_COMPARISON_APPROXIMATION = 321,
NOCONSTANT = 322, MODIFIEDHARMONICMEAN = 322,
NOCORR = 323, MOMENTS_VARENDO = 323,
NODIAGNOSTIC = 324, NAME = 324,
NOFUNCTIONS = 325, NOBS = 325,
NOGRAPH = 326, NOCONSTANT = 326,
NOMOMENTS = 327, NOCORR = 327,
NOPRINT = 328, NODIAGNOSTIC = 328,
NORMAL_PDF = 329, NOFUNCTIONS = 329,
OBSERVATION_TRENDS = 330, NOGRAPH = 330,
OLR = 331, NOMOMENTS = 331,
OLR_INST = 332, NOPRINT = 332,
OLR_BETA = 333, NORMAL_PDF = 333,
OPTIM = 334, OBSERVATION_TRENDS = 334,
OPTIM_WEIGHTS = 335, OLR = 335,
ORDER = 336, OLR_INST = 336,
OSR = 337, OLR_BETA = 337,
OSR_PARAMS = 338, OPTIM = 338,
PARAMETERS = 339, OPTIM_WEIGHTS = 339,
PERIODS = 340, ORDER = 340,
PLANNER_OBJECTIVE = 341, OSR = 341,
PREFILTER = 342, OSR_PARAMS = 342,
PRESAMPLE = 343, PARAMETERS = 343,
PRINT = 344, PERIODS = 344,
PRIOR_TRUNC = 345, PLANNER_OBJECTIVE = 345,
PRIOR_ANALYSIS = 346, PREFILTER = 346,
POSTERIOR_ANALYSIS = 347, PRESAMPLE = 347,
QZ_CRITERIUM = 348, PRINT = 348,
RELATIVE_IRF = 349, PRIOR_TRUNC = 349,
REPLIC = 350, PRIOR_ANALYSIS = 350,
RPLOT = 351, POSTERIOR_ANALYSIS = 351,
SHOCKS = 352, QZ_CRITERIUM = 352,
SIGMA_E = 353, RELATIVE_IRF = 353,
SIMUL = 354, REPLIC = 354,
SIMUL_ALGO = 355, RPLOT = 355,
SIMUL_SEED = 356, SHOCKS = 356,
SMOOTHER = 357, SIGMA_E = 357,
SOLVE_ALGO = 358, SIMUL = 358,
STDERR = 359, SIMUL_ALGO = 359,
STEADY = 360, SIMUL_SEED = 360,
STOCH_SIMUL = 361, SMOOTHER = 361,
TEX = 362, SOLVE_ALGO = 362,
RAMSEY_POLICY = 363, SPARSE_DLL = 363,
PLANNER_DISCOUNT = 364, STDERR = 364,
TEX_NAME = 365, STEADY = 365,
UNIFORM_PDF = 366, STOCH_SIMUL = 366,
UNIT_ROOT_VARS = 367, TEX = 367,
USE_DLL = 368, RAMSEY_POLICY = 368,
VALUES = 369, PLANNER_DISCOUNT = 369,
VAR = 370, TEX_NAME = 370,
VAREXO = 371, UNIFORM_PDF = 371,
VAREXO_DET = 372, UNIT_ROOT_VARS = 372,
VAROBS = 373, USE_DLL = 373,
XLS_SHEET = 374, VALUES = 374,
XLS_RANGE = 375, VAR = 375,
COMMA = 376, VAREXO = 376,
MINUS = 377, VAREXO_DET = 377,
PLUS = 378, VAROBS = 378,
DIVIDE = 379, XLS_SHEET = 379,
TIMES = 380, XLS_RANGE = 380,
UMINUS = 381, COMMA = 381,
POWER = 382, MINUS = 382,
EXP = 383, PLUS = 383,
LOG = 384, DIVIDE = 384,
LOG10 = 385, TIMES = 385,
SIN = 386, UMINUS = 386,
COS = 387, POWER = 387,
TAN = 388, EXP = 388,
ASIN = 389, LOG = 389,
ACOS = 390, LOG10 = 390,
ATAN = 391, SIN = 391,
SINH = 392, COS = 392,
COSH = 393, TAN = 393,
TANH = 394, ASIN = 394,
ASINH = 395, ACOS = 395,
ACOSH = 396, ATAN = 396,
ATANH = 397, SINH = 397,
SQRT = 398 COSH = 398,
TANH = 399,
ASINH = 400,
ACOSH = 401,
ATANH = 402,
SQRT = 403
}; };
}; };

View File

@ -12,6 +12,8 @@ class DataTree;
typedef class ExprNode *NodeID; typedef class ExprNode *NodeID;
typedef struct Model_Block;
struct ExprNodeLess; struct ExprNodeLess;
//! Type for set of temporary terms //! Type for set of temporary terms
@ -51,6 +53,9 @@ protected:
/*! Nodes included in temporary_terms are considered having a null cost */ /*! Nodes included in temporary_terms are considered having a null cost */
virtual int cost(const temporary_terms_type &temporary_terms) const; virtual int cost(const temporary_terms_type &temporary_terms) const;
//! set of endogenous variables in the current expression
//! <symbolID, lag>
set< pair<int,int> > present_endogenous;
public: public:
ExprNode(DataTree &datatree_arg); ExprNode(DataTree &datatree_arg);
virtual ~ExprNode(); virtual ~ExprNode();
@ -69,7 +74,18 @@ public:
virtual void computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms) const; virtual void computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms) const;
//! Writes output of node, using a Txxx notation for nodes in temporary_terms //! Writes output of node, using a Txxx notation for nodes in temporary_terms
virtual void writeOutput(ostream &output, bool is_dynamic, const temporary_terms_type &temporary_terms) const = 0; virtual void writeOutput(ostream &output, bool is_dynamic, const temporary_terms_type &temporary_terms, int offset) const = 0;
//! 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) const;
int present_endogenous_size() const;
int present_endogenous_find(int var, int lag) const;
virtual void Evaluate() const = 0;
}; };
//! Object used to compare two nodes (using their indexes) //! Object used to compare two nodes (using their indexes)
@ -90,7 +106,9 @@ private:
virtual NodeID computeDerivative(int varID); virtual NodeID computeDerivative(int varID);
public: public:
NumConstNode(DataTree &datatree_arg, int id_arg); NumConstNode(DataTree &datatree_arg, int id_arg);
virtual void writeOutput(ostream &output, bool is_dynamic, const temporary_terms_type &temporary_terms) const; virtual void writeOutput(ostream &output, bool is_dynamic, const temporary_terms_type &temporary_terms, int offset) const;
virtual void collectEndogenous(NodeID &Id);
virtual void Evaluate() const;
}; };
//! Symbol or variable node //! Symbol or variable node
@ -104,7 +122,9 @@ private:
virtual NodeID computeDerivative(int varID); virtual NodeID computeDerivative(int varID);
public: public:
VariableNode(DataTree &datatree_arg, int id_arg, Type type_arg); VariableNode(DataTree &datatree_arg, int id_arg, Type type_arg);
virtual void writeOutput(ostream &output, bool is_dynamic, const temporary_terms_type &temporary_terms) const; virtual void writeOutput(ostream &output, bool is_dynamic, const temporary_terms_type &temporary_terms, int offset) const;
virtual void collectEndogenous(NodeID &Id);
virtual void Evaluate() const;
}; };
enum UnaryOpcode enum UnaryOpcode
@ -141,7 +161,14 @@ private:
public: public:
UnaryOpNode(DataTree &datatree_arg, UnaryOpcode op_code_arg, const NodeID arg_arg); 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) const; virtual void computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms) const;
virtual void writeOutput(ostream &output, bool is_dynamic, const temporary_terms_type &temporary_terms) const; virtual void writeOutput(ostream &output, bool is_dynamic, const temporary_terms_type &temporary_terms, int offset) 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) const;
virtual void collectEndogenous(NodeID &Id);
virtual void Evaluate() const;
}; };
enum BinaryOpcode enum BinaryOpcode
@ -168,7 +195,38 @@ public:
BinaryOpcode op_code_arg, const NodeID arg2_arg); BinaryOpcode op_code_arg, const NodeID arg2_arg);
virtual int precedence(const temporary_terms_type &temporary_terms) const; virtual int precedence(const temporary_terms_type &temporary_terms) const;
virtual void computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms) const; virtual void computeTemporaryTerms(map<NodeID, int> &reference_count, temporary_terms_type &temporary_terms) const;
virtual void writeOutput(ostream &output, bool is_dynamic, const temporary_terms_type &temporary_terms) const; virtual void writeOutput(ostream &output, bool is_dynamic, const temporary_terms_type &temporary_terms, int offset) 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) const;
virtual void collectEndogenous(NodeID &Id);
virtual void Evaluate() 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;
int *Variable, *Variable_Sorted, *dVariable;
int *variable_dyn_index, *variable_dyn_leadlag;
temporary_terms_type *Temporary_terms;
IM_compact *IM_lead_lag;
};
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 #endif

View File

@ -43,8 +43,9 @@ public:
/*! /*!
\param basename The base name used for writing output files. Should be the name of the mod file without its extension \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 ? \param clear_all Should a "clear all" instruction be written to output ?
\todo make this method "const" again!
*/ */
void writeOutputFiles(const string &basename, bool clear_all) const; void writeOutputFiles(const string &basename, bool clear_all);
}; };
#endif // ! MOD_FILE_HH #endif // ! MOD_FILE_HH

View File

@ -0,0 +1,37 @@
#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,90 @@
#ifndef MODELNORMALIZATION
#define MODELNORMALIZATION
#include "SymbolTableTypes.hh"
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;
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(/*t_getNameByID gdi*/);
~Normalization();
void 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;
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

View File

@ -11,6 +11,8 @@ using namespace std;
#include "SymbolTable.hh" #include "SymbolTable.hh"
#include "NumericalConstants.hh" #include "NumericalConstants.hh"
#include "DataTree.hh" #include "DataTree.hh"
#include "OperatorTable.hh"
#include "BlockTriangular.hh"
//! Stores a model's equations and derivatives //! Stores a model's equations and derivatives
class ModelTree : public DataTree class ModelTree : public DataTree
@ -50,9 +52,10 @@ private:
//! Computes derivatives of ModelTree //! Computes derivatives of ModelTree
void derive(int order); void derive(int order);
void GetDerivatives(ostream &output, int eq, int var, int lag, bool is_dynamic, const temporary_terms_type &temporary_terms) const;
//! Computes temporary terms //! Computes temporary terms
void computeTemporaryTerms(int order); void computeTemporaryTerms(int order);
void computeTemporaryTermsOrdered(int order, Model_Block *ModelBlock);
//! Writes temporary terms //! Writes temporary terms
void writeTemporaryTerms(ostream &output, bool is_dynamic) const; void writeTemporaryTerms(ostream &output, bool is_dynamic) const;
//! Writes local parameters //! Writes local parameters
@ -64,7 +67,8 @@ private:
void writeStaticModel(ostream &StaticOutput) const; void writeStaticModel(ostream &StaticOutput) const;
//! Writes the dynamic model equations and its derivatives //! Writes the dynamic model equations and its derivatives
/*! \todo add third derivatives handling in C output */ /*! \todo add third derivatives handling in C output */
void writeDynamicModel(ostream &DynamicOutput) const; void writeDynamicModel(ostream &DynamicOutput, Model_Block *ModelBlock) const;
void writeModelEquationsOrdered(ostream &output, bool is_dynamic, Model_Block *ModelBlock) const;
//! Writes static model file (Matlab version) //! Writes static model file (Matlab version)
void writeStaticMFile(const string &static_basename) const; void writeStaticMFile(const string &static_basename) const;
//! Writes static model file (C version) //! Writes static model file (C version)
@ -74,6 +78,10 @@ private:
//! Writes dynamic model file (C version) //! Writes dynamic model file (C version)
/*! \todo add third derivatives handling */ /*! \todo add third derivatives handling */
void writeDynamicCFile(const string &dynamic_basename) const; void writeDynamicCFile(const string &dynamic_basename) const;
//! Evaluates part of a model tree
inline double Evaluate_Expression(NodeID StartID);
inline void Evaluate_Jacobian();
inline void BlockLinear(Model_Block *ModelBlock);
public: public:
ModelTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants); ModelTree(SymbolTable &symbol_table_arg, NumericalConstants &num_constants);
@ -100,6 +108,12 @@ public:
void writeStaticFile(const string &basename) const; void writeStaticFile(const string &basename) const;
//! Writes dynamic model file //! Writes dynamic model file
void writeDynamicFile(const string &basename) const; void writeDynamicFile(const string &basename) const;
void SaveCFiles(Model_Block* ModelBlock, std::string Model_file_name, std::ofstream &mDynamicModelFile) const;
void writeDynamicInitCFile(ostream &mDynamicModelFile);
string reform(string name) const;
//! Complete set to block decompose the model
BlockTriangular block_triangular;
int equation_number() const;
}; };
#endif #endif

View File

@ -0,0 +1,63 @@
#ifndef MODEL_GRAPH
#define MODEL_GRAPH
#define DIRECT_COMPUTE
#define SORTED
#define SIMPLIFY
#define SIMPLIFYS
#define SAVE
#define COMPUTE
#define PRINT_OUT_OUT
#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

@ -3,6 +3,8 @@
#include <iostream> #include <iostream>
#include <math.h>
#include "ModFile.hh" #include "ModFile.hh"
#include "Expression.hh" #include "Expression.hh"
#include "TmpSymbolTable.hh" #include "TmpSymbolTable.hh"
@ -144,6 +146,14 @@ public:
bool exists_symbol(const char *s); bool exists_symbol(const char *s);
//! Sets variable offset of ModelTree class to use C output //! Sets variable offset of ModelTree class to use C output
void use_dll(); void use_dll();
//! Sets variable offset of ModelTree class to block decompose the model and to use C output
void sparse_dll();
//! Initialize the model => creation of the incidence matrix
void initialize_model();
//! 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 by adding it to SymbolTable //! Declares an endogenous variable by adding it to SymbolTable
void declare_endogenous(string *name, string *tex_name = new string); void declare_endogenous(string *name, string *tex_name = new string);
//! Declares an exogenous variable by adding it to SymbolTable //! Declares an exogenous variable by adding it to SymbolTable
@ -172,6 +182,8 @@ public:
ExpObj *add_expression_token(ExpObj *arg1, string *op_name); ExpObj *add_expression_token(ExpObj *arg1, string *op_name);
//! Adds a "periods" statement //! Adds a "periods" statement
void periods(string *periods); void periods(string *periods);
//! Adds a "cutoff" statement
void cutoff(string *cutoff);
//! Adds a "dsample" statement //! Adds a "dsample" statement
void dsample(string *arg1); void dsample(string *arg1);
//! Adds a "dsample" statement //! Adds a "dsample" statement
@ -242,6 +254,10 @@ public:
void rplot(); void rplot();
//! Writes a stock_simul command //! Writes a stock_simul command
void stoch_simul(); 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 //! Writes a simul command
void simul(); void simul();
//! Writes check command //! Writes check command

View File

@ -0,0 +1,92 @@
#ifndef SYMBGAUSSELIM
#define SYMBGAUSSELIM
//------------------------------------------------------------------------------
/*! \file
\version 1.0
\date 28/10/2006
\par This file defines the BlockTriangular class.
*/
//------------------------------------------------------------------------------
#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 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);
};
//------------------------------------------------------------------------------
#endif

View File

@ -27,10 +27,11 @@ private:
vector<int> mSortedVariableID; vector<int> mSortedVariableID;
//! For each variable, gives its index number among variables of the same type //! For each variable, gives its index number among variables of the same type
/*! It is the index used in the output file: /*! It is the index used in the output file:
- in the lead/lag matrix - in the lead/lag matrix
- in the right hand side of equations (such as y(index)) - in the right hand side of equations (such as y(index))
*/ */
vector<int> mPrintFormatIndex; vector<int> mPrintFormatIndex;
map<pair<int, int>, int> mVariableSelector;
public: public:
VariableTable(const SymbolTable &symbol_table_arg); VariableTable(const SymbolTable &symbol_table_arg);
//! Number of dynamic endogenous variables inside the model block //! Number of dynamic endogenous variables inside the model block
@ -81,8 +82,28 @@ public:
void Sort(); void Sort();
//! Get the number of dynamic variables //! Get the number of dynamic variables
inline int get_dyn_var_nbr(void) const; inline int get_dyn_var_nbr(void) const;
int* GetVariableTable(int* Size, int* HSize);
int getIDS(int id, int lead_lag) const;
void setmVariableSelector();
int getmVariableSelector(int var, int lag) const;
}; };
inline void
VariableTable::setmVariableSelector()
{
for(int var = 0; var < (int) mVariableTable.size(); var++)
{
if(getType(var)==eEndogenous)
mVariableSelector[make_pair(getSymbolID(var),mVariableIndex[var].second)]=var;
}
}
inline int
VariableTable::getmVariableSelector(int var, int lag) const
{
return(mVariableSelector.find(make_pair(var,lag))->second);
}
inline int inline int
VariableTable::getSortID(int iVarID) const VariableTable::getSortID(int iVarID) const
{ {

View File

@ -0,0 +1,51 @@
#ifndef _INTERPRETE_HH
#define _INTERPRETE_HH
#include <stack>
#include <map>
#include <string>
#include <iostream>
#include "SymbolTable.hh"
#include "VariableTable.hh"
#include "ExprNode.hh"
//#define PRINT_IT
using namespace std;
typedef struct t_val_index
{
int index,type,indexed;
double value;
};
typedef struct t_val1_index
{
string name;
double value;
};
typedef stack<double> STACK_SIMPLE00;
typedef map<string, t_val_index, less<string > > t_map_to_val_index;
typedef map<int, t_val1_index > t_map_int;
class interprete
{
public:
double cutoff;
bool eval;
double u1, u2;
STACK_SIMPLE00 Stack;
interprete();
double S_to_Val(string *str);
double get_value(string *str, double ll);
void put_value(string *str, int num,int Type, double val);
void print_all();
void create_id_map(int* Table, int Size, int HSize);
double GetDataValue(/*NodeID*/int id, Type type);
void set_cutoff(double r);
private:
string tmp_put_value_name;
t_map_to_val_index variable;
t_map_int i_endo_variable, i_exo_variable, i_param_variable;
};
#endif

95
parser.src/interprete.cc Normal file
View File

@ -0,0 +1,95 @@
#include "interprete.hh"
interprete::interprete()
{
eval=true;
cutoff=1.0e-6;
}
void
interprete::set_cutoff(double r)
{
cutoff=r;
}
double
interprete::S_to_Val(string *str)
{
double v=atof((*str).c_str());
#ifdef PRINT_IT
cout << "v=" << v << "\n";
#endif
return(v);
}
double
interprete::get_value(string *str, double ll)
{
#ifdef PRINT_IT
cout << "value[" << *str << "]=" << variable[(*str)].value << "\n";
#endif
return(variable[(*str)].value);
}
void
interprete::put_value(string *str, int num,int Type, double val)
{
#ifdef PRINT_IT
cout << "*str=" << *str << " val=" << val << "\n";
#endif
tmp_put_value_name=*str;
variable[(*str)].value=val;
variable[(*str)].index=num;
variable[(*str)].type=Type;
}
void
interprete::print_all()
{
map<string, t_val_index>::iterator iter;
for( iter = variable.begin(); iter != variable.end(); iter++ )
{
cout << "Name= " << iter->first << ", Value= " << iter->second.value << ", Index= " << iter->second.index << ", Type= " << iter->second.type << ", Indexed=" << iter->second.index << endl;
}
}
void
interprete::create_id_map(int *Table, int Size, int HSize)
{
map<string, t_val_index>::iterator iter;
for( iter = variable.begin(); iter != variable.end(); iter++ )
{
if(iter->second.type==0)
{
i_endo_variable[iter->second.index].name=iter->first;
i_endo_variable[iter->second.index].value=iter->second.value;
}
else if(iter->second.type==1)
{
i_exo_variable[iter->second.index].name=iter->first;
i_exo_variable[iter->second.index].value=iter->second.value;
}
else if(iter->second.type==4)
{
i_param_variable[iter->second.index].name=iter->first;
i_param_variable[iter->second.index].value=iter->second.value;
}
}
}
double
interprete::GetDataValue(int id, Type type)
{
switch(type)
{
case eParameter:
return(i_param_variable[(long int) id].value);
case eEndogenous:
return(i_endo_variable[(long int) id].value);
case eExogenous:
return(i_exo_variable[(long int) id].value);
default:
cerr << "interprete::GetDataValue: unhandled type!!";
exit(-1);
}
}