From 68b552aef2b7b9ee76fd4e3f3db7d6560dd62a9e Mon Sep 17 00:00:00 2001 From: michel Date: Wed, 4 Oct 2006 18:32:33 +0000 Subject: [PATCH] v4 parser.src: undoing rev. 944 git-svn-id: https://www.dynare.org/svn/dynare/dynare_v4@945 ac1d8469-bf42-47a9-8791-bf33cf982152 --- parser.src/DynareBison.yy | 2029 +++++++------ parser.src/DynareFlex.ll | 59 +- parser.src/DynareParser.cc | 96 +- parser.src/ModelTree.cc | 3583 +++++++++-------------- parser.src/VariableTable.cc | 128 +- parser.src/include/DynareBison.h | 700 +++-- parser.src/include/DynareParser.h | 47 +- parser.src/include/ModelTree.h | 30 +- parser.src/include/VariableTable.h | 36 +- parser.src/include/ylmm/basic_buffer.hh | 240 +- 10 files changed, 3025 insertions(+), 3923 deletions(-) diff --git a/parser.src/DynareBison.yy b/parser.src/DynareBison.yy index 9256b280b..04e0865d9 100644 --- a/parser.src/DynareBison.yy +++ b/parser.src/DynareBison.yy @@ -1,1017 +1,1012 @@ -%{ - /* Declarations */ -#include "DynareParser.h" -#define yyparse tcparse -#define yylex tclex -//#define yyerror tcerror -#define yylval tclval -#define yychar tcchar -//#define yydebug -#define YYDEBUG 1 -#define yynerrs tcnerrs -//#define YYLSP_NEEDED 1 -#define YYERROR_VERBOSE -#define YLMM_PARSER_CLASS dynare::parser -#define YLMM_LEX_STATIC -#include "ylmm/yaccmm.hh" -#ifdef yyerror -#undef yyerror -#define yyerror _parser->error -#endif -%} -/* %pure_parser */ -%token AR AUTOCORR -%token BAYESIAN_IRF BETA_PDF -%token CALIB CALIB_VAR CHECK CONF_SIG CORR COVAR -%token DATAFILE DIAGNOSTIC DIFFUSE_D /*New*/ DLL /*EndNew*/ DOLLAR DR_ALGO DROP DSAMPLE DYN2VEC DYNASAVE DYNATYPE -%token END ENDVAL EQUAL ESTIMATION ESTIMATED_PARAMS ESTIMATED_PARAMS_BOUNDS ESTIMATED_PARAMS_INIT -%token FILTERED_VARS FIRST_OBS FLOAT_NUMBER FORECAST FUNCTIONS -%token GAMMA_PDF GRAPH -%token HISTVAL HP_FILTER HP_NGRID -%token INITVAL INITVALF INT_NUMBER INV_GAMMA_PDF INV_GAMMA1_PDF INV_GAMMA2_PDF IRF -%token KALMAN_ALGO KALMAN_TOL CONSTANT NOCONSTANT -%token LAPLACE LIK_ALGO LIK_INIT LINEAR LOAD_MH_FILE LOGLINEAR -%token MH_DROP MH_INIT_SCALE MH_JSCALE MH_MODE MH_NBLOCKS MH_REPLIC MODE_CHECK MODE_COMPUTE MODE_FILE MODEL MODEL_COMPARISON MODEL_COMPARISON_APPROXIMATION MODIFIEDHARMONICMEAN MOMENTS MOMENTS_VARENDO MSHOCKS -%token NAME NOBS NOCORR NODIAGNOSTIC NOFUNCTIONS NOGRAPH XLS_SHEET XLS_RANGE -%token NOMOMENTS NOPRINT NORMAL_PDF -%token OBSERVATION_TRENDS OLR OLR_INST OLR_BETA OPTIM OPTIM_WEIGHTS ORDER OSR OSR_PARAMS -%token PARAMETERS PERIODS PREFILTER PRESAMPLE PRINT PRIOR_TRUNC FILTER_STEP_AHEAD -%token QZ_CRITERIUM -%token RELATIVE_IRF REPLIC RESOL RPLOT -%token SHOCKS SIGMA_E SIMUL SIMUL_ALGO SIMUL_SEED SMOOTHER SOLVE_ALGO STDERR STEADY STOCH_SIMUL -%token TEX TEX_NAME -%token UNIFORM_PDF UNIT_ROOT_VARS USE_DLL -%token VALUES VAR VAREXO VAREXO_DET VAROBS -%token XTICK XTICKLABEL -%left COMMA -%left PLUS MINUS -%left TIMES DIVIDE -%left UMINUS -%right POWER -%nonassoc FACTORIAL -%token EXP LOG LOG10 LN SIN COS TAN ASIN ACOS ATAN SINH COSH TANH ASINH ACOSH ATANH SQRT -/* isn't parsed from the *.mod file, but used to distinguish EQUAL in equation and EQUAL in assignment in operation codes -*/ -%token ASSIGN -%% - - statement_list - : statement - | statement_list statement - ; - - statement - : declaration - | periods - | model - | initval - | endval - | histval - | equality_expression - | shocks - | mshocks - | sigma_e - | steady - | check - | simul - | stoch_simul - | estimation - | estimated_params - | estimated_params_bounds - | estimated_params_init - | varobs - | observation_trends - | unit_root_vars - | dsample - | rplot - | optim_weights - | osr_params - | osr - | calib_var - | calib - | dynatype - | dynasave - | olr - | olr_inst - | model_comparison - ; - - - declaration - : parameters - | var - | varexo - | varexo_det - ; - - - dsample : DSAMPLE INT_NUMBER ';' {_parser->option_num("dsample",$2);} - | DSAMPLE INT_NUMBER INT_NUMBER ';' {_parser->option_num("dsample",$2,$3);} - ; - - rplot : RPLOT tmp_var_list ';' {_parser->rplot();} - ; - var - : VAR var_list ';' - ; - - varexo - : VAREXO varexo_list ';' - ; - - varexo_det - : VAREXO_DET varexo_det_list ';' - ; - - parameters - : PARAMETERS parameter_list ';' - ; - - var_list - : var_list NAME - {$$ = _parser->add_endogenous($2);} - | var_list COMMA NAME - {$$ = _parser->add_endogenous($3);} - | NAME - {$$ = _parser->add_endogenous($1);} - | var_list NAME TEX_NAME - {$$ = _parser->add_endogenous($2,$3);} - | var_list COMMA NAME TEX_NAME - {$$ = _parser->add_endogenous($3,$4);} - | NAME TEX_NAME - {$$ = _parser->add_endogenous($1,$2);} - ; - - varexo_list - : varexo_list NAME - {$$ = _parser->add_exogenous($2);} - | varexo_list COMMA NAME - {$$ = _parser->add_exogenous($3);} - | NAME - {$$ = _parser->add_exogenous($1);} - | varexo_list NAME TEX_NAME - {$$ = _parser->add_exogenous($2, $3);} - | varexo_list COMMA NAME TEX_NAME - {$$ = _parser->add_exogenous($3, $4);} - | NAME TEX_NAME - {$$ = _parser->add_exogenous($1, $2);} - ; - - varexo_det_list - : varexo_det_list NAME - {$$ = _parser->add_exogenous_det($2);} - | varexo_det_list COMMA NAME - {$$ = _parser->add_exogenous_det($3);} - | NAME - {$$ = _parser->add_exogenous_det($1);} - | varexo_det_list NAME TEX_NAME - {$$ = _parser->add_exogenous_det($2, $3);} - | varexo_det_list COMMA NAME TEX_NAME - {$$ = _parser->add_exogenous_det($3, $4);} - | NAME TEX_NAME - {$$ = _parser->add_exogenous_det($1, $2);} - ; - - parameter_list - : parameter_list NAME - {$$ = _parser->add_parameter($2);} - | parameter_list COMMA NAME - {$$ = _parser->add_parameter($3);} - | NAME - {$$ = _parser->add_parameter($1);} - | parameter_list NAME TEX_NAME - {$$ = _parser->add_parameter($2, $3);} - | parameter_list COMMA NAME TEX_NAME - {$$ = _parser->add_parameter($3,$4);} - | NAME TEX_NAME - {$$ = _parser->add_parameter($1, $2);} - ; - - periods - : PERIODS INT_NUMBER ';' - { - _parser->option_num("periods",$2); - _parser->option_num("simul","1"); - } - | PERIODS EQUAL INT_NUMBER ';' - { - _parser->option_num("periods",$3); - _parser->option_num("simul","1"); - } - ; - - - equality_expression - : NAME EQUAL expression {$$ = _parser->get_expression($3);} ';' - {_parser->init_param($1, $4);} - ; - - expression - : '(' expression ')' - { $$ = $2;} - | NAME - {$$ = _parser->translate_symbol($1);} - | FLOAT_NUMBER - {$$ = _parser->add_constant($1);} - | INT_NUMBER - {$$ = _parser->add_constant($1);} - | expression PLUS expression - {$$ = _parser->add_expression_token($1,$3, $2);} - | expression MINUS expression - {$$ = _parser->add_expression_token($1,$3, $2);} - | expression DIVIDE expression - {$$ = _parser->add_expression_token($1,$3, $2);} - | expression TIMES expression - {$$ = _parser->add_expression_token($1,$3, $2);} - | expression POWER expression - {$$ = _parser->add_expression_token($1,$3, $2);} - | MINUS expression %prec UMINUS - {$1->opcode = UMINUS;$$ = _parser->add_expression_token($2,$1);} - | PLUS expression - {$$ = $2;} - | EXP '(' expression ')' - {$$ = _parser->add_expression_token($3, $1);} - | LOG '(' expression ')' - {$$ = _parser->add_expression_token($3, $1);} - | LOG10 '(' expression ')' - {$$ = _parser->add_expression_token($3, $1);} - | LN '(' expression ')' - {$$ = _parser->add_expression_token($3, $1);} - | SIN '(' expression ')' - {$$ = _parser->add_expression_token($3, $1);} - | COS '(' expression ')' - {$$ = _parser->add_expression_token($3, $1);} - | TAN '(' expression ')' - {$$ = _parser->add_expression_token($3, $1);} - | ASIN '(' expression ')' - {$$ = _parser->add_expression_token($3, $1);} - | ACOS '(' expression ')' - {$$ = _parser->add_expression_token($3, $1);} - | ATAN '(' expression ')' - {$$ = _parser->add_expression_token($3, $1);} - | SQRT '(' expression ')' - {$$ = _parser->add_expression_token($3, $1);} - | NAME '(' expression ')' - {$$ = _parser->add_expression_token($3, $1);} - | NAME '(' comma_expression ')' - {$$ = _parser->add_expression_token($3, $1);} - ; - - comma_expression : expression COMMA expression {$$ = _parser->add_expression_token($1,$3,$2);} - | comma_expression COMMA expression {$$ = _parser->add_expression_token($1,$3,$2);} - - initval - : INITVAL ';' {_parser->begin_initval();} initval_list END - {_parser->end_initval();} - ; - - endval - : ENDVAL ';' {_parser->begin_endval();} initval_list END - {_parser->end_endval();} - ; - - initval_list - : initval_list initval_elem - | initval_elem - ; - - initval_elem - : NAME EQUAL expression {$$ = _parser->get_expression($3);} ';' - {_parser->init_val($1, $4);} - ; - - histval - : HISTVAL ';' {_parser->begin_histval();} histval_list END - - histval_list - : histval_list histval_elem - | histval_elem - ; - - histval_elem - : NAME '(' signed_integer ')' EQUAL expression ';' - {_parser->hist_val($1, $3, $6);} - ; - - model - : MODEL {_parser->initialize_model();} ';' equation_list END - {_parser->check_model();} - | MODEL '(' LINEAR ')' ';' {_parser->option_num("linear","1"); - _parser->initialize_model();} - equation_list END {_parser->check_model();} - | MODEL '(' USE_DLL ')' ';' {_parser->use_dll(); - _parser->initialize_model();} - equation_list END {_parser->check_model();} - /*New*/ - | MODEL '(' DLL ')' ';' {_parser->dll(); - _parser->initialize_model();} - equation_list END {_parser->check_model();} - /*EnbdNew*/ - ; - - equation_list - : equation_list equation - | equation_list pound_expression - | equation - | pound_expression - ; - - equation - : hand_side EQUAL hand_side ';' - {$$ = _parser->add_equal($1,$3);} - | hand_side ';' - {$$ = _parser->add_equal($1);} - ; - - hand_side - : '(' hand_side ')' {$$ = $2;} - | model_var - | FLOAT_NUMBER - {$$ = _parser->add_model_constant($1);} - | INT_NUMBER - {$1->symbol += ".0";$$ = _parser->add_model_constant($1);} - | hand_side PLUS hand_side - {$$ = _parser->add_plus($1,$3);} - | hand_side MINUS hand_side - {$$ = _parser->add_minus($1,$3);} - | hand_side DIVIDE hand_side - {$$ = _parser->add_divide($1,$3);} - | hand_side TIMES hand_side - {$$ = _parser->add_times($1,$3);} - | hand_side POWER hand_side - {$$ = _parser->add_power($1,$3);} - | MINUS hand_side %prec UMINUS - {$1->opcode = UMINUS;$$ = _parser->add_uminus($2);} - | PLUS hand_side - {$$ = $2;} - | EXP '(' hand_side ')' - {$$ = _parser->add_exp($3);} - | LOG '(' hand_side ')' - {$$ = _parser->add_log($3);} - | LOG10 '(' hand_side ')' - {$$ = _parser->add_log10($3);} - | LN '(' hand_side ')' - {$$ = _parser->add_log($3);} - | SIN '(' hand_side ')' - {$$ = _parser->add_sin($3);} - | COS '(' hand_side ')' - {$$ = _parser->add_cos($3);} - | TAN '(' hand_side ')' - {$$ = _parser->add_tan($3);} - | ASIN '(' hand_side ')' - {$$ = _parser->add_asin($3);} - | ACOS '(' hand_side ')' - {$$ = _parser->add_acos($3);} - | ATAN '(' hand_side ')' - {$$ = _parser->add_atan($3);} - | SQRT '(' hand_side ')' - {$$ = _parser->add_sqrt($3);} - ; - - pound_expression: '#' NAME - {$$ = _parser->add_local_parameter($2);} - EQUAL hand_side ';' - {$$ = _parser->init_local_parameter($3,$5);} - - model_var - : NAME - {$$ = _parser->add_variable($1);} - | NAME '(' signed_integer ')' - {$$ = _parser->add_variable($1,$3);} - ; - - shocks - : SHOCKS ';' {_parser->begin_shocks();} shock_list END {_parser->end_shocks();} - ; - - mshocks - : MSHOCKS ';' {_parser->begin_mshocks();} shock_list END {_parser->end_shocks();} - ; - - shock_list - : shock_list shock_elem - | shock_elem - ; - - shock_elem - : VAR NAME ';' PERIODS period_list ';' VALUES value_list ';' - {_parser->add_det_shock($2);} - | VAR NAME ';' STDERR expression {$$ = _parser->get_expression($5);} ';' - {_parser->add_stderr_shock($2, $6);} - | VAR NAME EQUAL expression {$$ = _parser->get_expression($4);} ';' - {_parser->add_var_shock($2, $5);} - | VAR NAME COMMA NAME EQUAL expression {$$ = _parser->get_expression($6);} ';' - {_parser->add_covar_shock($2, $4, $7);} - | CORR NAME COMMA NAME EQUAL expression {$$ = _parser->get_expression($6);} ';' - {_parser->add_correl_shock($2, $4, $7);} - ; - - period_list - : period_list INT_NUMBER - {_parser->add_period($2);} - | period_list INT_NUMBER ':' INT_NUMBER - {_parser->add_period($2,$4);} - | period_list COMMA INT_NUMBER - {_parser->add_period($3);} - | period_list COMMA INT_NUMBER ':' INT_NUMBER - {_parser->add_period($3,$5);} - | INT_NUMBER ':' INT_NUMBER - {_parser->add_period($1,$3);} - | INT_NUMBER - {_parser->add_period($1);} - ; - - - value_list - : value_list signed_float - {_parser->add_value($2);} - | value_list signed_integer - {_parser->add_value($2);} - | value_list NAME - {_parser->add_value($2);} - | signed_float - {_parser->add_value($1);} - | signed_integer - {_parser->add_value($1);} - | NAME - {_parser->add_value($1);} - | value_list '(' expression {$$ = _parser->get_expression($3);} ')' - {_parser->add_value($4);} - | '(' expression {$$ = _parser->get_expression($2);} ')' - {_parser->add_value($3);} - ; - - sigma_e - : SIGMA_E EQUAL '[' triangular_matrix ']' ';' - {_parser->do_sigma_e();} - ; - - triangular_matrix - : triangular_matrix ';' triangular_row - {_parser->end_of_row();} - | triangular_row - {_parser->end_of_row();} - ; - - triangular_row - : triangular_row COMMA '(' expression {$$ = _parser->get_expression($4);} ')' - {_parser->add_to_row($5);} - | triangular_row COMMA FLOAT_NUMBER - {_parser->add_to_row($3);} - | triangular_row COMMA INT_NUMBER - {_parser->add_to_row($3);} - | triangular_row '(' expression {$$ = _parser->get_expression($3);} ')' - {_parser->add_to_row($4);} - | triangular_row FLOAT_NUMBER - {_parser->add_to_row($2);} - | triangular_row INT_NUMBER - {_parser->add_to_row($2);} - | '(' expression {$$ = _parser->get_expression($2);} ')' - {_parser->add_to_row($3);} - | FLOAT_NUMBER - {_parser->add_to_row($1);} - | INT_NUMBER - {_parser->add_to_row($1);} - ; - - steady - : STEADY ';' - { - _parser->steady(); - } - | STEADY '(' steady_options_list ')' ';' - {_parser->steady();} - ; - - steady_options_list : steady_options_list COMMA steady_options - | steady_options - ; - - steady_options: o_solve_algo - ; - - check - : CHECK ';' - {_parser->check();} - | CHECK '(' check_options_list ')' ';' - {_parser->check();} - ; - - check_options_list : check_options_list COMMA check_options - | check_options - ; - - check_options : o_solve_algo - ; - - simul - : SIMUL ';' - {_parser->simul();} - | SIMUL '(' simul_options_list ')' ';' - {_parser->simul();} - ; - - simul_options_list: simul_options_list COMMA simul_options - | simul_options - ; - - simul_options: o_periods - ; - - stoch_simul - : STOCH_SIMUL ';' - {_parser->stoch_simul();} - | STOCH_SIMUL '(' stoch_simul_options_list ')' ';' - {_parser->stoch_simul();} - | STOCH_SIMUL tmp_var_list ';' - {_parser->stoch_simul();} - | STOCH_SIMUL '(' stoch_simul_options_list ')' tmp_var_list ';' - {_parser->stoch_simul();} - ; - - stoch_simul_options_list: stoch_simul_options_list COMMA stoch_simul_options - | stoch_simul_options - ; - - stoch_simul_options : o_dr_algo - | o_solve_algo - | o_simul_algo - | o_linear - | o_order - | o_replic - | o_drop - | o_ar - | o_nocorr - | o_nofunction - | o_nomoments - | o_irf - | o_relative_irf - | o_hp_filter - | o_hp_ngrid - | o_periods - | o_simul - | o_simul_seed - | o_qz_criterium - ; - - tmp_var_list - : tmp_var_list NAME - {_parser->add_tmp_var($2);} - | tmp_var_list NAME EQUAL NAME - {_parser->add_tmp_var($2,$4);} - | tmp_var_list COMMA NAME - {_parser->add_tmp_var($3);} - | tmp_var_list COMMA NAME EQUAL NAME - {_parser->add_tmp_var($3,$5);} - | NAME - {_parser->add_tmp_var($1);} - | NAME EQUAL NAME - {_parser->add_tmp_var($1,$3);} - ; - - signed_integer - : PLUS INT_NUMBER - {$$ = $2;} - | MINUS INT_NUMBER - {$2->symbol.insert(0,"-"); $$ = $2;} - | INT_NUMBER - {$$ = $1;} - ; - - signed_float - : PLUS FLOAT_NUMBER - {$$ = $2;} - | MINUS FLOAT_NUMBER - {$2->symbol.insert(0,"-"); $$ = $2;} - | FLOAT_NUMBER - {$$ = $1;} - ; - - estimated_params - : ESTIMATED_PARAMS ';' {_parser->estimation_init();} estimated_list END - ; - - estimated_list - : estimated_list estimated_elem - {_parser->set_estimated_elements();} - | estimated_elem - {_parser->set_estimated_elements();} - ; - - estimated_elem - : estimated_elem1 COMMA estimated_elem2 ';' - ; - - estimated_elem1 - : STDERR NAME - {_parser->estim_params.type = 1; - _parser->estim_params.name = *$2; - } - | NAME - {_parser->estim_params.type = 2; - _parser->estim_params.name = *$1; - } - | CORR NAME COMMA NAME - {_parser->estim_params.type = 3; - _parser->estim_params.name = *$2; - _parser->estim_params.name2 = *$4; - } - ; - - estimated_elem2 - : prior COMMA estimated_elem3 - {_parser->estim_params.prior=*$1;} - | value COMMA prior COMMA estimated_elem3 - {_parser->estim_params.init_val=*$1; - _parser->estim_params.prior=*$3; - } - | value COMMA value COMMA value COMMA prior COMMA estimated_elem3 - {_parser->estim_params.init_val=*$1; - _parser->estim_params.low_bound=*$3; - _parser->estim_params.up_bound=*$5; - _parser->estim_params.prior=*$7; - } - | value - {_parser->estim_params.init_val=*$1;} - | value COMMA value COMMA value - {_parser->estim_params.init_val=*$1; - _parser->estim_params.low_bound=*$3; - _parser->estim_params.up_bound=*$5; - } - ; - - estimated_elem3 - : value COMMA value - {_parser->estim_params.mean=*$1; - _parser->estim_params.std=*$3; - } - | value COMMA value COMMA value - {_parser->estim_params.mean=*$1; - _parser->estim_params.std=*$3; - _parser->estim_params.p3=*$5; - } - | value COMMA value COMMA value COMMA value - {_parser->estim_params.mean=*$1; - _parser->estim_params.std=*$3; - _parser->estim_params.p3=*$5; - _parser->estim_params.p4=*$7; - } - | value COMMA value COMMA value COMMA value COMMA value - {_parser->estim_params.mean=*$1; - _parser->estim_params.std=*$3; - _parser->estim_params.p3=*$5; - _parser->estim_params.p4=*$7; - _parser->estim_params.jscale=*$9; - } - ; - - estimated_params_init: ESTIMATED_PARAMS_INIT ';' estimated_init_list END - ; - - estimated_init_list : estimated_init_list estimated_init_elem - {_parser->set_estimated_init_elements();} - | estimated_init_elem - {_parser->set_estimated_init_elements();} - ; - - estimated_init_elem : STDERR NAME COMMA value ';' - {_parser->estim_params.type = 1; - _parser->estim_params.name = *$2; - _parser->estim_params.init_val=*$4; - } - | CORR NAME COMMA NAME COMMA value ';' - {_parser->estim_params.type = 3; - _parser->estim_params.name = *$2; - _parser->estim_params.name2 = *$4; - _parser->estim_params.init_val=*$6; - } - | NAME COMMA value ';' - {_parser->estim_params.type = 2; - _parser->estim_params.name = *$1; - _parser->estim_params.init_val=*$3; - } - ; - - estimated_params_bounds: ESTIMATED_PARAMS_BOUNDS ';' estimated_bounds_list END - ; - - estimated_bounds_list : estimated_bounds_list estimated_bounds_elem - {_parser->set_estimated_bounds_elements();} - | estimated_bounds_elem - {_parser->set_estimated_bounds_elements();} - ; - - estimated_bounds_elem : STDERR NAME COMMA value COMMA value ';' - {_parser->estim_params.type = 1; - _parser->estim_params.name = *$2; - _parser->estim_params.low_bound=*$4; - _parser->estim_params.up_bound=*$6; - } - | CORR NAME COMMA NAME COMMA value COMMA value ';' - {_parser->estim_params.type = 3; - _parser->estim_params.name = *$2; - _parser->estim_params.name2 = *$4; - _parser->estim_params.low_bound=*$6; - _parser->estim_params.up_bound=*$8; - } - | NAME COMMA value COMMA value ';' - {_parser->estim_params.type = 2; - _parser->estim_params.name = *$1; - _parser->estim_params.low_bound=*$3; - _parser->estim_params.up_bound=*$5; - } - ; - - prior - : BETA_PDF - {$$ = new dynare::Objects("1");} - | GAMMA_PDF - {$$ = new dynare::Objects("2");} - | NORMAL_PDF - {$$ = new dynare::Objects("3");} - | INV_GAMMA_PDF - {$$ = new dynare::Objects("4");} - | UNIFORM_PDF - {$$ = new dynare::Objects("5");} - ; - - value - : {$$ = new dynare::Objects("NaN");} - | INT_NUMBER - | FLOAT_NUMBER - | NAME - | MINUS INT_NUMBER - {$2->symbol.insert(0,"-"); $$ = $2;} - | MINUS FLOAT_NUMBER - {$2->symbol.insert(0,"-"); $$ = $2;} - ; - - - - estimation - : ESTIMATION ';' - {_parser->run_estimation();} - | ESTIMATION '(' estimation_options_list ')' ';' - {_parser->run_estimation();} - | ESTIMATION tmp_var_list ';' - {_parser->run_estimation();} - | ESTIMATION '(' estimation_options_list ')' tmp_var_list ';' - {_parser->run_estimation();} - ; - - estimation_options_list - : estimation_options_list COMMA estimation_options - | estimation_options - ; - - estimation_options : o_datafile - | o_nobs - | o_first_obs - | o_prefilter - | o_presample - | o_lik_algo - | o_lik_init - | o_nograph - | o_conf_sig - | o_mh_replic - | o_mh_drop - | o_mh_jscale - | o_optim - | o_mh_init_scale - | o_mode_file - | o_mode_compute - | o_mode_check - | o_prior_trunc - | o_mh_mode - | o_mh_nblcks - | o_load_mh_file - | o_loglinear - | o_nodiagnostic - | o_bayesian_irf - | o_irf - | o_tex - | o_forecast - | o_smoother - | o_moments_varendo - | o_filtered_vars - | o_kalman_algo - | o_kalman_tol - | o_xls_sheet - | o_xls_range - | o_filter_step_ahead - | o_solve_algo - | o_constant - | o_noconstant - ; - - list_optim_option - : '\'' NAME '\'' COMMA '\'' NAME '\'' {_parser->optim_options($2,$6,2);} - | '\'' NAME '\'' COMMA value {_parser->optim_options($2,$5,2);} - ; - - optim_options - : list_optim_option - | optim_options COMMA list_optim_option - ; - - varobs - : VAROBS tmp_var_list ';' - {_parser->set_varobs();} - ; - - observation_trends - : OBSERVATION_TRENDS ';' {_parser->set_trend_init();} trend_list END - ; - - trend_list - : trend_list trend_element - | trend_element - ; - - trend_element : NAME '(' expression {$$ = _parser->get_expression($3);} ')' ';' {_parser->set_trend_element($1,$4);} - ; - - unit_root_vars : UNIT_ROOT_VARS tmp_var_list ';' {_parser->set_unit_root_vars();} - ; - - optim_weights : OPTIM_WEIGHTS ';' {_parser->begin_optim_weights();} optim_weights_list END - ; - - optim_weights_list : optim_weights_list NAME expression {$$=_parser->get_expression($3);} ';' {_parser->set_optim_weights($2, $4);} - | optim_weights_list NAME COMMA NAME expression {$$=_parser->get_expression($3);} ';' {_parser->set_optim_weights($2, $4, $6);} - | NAME expression {$$=_parser->get_expression($2);} ';' {_parser->set_optim_weights($1, $3);} - | NAME COMMA NAME expression {$$=_parser->get_expression($3);} ';' {_parser->set_optim_weights($1, $3, $5);} - ; - - osr_params : OSR_PARAMS tmp_var_list ';' {_parser->set_osr_params();} - ; - - osr : OSR ';' {_parser->run_osr();} - | OSR '(' olr_options ')' ';' {_parser->run_osr();} - | OSR tmp_var_list ';' {_parser->run_osr();} - | OSR '(' olr_options ')' tmp_var_list ';' {_parser->run_osr();} - ; - - olr : OLR ';' {_parser->run_olr();} - | OLR '(' olr_options ')' ';' {_parser->run_olr();} - | OLR tmp_var_list ';' {_parser->run_olr();} - | OLR '(' olr_options ')' tmp_var_list ';' {_parser->run_olr();} - ; - - olr_option : o_olr_beta - | stoch_simul_options_list - ; - - olr_options : olr_option - | olr_options COMMA olr_option - ; - - olr_inst : OLR_INST tmp_var_list ';' {_parser->set_olr_inst();} - ; - - calib_var : CALIB_VAR ';' {_parser->begin_calib_var();} calib_var_list END - ; - - calib_var_list : calib_var_list calib_arg1 - | calib_arg1 - ; - - calib_arg1 : NAME calib_arg2 EQUAL expression ';' {_parser->set_calib_var($1,$2,$4);} - | NAME COMMA NAME calib_arg2 EQUAL expression ';' {_parser->set_calib_var($1,$3,$4,$6);} - | AUTOCORR NAME '(' INT_NUMBER ')' calib_arg2 EQUAL expression ';' {_parser->set_calib_ac($2,$4,$6,$8);} - ; - - calib_arg2 : {$$ = new dynare::Objects("1");} - | '(' INT_NUMBER ')' {$$ = $2;} - | '(' FLOAT_NUMBER ')' {$$ = $2;} - ; - - calib : CALIB ';' {_parser->run_calib(0);} - | CALIB '(' COVAR ')' ';' {_parser->run_calib(1);} - ; - - dynatype : DYNATYPE '(' NAME ')'';' {_parser->run_dynatype($3);} - | DYNATYPE '(' NAME ')' tmp_var_list ';' {_parser->run_dynatype($3);} - | DYNATYPE NAME ';' {_parser->run_dynatype($2);} - | DYNATYPE '(' NAME '.' NAME ')'';' {_parser->run_dynatype($3,$5);} - | DYNATYPE '(' NAME '.' NAME ')' tmp_var_list ';' {_parser->run_dynatype($3,$5);} - | DYNATYPE NAME '.' NAME ';' {_parser->run_dynatype($2,$4);}; - - dynasave : DYNASAVE '(' NAME ')'';' {_parser->run_dynasave($3);} - | DYNASAVE '(' NAME ')' tmp_var_list ';' {_parser->run_dynasave($3);} - | DYNASAVE NAME ';' {_parser->run_dynasave($2);} - | DYNASAVE '(' NAME '.' NAME ')'';' {_parser->run_dynasave($3,$5);} - | DYNASAVE '(' NAME '.' NAME ')' tmp_var_list ';' {_parser->run_dynasave($3,$5);} - | DYNASAVE NAME '.' NAME ';' {_parser->run_dynasave($2,$4);}; - - model_comparison : MODEL_COMPARISON '(' model_comparison_options ')' {_parser->begin_model_comparison();} - filename_list ';' {_parser->run_model_comparison();} - ; - - model_comparison_options: model_comparison_options ',' model_comparison_option - | model_comparison_option - ; - - model_comparison_option : o_model_comparison_approximation - | o_print - | o_noprint - ; - - filename_list : filename {_parser->add_mc_filename($1);} - | filename_list ',' filename {_parser->add_mc_filename($3);} - | filename '(' value ')' {_parser->add_mc_filename($1,$3);} - | filename_list ',' filename '(' value ')' {_parser->add_mc_filename($3,$5);} - ; - - filename : filename_elem {$$=$1;} - | filename filename_elem {$$ = _parser->cat($1,$2);} - ; - - filename_elem : NAME - | '\\' {$$ = new dynare::Objects("\\");} - | '/' {$$ = new dynare::Objects("/");} - | ':' {$$ = new dynare::Objects(":");} - | '.' {$$ = new dynare::Objects(".");} - ; - - o_dr_algo: DR_ALGO EQUAL INT_NUMBER {_parser->option_num("dr_algo",$3);}; - o_solve_algo: SOLVE_ALGO EQUAL INT_NUMBER {_parser->option_num("solve_algo",$3);}; - o_simul_algo: SIMUL_ALGO EQUAL INT_NUMBER {_parser->option_num("simul_algo",$3);}; - o_linear: LINEAR {_parser->option_num("linear","1");}; - o_order: ORDER EQUAL INT_NUMBER {_parser->option_num("order",$3);}; - o_replic: REPLIC EQUAL INT_NUMBER {_parser->option_num("replic",$3);}; - o_drop: DROP EQUAL INT_NUMBER {_parser->option_num("drop",$3);}; - o_ar: AR EQUAL INT_NUMBER {_parser->option_num("ar",$3);}; - o_nocorr: NOCORR {_parser->option_num("nocorr","1");}; - o_nofunction: NOFUNCTIONS {_parser->option_num("nofunctions","1");}; - o_nomoments: NOMOMENTS {_parser->option_num("nomoments","1");}; - o_irf: IRF EQUAL INT_NUMBER {_parser->option_num("irf",$3);}; - o_hp_filter: HP_FILTER EQUAL INT_NUMBER {_parser->option_num("hp_filter",$3);}; - o_hp_ngrid: HP_NGRID EQUAL INT_NUMBER {_parser->option_num("hp_ngrid",$3);}; - o_periods: PERIODS EQUAL INT_NUMBER {_parser->option_num("periods",$3);_parser->option_num("simul","1");}; - o_simul: SIMUL {_parser->option_num("simul","1");}; - o_simul_seed: SIMUL_SEED EQUAL INT_NUMBER { _parser->option_num("simul_seed",$3)}; - o_qz_criterium: QZ_CRITERIUM EQUAL INT_NUMBER { _parser->option_num("qz_criterium",$3)} - | QZ_CRITERIUM EQUAL FLOAT_NUMBER { _parser->option_num("qz_criterium",$3)} - ; - o_datafile: DATAFILE EQUAL NAME {_parser->option_str("datafile",$3);}; - o_nobs: NOBS EQUAL vec_int {_parser->option_num("nobs",$3);} - | NOBS EQUAL INT_NUMBER {_parser->option_num("nobs",$3);} - ; - o_first_obs: FIRST_OBS EQUAL INT_NUMBER {_parser->option_num("first_obs",$3);}; - o_prefilter: PREFILTER EQUAL INT_NUMBER {_parser->option_num("prefilter",$3);}; - o_presample: PRESAMPLE EQUAL INT_NUMBER {_parser->option_num("presample",$3);}; - o_lik_algo: LIK_ALGO EQUAL INT_NUMBER {_parser->option_num("lik_algo",$3);}; - o_lik_init: LIK_INIT EQUAL INT_NUMBER {_parser->option_num("lik_init",$3);}; - o_nograph: NOGRAPH {_parser->option_num("nograph","1");}; - o_conf_sig: CONF_SIG EQUAL FLOAT_NUMBER {_parser->option_num("conf_sig",$3);}; - o_mh_replic: MH_REPLIC EQUAL INT_NUMBER {_parser->option_num("mh_replic",$3);}; - o_mh_drop: MH_DROP EQUAL FLOAT_NUMBER {_parser->option_num("mh_drop",$3);}; - o_mh_jscale: MH_JSCALE EQUAL FLOAT_NUMBER {_parser->option_num("mh_jscale",$3);}; - o_optim: OPTIM EQUAL '(' optim_options ')'; - o_mh_init_scale :MH_INIT_SCALE EQUAL FLOAT_NUMBER {_parser->option_num("mh_init_scale",$3);}; - o_mh_init_scale :MH_INIT_SCALE EQUAL INT_NUMBER {_parser->option_num("mh_init_scale",$3);}; - o_mode_file : MODE_FILE EQUAL NAME {_parser->option_str("mode_file",$3);}; - o_mode_compute : MODE_COMPUTE EQUAL INT_NUMBER {_parser->option_num("mode_compute",$3);}; - o_mode_check : MODE_CHECK {_parser->option_num("mode_check","1");}; - o_prior_trunc : PRIOR_TRUNC EQUAL FLOAT_NUMBER {_parser->option_num("prior_trunc",$3);}; - o_mh_mode : MH_MODE EQUAL INT_NUMBER {_parser->option_num("mh_mode",$3);}; - o_mh_nblcks : MH_NBLOCKS EQUAL INT_NUMBER {_parser->option_num("mh_nblck",$3);}; - o_load_mh_file : LOAD_MH_FILE {_parser->option_num("load_mh_file","1");}; - o_loglinear : LOGLINEAR {_parser->option_num("loglinear","1");}; - o_nodiagnostic : NODIAGNOSTIC {_parser->option_num("nodiagnostic","1");}; - o_bayesian_irf : BAYESIAN_IRF {_parser->option_num("bayesian_irf","1");}; - o_tex : TEX {_parser->option_num("TeX","1");}; - o_forecast : FORECAST EQUAL INT_NUMBER {_parser->option_num("forecast",$3);}; - o_smoother : SMOOTHER {_parser->option_num("smoother","1");}; - o_moments_varendo : MOMENTS_VARENDO {_parser->option_num("moments_varendo","1");}; - o_filtered_vars : FILTERED_VARS {_parser->option_num("filtered_vars","1");}; - o_relative_irf : RELATIVE_IRF {_parser->option_num("relative_irf","1");}; - o_kalman_algo : KALMAN_ALGO EQUAL INT_NUMBER {_parser->option_num("kalman_algo",$3);}; - o_kalman_tol : KALMAN_TOL EQUAL INT_NUMBER {_parser->option_num("kalman_tol",$3);}; - o_olr_beta: OLR_BETA EQUAL value {_parser->option_num("olr_beta",$3);}; - o_model_comparison_approximation: MODEL_COMPARISON_APPROXIMATION EQUAL LAPLACE {dynare::Objects* tmp = new dynare::Objects("Laplace");_parser->option_str("model_comparison_approximation",tmp);} - | MODEL_COMPARISON_APPROXIMATION EQUAL MODIFIEDHARMONICMEAN {dynare::Objects* tmp = new dynare::Objects("MODIFIEDHARMONICMEAN");_parser->option_str("model_comparison_approximation",tmp);} - ; - o_print : PRINT {_parser->option_num("noprint","0");}; - o_noprint : NOPRINT {_parser->option_num("noprint","1");}; - o_nograph : GRAPH {_parser->option_num("nograph","0");}; - o_xls_sheet : XLS_SHEET EQUAL NAME {_parser->option_str("xls_sheet",$3);} - o_xls_range : XLS_RANGE EQUAL range {_parser->option_str("xls_range",$3);} - o_filter_step_ahead : FILTER_STEP_AHEAD EQUAL vec_int {_parser->option_num("filter_step_ahead",$3);} - o_constant : CONSTANT {_parser->option_num("noconstant","0");} - o_noconstant : NOCONSTANT {_parser->option_num("noconstant","1");} - - range : NAME ':' NAME {$$ = new dynare::Objects(":");$$ = _parser->cat($1,$$);$$ = _parser->cat($$,$3);} - vec_int_elem : INT_NUMBER - | INT_NUMBER ':' {$$ = new dynare::Objects(":"); $$ = _parser->cat($1,$$); } - INT_NUMBER {$$ = _parser->cat($3,$4);} - ; - - vec_int_1 : '[' vec_int_elem {$$ = new dynare::Objects("["); $$ =_parser->cat($$,$2);} - | vec_int_1 vec_int_elem {$$ = _parser->cat_with_space($1,$2);} - ; - - vec_int : vec_int_1 ']' {$$ = new dynare::Objects("]"); $$ = _parser->cat($1,$$);}; - - %% +%{ + /* Declarations */ +#include "DynareParser.h" +#define yyparse tcparse +#define yylex tclex +//#define yyerror tcerror +#define yylval tclval +#define yychar tcchar +//#define yydebug +#define YYDEBUG 1 +#define yynerrs tcnerrs +//#define YYLSP_NEEDED 1 +#define YYERROR_VERBOSE +#define YLMM_PARSER_CLASS dynare::parser +#define YLMM_LEX_STATIC +#include "ylmm/yaccmm.hh" +#ifdef yyerror +#undef yyerror +#define yyerror _parser->error +#endif +%} +/* %pure_parser */ +%token AR AUTOCORR +%token BAYESIAN_IRF BETA_PDF +%token CALIB CALIB_VAR CHECK CONF_SIG CORR COVAR +%token DATAFILE DIAGNOSTIC DIFFUSE_D DOLLAR DR_ALGO DROP DSAMPLE DYN2VEC DYNASAVE DYNATYPE +%token END ENDVAL EQUAL ESTIMATION ESTIMATED_PARAMS ESTIMATED_PARAMS_BOUNDS ESTIMATED_PARAMS_INIT +%token FILTERED_VARS FIRST_OBS FLOAT_NUMBER FORECAST FUNCTIONS +%token GAMMA_PDF GRAPH +%token HISTVAL HP_FILTER HP_NGRID +%token INITVAL INITVALF INT_NUMBER INV_GAMMA_PDF INV_GAMMA1_PDF INV_GAMMA2_PDF IRF +%token KALMAN_ALGO KALMAN_TOL CONSTANT NOCONSTANT +%token LAPLACE LIK_ALGO LIK_INIT LINEAR LOAD_MH_FILE LOGLINEAR +%token MH_DROP MH_INIT_SCALE MH_JSCALE MH_MODE MH_NBLOCKS MH_REPLIC MODE_CHECK MODE_COMPUTE MODE_FILE MODEL MODEL_COMPARISON MODEL_COMPARISON_APPROXIMATION MODIFIEDHARMONICMEAN MOMENTS MOMENTS_VARENDO MSHOCKS +%token NAME NOBS NOCORR NODIAGNOSTIC NOFUNCTIONS NOGRAPH XLS_SHEET XLS_RANGE +%token NOMOMENTS NOPRINT NORMAL_PDF +%token OBSERVATION_TRENDS OLR OLR_INST OLR_BETA OPTIM OPTIM_WEIGHTS ORDER OSR OSR_PARAMS +%token PARAMETERS PERIODS PREFILTER PRESAMPLE PRINT PRIOR_TRUNC FILTER_STEP_AHEAD +%token QZ_CRITERIUM +%token RELATIVE_IRF REPLIC RESOL RPLOT +%token SHOCKS SIGMA_E SIMUL SIMUL_ALGO SIMUL_SEED SMOOTHER SOLVE_ALGO STDERR STEADY STOCH_SIMUL +%token TEX TEX_NAME +%token UNIFORM_PDF UNIT_ROOT_VARS USE_DLL +%token VALUES VAR VAREXO VAREXO_DET VAROBS +%token XTICK XTICKLABEL +%left COMMA +%left PLUS MINUS +%left TIMES DIVIDE +%left UMINUS +%right POWER +%nonassoc FACTORIAL +%token EXP LOG LOG10 LN SIN COS TAN ASIN ACOS ATAN SINH COSH TANH ASINH ACOSH ATANH SQRT +/* isn't parsed from the *.mod file, but used to distinguish EQUAL in equation and EQUAL in assignment in operation codes +*/ +%token ASSIGN +%% + + statement_list + : statement + | statement_list statement + ; + + statement + : declaration + | periods + | model + | initval + | endval + | histval + | equality_expression + | shocks + | mshocks + | sigma_e + | steady + | check + | simul + | stoch_simul + | estimation + | estimated_params + | estimated_params_bounds + | estimated_params_init + | varobs + | observation_trends + | unit_root_vars + | dsample + | rplot + | optim_weights + | osr_params + | osr + | calib_var + | calib + | dynatype + | dynasave + | olr + | olr_inst + | model_comparison + ; + + + declaration + : parameters + | var + | varexo + | varexo_det + ; + + + dsample : DSAMPLE INT_NUMBER ';' {_parser->option_num("dsample",$2);} + | DSAMPLE INT_NUMBER INT_NUMBER ';' {_parser->option_num("dsample",$2,$3);} + ; + + rplot : RPLOT tmp_var_list ';' {_parser->rplot();} + ; + var + : VAR var_list ';' + ; + + varexo + : VAREXO varexo_list ';' + ; + + varexo_det + : VAREXO_DET varexo_det_list ';' + ; + + parameters + : PARAMETERS parameter_list ';' + ; + + var_list + : var_list NAME + {$$ = _parser->add_endogenous($2);} + | var_list COMMA NAME + {$$ = _parser->add_endogenous($3);} + | NAME + {$$ = _parser->add_endogenous($1);} + | var_list NAME TEX_NAME + {$$ = _parser->add_endogenous($2,$3);} + | var_list COMMA NAME TEX_NAME + {$$ = _parser->add_endogenous($3,$4);} + | NAME TEX_NAME + {$$ = _parser->add_endogenous($1,$2);} + ; + + varexo_list + : varexo_list NAME + {$$ = _parser->add_exogenous($2);} + | varexo_list COMMA NAME + {$$ = _parser->add_exogenous($3);} + | NAME + {$$ = _parser->add_exogenous($1);} + | varexo_list NAME TEX_NAME + {$$ = _parser->add_exogenous($2, $3);} + | varexo_list COMMA NAME TEX_NAME + {$$ = _parser->add_exogenous($3, $4);} + | NAME TEX_NAME + {$$ = _parser->add_exogenous($1, $2);} + ; + + varexo_det_list + : varexo_det_list NAME + {$$ = _parser->add_exogenous_det($2);} + | varexo_det_list COMMA NAME + {$$ = _parser->add_exogenous_det($3);} + | NAME + {$$ = _parser->add_exogenous_det($1);} + | varexo_det_list NAME TEX_NAME + {$$ = _parser->add_exogenous_det($2, $3);} + | varexo_det_list COMMA NAME TEX_NAME + {$$ = _parser->add_exogenous_det($3, $4);} + | NAME TEX_NAME + {$$ = _parser->add_exogenous_det($1, $2);} + ; + + parameter_list + : parameter_list NAME + {$$ = _parser->add_parameter($2);} + | parameter_list COMMA NAME + {$$ = _parser->add_parameter($3);} + | NAME + {$$ = _parser->add_parameter($1);} + | parameter_list NAME TEX_NAME + {$$ = _parser->add_parameter($2, $3);} + | parameter_list COMMA NAME TEX_NAME + {$$ = _parser->add_parameter($3,$4);} + | NAME TEX_NAME + {$$ = _parser->add_parameter($1, $2);} + ; + + periods + : PERIODS INT_NUMBER ';' + { + _parser->option_num("periods",$2); + _parser->option_num("simul","1"); + } + | PERIODS EQUAL INT_NUMBER ';' + { + _parser->option_num("periods",$3); + _parser->option_num("simul","1"); + } + ; + + + equality_expression + : NAME EQUAL expression {$$ = _parser->get_expression($3);} ';' + {_parser->init_param($1, $4);} + ; + + expression + : '(' expression ')' + { $$ = $2;} + | NAME + {$$ = _parser->translate_symbol($1);} + | FLOAT_NUMBER + {$$ = _parser->add_constant($1);} + | INT_NUMBER + {$$ = _parser->add_constant($1);} + | expression PLUS expression + {$$ = _parser->add_expression_token($1,$3, $2);} + | expression MINUS expression + {$$ = _parser->add_expression_token($1,$3, $2);} + | expression DIVIDE expression + {$$ = _parser->add_expression_token($1,$3, $2);} + | expression TIMES expression + {$$ = _parser->add_expression_token($1,$3, $2);} + | expression POWER expression + {$$ = _parser->add_expression_token($1,$3, $2);} + | MINUS expression %prec UMINUS + {$1->opcode = UMINUS;$$ = _parser->add_expression_token($2,$1);} + | PLUS expression + {$$ = $2;} + | EXP '(' expression ')' + {$$ = _parser->add_expression_token($3, $1);} + | LOG '(' expression ')' + {$$ = _parser->add_expression_token($3, $1);} + | LOG10 '(' expression ')' + {$$ = _parser->add_expression_token($3, $1);} + | LN '(' expression ')' + {$$ = _parser->add_expression_token($3, $1);} + | SIN '(' expression ')' + {$$ = _parser->add_expression_token($3, $1);} + | COS '(' expression ')' + {$$ = _parser->add_expression_token($3, $1);} + | TAN '(' expression ')' + {$$ = _parser->add_expression_token($3, $1);} + | ASIN '(' expression ')' + {$$ = _parser->add_expression_token($3, $1);} + | ACOS '(' expression ')' + {$$ = _parser->add_expression_token($3, $1);} + | ATAN '(' expression ')' + {$$ = _parser->add_expression_token($3, $1);} + | SQRT '(' expression ')' + {$$ = _parser->add_expression_token($3, $1);} + | NAME '(' expression ')' + {$$ = _parser->add_expression_token($3, $1);} + | NAME '(' comma_expression ')' + {$$ = _parser->add_expression_token($3, $1);} + ; + + comma_expression : expression COMMA expression {$$ = _parser->add_expression_token($1,$3,$2);} + | comma_expression COMMA expression {$$ = _parser->add_expression_token($1,$3,$2);} + + initval + : INITVAL ';' {_parser->begin_initval();} initval_list END + {_parser->end_initval();} + ; + + endval + : ENDVAL ';' {_parser->begin_endval();} initval_list END + {_parser->end_endval();} + ; + + initval_list + : initval_list initval_elem + | initval_elem + ; + + initval_elem + : NAME EQUAL expression {$$ = _parser->get_expression($3);} ';' + {_parser->init_val($1, $4);} + ; + + histval + : HISTVAL ';' {_parser->begin_histval();} histval_list END + + histval_list + : histval_list histval_elem + | histval_elem + ; + + histval_elem + : NAME '(' signed_integer ')' EQUAL expression ';' + {_parser->hist_val($1, $3, $6);} + ; + + model + : MODEL {_parser->initialize_model();} ';' equation_list END + {_parser->check_model();} + | MODEL '(' LINEAR ')' ';' {_parser->option_num("linear","1"); + _parser->initialize_model();} + equation_list END {_parser->check_model();} + | MODEL '(' USE_DLL ')' ';' {_parser->use_dll(); + _parser->initialize_model();} + equation_list END {_parser->check_model();} + ; + + equation_list + : equation_list equation + | equation_list pound_expression + | equation + | pound_expression + ; + + equation + : hand_side EQUAL hand_side ';' + {$$ = _parser->add_equal($1,$3);} + | hand_side ';' + {$$ = _parser->add_equal($1);} + ; + + hand_side + : '(' hand_side ')' {$$ = $2;} + | model_var + | FLOAT_NUMBER + {$$ = _parser->add_model_constant($1);} + | INT_NUMBER + {$1->symbol += ".0";$$ = _parser->add_model_constant($1);} + | hand_side PLUS hand_side + {$$ = _parser->add_plus($1,$3);} + | hand_side MINUS hand_side + {$$ = _parser->add_minus($1,$3);} + | hand_side DIVIDE hand_side + {$$ = _parser->add_divide($1,$3);} + | hand_side TIMES hand_side + {$$ = _parser->add_times($1,$3);} + | hand_side POWER hand_side + {$$ = _parser->add_power($1,$3);} + | MINUS hand_side %prec UMINUS + {$1->opcode = UMINUS;$$ = _parser->add_uminus($2);} + | PLUS hand_side + {$$ = $2;} + | EXP '(' hand_side ')' + {$$ = _parser->add_exp($3);} + | LOG '(' hand_side ')' + {$$ = _parser->add_log($3);} + | LOG10 '(' hand_side ')' + {$$ = _parser->add_log10($3);} + | LN '(' hand_side ')' + {$$ = _parser->add_log($3);} + | SIN '(' hand_side ')' + {$$ = _parser->add_sin($3);} + | COS '(' hand_side ')' + {$$ = _parser->add_cos($3);} + | TAN '(' hand_side ')' + {$$ = _parser->add_tan($3);} + | ASIN '(' hand_side ')' + {$$ = _parser->add_asin($3);} + | ACOS '(' hand_side ')' + {$$ = _parser->add_acos($3);} + | ATAN '(' hand_side ')' + {$$ = _parser->add_atan($3);} + | SQRT '(' hand_side ')' + {$$ = _parser->add_sqrt($3);} + ; + + pound_expression: '#' NAME + {$$ = _parser->add_local_parameter($2);} + EQUAL hand_side ';' + {$$ = _parser->init_local_parameter($3,$5);} + + model_var + : NAME + {$$ = _parser->add_variable($1);} + | NAME '(' signed_integer ')' + {$$ = _parser->add_variable($1,$3);} + ; + + shocks + : SHOCKS ';' {_parser->begin_shocks();} shock_list END {_parser->end_shocks();} + ; + + mshocks + : MSHOCKS ';' {_parser->begin_mshocks();} shock_list END {_parser->end_shocks();} + ; + + shock_list + : shock_list shock_elem + | shock_elem + ; + + shock_elem + : VAR NAME ';' PERIODS period_list ';' VALUES value_list ';' + {_parser->add_det_shock($2);} + | VAR NAME ';' STDERR expression {$$ = _parser->get_expression($5);} ';' + {_parser->add_stderr_shock($2, $6);} + | VAR NAME EQUAL expression {$$ = _parser->get_expression($4);} ';' + {_parser->add_var_shock($2, $5);} + | VAR NAME COMMA NAME EQUAL expression {$$ = _parser->get_expression($6);} ';' + {_parser->add_covar_shock($2, $4, $7);} + | CORR NAME COMMA NAME EQUAL expression {$$ = _parser->get_expression($6);} ';' + {_parser->add_correl_shock($2, $4, $7);} + ; + + period_list + : period_list INT_NUMBER + {_parser->add_period($2);} + | period_list INT_NUMBER ':' INT_NUMBER + {_parser->add_period($2,$4);} + | period_list COMMA INT_NUMBER + {_parser->add_period($3);} + | period_list COMMA INT_NUMBER ':' INT_NUMBER + {_parser->add_period($3,$5);} + | INT_NUMBER ':' INT_NUMBER + {_parser->add_period($1,$3);} + | INT_NUMBER + {_parser->add_period($1);} + ; + + + value_list + : value_list signed_float + {_parser->add_value($2);} + | value_list signed_integer + {_parser->add_value($2);} + | value_list NAME + {_parser->add_value($2);} + | signed_float + {_parser->add_value($1);} + | signed_integer + {_parser->add_value($1);} + | NAME + {_parser->add_value($1);} + | value_list '(' expression {$$ = _parser->get_expression($3);} ')' + {_parser->add_value($4);} + | '(' expression {$$ = _parser->get_expression($2);} ')' + {_parser->add_value($3);} + ; + + sigma_e + : SIGMA_E EQUAL '[' triangular_matrix ']' ';' + {_parser->do_sigma_e();} + ; + + triangular_matrix + : triangular_matrix ';' triangular_row + {_parser->end_of_row();} + | triangular_row + {_parser->end_of_row();} + ; + + triangular_row + : triangular_row COMMA '(' expression {$$ = _parser->get_expression($4);} ')' + {_parser->add_to_row($5);} + | triangular_row COMMA FLOAT_NUMBER + {_parser->add_to_row($3);} + | triangular_row COMMA INT_NUMBER + {_parser->add_to_row($3);} + | triangular_row '(' expression {$$ = _parser->get_expression($3);} ')' + {_parser->add_to_row($4);} + | triangular_row FLOAT_NUMBER + {_parser->add_to_row($2);} + | triangular_row INT_NUMBER + {_parser->add_to_row($2);} + | '(' expression {$$ = _parser->get_expression($2);} ')' + {_parser->add_to_row($3);} + | FLOAT_NUMBER + {_parser->add_to_row($1);} + | INT_NUMBER + {_parser->add_to_row($1);} + ; + + steady + : STEADY ';' + { + _parser->steady(); + } + | STEADY '(' steady_options_list ')' ';' + {_parser->steady();} + ; + + steady_options_list : steady_options_list COMMA steady_options + | steady_options + ; + + steady_options: o_solve_algo + ; + + check + : CHECK ';' + {_parser->check();} + | CHECK '(' check_options_list ')' ';' + {_parser->check();} + ; + + check_options_list : check_options_list COMMA check_options + | check_options + ; + + check_options : o_solve_algo + ; + + simul + : SIMUL ';' + {_parser->simul();} + | SIMUL '(' simul_options_list ')' ';' + {_parser->simul();} + ; + + simul_options_list: simul_options_list COMMA simul_options + | simul_options + ; + + simul_options: o_periods + ; + + stoch_simul + : STOCH_SIMUL ';' + {_parser->stoch_simul();} + | STOCH_SIMUL '(' stoch_simul_options_list ')' ';' + {_parser->stoch_simul();} + | STOCH_SIMUL tmp_var_list ';' + {_parser->stoch_simul();} + | STOCH_SIMUL '(' stoch_simul_options_list ')' tmp_var_list ';' + {_parser->stoch_simul();} + ; + + stoch_simul_options_list: stoch_simul_options_list COMMA stoch_simul_options + | stoch_simul_options + ; + + stoch_simul_options : o_dr_algo + | o_solve_algo + | o_simul_algo + | o_linear + | o_order + | o_replic + | o_drop + | o_ar + | o_nocorr + | o_nofunction + | o_nomoments + | o_irf + | o_relative_irf + | o_hp_filter + | o_hp_ngrid + | o_periods + | o_simul + | o_simul_seed + | o_qz_criterium + ; + + tmp_var_list + : tmp_var_list NAME + {_parser->add_tmp_var($2);} + | tmp_var_list NAME EQUAL NAME + {_parser->add_tmp_var($2,$4);} + | tmp_var_list COMMA NAME + {_parser->add_tmp_var($3);} + | tmp_var_list COMMA NAME EQUAL NAME + {_parser->add_tmp_var($3,$5);} + | NAME + {_parser->add_tmp_var($1);} + | NAME EQUAL NAME + {_parser->add_tmp_var($1,$3);} + ; + + signed_integer + : PLUS INT_NUMBER + {$$ = $2;} + | MINUS INT_NUMBER + {$2->symbol.insert(0,"-"); $$ = $2;} + | INT_NUMBER + {$$ = $1;} + ; + + signed_float + : PLUS FLOAT_NUMBER + {$$ = $2;} + | MINUS FLOAT_NUMBER + {$2->symbol.insert(0,"-"); $$ = $2;} + | FLOAT_NUMBER + {$$ = $1;} + ; + + estimated_params + : ESTIMATED_PARAMS ';' {_parser->estimation_init();} estimated_list END + ; + + estimated_list + : estimated_list estimated_elem + {_parser->set_estimated_elements();} + | estimated_elem + {_parser->set_estimated_elements();} + ; + + estimated_elem + : estimated_elem1 COMMA estimated_elem2 ';' + ; + + estimated_elem1 + : STDERR NAME + {_parser->estim_params.type = 1; + _parser->estim_params.name = *$2; + } + | NAME + {_parser->estim_params.type = 2; + _parser->estim_params.name = *$1; + } + | CORR NAME COMMA NAME + {_parser->estim_params.type = 3; + _parser->estim_params.name = *$2; + _parser->estim_params.name2 = *$4; + } + ; + + estimated_elem2 + : prior COMMA estimated_elem3 + {_parser->estim_params.prior=*$1;} + | value COMMA prior COMMA estimated_elem3 + {_parser->estim_params.init_val=*$1; + _parser->estim_params.prior=*$3; + } + | value COMMA value COMMA value COMMA prior COMMA estimated_elem3 + {_parser->estim_params.init_val=*$1; + _parser->estim_params.low_bound=*$3; + _parser->estim_params.up_bound=*$5; + _parser->estim_params.prior=*$7; + } + | value + {_parser->estim_params.init_val=*$1;} + | value COMMA value COMMA value + {_parser->estim_params.init_val=*$1; + _parser->estim_params.low_bound=*$3; + _parser->estim_params.up_bound=*$5; + } + ; + + estimated_elem3 + : value COMMA value + {_parser->estim_params.mean=*$1; + _parser->estim_params.std=*$3; + } + | value COMMA value COMMA value + {_parser->estim_params.mean=*$1; + _parser->estim_params.std=*$3; + _parser->estim_params.p3=*$5; + } + | value COMMA value COMMA value COMMA value + {_parser->estim_params.mean=*$1; + _parser->estim_params.std=*$3; + _parser->estim_params.p3=*$5; + _parser->estim_params.p4=*$7; + } + | value COMMA value COMMA value COMMA value COMMA value + {_parser->estim_params.mean=*$1; + _parser->estim_params.std=*$3; + _parser->estim_params.p3=*$5; + _parser->estim_params.p4=*$7; + _parser->estim_params.jscale=*$9; + } + ; + + estimated_params_init: ESTIMATED_PARAMS_INIT ';' estimated_init_list END + ; + + estimated_init_list : estimated_init_list estimated_init_elem + {_parser->set_estimated_init_elements();} + | estimated_init_elem + {_parser->set_estimated_init_elements();} + ; + + estimated_init_elem : STDERR NAME COMMA value ';' + {_parser->estim_params.type = 1; + _parser->estim_params.name = *$2; + _parser->estim_params.init_val=*$4; + } + | CORR NAME COMMA NAME COMMA value ';' + {_parser->estim_params.type = 3; + _parser->estim_params.name = *$2; + _parser->estim_params.name2 = *$4; + _parser->estim_params.init_val=*$6; + } + | NAME COMMA value ';' + {_parser->estim_params.type = 2; + _parser->estim_params.name = *$1; + _parser->estim_params.init_val=*$3; + } + ; + + estimated_params_bounds: ESTIMATED_PARAMS_BOUNDS ';' estimated_bounds_list END + ; + + estimated_bounds_list : estimated_bounds_list estimated_bounds_elem + {_parser->set_estimated_bounds_elements();} + | estimated_bounds_elem + {_parser->set_estimated_bounds_elements();} + ; + + estimated_bounds_elem : STDERR NAME COMMA value COMMA value ';' + {_parser->estim_params.type = 1; + _parser->estim_params.name = *$2; + _parser->estim_params.low_bound=*$4; + _parser->estim_params.up_bound=*$6; + } + | CORR NAME COMMA NAME COMMA value COMMA value ';' + {_parser->estim_params.type = 3; + _parser->estim_params.name = *$2; + _parser->estim_params.name2 = *$4; + _parser->estim_params.low_bound=*$6; + _parser->estim_params.up_bound=*$8; + } + | NAME COMMA value COMMA value ';' + {_parser->estim_params.type = 2; + _parser->estim_params.name = *$1; + _parser->estim_params.low_bound=*$3; + _parser->estim_params.up_bound=*$5; + } + ; + + prior + : BETA_PDF + {$$ = new dynare::Objects("1");} + | GAMMA_PDF + {$$ = new dynare::Objects("2");} + | NORMAL_PDF + {$$ = new dynare::Objects("3");} + | INV_GAMMA_PDF + {$$ = new dynare::Objects("4");} + | UNIFORM_PDF + {$$ = new dynare::Objects("5");} + ; + + value + : {$$ = new dynare::Objects("NaN");} + | INT_NUMBER + | FLOAT_NUMBER + | NAME + | MINUS INT_NUMBER + {$2->symbol.insert(0,"-"); $$ = $2;} + | MINUS FLOAT_NUMBER + {$2->symbol.insert(0,"-"); $$ = $2;} + ; + + + + estimation + : ESTIMATION ';' + {_parser->run_estimation();} + | ESTIMATION '(' estimation_options_list ')' ';' + {_parser->run_estimation();} + | ESTIMATION tmp_var_list ';' + {_parser->run_estimation();} + | ESTIMATION '(' estimation_options_list ')' tmp_var_list ';' + {_parser->run_estimation();} + ; + + estimation_options_list + : estimation_options_list COMMA estimation_options + | estimation_options + ; + + estimation_options : o_datafile + | o_nobs + | o_first_obs + | o_prefilter + | o_presample + | o_lik_algo + | o_lik_init + | o_nograph + | o_conf_sig + | o_mh_replic + | o_mh_drop + | o_mh_jscale + | o_optim + | o_mh_init_scale + | o_mode_file + | o_mode_compute + | o_mode_check + | o_prior_trunc + | o_mh_mode + | o_mh_nblcks + | o_load_mh_file + | o_loglinear + | o_nodiagnostic + | o_bayesian_irf + | o_irf + | o_tex + | o_forecast + | o_smoother + | o_moments_varendo + | o_filtered_vars + | o_kalman_algo + | o_kalman_tol + | o_xls_sheet + | o_xls_range + | o_filter_step_ahead + | o_solve_algo + | o_constant + | o_noconstant + ; + + list_optim_option + : '\'' NAME '\'' COMMA '\'' NAME '\'' {_parser->optim_options($2,$6,2);} + | '\'' NAME '\'' COMMA value {_parser->optim_options($2,$5,2);} + ; + + optim_options + : list_optim_option + | optim_options COMMA list_optim_option; + ; + + varobs + : VAROBS tmp_var_list ';' + {_parser->set_varobs();} + ; + + observation_trends + : OBSERVATION_TRENDS ';' {_parser->set_trend_init();} trend_list END + ; + + trend_list + : trend_list trend_element + | trend_element + ; + + trend_element : NAME '(' expression {$$ = _parser->get_expression($3);} ')' ';' {_parser->set_trend_element($1,$4);} + ; + + unit_root_vars : UNIT_ROOT_VARS tmp_var_list ';' {_parser->set_unit_root_vars();} + ; + + optim_weights : OPTIM_WEIGHTS ';' {_parser->begin_optim_weights();} optim_weights_list END + ; + + optim_weights_list : optim_weights_list NAME expression {$$=_parser->get_expression($3);} ';' {_parser->set_optim_weights($2, $4);} + | optim_weights_list NAME COMMA NAME expression {$$=_parser->get_expression($3);} ';' {_parser->set_optim_weights($2, $4, $6);} + | NAME expression {$$=_parser->get_expression($2);} ';' {_parser->set_optim_weights($1, $3);} + | NAME COMMA NAME expression {$$=_parser->get_expression($3);} ';' {_parser->set_optim_weights($1, $3, $5);} + ; + + osr_params : OSR_PARAMS tmp_var_list ';' {_parser->set_osr_params();} + ; + + osr : OSR ';' {_parser->run_osr();} + | OSR '(' olr_options ')' ';' {_parser->run_osr();} + | OSR tmp_var_list ';' {_parser->run_osr();} + | OSR '(' olr_options ')' tmp_var_list ';' {_parser->run_osr();} + ; + + olr : OLR ';' {_parser->run_olr();} + | OLR '(' olr_options ')' ';' {_parser->run_olr();} + | OLR tmp_var_list ';' {_parser->run_olr();} + | OLR '(' olr_options ')' tmp_var_list ';' {_parser->run_olr();} + ; + + olr_option : o_olr_beta + | stoch_simul_options_list + ; + + olr_options : olr_option + | olr_options COMMA olr_option + ; + + olr_inst : OLR_INST tmp_var_list ';' {_parser->set_olr_inst();} + ; + + calib_var : CALIB_VAR ';' {_parser->begin_calib_var();} calib_var_list END + ; + + calib_var_list : calib_var_list calib_arg1 + | calib_arg1 + ; + + calib_arg1 : NAME calib_arg2 EQUAL expression ';' {_parser->set_calib_var($1,$2,$4);} + | NAME COMMA NAME calib_arg2 EQUAL expression ';' {_parser->set_calib_var($1,$3,$4,$6);} + | AUTOCORR NAME '(' INT_NUMBER ')' calib_arg2 EQUAL expression ';' {_parser->set_calib_ac($2,$4,$6,$8);} + ; + + calib_arg2 : {$$ = new dynare::Objects("1");} + | '(' INT_NUMBER ')' {$$ = $2;} + | '(' FLOAT_NUMBER ')' {$$ = $2;} + ; + + calib : CALIB ';' {_parser->run_calib(0);} + | CALIB '(' COVAR ')' ';' {_parser->run_calib(1);} + ; + + dynatype : DYNATYPE '(' NAME ')'';' {_parser->run_dynatype($3);} + | DYNATYPE '(' NAME ')' tmp_var_list ';' {_parser->run_dynatype($3);} + | DYNATYPE NAME ';' {_parser->run_dynatype($2);} + | DYNATYPE '(' NAME '.' NAME ')'';' {_parser->run_dynatype($3,$5);} + | DYNATYPE '(' NAME '.' NAME ')' tmp_var_list ';' {_parser->run_dynatype($3,$5);} + | DYNATYPE NAME '.' NAME ';' {_parser->run_dynatype($2,$4);}; + + dynasave : DYNASAVE '(' NAME ')'';' {_parser->run_dynasave($3);} + | DYNASAVE '(' NAME ')' tmp_var_list ';' {_parser->run_dynasave($3);} + | DYNASAVE NAME ';' {_parser->run_dynasave($2);} + | DYNASAVE '(' NAME '.' NAME ')'';' {_parser->run_dynasave($3,$5);} + | DYNASAVE '(' NAME '.' NAME ')' tmp_var_list ';' {_parser->run_dynasave($3,$5);} + | DYNASAVE NAME '.' NAME ';' {_parser->run_dynasave($2,$4);}; + + model_comparison : MODEL_COMPARISON '(' model_comparison_options ')' {_parser->begin_model_comparison();} + filename_list ';' {_parser->run_model_comparison();} + ; + + model_comparison_options: model_comparison_options ',' model_comparison_option + | model_comparison_option + ; + + model_comparison_option : o_model_comparison_approximation + | o_print + | o_noprint + ; + + filename_list : filename {_parser->add_mc_filename($1);} + | filename_list ',' filename {_parser->add_mc_filename($3);} + | filename '(' value ')' {_parser->add_mc_filename($1,$3);} + | filename_list ',' filename '(' value ')' {_parser->add_mc_filename($3,$5);} + ; + + filename : filename_elem {$$=$1;} + | filename filename_elem {$$ = _parser->cat($1,$2);} + ; + + filename_elem : NAME + | '\\' {$$ = new dynare::Objects("\\");} + | '/' {$$ = new dynare::Objects("/");} + | ':' {$$ = new dynare::Objects(":");} + | '.' {$$ = new dynare::Objects(".");} + ; + + o_dr_algo: DR_ALGO EQUAL INT_NUMBER {_parser->option_num("dr_algo",$3);}; + o_solve_algo: SOLVE_ALGO EQUAL INT_NUMBER {_parser->option_num("solve_algo",$3);}; + o_simul_algo: SIMUL_ALGO EQUAL INT_NUMBER {_parser->option_num("simul_algo",$3);}; + o_linear: LINEAR {_parser->option_num("linear","1");}; + o_order: ORDER EQUAL INT_NUMBER {_parser->option_num("order",$3);}; + o_replic: REPLIC EQUAL INT_NUMBER {_parser->option_num("replic",$3);}; + o_drop: DROP EQUAL INT_NUMBER {_parser->option_num("drop",$3);}; + o_ar: AR EQUAL INT_NUMBER {_parser->option_num("ar",$3);}; + o_nocorr: NOCORR {_parser->option_num("nocorr","1");}; + o_nofunction: NOFUNCTIONS {_parser->option_num("nofunctions","1");}; + o_nomoments: NOMOMENTS {_parser->option_num("nomoments","1");}; + o_irf: IRF EQUAL INT_NUMBER {_parser->option_num("irf",$3);}; + o_hp_filter: HP_FILTER EQUAL INT_NUMBER {_parser->option_num("hp_filter",$3);}; + o_hp_ngrid: HP_NGRID EQUAL INT_NUMBER {_parser->option_num("hp_ngrid",$3);}; + o_periods: PERIODS EQUAL INT_NUMBER {_parser->option_num("periods",$3);_parser->option_num("simul","1");}; + o_simul: SIMUL {_parser->option_num("simul","1");}; + o_simul_seed: SIMUL_SEED EQUAL INT_NUMBER { _parser->option_num("simul_seed",$3)}; + o_qz_criterium: QZ_CRITERIUM EQUAL INT_NUMBER { _parser->option_num("qz_criterium",$3)} + | QZ_CRITERIUM EQUAL FLOAT_NUMBER { _parser->option_num("qz_criterium",$3)} + ; + o_datafile: DATAFILE EQUAL NAME {_parser->option_str("datafile",$3);}; + o_nobs: NOBS EQUAL vec_int {_parser->option_num("nobs",$3);} + | NOBS EQUAL INT_NUMBER {_parser->option_num("nobs",$3);} + ; + o_first_obs: FIRST_OBS EQUAL INT_NUMBER {_parser->option_num("first_obs",$3);}; + o_prefilter: PREFILTER EQUAL INT_NUMBER {_parser->option_num("prefilter",$3);}; + o_presample: PRESAMPLE EQUAL INT_NUMBER {_parser->option_num("presample",$3);}; + o_lik_algo: LIK_ALGO EQUAL INT_NUMBER {_parser->option_num("lik_algo",$3);}; + o_lik_init: LIK_INIT EQUAL INT_NUMBER {_parser->option_num("lik_init",$3);}; + o_nograph: NOGRAPH {_parser->option_num("nograph","1");}; + o_conf_sig: CONF_SIG EQUAL FLOAT_NUMBER {_parser->option_num("conf_sig",$3);}; + o_mh_replic: MH_REPLIC EQUAL INT_NUMBER {_parser->option_num("mh_replic",$3);}; + o_mh_drop: MH_DROP EQUAL FLOAT_NUMBER {_parser->option_num("mh_drop",$3);}; + o_mh_jscale: MH_JSCALE EQUAL FLOAT_NUMBER {_parser->option_num("mh_jscale",$3);}; + o_optim: OPTIM EQUAL '(' optim_options ')'; + o_mh_init_scale :MH_INIT_SCALE EQUAL FLOAT_NUMBER {_parser->option_num("mh_init_scale",$3);}; + o_mh_init_scale :MH_INIT_SCALE EQUAL INT_NUMBER {_parser->option_num("mh_init_scale",$3);}; + o_mode_file : MODE_FILE EQUAL NAME {_parser->option_str("mode_file",$3);}; + o_mode_compute : MODE_COMPUTE EQUAL INT_NUMBER {_parser->option_num("mode_compute",$3);}; + o_mode_check : MODE_CHECK {_parser->option_num("mode_check","1");}; + o_prior_trunc : PRIOR_TRUNC EQUAL FLOAT_NUMBER {_parser->option_num("prior_trunc",$3);}; + o_mh_mode : MH_MODE EQUAL INT_NUMBER {_parser->option_num("mh_mode",$3);}; + o_mh_nblcks : MH_NBLOCKS EQUAL INT_NUMBER {_parser->option_num("mh_nblck",$3);}; + o_load_mh_file : LOAD_MH_FILE {_parser->option_num("load_mh_file","1");}; + o_loglinear : LOGLINEAR {_parser->option_num("loglinear","1");}; + o_nodiagnostic : NODIAGNOSTIC {_parser->option_num("nodiagnostic","1");}; + o_bayesian_irf : BAYESIAN_IRF {_parser->option_num("bayesian_irf","1");}; + o_tex : TEX {_parser->option_num("TeX","1");}; + o_forecast : FORECAST EQUAL INT_NUMBER {_parser->option_num("forecast",$3);}; + o_smoother : SMOOTHER {_parser->option_num("smoother","1");}; + o_moments_varendo : MOMENTS_VARENDO {_parser->option_num("moments_varendo","1");}; + o_filtered_vars : FILTERED_VARS {_parser->option_num("filtered_vars","1");}; + o_relative_irf : RELATIVE_IRF {_parser->option_num("relative_irf","1");}; + o_kalman_algo : KALMAN_ALGO EQUAL INT_NUMBER {_parser->option_num("kalman_algo",$3);}; + o_kalman_tol : KALMAN_TOL EQUAL INT_NUMBER {_parser->option_num("kalman_tol",$3);}; + o_olr_beta: OLR_BETA EQUAL value {_parser->option_num("olr_beta",$3);}; + o_model_comparison_approximation: MODEL_COMPARISON_APPROXIMATION EQUAL LAPLACE {dynare::Objects* tmp = new dynare::Objects("Laplace");_parser->option_str("model_comparison_approximation",tmp);} + | MODEL_COMPARISON_APPROXIMATION EQUAL MODIFIEDHARMONICMEAN {dynare::Objects* tmp = new dynare::Objects("MODIFIEDHARMONICMEAN");_parser->option_str("model_comparison_approximation",tmp);} + ; + o_print : PRINT {_parser->option_num("noprint","0");}; + o_noprint : NOPRINT {_parser->option_num("noprint","1");}; + o_nograph : GRAPH {_parser->option_num("nograph","0");}; + o_xls_sheet : XLS_SHEET EQUAL NAME {_parser->option_str("xls_sheet",$3);} + o_xls_range : XLS_RANGE EQUAL range {_parser->option_str("xls_range",$3);} + o_filter_step_ahead : FILTER_STEP_AHEAD EQUAL vec_int {_parser->option_num("filter_step_ahead",$3);} + o_constant : CONSTANT {_parser->option_num("noconstant","0");} + o_noconstant : NOCONSTANT {_parser->option_num("noconstant","1");} + + range : NAME ':' NAME {$$ = new dynare::Objects(":");$$ = _parser->cat($1,$$);$$ = _parser->cat($$,$3);} + vec_int_elem : INT_NUMBER + | INT_NUMBER ':' {$$ = new dynare::Objects(":"); $$ = _parser->cat($1,$$); } + INT_NUMBER {$$ = _parser->cat($3,$4);} + ; + + vec_int_1 : '[' vec_int_elem {$$ = new dynare::Objects("["); $$ =_parser->cat($$,$2);} + | vec_int_1 vec_int_elem {$$ = _parser->cat_with_space($1,$2);} + ; + + vec_int : vec_int_1 ']' {$$ = new dynare::Objects("]"); $$ = _parser->cat($1,$$);}; + + %% diff --git a/parser.src/DynareFlex.ll b/parser.src/DynareFlex.ll index 14ea95f4d..76bac5582 100644 --- a/parser.src/DynareFlex.ll +++ b/parser.src/DynareFlex.ll @@ -2,7 +2,7 @@ #define YY_BUF_SIZE 1000000 #include #include -#include "DynareScanner.h" +#include "DynareScanner.h" #ifdef HAVE_CONFIG_H # include "config.hh" #endif @@ -11,13 +11,13 @@ #define FINISH 0 #define YY_READ_BUF_SIZE 1000000 #include "ylmm/lexmm.hh" -int lineno = 1; +int lineno = 1; int comment_caller; -/* Particular value : when sigma_e command is found +/* Particular value : when sigma_e command is found this flag is set to 1, when command finished it is set to 0 */ int sigma_e = 0; -%} +%} %option stack @@ -34,11 +34,11 @@ int sigma_e = 0; /* Comments */ ["%"].* -["/"]["/"].* +["/"]["/"].* "/*" {comment_caller = YYSTATE; BEGIN COMMENT;} -[^*\n]* -"*"+[^*/\n]* +[^*\n]* +"*"+[^*/\n]* "*"+"/" {BEGIN comment_caller;} /* Begin of a Dynare statement */ @@ -86,24 +86,24 @@ int sigma_e = 0; optim_weights {BEGIN DYNARE_BLOCK;return OPTIM_WEIGHTS;} /* End of a Dynare block */ -end[ \t\n]*; {BEGIN INITIAL;return END;} +end[ \t\n]*; {BEGIN INITIAL;return END;} /* Inside of a Dynare statement */ datafile {return DATAFILE;} nobs {return NOBS;} first_obs {return FIRST_OBS;} -prefilter {return PREFILTER;} -presample {return PRESAMPLE;} -lik_algo {return LIK_ALGO;} -lik_init {return LIK_INIT;} -graph {return GRAPH;} -nograph {return NOGRAPH;} -print {return PRINT;} -noprint {return NOPRINT;} -conf_sig {return CONF_SIG;} -mh_replic {return MH_REPLIC;} -mh_drop {return MH_DROP;} -mh_jscale {return MH_JSCALE;} +prefilter {return PREFILTER;} +presample {return PRESAMPLE;} +lik_algo {return LIK_ALGO;} +lik_init {return LIK_INIT;} +graph {return GRAPH;} +nograph {return NOGRAPH;} +print {return PRINT;} +noprint {return NOPRINT;} +conf_sig {return CONF_SIG;} +mh_replic {return MH_REPLIC;} +mh_drop {return MH_DROP;} +mh_jscale {return MH_JSCALE;} mh_init_scale {return MH_INIT_SCALE;} mode_file {return MODE_FILE;} mode_compute {return MODE_COMPUTE;} @@ -139,7 +139,7 @@ int sigma_e = 0; [\$][^$]*[\$] { strtok(yytext+1,"$"); - _scanner->do_name(yytext+1); + _scanner->do_name(yytext+1); return TEX_NAME;} /* Inside a Dynare block */ @@ -177,20 +177,15 @@ int sigma_e = 0; simul {return SIMUL;} autocorr {return AUTOCORR;} olr_beta {return OLR_BETA;} -xtick {return XTICK;} -xticklabel {return XTICKLABEL;} +xtick {return XTICK;} +xticklabel {return XTICKLABEL;} xls_sheet {return XLS_SHEET;} xls_range {return XLS_RANGE;} use_dll {return USE_DLL;} - - /* New */ -dll {return DLL;} - /* EndNew */ - linear {return LINEAR;} [,] {_scanner->do_operator(COMMA); return COMMA;} -[\(\)] {return yytext[0];} +[\(\)] {return yytext[0];} [\[] {return yytext[0];} [\]] {if (sigma_e) sigma_e=0; return yytext[0];} [+] {_scanner->do_operator(PLUS); return PLUS;} @@ -219,7 +214,7 @@ int sigma_e = 0; sqrt {_scanner->do_operator(SQRT);return SQRT;} [A-Za-z_][A-Za-z0-9_]* { - _scanner->do_name(yytext); + _scanner->do_name(yytext); return NAME;} ((([0-9]*\.[0-9]+)|([0-9]+\.))([edED][-+]?[0-9]+)?)|([0-9]+[edED][-+]?[0-9]+) { @@ -229,11 +224,11 @@ int sigma_e = 0; [0-9]+ { _scanner->do_num_constant(yytext); return INT_NUMBER;} - + /* an instruction starting with a recognized symbol is passed as NAME, otherwise it is a native statement until the end of the line */ -[A-Za-z_][A-Za-z0-9_]* { +[A-Za-z_][A-Za-z0-9_]* { if (SymbolTable::getID(yytext) != -1) { BEGIN DYNARE_STATEMENT; diff --git a/parser.src/DynareParser.cc b/parser.src/DynareParser.cc index 31cd981e3..063a76dc6 100644 --- a/parser.src/DynareParser.cc +++ b/parser.src/DynareParser.cc @@ -1,4 +1,4 @@ -/*! \file +/*! \file \version 1.0 \date 04/09/2004 \par This file implements the parser class methodes. @@ -15,10 +15,6 @@ #include "ComputingTasks.h" #include "TmpSymbolTable.h" #include "DynareParser.h" -/*New*/ -#include "BlockTriangular.h" -/*EndNew*/ - string dynare::parser::file_name = ""; void dynare::parser::set_file_name(string fname) @@ -26,9 +22,9 @@ void dynare::parser::set_file_name(string fname) file_name = fname; } -void dynare::parser::setoutput(ostringstream* ostr) +void dynare::parser::setoutput(ostringstream* ostr) { - output = ostr; + output = ostr; numerical_initialization.setOutput(ostr); shocks.setOutput(ostr); sigmae.setOutput(ostr); @@ -38,7 +34,7 @@ void dynare::parser::setoutput(ostringstream* ostr) dynare::Objects* dynare::parser::add_endogenous(Objects* obj, Objects* tex_name) { //cout << "add_endogenous \n"; - + obj->ID = (NodeID) symbol_table.AddSymbolDeclar(obj->symbol,eEndogenous, tex_name->symbol); obj->type = eEndogenous; return (obj); @@ -49,7 +45,7 @@ dynare::Objects* dynare::parser::add_exogenous(Objects* obj, Objects* tex_name) obj->type = eExogenous; return (obj); } -dynare::Objects* dynare::parser::add_exogenous_det(Objects* obj, Objects* tex_name) +dynare::Objects* dynare::parser::add_exogenous_det(Objects* obj, Objects* tex_name) { obj->ID = (NodeID) symbol_table.AddSymbolDeclar(obj->symbol,eExogenousDet, tex_name->symbol); obj->type = eExogenousDet; @@ -84,31 +80,25 @@ dynare::Objects* dynare::parser::add_variable(Objects* var) { //cout << "add_variable1 : " << var->symbol << endl; var = get_symbol(var); - if((var->type == eEndogenous) + if((var->type == eEndogenous) || (var->type == eExogenous) || (var->type == eExogenousDet)) variable_table.AddVariable(var->symbol,0); //cout << "add_model_token : " << var->ID << endl; NodeID id = model_tree.AddTerminal(var->symbol); - /*New*/ - if (var->type == eEndogenous) - { - block_triangular.fill_IM(ModelParameters::eq_nbr, symbol_table.getID(var->symbol), 0); - } - /*EndNew*/ return new Objects("", id, eTempResult); } dynare::Objects* dynare::parser::add_variable(Objects* var,Objects* olag) { //cout << "add_variable2\n"; - + var = get_symbol(var); int lag = atoi((olag->symbol).c_str()); //cout << "symbol = " << olag->symbol << endl; //cout << "lag = " << lag << endl; if ((var->type == eExogenous) && lag != 0) { - std::cout << "Warning: exogenous variable " + std::cout << "Warning: exogenous variable " << var->symbol << " has lag " << lag << "\n"; } @@ -116,14 +106,6 @@ dynare::Objects* dynare::parser::add_variable(Objects* var,Objects* olag) variable_table.AddVariable(var->symbol,lag); //cout << "add_model_token : " << var->ID << endl; NodeID id = model_tree.AddTerminal(var->symbol,lag); - /*New*/ - if (var->type == eEndogenous) - { - //cout << "var->symbol : " << var->symbol << symbol_table.getID(var->symbol) << "\n"; - //cout << "ModelParameters::eq_nbr : " << ModelParameters::eq_nbr << "\n"; - block_triangular.fill_IM(ModelParameters::eq_nbr, symbol_table.getID(var->symbol), lag); - } - /*EndNew*/ return new Objects("", id, eTempResult); } dynare::Objects* dynare::parser::get_symbol(Objects* obj) @@ -199,7 +181,7 @@ dynare::Objects* dynare::parser::add_expression_token( Objects* arg1, Objects* o //cout << "after add_expression_token\n"; return new Objects("", (NodeID) id, eTempResult); } -dynare::Objects* dynare::parser::get_expression(Objects* exp) +dynare::Objects* dynare::parser::get_expression(Objects* exp) { if (exp->type == eTempResult) { @@ -230,7 +212,7 @@ void dynare::parser::init_param(Objects* lhs, Objects* rhs) void dynare::parser::init_param(Objects* lhs) { //cout << "Befor set\n"; - expression.set(); + expression.set(); numerical_initialization.SetConstant(lhs->symbol, expression.get()); expression.clear(); } @@ -246,52 +228,28 @@ void dynare::parser::hist_val(Objects* lhs, Objects* slag, Objects* rhs) void dynare::parser::hist_val(Objects* lhs, Objects* slag) { int lag = atoi((slag->symbol).c_str()); - expression.set(); + expression.set(); numerical_initialization.SetHist(lhs->symbol, lag, expression.get()); expression.clear(); } void dynare::parser::initialize_model(void) { - /*New*/ - block_triangular.init_incidence_matrix(); - /*EndNew*/ } void dynare::parser::use_dll(void) { - // Setting variable mumber offset to use C outputs + // Seetting variable momber offset to use C outputs model_tree.offset = 0; } - -/*New*/ -void dynare::parser::dll(void) -{ - // Seetting variable mumber offset to use C outputs - model_tree.offset = 2; -} -/*EndNew*/ - void dynare::parser::check_model(void) { - /*New*/ - if (block_triangular.bt_verbose) - { - /*cout << "block_triangular.bt_verbose : " << block_triangular.bt_verbose << "\n"; - cout << "----------------------------------------------------------------------------\n";*/ - cout << "The gross incidence matrix \n"; - block_triangular.Print_IM(ModelParameters::endo_nbr); - cout << "First ordering \n"; - } - //block_triangular.Normalize_and_BlockDecompose_0(); - block_triangular.Normalize_and_BlockDecompose_Static_Model(); - /*EndNew*/ symbol_table.clean(); } void dynare::parser::finish(void) { + + string model_file_name(file_name); - string model_file_name(file_name); - - // Setting flags to compute what is necessary + // Setting flags to compute what is necessary if (order == 1 || linear == 1) { model_tree.computeJacobianExo = true; @@ -314,28 +272,22 @@ void dynare::parser::finish(void) { model_tree.derive(1); } - + cout << "Processing outputs ...\n"; model_tree.setStaticModel(); - /*New*/ - if (model_tree.offset == 2) - model_tree.setDynamicModel_New(block_triangular.ModelBlock,block_triangular.Index_Var_IM); - else - model_tree.setDynamicModel(); - if (model_tree.offset != 1) - /*EndNew*/ + model_tree.setDynamicModel(); + + if (model_tree.offset == 0) { model_tree.OpenCFiles(model_file_name+"_static", model_file_name+"_dynamic"); - /*New*/ - model_tree.SaveCFiles(block_triangular.ModelBlock); - /*EndNew*/ + model_tree.SaveCFiles(); } else { model_tree.OpenMFiles(model_file_name+"_static", model_file_name+"_dynamic"); model_tree.SaveMFiles(); } - + *output << "save('" << model_file_name << "_results', 'oo_');\n"; *output << "diary off\n"; @@ -389,7 +341,7 @@ void dynare::parser::add_det_shock(Objects* var) case eExogenousDet: shocks.AddDetShockExoDet(id); return; - default: + default: error("Shocks can only be applied to exogenous variables"); } } @@ -690,13 +642,13 @@ dynare::Objects* dynare::parser::add_equal(Objects* arg1, Objects* arg2) model_parameters.eq_nbr++; return new Objects("", id, eTempResult); } - + dynare::Objects* dynare::parser::init_local_parameter(Objects* arg1, Objects* arg2) { NodeID id = model_tree.AddAssign(arg1->ID, arg2->ID); return new Objects("", id, eTempResult); } - + dynare::Objects* dynare::parser::add_plus(Objects* arg1, Objects* arg2) { NodeID id = model_tree.AddPlus(arg1->ID, arg2->ID); diff --git a/parser.src/ModelTree.cc b/parser.src/ModelTree.cc index 1ab77037c..55163e708 100644 --- a/parser.src/ModelTree.cc +++ b/parser.src/ModelTree.cc @@ -1,4 +1,4 @@ -/*! \file +/*! \file \version 1.0 \date 04/09/2004 \par This file implements the ModelTree class methodes. @@ -25,1947 +25,1223 @@ ostringstream ModelTree::output; //------------------------------------------------------------------------------ ModelTree::ModelTree() { - computeJacobian = false; - computeJacobianExo = false; - computeHessian = false; + computeJacobian = false; + computeJacobianExo = false; + computeHessian = false; } //------------------------------------------------------------------------------ ModelTree::~ModelTree() { - // Empty + // Empty } //------------------------------------------------------------------------------ void ModelTree::OpenMFiles(string iModelFileName1, string iModelFileName2) { - if (iModelFileName1.size()) - { - iModelFileName1 += interfaces::function_file_extension(); - mStaticModelFile.open(iModelFileName1.c_str(),ios::out|ios::binary); - if (!mStaticModelFile.is_open()) - { - cout << "ModelTree::Open : Error : Can't open file " << iModelFileName1 - << " for writing\n"; - exit(-1); - } - iModelFileName1.erase(iModelFileName1.end()-2,iModelFileName1.end()); - //Writing comments and function definition command - mStaticModelFile << "function [residual, g1] = " << iModelFileName1 << "( y, x )\n"; - mStaticModelFile << interfaces::comment()+"\n"+interfaces::comment(); - mStaticModelFile << "Status : Computes static model for Dynare\n%\n"; - mStaticModelFile << interfaces::comment(); - mStaticModelFile << "Warning : this file is generated automatically by Dynare\n"; - mStaticModelFile << interfaces::comment(); - mStaticModelFile << " from model file (.mod)\n\n"; - if (iModelFileName2.size() && (computeJacobian||computeJacobianExo||computeHessian)) - { - iModelFileName2 += interfaces::function_file_extension(); - mDynamicModelFile.open(iModelFileName2.c_str(),ios::out|ios::binary); - if (!mDynamicModelFile.is_open()) - { - cout << "ModelTree::Open : Error : Can't open file " << iModelFileName2 - << " for writing\n"; - exit(-1); - } - iModelFileName2.erase(iModelFileName2.end()-2,iModelFileName2.end()); - mDynamicModelFile << "function [residual, g1, g2] = " << iModelFileName2 << "(y, x)\n"; - mDynamicModelFile << interfaces::comment()+"\n"+interfaces::comment(); - mDynamicModelFile << "Status : Computes dynamic model for Dynare\n%\n"; - mDynamicModelFile << interfaces::comment(); - mDynamicModelFile << "Warning : this file is generated automatically by Dynare\n"; - mDynamicModelFile << interfaces::comment(); - mDynamicModelFile << " from model file (.mod)\n\n"; - - } - } - else - { - cout << "ModelTree::Open : Error : Missing file name\n"; - exit(-1); - } + if (iModelFileName1.size()) + { + iModelFileName1 += interfaces::function_file_extension(); + mStaticModelFile.open(iModelFileName1.c_str(),ios::out|ios::binary); + if (!mStaticModelFile.is_open()) + { + cout << "ModelTree::Open : Error : Can't open file " << iModelFileName1 + << " for writing\n"; + exit(-1); + } + iModelFileName1.erase(iModelFileName1.end()-2,iModelFileName1.end()); + //Writing comments and function definition command + mStaticModelFile << "function [residual, g1] = " << iModelFileName1 << "( y, x )\n"; + mStaticModelFile << interfaces::comment()+"\n"+interfaces::comment(); + mStaticModelFile << "Status : Computes static model for Dynare\n%\n"; + mStaticModelFile << interfaces::comment(); + mStaticModelFile << "Warning : this file is generated automatically by Dynare\n"; + mStaticModelFile << interfaces::comment(); + mStaticModelFile << " from model file (.mod)\n\n"; + if (iModelFileName2.size() && (computeJacobian||computeJacobianExo||computeHessian)) + { + iModelFileName2 += interfaces::function_file_extension(); + mDynamicModelFile.open(iModelFileName2.c_str(),ios::out|ios::binary); + if (!mDynamicModelFile.is_open()) + { + cout << "ModelTree::Open : Error : Can't open file " << iModelFileName2 + << " for writing\n"; + exit(-1); + } + iModelFileName2.erase(iModelFileName2.end()-2,iModelFileName2.end()); + mDynamicModelFile << "function [residual, g1, g2] = " << iModelFileName2 << "(y, x)\n"; + mDynamicModelFile << interfaces::comment()+"\n"+interfaces::comment(); + mDynamicModelFile << "Status : Computes dynamic model for Dynare\n%\n"; + mDynamicModelFile << interfaces::comment(); + mDynamicModelFile << "Warning : this file is generated automatically by Dynare\n"; + mDynamicModelFile << interfaces::comment(); + mDynamicModelFile << " from model file (.mod)\n\n"; + + } + } + else + { + cout << "ModelTree::Open : Error : Missing file name\n"; + exit(-1); + } } //------------------------------------------------------------------------------ void ModelTree::OpenCFiles(string iModelFileName1, string iModelFileName2) -{ - /*New*/ - string tmp_s; - int i,j; - /*EndNew*/ - - if (iModelFileName1.size()) - { - iModelFileName1 += ".c"; - mStaticModelFile.open(iModelFileName1.c_str(),ios::out|ios::binary); - if (!mStaticModelFile.is_open()) - { - cout << "ModelTree::Open : Error : Can't open file " << iModelFileName1 - << " for writing\n"; - exit(-1); - } - iModelFileName1.erase(iModelFileName1.end()-2,iModelFileName1.end()); - mStaticModelFile << "/*\n"; - mStaticModelFile << " *" << iModelFileName1 << ".c : Computes static model for Dynare\n"; - mStaticModelFile << " * Warning : this file is generated automatically by Dynare\n"; - mStaticModelFile << " * from model file (.mod)\n\n"; - mStaticModelFile << " */\n"; - mStaticModelFile << "#include \n"; - /*New*/ - if(offset==0) - mStaticModelFile << "#include \"mex.h\"\n"; - else - mStaticModelFile << "#include \n"; - /*EndNew*/ - mStaticModelFile << "#include \"mex.h\"\n"; - // A global variable for model parameters - mStaticModelFile << "double *params;\n"; - if (iModelFileName2.size() && (computeJacobian||computeJacobianExo||computeHessian)) - { - /*New*/ - if(offset==2) - { - iModelFileName2 += ".h"; - mDynamicModelFile.open(iModelFileName2.c_str(),ios::out|ios::binary); - if (!mDynamicModelFile.is_open()) - { - cout << "ModelTree::Open : Error : Can't open file " << iModelFileName2 - << ".h for writing\n"; - exit(-1); - } - iModelFileName2.erase(iModelFileName2.end()-2,iModelFileName2.end()); - tmp_s=iModelFileName2; - j=tmp_s.size(); - for(i=0;i\n"; - /*New*/ - if(offset==0) - mDynamicModelFile << "#include \"mex.h\"\n"; - else - { - mDynamicModelFile << "#include \n"; - mDynamicModelFile << "#include \"" << iModelFileName2.c_str() << ".h\"\n"; - } - /*EndNew*/ - // A flobal variable for model parameters - mDynamicModelFile << "double *params;\n"; - // A global variable for it_ - mDynamicModelFile << "int it_;\n"; - mDynamicModelFile << "int nb_row_x;\n"; - } - } - else - { - cout << "ModelTree::Open : Error : Missing file name\n"; - exit(-1); - } +{ + if (iModelFileName1.size()) + { + iModelFileName1 += ".c"; + mStaticModelFile.open(iModelFileName1.c_str(),ios::out|ios::binary); + if (!mStaticModelFile.is_open()) + { + cout << "ModelTree::Open : Error : Can't open file " << iModelFileName1 + << " for writing\n"; + exit(-1); + } + iModelFileName1.erase(iModelFileName1.end()-2,iModelFileName1.end()); + mStaticModelFile << "/*\n"; + mStaticModelFile << " *" << iModelFileName1 << ".c : Computes static model for Dynare\n"; + mStaticModelFile << " * Warning : this file is generated automatically by Dynare\n"; + mStaticModelFile << " * from model file (.mod)\n\n"; + mStaticModelFile << " */\n"; + mStaticModelFile << "#include \n"; + mStaticModelFile << "#include \"mex.h\"\n"; + // A flobal variable for model parameters + mStaticModelFile << "double *params;\n"; + if (iModelFileName2.size() && (computeJacobian||computeJacobianExo||computeHessian)) + { + iModelFileName2 += ".c"; + mDynamicModelFile.open(iModelFileName2.c_str(),ios::out|ios::binary); + if (!mDynamicModelFile.is_open()) + { + cout << "ModelTree::Open : Error : Can't open file " << iModelFileName2 + << " for writing\n"; + exit(-1); + } + iModelFileName2.erase(iModelFileName2.end()-2,iModelFileName2.end()); + mDynamicModelFile << "/*\n"; + mDynamicModelFile << " *" << iModelFileName2 << ".c : Computes dynamic model for Dynare\n"; + mDynamicModelFile << " *\n"; + mDynamicModelFile << " * Warning : this file is generated automatically by Dynare\n"; + mDynamicModelFile << " * from model file (.mod)\n\n"; + mDynamicModelFile << " */\n"; + mDynamicModelFile << "#include \n"; + mDynamicModelFile << "#include \"mex.h\"\n"; + // A flobal variable for model parameters + mDynamicModelFile << "double *params;\n"; + // A global variable for it_ + mDynamicModelFile << "int it_;\n"; + mDynamicModelFile << "int nb_row_x;\n"; + } + } + else + { + cout << "ModelTree::Open : Error : Missing file name\n"; + exit(-1); + } } //------------------------------------------------------------------------------ void ModelTree::SaveMFiles() { - if (mStaticModelFile.is_open()) - { - mStaticModelFile << StaticOutput.str(); - interfaces::function_close(); - mStaticModelFile.close(); - } - if (mDynamicModelFile.is_open() && (computeJacobian||computeJacobianExo||computeHessian)) - { - mDynamicModelFile << DynamicOutput.str(); - interfaces::function_close(); - mDynamicModelFile.close(); - } + if (mStaticModelFile.is_open()) + { + mStaticModelFile << StaticOutput.str(); + interfaces::function_close(); + mStaticModelFile.close(); + } + if (mDynamicModelFile.is_open() && (computeJacobian||computeJacobianExo||computeHessian)) + { + mDynamicModelFile << DynamicOutput.str(); + interfaces::function_close(); + mDynamicModelFile.close(); + } } //------------------------------------------------------------------------------ -/*New*/ -void ModelTree::SaveCFiles(Model_Block* ModelBlock) +void ModelTree::SaveCFiles() { - int i, j, k; - /*EndNew*/ - if (mStaticModelFile.is_open()) - { - // Writing the function Static - mStaticModelFile << StaticOutput.str(); - /*New*/ - if (offset==0) - { - /*EndNew*/ - // Writing the gateway routine - mStaticModelFile << "/* The gateway routine */\n"; - mStaticModelFile << "void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n"; - mStaticModelFile << "{\n"; - mStaticModelFile << " double *y, *x;\n"; - mStaticModelFile << " double *residual, *g1;\n"; - mStaticModelFile << " mxArray *M_;\n"; - mStaticModelFile << "\n"; - mStaticModelFile << " /* Create a pointer to the input matrix y. */\n"; - mStaticModelFile << " y = mxGetPr(prhs[0]);\n"; - mStaticModelFile << "\n"; - mStaticModelFile << " /* Create a pointer to the input matrix x. */\n"; - mStaticModelFile << " x = mxGetPr(prhs[1]);\n"; - mStaticModelFile << "\n"; - - mStaticModelFile << " residual = NULL;\n"; - mStaticModelFile << " if (nlhs >= 1)\n"; - mStaticModelFile << " {\n"; - mStaticModelFile << " /* Set the output pointer to the output matrix residual. */\n"; - mStaticModelFile << " plhs[0] = mxCreateDoubleMatrix(" << ModelParameters::eq_nbr << ",1, mxREAL);\n"; - mStaticModelFile << " /* Create a C pointer to a copy of the output matrix residual. */\n"; - mStaticModelFile << " residual = mxGetPr(plhs[0]);\n"; - mStaticModelFile << " }\n\n"; - mStaticModelFile << " g1 = NULL;\n"; - mStaticModelFile << " if (nlhs >= 2)\n"; - mStaticModelFile << " {\n"; - mStaticModelFile << " /* Set the output pointer to the output matrix g1. */\n"; - mStaticModelFile << " plhs[1] = mxCreateDoubleMatrix(" << ModelParameters::eq_nbr << ", " << ModelParameters::endo_nbr << ", mxREAL);\n"; - mStaticModelFile << " /* Create a C pointer to a copy of the output matrix g1. */\n"; - mStaticModelFile << " g1 = mxGetPr(plhs[1]);\n"; - mStaticModelFile << " }\n\n"; - mStaticModelFile << " /* Gets model parameters from global workspace of Matlab */\n"; - mStaticModelFile << " M_ = mexGetVariable(\"global\",\"M_\");\n"; - mStaticModelFile << " if (M_ == NULL ){\n"; - mStaticModelFile << " mexPrintf(\"Global variable not found : \");\n"; - mStaticModelFile << " mexErrMsgTxt(\"M_ \\n\");\n"; - mStaticModelFile << " }\n"; - mStaticModelFile << " params = mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_,\"params\")));\n"; - mStaticModelFile << " /* Call the C Static. */\n"; - mStaticModelFile << " Static(y, x, residual, g1);\n"; - mStaticModelFile << "}\n"; - mStaticModelFile.close(); - /*New*/ - } - /*EndNew*/ - } - if (mDynamicModelFile.is_open() && (computeJacobian||computeJacobianExo||computeHessian)) - { - // Writing the function body - mDynamicModelFile << DynamicOutput.str(); - if (offset==0) - { - // Writing the gateway routine - mDynamicModelFile << "/* The gateway routine */\n"; - mDynamicModelFile << "void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n"; - mDynamicModelFile << "{\n"; - mDynamicModelFile << " double *y, *x;\n"; - mDynamicModelFile << " double *residual, *g1, *g2;\n"; - mDynamicModelFile << " mxArray *M_;\n"; - mDynamicModelFile << "\n"; - mDynamicModelFile << " /* Create a pointer to the input matrix y. */\n"; - mDynamicModelFile << " y = mxGetPr(prhs[0]);\n"; - mDynamicModelFile << "\n"; - mDynamicModelFile << " /* Create a pointer to the input matrix x. */\n"; - mDynamicModelFile << " x = mxGetPr(prhs[1]);\n"; - mDynamicModelFile << " /* Gets number of rows of matrix x. */\n"; - mDynamicModelFile << " nb_row_x = mxGetM(prhs[1]);\n"; - mDynamicModelFile << "\n"; - mDynamicModelFile << " residual = NULL;\n"; - mDynamicModelFile << " if (nlhs >= 1)\n"; - mDynamicModelFile << " {\n"; - mDynamicModelFile << " /* Set the output pointer to the output matrix residual. */\n"; - mDynamicModelFile << " plhs[0] = mxCreateDoubleMatrix(" << ModelParameters::eq_nbr << ",1, mxREAL);\n"; - mDynamicModelFile << " /* Create a C pointer to a copy of the output matrix residual. */\n"; - mDynamicModelFile << " residual = mxGetPr(plhs[0]);\n"; - mDynamicModelFile << " }\n\n"; - mDynamicModelFile << " g1 = NULL;\n"; - mDynamicModelFile << " if (nlhs >= 2)\n"; - mDynamicModelFile << " {\n"; - mDynamicModelFile << " /* Set the output pointer to the output matrix g1. */\n"; - if (computeJacobianExo) - mDynamicModelFile << " plhs[1] = mxCreateDoubleMatrix(" << ModelParameters::eq_nbr << ", " << VariableTable::size() << ", mxREAL);\n"; - else if (computeJacobian) - mDynamicModelFile << " plhs[1] = mxCreateDoubleMatrix(" << ModelParameters::eq_nbr << ", " << ModelParameters::var_endo_nbr << ", mxREAL);\n"; - mDynamicModelFile << " /* Create a C pointer to a copy of the output matrix g1. */\n"; - mDynamicModelFile << " g1 = mxGetPr(plhs[1]);\n"; - mDynamicModelFile << " }\n\n"; - mDynamicModelFile << " g2 = NULL;\n"; - mDynamicModelFile << " if (nlhs >= 3)\n"; - mDynamicModelFile << " {\n"; - mDynamicModelFile << " /* Set the output pointer to the output matrix g2. */\n"; - mDynamicModelFile << " plhs[2] = mxCreateDoubleMatrix(" << ModelParameters::eq_nbr << ", " << VariableTable::size()*VariableTable::size() << ", mxREAL);\n"; - mDynamicModelFile << " /* Create a C pointer to a copy of the output matrix g1. */\n"; - mDynamicModelFile << " g2 = mxGetPr(plhs[2]);\n"; - mDynamicModelFile << " }\n\n"; - mDynamicModelFile << " /* Gets model parameters from global workspace of Matlab */\n"; - mDynamicModelFile << " M_ = mexGetVariable(\"global\",\"M_\");\n"; - mDynamicModelFile << " if (M_ == NULL )\n"; - mDynamicModelFile << " {\n"; - mDynamicModelFile << " mexPrintf(\"Global variable not found : \");\n"; - mDynamicModelFile << " mexErrMsgTxt(\"M_ \\n\");\n"; - mDynamicModelFile << " }\n"; - mDynamicModelFile << " params = mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_,\"params\")));\n"; - mDynamicModelFile << " /* Gets it_ from global workspace of Matlab */\n"; - mDynamicModelFile << " it_ = (int) floor(mxGetScalar(mexGetVariable(\"global\", \"it_\")))-1;\n"; - mDynamicModelFile << " /* Call the C subroutines. */\n"; - mDynamicModelFile << " Dynamic(y, x, residual, g1, g2);\n"; - mDynamicModelFile << "}\n"; - /*New*/ - } - else - { - mDynamicModelFile << "void Dynamic_Init(tModel_Block *Model_Block)\n"; - mDynamicModelFile << " {\n"; - mDynamicModelFile << " Model_Block=(tModel_Block*)malloc(sizeof(tModel_Block));\n"; - mDynamicModelFile << " Model_Block->Size=" << ModelBlock->Size << ";\n"; - mDynamicModelFile << " Model_Block->List=(tBlock*)malloc(sizeof(tBlock)*Model_Block->Size);\n"; - for(i=0;iSize;i++) - { - mDynamicModelFile << " Model_Block->List[" << i << "].Size=" << ModelBlock->Block_List[i].Size << ";\n"; - mDynamicModelFile << " Model_Block->List[" << i << "].Type=" << ModelBlock->Block_List[i].Type << ";\n"; - mDynamicModelFile << " Model_Block->List[" << i << "].Sized=" << ModelBlock->Block_List[i].Sized << ";\n"; - mDynamicModelFile << " Model_Block->List[" << i << "].Max_Lag=" << ModelBlock->Block_List[i].Max_Lag << ";\n"; - mDynamicModelFile << " Model_Block->List[" << i << "].Max_Lead=" << ModelBlock->Block_List[i].Max_Lead << ";\n"; - mDynamicModelFile << " Model_Block->List[" << i << "].Simulation_Type=" << BlockTriangular::BlockSim_d(ModelBlock->Block_List[i].Simulation_Type) << ";\n"; - mDynamicModelFile << " Model_Block->List[" << i << "].Variable=(int*)malloc(Model_Block->List[" << i << "].Size*sizeof(int));\n"; - mDynamicModelFile << " Model_Block->List[" << i << "].Equation=(int*)malloc(Model_Block->List[" << i << "].Size*sizeof(int));\n"; - mDynamicModelFile << " Model_Block->List[" << i << "].icc1_size=" << ModelBlock->Block_List[i].icc1_size << ";\n"; - mDynamicModelFile << " Model_Block->List[" << i << "].icc1=(int*)malloc(Model_Block->List[" << i << "].icc1_size*sizeof(int));\n"; - mDynamicModelFile << " Model_Block->List[" << i << "].Incidence_M=(Variable_l*)malloc(Model_Block->List[" << i << "].Size*sizeof(*Model_Block->List[" << i << "].Incidence_M));\n"; - if(ModelBlock->Block_List[i].Sized>0) - mDynamicModelFile << " Model_Block->List[" << i << "].dVariable=(int*)malloc(Model_Block->List[" << i << "].Sized*sizeof(int));\n"; - for(j=0;jBlock_List[i].Size;j++) - mDynamicModelFile << " Model_Block->List[" << i << "].Variable[" << j << "]=" << ModelBlock->Block_List[i].Variable_Sorted[j] << ";\n"; - for(j=0;jBlock_List[i].Size;j++) - mDynamicModelFile << " Model_Block->List[" << i << "].Equation[" << j << "]=" << ModelBlock->Block_List[i].Equation[j] << ";\n"; - for(j=0;jBlock_List[i].Sized;j++) - mDynamicModelFile << " Model_Block->List[" << i << "].dVariable[" << j << "]=" << ModelBlock->Block_List[i].dVariable[j] << ";\n"; - } - mDynamicModelFile << " }\n"; - } - /*EndNew*/ - mDynamicModelFile.close(); - } + if (mStaticModelFile.is_open()) + { + // Writing the function Static + mStaticModelFile << StaticOutput.str(); + // Writing the gateway routine + mStaticModelFile << "/* The gateway routine */\n"; + mStaticModelFile << "void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n"; + mStaticModelFile << "{\n"; + mStaticModelFile << " double *y, *x;\n"; + mStaticModelFile << " double *residual, *g1;\n"; + mStaticModelFile << " mxArray *M_;\n"; + mStaticModelFile << "\n"; + mStaticModelFile << " /* Create a pointer to the input matrix y. */\n"; + mStaticModelFile << " y = mxGetPr(prhs[0]);\n"; + mStaticModelFile << "\n"; + mStaticModelFile << " /* Create a pointer to the input matrix x. */\n"; + mStaticModelFile << " x = mxGetPr(prhs[1]);\n"; + mStaticModelFile << "\n"; + + mStaticModelFile << " residual = NULL;\n"; + mStaticModelFile << " if (nlhs >= 1)\n"; + mStaticModelFile << " {\n"; + mStaticModelFile << " /* Set the output pointer to the output matrix residual. */\n"; + mStaticModelFile << " plhs[0] = mxCreateDoubleMatrix(" << ModelParameters::eq_nbr << ",1, mxREAL);\n"; + mStaticModelFile << " /* Create a C pointer to a copy of the output matrix residual. */\n"; + mStaticModelFile << " residual = mxGetPr(plhs[0]);\n"; + mStaticModelFile << " }\n\n"; + mStaticModelFile << " g1 = NULL;\n"; + mStaticModelFile << " if (nlhs >= 2)\n"; + mStaticModelFile << " {\n"; + mStaticModelFile << " /* Set the output pointer to the output matrix g1. */\n"; + mStaticModelFile << " plhs[1] = mxCreateDoubleMatrix(" << ModelParameters::eq_nbr << ", " << ModelParameters::endo_nbr << ", mxREAL);\n"; + mStaticModelFile << " /* Create a C pointer to a copy of the output matrix g1. */\n"; + mStaticModelFile << " g1 = mxGetPr(plhs[1]);\n"; + mStaticModelFile << " }\n\n"; + mStaticModelFile << " /* Gets model parameters from global workspace of Matlab */\n"; + mStaticModelFile << " M_ = mexGetVariable(\"global\",\"M_\");\n"; + mStaticModelFile << " if (M_ == NULL ){\n"; + mStaticModelFile << " mexPrintf(\"Global variable not found : \");\n"; + mStaticModelFile << " mexErrMsgTxt(\"M_ \\n\");\n"; + mStaticModelFile << " }\n"; + mStaticModelFile << " params = mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_,\"params\")));\n"; + mStaticModelFile << " /* Call the C Static. */\n"; + mStaticModelFile << " Static(y, x, residual, g1);\n"; + mStaticModelFile << "}\n"; + mStaticModelFile.close(); + } + if (mDynamicModelFile.is_open() && (computeJacobian||computeJacobianExo||computeHessian)) + { + // Writing the function body + mDynamicModelFile << DynamicOutput.str(); + // Writing the gateway routine + mDynamicModelFile << "/* The gateway routine */\n"; + mDynamicModelFile << "void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n"; + mDynamicModelFile << "{\n"; + mDynamicModelFile << " double *y, *x;\n"; + mDynamicModelFile << " double *residual, *g1, *g2;\n"; + mDynamicModelFile << " mxArray *M_;\n"; + mDynamicModelFile << "\n"; + mDynamicModelFile << " /* Create a pointer to the input matrix y. */\n"; + mDynamicModelFile << " y = mxGetPr(prhs[0]);\n"; + mDynamicModelFile << "\n"; + mDynamicModelFile << " /* Create a pointer to the input matrix x. */\n"; + mDynamicModelFile << " x = mxGetPr(prhs[1]);\n"; + mDynamicModelFile << " /* Gets number of rows of matrix x. */\n"; + mDynamicModelFile << " nb_row_x = mxGetM(prhs[1]);\n"; + mDynamicModelFile << "\n"; + mDynamicModelFile << " residual = NULL;\n"; + mDynamicModelFile << " if (nlhs >= 1)\n"; + mDynamicModelFile << " {\n"; + mDynamicModelFile << " /* Set the output pointer to the output matrix residual. */\n"; + mDynamicModelFile << " plhs[0] = mxCreateDoubleMatrix(" << ModelParameters::eq_nbr << ",1, mxREAL);\n"; + mDynamicModelFile << " /* Create a C pointer to a copy of the output matrix residual. */\n"; + mDynamicModelFile << " residual = mxGetPr(plhs[0]);\n"; + mDynamicModelFile << " }\n\n"; + mDynamicModelFile << " g1 = NULL;\n"; + mDynamicModelFile << " if (nlhs >= 2)\n"; + mDynamicModelFile << " {\n"; + mDynamicModelFile << " /* Set the output pointer to the output matrix g1. */\n"; + if (computeJacobianExo) + mDynamicModelFile << " plhs[1] = mxCreateDoubleMatrix(" << ModelParameters::eq_nbr << ", " << VariableTable::size() << ", mxREAL);\n"; + else if (computeJacobian) + mDynamicModelFile << " plhs[1] = mxCreateDoubleMatrix(" << ModelParameters::eq_nbr << ", " << ModelParameters::var_endo_nbr << ", mxREAL);\n"; + mDynamicModelFile << " /* Create a C pointer to a copy of the output matrix g1. */\n"; + mDynamicModelFile << " g1 = mxGetPr(plhs[1]);\n"; + mDynamicModelFile << " }\n\n"; + mDynamicModelFile << " g2 = NULL;\n"; + mDynamicModelFile << " if (nlhs >= 3)\n"; + mDynamicModelFile << " {\n"; + mDynamicModelFile << " /* Set the output pointer to the output matrix g2. */\n"; + mDynamicModelFile << " plhs[2] = mxCreateDoubleMatrix(" << ModelParameters::eq_nbr << ", " << VariableTable::size()*VariableTable::size() << ", mxREAL);\n"; + mDynamicModelFile << " /* Create a C pointer to a copy of the output matrix g1. */\n"; + mDynamicModelFile << " g2 = mxGetPr(plhs[2]);\n"; + mDynamicModelFile << " }\n\n"; + mDynamicModelFile << " /* Gets model parameters from global workspace of Matlab */\n"; + mDynamicModelFile << " M_ = mexGetVariable(\"global\",\"M_\");\n"; + mDynamicModelFile << " if (M_ == NULL )\n"; + mDynamicModelFile << " {\n"; + mDynamicModelFile << " mexPrintf(\"Global variable not found : \");\n"; + mDynamicModelFile << " mexErrMsgTxt(\"M_ \\n\");\n"; + mDynamicModelFile << " }\n"; + mDynamicModelFile << " params = mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_,\"params\")));\n"; + mDynamicModelFile << " /* Gets it_ from global workspace of Matlab */\n"; + mDynamicModelFile << " it_ = (int) floor(mxGetScalar(mexGetVariable(\"global\", \"it_\")))-1;\n"; + mDynamicModelFile << " /* Call the C subroutines. */\n"; + mDynamicModelFile << " Dynamic(y, x, residual, g1, g2);\n"; + mDynamicModelFile << "}\n"; + mDynamicModelFile.close(); + } } //------------------------------------------------------------------------------ void ModelTree::derive(int iOrder) { - NodeID lToken; // To store current working token - NodeID lD1, lD2; // To store derivative arguments of - // current argument - NodeID lArg1, lArg2; // To store current arguments - Type lType1; // Type of first argument - NodeID t1,t11,t12,t13, - t14, t15; // To store temoporary result arguments - TreeIterator BeginIT; // Iterator of the 1st token to derive - TreeIterator EndIT; // Iterator of the last token to derive - TreeIterator currentIT; // Iterator (counter) for model tree loop + NodeID lToken; // To store current working token + NodeID lD1, lD2; // To store derivative arguments of + // current argument + NodeID lArg1, lArg2; // To store current arguments + Type lType1; // Type of first argument + NodeID t1,t11,t12,t13, + t14, t15; // To store temoporary result arguments + TreeIterator BeginIT; // Iterator of the 1st token to derive + TreeIterator EndIT; // Iterator of the last token to derive + TreeIterator currentIT; // Iterator (counter) for model tree loop - vector EqualTokenIDs; // IDs of "equal token" in model Tree - // Capturing equation IDs - for (currentIT = BeginModel; currentIT != mModelTree.end(); currentIT++) - { - if ((*currentIT)->op_code == EQUAL) - { - EqualTokenIDs.push_back(*currentIT); - // Equation is forced to be in Model Tree as refferenced - // This is usfull to remove symetric elements - (*currentIT)->reference_count[0]++; - } - } - //std::cout << "size " << EqualTokenIDs.size() << "\n"; - mDerivativeIndex.resize(iOrder); - // Uncomment this to print model tree data - /* - //cout << "ModelTree==================================\n"; - for (currentIT = mModelTree.begin(); currentIT != mModelTree.end(); currentIT++) - { - lToken = *currentIT; - int ID = lToken->idx; - cout << ID << ":" << lToken << "->" << lToken->id1 << " " << lToken->type1 << " " << - lToken->id2 << " " << lToken->op_code << "\n"; - } - */ + vector EqualTokenIDs; // IDs of "equal token" in model Tree + // Capturing equation IDs + for (currentIT = BeginModel; currentIT != mModelTree.end(); currentIT++) + { + if ((*currentIT)->op_code == EQUAL) + { + EqualTokenIDs.push_back(*currentIT); + // Equation is forced to be in Model Tree as refferenced + // This is usfull to remove symetric elements + (*currentIT)->reference_count[0]++; + } + } + std::cout << "size " << EqualTokenIDs.size() << "\n"; + mDerivativeIndex.resize(iOrder); + // Uncomment this to print model tree data + /* + //cout << "ModelTree==================================\n"; + for (currentIT = mModelTree.begin(); currentIT != mModelTree.end(); currentIT++) + { + lToken = *currentIT; + int ID = lToken->idx; + cout << ID << ":" << lToken << "->" << lToken->id1 << " " << lToken->type1 << " " << + lToken->id2 << " " << lToken->op_code << "\n"; + } + */ - EndIT = mModelTree.begin(); - EndIT--; - cout << "Processing derivation ...\n"; - // loop on order of derivation - for(int Order = 1; Order <= iOrder; Order++) - { + EndIT = mModelTree.begin(); + EndIT--; + cout << "Processing derivation ...\n"; + // loop on order of derivation + for(int Order = 1; Order <= iOrder; Order++) + { + + cout << "\tProcessing Order " << Order << "... "; + current_order = Order; + BeginIT = EndIT; + BeginIT++; + EndIT = mModelTree.end(); + EndIT--; + // Adding a reference counter for current order to tokens in mModelTree + // and updating them - cout << "\tProcessing Order " << Order << "... "; - current_order = Order; - BeginIT = EndIT; - BeginIT++; - EndIT = mModelTree.end(); - EndIT--; - // Adding a reference counter for current order to tokens in mModelTree - // and updating them + for (TreeIterator it = mModelTree.begin(); it != mModelTree.end(); it++) + { + int s = (*it)->reference_count.size(); + for (int i = s; i <= current_order; i++) + { + int rc = (*it)->reference_count[i-1]; + (*it)->reference_count.push_back(rc); + } + } + // Loop on variables of derivation + for (int var = 0; var < VariableTable::size(); var++) + { + + + // Loop on tokens + for (currentIT = BeginIT;; currentIT++) + { + //cout << "Token " << (*currentIT)->idx << endl; + if (accumulate((*currentIT)->reference_count.begin(), (*currentIT)->reference_count.end(),0) > 0) + { + lToken = *currentIT;//mModelTree[TokenCount]; - for (TreeIterator it = mModelTree.begin(); it != mModelTree.end(); it++) - { - int s = (*it)->reference_count.size(); - for (int i = s; i <= current_order; i++) - { - int rc = (*it)->reference_count[i-1]; - (*it)->reference_count.push_back(rc); - } - } - // Loop on variables of derivation - for (int var = 0; var < VariableTable::size(); var++) - { + lArg1 = lToken->id1; + lArg2 = lToken->id2; + lType1 = lToken->type1; + lD1 = DeriveArgument(lArg1, lType1, var); + lD2 = Zero; + if (lArg2 != NullID) + lD2 = DeriveArgument(lArg2, eTempResult, var); + // Case where token is a final argument + if (lToken->op_code == NoOpCode) + { + setDerivativeAdress(*currentIT, lD1, var); + } + else if (lD1 == Zero && lD2 == Zero) + { + setDerivativeAdress(*currentIT, Zero, var); + } + else + { + switch (lToken->op_code) + { + case UMINUS: + t1 = AddUMinus(lD1); + setDerivativeAdress(*currentIT, t1, var); + break; + case PLUS: + t1 = AddPlus(lD1, lD2); + setDerivativeAdress(*currentIT, t1, var); + break; + case MINUS: + t1 = AddMinus(lD1, lD2); + setDerivativeAdress(*currentIT, t1, var); + break; + case TIMES: + t11 = AddTimes(lD1, lArg2); + t12 = AddTimes(lD2, lArg1); + t1 = AddPlus(t11, t12); + setDerivativeAdress(*currentIT, t1, var); + break; + case DIVIDE: + t11 = AddTimes(lD1, lArg2); + t12 = AddTimes(lD2, lArg1); + t13 = AddMinus(t11, t12); + t14 = AddTimes(lArg2, lArg2); + t1 = AddDivide(t13, t14); + setDerivativeAdress(*currentIT, t1, var); + break; + case SQRT: + t11 = AddPlus(*currentIT, *currentIT); + t1 = AddDivide(lD1, t11); + setDerivativeAdress(*currentIT, t1,var); + break; + case POWER: + if (lD2 == Zero) + { + if (lD1 == Zero) + t1 = Zero; + else + { + t11 = AddMinus(lArg2, One); + t12 = AddPower(lArg1, t11); + t13 = AddTimes(lArg2, t12); + t1 = AddTimes(lD1, t13); + } + } + else + { + t11 = AddLog(lArg1); + t12 = AddTimes(lD2, t11); + t13 = AddTimes(lD1, lArg2); + t14 = AddDivide(t13, lArg1); + t15 = AddPlus(t12, t14); + t1 = AddTimes(t15, *currentIT); + } + setDerivativeAdress(*currentIT, t1, var); + break; + case EXP: + t1 = AddTimes(lD1, *currentIT); + setDerivativeAdress(*currentIT, t1, var); + break; + case LOG: + t1 = AddDivide(lD1, lArg1); + setDerivativeAdress(*currentIT, t1, var); + break; + case LOG10: + t11 = AddExp(One); + t12 = AddLog10(t11); + t13 = AddDivide(lD1, lArg1); + t1 = AddTimes(t12, t13); + setDerivativeAdress(*currentIT, t1, var); + break; + case COS: + t11 = AddSin(lArg1); + t12 = AddUMinus(t11); + t1 = AddTimes( lD1, t12); + setDerivativeAdress(*currentIT, t1, var); + break; + case SIN: + t11 = AddCos(lArg1); + t1 = AddTimes(lD1,t11); + setDerivativeAdress(*currentIT, t1, var); + break; + case TAN: + t11 = AddTimes(*currentIT, *currentIT); + t12 = AddPlus(t11, One); + t1 = AddTimes(lD1, t12); + setDerivativeAdress(*currentIT, t1, var); + break; + case ACOS: + t11 = AddSin(*currentIT); + t12 = AddDivide(lD1, t11); + t1 = AddUMinus(t12); + setDerivativeAdress(*currentIT, t1, var); + break; + case ASIN: + t11 = AddCos(*currentIT); + t1 = AddDivide(lD1, t11); + setDerivativeAdress(*currentIT, t1, var); + break; + case ATAN: + t11 = AddTimes(lArg1, lArg1); + t12 = AddPlus(One, t11); + t1 = AddDivide(lD1, t12); + setDerivativeAdress(*currentIT, t1,var); + break; + case COSH: + t11 = AddSinH(lArg1); + t1 = AddTimes( lD1,t11); + setDerivativeAdress(*currentIT, t1, var); + break; + case SINH: + t11 = AddCosH(lArg1); + t1 = AddTimes( lD1, t11); + setDerivativeAdress(*currentIT, t1, var); + break; + case TANH: + t11 = AddTimes(*currentIT, *currentIT); + t12 = AddMinus(One, t11); + t1 = AddTimes(lD1, t12); + setDerivativeAdress(*currentIT, t1,var); + break; + case ACOSH: + t11 = AddSinH(*currentIT); + t1 = AddDivide(lD1, t11); + setDerivativeAdress(*currentIT, t1,var); + break; + case ASINH: + t11 = AddCosH(*currentIT); + t1 = AddDivide(lD1, t11); + setDerivativeAdress(*currentIT, t1,var); + break; + case ATANH: + t11 = AddTimes(lArg1, lArg1); + t12 = AddMinus(One, t11); + t1 = AddTimes(lD1, t12); + setDerivativeAdress(*currentIT, t1,var); + break; + } + } + } + if (currentIT == EndIT) break; + } - - // Loop on tokens - for (currentIT = BeginIT;; currentIT++) - { - //cout << "Token " << (*currentIT)->idx << endl; - if (accumulate((*currentIT)->reference_count.begin(), (*currentIT)->reference_count.end(),0) > 0) - { - lToken = *currentIT;//mModelTree[TokenCount]; - - lArg1 = lToken->id1; - lArg2 = lToken->id2; - lType1 = lToken->type1; - lD1 = DeriveArgument(lArg1, lType1, var); - lD2 = Zero; - if (lArg2 != NullID) - lD2 = DeriveArgument(lArg2, eTempResult, var); - // Case where token is a final argument - if (lToken->op_code == NoOpCode) - { - setDerivativeAdress(*currentIT, lD1, var); - } - else if (lD1 == Zero && lD2 == Zero) - { - setDerivativeAdress(*currentIT, Zero, var); - } - else - { - switch (lToken->op_code) - { - case UMINUS: - t1 = AddUMinus(lD1); - setDerivativeAdress(*currentIT, t1, var); - break; - case PLUS: - t1 = AddPlus(lD1, lD2); - setDerivativeAdress(*currentIT, t1, var); - break; - case MINUS: - t1 = AddMinus(lD1, lD2); - setDerivativeAdress(*currentIT, t1, var); - break; - case TIMES: - t11 = AddTimes(lD1, lArg2); - t12 = AddTimes(lD2, lArg1); - t1 = AddPlus(t11, t12); - setDerivativeAdress(*currentIT, t1, var); - break; - case DIVIDE: - t11 = AddTimes(lD1, lArg2); - t12 = AddTimes(lD2, lArg1); - t13 = AddMinus(t11, t12); - t14 = AddTimes(lArg2, lArg2); - t1 = AddDivide(t13, t14); - setDerivativeAdress(*currentIT, t1, var); - break; - case SQRT: - t11 = AddPlus(*currentIT, *currentIT); - t1 = AddDivide(lD1, t11); - setDerivativeAdress(*currentIT, t1,var); - break; - case POWER: - if (lD2 == Zero) - { - if (lD1 == Zero) - t1 = Zero; - else - { - t11 = AddMinus(lArg2, One); - t12 = AddPower(lArg1, t11); - t13 = AddTimes(lArg2, t12); - t1 = AddTimes(lD1, t13); - } - } - else - { - t11 = AddLog(lArg1); - t12 = AddTimes(lD2, t11); - t13 = AddTimes(lD1, lArg2); - t14 = AddDivide(t13, lArg1); - t15 = AddPlus(t12, t14); - t1 = AddTimes(t15, *currentIT); - } - setDerivativeAdress(*currentIT, t1, var); - break; - case EXP: - t1 = AddTimes(lD1, *currentIT); - setDerivativeAdress(*currentIT, t1, var); - break; - case LOG: - t1 = AddDivide(lD1, lArg1); - setDerivativeAdress(*currentIT, t1, var); - break; - case LOG10: - t11 = AddExp(One); - t12 = AddLog10(t11); - t13 = AddDivide(lD1, lArg1); - t1 = AddTimes(t12, t13); - setDerivativeAdress(*currentIT, t1, var); - break; - case COS: - t11 = AddSin(lArg1); - t12 = AddUMinus(t11); - t1 = AddTimes( lD1, t12); - setDerivativeAdress(*currentIT, t1, var); - break; - case SIN: - t11 = AddCos(lArg1); - t1 = AddTimes(lD1,t11); - setDerivativeAdress(*currentIT, t1, var); - break; - case TAN: - t11 = AddTimes(*currentIT, *currentIT); - t12 = AddPlus(t11, One); - t1 = AddTimes(lD1, t12); - setDerivativeAdress(*currentIT, t1, var); - break; - case ACOS: - t11 = AddSin(*currentIT); - t12 = AddDivide(lD1, t11); - t1 = AddUMinus(t12); - setDerivativeAdress(*currentIT, t1, var); - break; - case ASIN: - t11 = AddCos(*currentIT); - t1 = AddDivide(lD1, t11); - setDerivativeAdress(*currentIT, t1, var); - break; - case ATAN: - t11 = AddTimes(lArg1, lArg1); - t12 = AddPlus(One, t11); - t1 = AddDivide(lD1, t12); - setDerivativeAdress(*currentIT, t1,var); - break; - case COSH: - t11 = AddSinH(lArg1); - t1 = AddTimes( lD1,t11); - setDerivativeAdress(*currentIT, t1, var); - break; - case SINH: - t11 = AddCosH(lArg1); - t1 = AddTimes( lD1, t11); - setDerivativeAdress(*currentIT, t1, var); - break; - case TANH: - t11 = AddTimes(*currentIT, *currentIT); - t12 = AddMinus(One, t11); - t1 = AddTimes(lD1, t12); - setDerivativeAdress(*currentIT, t1,var); - break; - case ACOSH: - t11 = AddSinH(*currentIT); - t1 = AddDivide(lD1, t11); - setDerivativeAdress(*currentIT, t1,var); - break; - case ASINH: - t11 = AddCosH(*currentIT); - t1 = AddDivide(lD1, t11); - setDerivativeAdress(*currentIT, t1,var); - break; - case ATANH: - t11 = AddTimes(lArg1, lArg1); - t12 = AddMinus(One, t11); - t1 = AddTimes(lD1, t12); - setDerivativeAdress(*currentIT, t1,var); - break; - } - } - } - if (currentIT == EndIT) - break; - } - - // Treating equal tokens - // Skeeping symetric elements - //vector::iterator tree_it2 = mModelTree.begin(); - //int id = 0; - int starti = var*Order*(Order-1)*ModelParameters::eq_nbr/2; - for (unsigned int i = starti; i < EqualTokenIDs.size() ; i++ ) - { - lToken = EqualTokenIDs[i]; - lArg1 = lToken->id1; - lArg2 = lToken->id2; - lType1 = lToken->type1; - lD1 = DeriveArgument(lArg1, lType1, var); - lD2 = DeriveArgument(lArg2, eTempResult, var); - // If one hand sid is null, take the other - if (lD1 == Zero && lD2 != Zero) - { - t11 = AddUMinus(lD2); - t1 = AddEqual(t11, Zero); - } - else if (lD1 != Zero && lD2 == Zero) - { - t1 = AddEqual(lD1, Zero); - } - else - { - t11 = AddMinus(lD1, lD2); - t1 = AddEqual(t11, Zero); - } - // The derivative is forced to be in Model Tree as refferenced - // This is usfull to remove symetric elements - IncrementReferenceCount(t1); - setDerivativeAdress(EqualTokenIDs[i], t1, var); - if (Order == 1) - { - mDerivativeIndex[0].push_back(DerivativeIndex(t1, i-starti, var)); - } - else if (Order == 2) - { - int var1 = VariableTable::getSortID(i/ModelParameters::eq_nbr); - int var2 = VariableTable::getSortID(var); - mDerivativeIndex[1].push_back(DerivativeIndex( - t1, - i-ModelParameters::eq_nbr*(i/ModelParameters::eq_nbr), - var1*VariableTable::size()+var2)); - } - } - - } - // Uncomment to debug : prints unreferenced tokens - /* - cout << "Order : " << Order << "\n"; - for (TokenCount = BeginModel; TokenCount < mModelTree.size() ; TokenCount++ ) - { - if (accumulate(mModelTree[TokenCount].reference_count.begin(),mModelTree[TokenCount].reference_count.end(),0) == 0) - cout << "\tNot referenced : token ID :" << TokenCount << endl; - } - */ - // Uncomment this to debug : mDerivative(1and2)Index data - // before removing unreferenced tokens - /* - cout << "Contenence of mDerivative1Index\n"; - for (int i=0; i< mDerivativeIndex[0].size();i++) - //if (mDerivativeIndex[0][i].token_id != 3) - cout << "\t" << mDerivativeIndex[0][i].token_id << endl; - cout << "Contenence of mDerivative2Index\n"; - for (int i=0; i< mDerivativeIndex[1].size();i++) - //if (mDerivativeIndex[1][i].token_id != 3) - cout << "\t" << mDerivativeIndex[1][i].token_id << endl; - */ - //cout << "Removing unreferenced tokens range ids :" << CurrentID << " - " << mModelTree.size()-1 << endl; - // Removing unreferenced tokens in last derivative - // RemoveUnref(CurrentID, mModelTree.size()-1, Order); - // Decrementing reference couter of unreferenced tokens in last derivative - //DecrementUnref(CurrentID, mModelTree.size()-1, Order); - /* - cout << "Order : " << Order << "\n"; - for (TokenCount = BeginModel; TokenCount < mModelTree.size() ; TokenCount++ ) - { - if (accumulate(mModelTree[TokenCount].reference_count.begin(),mModelTree[TokenCount].reference_count.end(),0) == 0) - cout << "\tNot referenced : token ID :" << TokenCount << endl; - } - */ - EqualTokenIDs.clear(); - // Updating EqualTokenIDs - for (unsigned int i=0; i< mDerivativeIndex[Order-1].size();i++) - { - EqualTokenIDs.push_back(mDerivativeIndex[Order-1][i].token_id); - } - - // Uncomment this to debug : mDerivative(1and2)Index data - // after removing unreferenced tokens - /* - cout << "Contenence of mDerivative1Index after removing\n"; - for (int i=0; i< mDerivativeIndex[0].size();i++) - if (mDerivativeIndex[0][i].token_id != 3) - cout << "\t" << mDerivativeIndex[0][i].token_id << endl; - cout << "Contenence of mDerivative2Index after removing\n"; - for (int i=0; i< mDerivativeIndex[1].size();i++) - //if (mDerivativeIndex[1][i].token_id != 3) - cout << "\t" << mDerivativeIndex[1][i].token_id << endl; - */ - cout << "done \n"; + // Treating equal tokens + // Skeeping symetric elements + //vector::iterator tree_it2 = mModelTree.begin(); + //int id = 0; + int starti = var*Order*(Order-1)*ModelParameters::eq_nbr/2; + for (unsigned int i = starti; i < EqualTokenIDs.size() ; i++ ) + { + lToken = EqualTokenIDs[i]; + lArg1 = lToken->id1; + lArg2 = lToken->id2; + lType1 = lToken->type1; + lD1 = DeriveArgument(lArg1, lType1, var); + lD2 = DeriveArgument(lArg2, eTempResult, var); + // If one hand sid is null, take the other + if (lD1 == Zero && lD2 != Zero) + { + t11 = AddUMinus(lD2); + t1 = AddEqual(t11, Zero); + } + else if (lD1 != Zero && lD2 == Zero) + { + t1 = AddEqual(lD1, Zero); + } + else + { + t11 = AddMinus(lD1, lD2); + t1 = AddEqual(t11, Zero); + } + // The derivative is forced to be in Model Tree as refferenced + // This is usfull to remove symetric elements + IncrementReferenceCount(t1); + setDerivativeAdress(EqualTokenIDs[i], t1, var); + if (Order == 1) + { + mDerivativeIndex[0].push_back(DerivativeIndex(t1, i-starti, var)); + } + else if (Order == 2) + { + int var1 = VariableTable::getSortID(i/ModelParameters::eq_nbr); + int var2 = VariableTable::getSortID(var); + mDerivativeIndex[1].push_back(DerivativeIndex( + t1, + i-ModelParameters::eq_nbr*(i/ModelParameters::eq_nbr), + var1*VariableTable::size()+var2)); + } + } + + } + // Uncomment to debug : prints unreferenced tokens + /* + cout << "Order : " << Order << "\n"; + for (TokenCount = BeginModel; TokenCount < mModelTree.size() ; TokenCount++ ) + { + if (accumulate(mModelTree[TokenCount].reference_count.begin(),mModelTree[TokenCount].reference_count.end(),0) == 0) + cout << "\tNot referenced : token ID :" << TokenCount << endl; + } + */ + // Uncomment this to debug : mDerivative(1and2)Index data + // before removing unreferenced tokens + /* + cout << "Contenence of mDerivative1Index\n"; + for (int i=0; i< mDerivativeIndex[0].size();i++) + //if (mDerivativeIndex[0][i].token_id != 3) + cout << "\t" << mDerivativeIndex[0][i].token_id << endl; + cout << "Contenence of mDerivative2Index\n"; + for (int i=0; i< mDerivativeIndex[1].size();i++) + //if (mDerivativeIndex[1][i].token_id != 3) + cout << "\t" << mDerivativeIndex[1][i].token_id << endl; + */ + //cout << "Removing unreferenced tokens range ids :" << CurrentID << " - " << mModelTree.size()-1 << endl; + // Removing unreferenced tokens in last derivative + // RemoveUnref(CurrentID, mModelTree.size()-1, Order); + // Decrementing reference couter of unreferenced tokens in last derivative + //DecrementUnref(CurrentID, mModelTree.size()-1, Order); + /* + cout << "Order : " << Order << "\n"; + for (TokenCount = BeginModel; TokenCount < mModelTree.size() ; TokenCount++ ) + { + if (accumulate(mModelTree[TokenCount].reference_count.begin(),mModelTree[TokenCount].reference_count.end(),0) == 0) + cout << "\tNot referenced : token ID :" << TokenCount << endl; + } + */ + EqualTokenIDs.clear(); + // Updating EqualTokenIDs + for (unsigned int i=0; i< mDerivativeIndex[Order-1].size();i++) + { + EqualTokenIDs.push_back(mDerivativeIndex[Order-1][i].token_id); + } + + // Uncomment this to debug : mDerivative(1and2)Index data + // after removing unreferenced tokens + /* + cout << "Contenence of mDerivative1Index after removing\n"; + for (int i=0; i< mDerivativeIndex[0].size();i++) + if (mDerivativeIndex[0][i].token_id != 3) + cout << "\t" << mDerivativeIndex[0][i].token_id << endl; + cout << "Contenence of mDerivative2Index after removing\n"; + for (int i=0; i< mDerivativeIndex[1].size();i++) + //if (mDerivativeIndex[1][i].token_id != 3) + cout << "\t" << mDerivativeIndex[1][i].token_id << endl; + */ + cout << "done \n"; } } //------------------------------------------------------------------------------ inline bool ModelTree::writeAsTemp(NodeID id) { - int ref_count = id->reference_count[current_order]; - if (( ref_count > 1) && (ref_count*(id->cost) > min_cost)) - return true; - else - return false; + int ref_count = id->reference_count[current_order]; + if (( ref_count > 1) && (ref_count*(id->cost) > min_cost)) + return true; + else + return false; } //------------------------------------------------------------------------------ inline NodeID ModelTree::DeriveArgument(NodeID iArg, Type iType, int iVarID) { - NodeID d; - switch(iType) - { - case eTempResult : - d = iArg->d1[iVarID]; - return d; - break; - case eExogenous : - case eExogenousDet : - case eEndogenous : - case eRecursiveVariable : - if ((int) iArg == iVarID) - //if ((VariableTable::getSymbolID(iArg) == VariableTable::getSymbolID(iVarID)) && - // (VariableTable::getType(iArg) == VariableTable::getType(iVarID))) - { - /* - cout << SymbolTable::getNameByID(iType, - VariableTable::getSymbolID(iArg)) << endl; - cout << SymbolTable::getNameByID(iType, - VariableTable::getSymbolID(iVarID)) << endl; - */ - return One; - } - else - { - return Zero; - } - break; - case eNumericalConstant : - case eParameter : - return Zero; - break; - case eLocalParameter : - return Zero; - break; - case eUNDEF : - return NullID; - break; - case eLoopIndex : - case eUnkownFunction : - return Zero; - break; - default : - cout << "ModelTree::DeriveArgument : Error :Unkown Type \n"; - exit(-1); - }; - + NodeID d; + switch(iType) + { + case eTempResult : + d = iArg->d1[iVarID]; + return d; + break; + case eExogenous : + case eExogenousDet : + case eEndogenous : + case eRecursiveVariable : + if ((int) iArg == iVarID) + //if ((VariableTable::getSymbolID(iArg) == VariableTable::getSymbolID(iVarID)) && + // (VariableTable::getType(iArg) == VariableTable::getType(iVarID))) + { + /* + cout << SymbolTable::getNameByID(iType, + VariableTable::getSymbolID(iArg)) << endl; + cout << SymbolTable::getNameByID(iType, + VariableTable::getSymbolID(iVarID)) << endl; + */ + return One; + } + else + { + return Zero; + } + break; + case eNumericalConstant : + case eParameter : + return Zero; + break; + case eLocalParameter : + return Zero; + break; + case eUNDEF : + return NullID; + break; + case eLoopIndex : + case eUnkownFunction : + return Zero; + break; + default : + cout << "ModelTree::DeriveArgument : Error :Unkown Type \n"; + exit(-1); + }; + } //------------------------------------------------------------------------------ inline void ModelTree::setDerivativeAdress(NodeID iTokenID, NodeID iDerivative,int iVarID) { - //Derivative lDerivative; - - //lDerivative.variable_id = iVarID; - //lDerivative.derivative_address = iDerivative; - iTokenID->d1[iVarID] = iDerivative; - //mModelTree[iDerivative].p1[iVarID] = iTokenID; + //Derivative lDerivative; + + //lDerivative.variable_id = iVarID; + //lDerivative.derivative_address = iDerivative; + iTokenID->d1[iVarID] = iDerivative; + //mModelTree[iDerivative].p1[iVarID] = iTokenID; } //------------------------------------------------------------------------------ -string ModelTree::setStaticModel(void) +string ModelTree::setStaticModel(void) { - TreeIterator tree_it; - int lEquationNBR = 0; - ostringstream model_output; // Used for storing model equations - ostringstream model_tmp_output; // Used for storing tmp expressions for model equations - ostringstream jacobian_output; // Used for storing jacobian equations - ostringstream jacobian_tmp_output; // Used for storing tmp expressions for jacobian equations - - int d = current_order; // Minimum number of times a temparary expression apears in equations - int EquationNBR; // Number of model equations - - EquationNBR = ModelParameters::eq_nbr; - // Reference count of token "0=0" is set to 0 - // Not to be printed as a temp expression - fill(ZeroEqZero->reference_count.begin(), - ZeroEqZero->reference_count.end(),0); - // Writing model Equations - current_order = 1; - tree_it = BeginModel; - for (; tree_it != mModelTree.end(); tree_it++) + TreeIterator tree_it; + int lEquationNBR = 0; + ostringstream model_output; // Used for storing model equations + ostringstream model_tmp_output; // Used for storing tmp expressions for model equations + ostringstream jacobian_output; // Used for storing jacobian equations + ostringstream jacobian_tmp_output; // Used for storing tmp expressions for jacobian equations + + int d = current_order; // Minimum number of times a temparary expression apears in equations + int EquationNBR; // Number of model equations + + EquationNBR = ModelParameters::eq_nbr; + // Reference count of token "0=0" is set to 0 + // Not to be printed as a temp expression + fill(ZeroEqZero->reference_count.begin(), + ZeroEqZero->reference_count.end(),0); + // Writing model Equations + current_order = 1; + tree_it = BeginModel; + for (; tree_it != mModelTree.end(); tree_it++) { - if ((*tree_it)->op_code == EQUAL || (*tree_it)->op_code == ASSIGN ) - { - if ((*tree_it)->id1->type1 == eLocalParameter) - { - model_output << getExpression((*tree_it)->id1, eStaticEquations, lEquationNBR); - model_output << " = "; - model_output << getExpression((*tree_it)->id2, eStaticEquations, lEquationNBR) << ";" << endl; - } - else if (lEquationNBR < ModelParameters::eq_nbr) - { - model_output << "lhs ="; - model_output << getExpression((*tree_it)->id1, eStaticEquations, lEquationNBR) << ";" << endl; - model_output << "rhs ="; - model_output << getExpression((*tree_it)->id2, eStaticEquations, lEquationNBR) << ";" << endl; - model_output << "residual" << lpar << lEquationNBR+1 << rpar << "= lhs-rhs;" << endl; - lEquationNBR++; - } - else - break; - } - else if ((*tree_it)->op_code != NoOpCode) - { - if (optimize(*tree_it)) - { - model_output << "T" << (*tree_it)->idx << "=" << getExpression(*tree_it, eStaticEquations, lEquationNBR) << ";" << endl; - (*tree_it)->tmp_status = 1; - } - else - { - (*tree_it)->tmp_status = 0; - } - } + if ((*tree_it)->op_code == EQUAL || (*tree_it)->op_code == ASSIGN ) + { + if ((*tree_it)->id1->type1 == eLocalParameter) + { + model_output << getExpression((*tree_it)->id1, eStaticEquations, lEquationNBR); + model_output << " = "; + model_output << getExpression((*tree_it)->id2, eStaticEquations, lEquationNBR) << ";" << endl; + } + else if (lEquationNBR < ModelParameters::eq_nbr) + { + model_output << "lhs ="; + model_output << getExpression((*tree_it)->id1, eStaticEquations, lEquationNBR) << ";" << endl; + model_output << "rhs ="; + model_output << getExpression((*tree_it)->id2, eStaticEquations, lEquationNBR) << ";" << endl; + model_output << "residual" << lpar << lEquationNBR+1 << rpar << "= lhs-rhs;" << endl; + lEquationNBR++; + } + else break; + } + else if ((*tree_it)->op_code != NoOpCode) + { + if (optimize(*tree_it)) + { + model_output << "T" << (*tree_it)->idx << "=" << getExpression(*tree_it, eStaticEquations, lEquationNBR) << ";" << endl; + (*tree_it)->tmp_status = 1; + } + else + { + (*tree_it)->tmp_status = 0; + } + } } - // Writing Jacobian for endogenous variables without lag - for(; tree_it != mModelTree.end(); tree_it++) + // Writing Jacobian for endogenous variables without lag + for(; tree_it != mModelTree.end(); tree_it++) { - if ((*tree_it)->op_code != NoOpCode - && (*tree_it)->op_code != EQUAL - && (*tree_it)->op_code != ASSIGN) - { - if (optimize(*tree_it) == 1) - { - jacobian_output << "T" << (*tree_it)->idx << "=" << getExpression(*tree_it, eStaticEquations, lEquationNBR) << ";" << endl; - (*tree_it)->tmp_status = 1; - } - else - { - (*tree_it)->tmp_status = 0; - } - } + if ((*tree_it)->op_code != NoOpCode + && (*tree_it)->op_code != EQUAL + && (*tree_it)->op_code != ASSIGN) + { + if (optimize(*tree_it) == 1) + { + jacobian_output << "T" << (*tree_it)->idx << "=" << getExpression(*tree_it, eStaticEquations, lEquationNBR) << ";" << endl; + (*tree_it)->tmp_status = 1; + } + else + { + (*tree_it)->tmp_status = 0; + } + } } - lEquationNBR = 0; - for (unsigned int i = 0; i < mDerivativeIndex[0].size(); i++) + lEquationNBR = 0; + for (unsigned int i = 0; i < mDerivativeIndex[0].size(); i++) { - if (VariableTable::getType(mDerivativeIndex[0][i].derivators) == eEndogenous) - { - NodeID startJacobian = mDerivativeIndex[0][i].token_id; - if (startJacobian != ZeroEqZero) - { - string exp = getExpression(startJacobian->id1, eStaticDerivatives); - ostringstream g1; - g1 << " g1" << lpar << mDerivativeIndex[0][i].equation_id+1 << ", " << - VariableTable::getSymbolID(mDerivativeIndex[0][i].derivators)+1 << rpar; - jacobian_output << g1.str() << "=" << g1.str() << "+" << exp << ";\n"; - } - } + if (VariableTable::getType(mDerivativeIndex[0][i].derivators) == eEndogenous) + { + NodeID startJacobian = mDerivativeIndex[0][i].token_id; + if (startJacobian != ZeroEqZero) + { + string exp = getExpression(startJacobian->id1, eStaticDerivatives); + ostringstream g1; + g1 << " g1" << lpar << mDerivativeIndex[0][i].equation_id+1 << ", " << + VariableTable::getSymbolID(mDerivativeIndex[0][i].derivators)+1 << rpar; + jacobian_output << g1.str() << "=" << g1.str() << "+" << exp << ";\n"; + } + } } - // Writing ouputs - if (offset == 1) + // Writing ouputs + if (offset == 1) { - StaticOutput << "global M_ \n"; - StaticOutput << "if M_.param_nbr > 0\n params = M_.params;\nend\n"; + StaticOutput << "global M_ \n"; + StaticOutput << "if M_.param_nbr > 0\n params = M_.params;\nend\n"; - StaticOutput << " residual = zeros( " << ModelParameters::eq_nbr << ", 1);\n"; - StaticOutput << "\n\t"+interfaces::comment()+"\n\t"+interfaces::comment(); - StaticOutput << "Model equations\n\t"; - StaticOutput << interfaces::comment() + "\n\n"; - StaticOutput << model_output.str(); - StaticOutput << "if ~isreal(residual)\n"; - StaticOutput << " residual = real(residual)+imag(residual).^2;\n"; - StaticOutput << "end\n"; - StaticOutput << "if nargout >= 2,\n"; - StaticOutput << " g1 = " << - "zeros(" << ModelParameters::eq_nbr << ", " << - ModelParameters::endo_nbr << ");\n" ; - StaticOutput << "\n\t"+interfaces::comment()+"\n\t"+interfaces::comment(); - StaticOutput << "Jacobian matrix\n\t"; - StaticOutput << interfaces::comment() + "\n\n"; - StaticOutput << jacobian_output.str(); - StaticOutput << " if ~isreal(g1)\n"; - StaticOutput << " g1 = real(g1)+2*imag(g1);\n"; - StaticOutput << " end\n"; - StaticOutput << "end\n"; + StaticOutput << " residual = zeros( " << ModelParameters::eq_nbr << ", 1);\n"; + StaticOutput << "\n\t"+interfaces::comment()+"\n\t"+interfaces::comment(); + StaticOutput << "Model equations\n\t"; + StaticOutput << interfaces::comment() + "\n\n"; + StaticOutput << model_output.str(); + StaticOutput << "if ~isreal(residual)\n"; + StaticOutput << " residual = real(residual)+imag(residual).^2;\n"; + StaticOutput << "end\n"; + StaticOutput << "if nargout >= 2,\n"; + StaticOutput << " g1 = " << + "zeros(" << ModelParameters::eq_nbr << ", " << + ModelParameters::endo_nbr << ");\n" ; + StaticOutput << "\n\t"+interfaces::comment()+"\n\t"+interfaces::comment(); + StaticOutput << "Jacobian matrix\n\t"; + StaticOutput << interfaces::comment() + "\n\n"; + StaticOutput << jacobian_output.str(); + StaticOutput << " if ~isreal(g1)\n"; + StaticOutput << " g1 = real(g1)+2*imag(g1);\n"; + StaticOutput << " end\n"; + StaticOutput << "end\n"; } - else + else { - StaticOutput << "void Static(double *y, double *x, double *residual, double *g1)\n"; - StaticOutput << "{\n"; - StaticOutput << " double lhs, rhs;\n\n"; - // Writing residual equations - StaticOutput << " /* Residual equations */\n"; - StaticOutput << " if (residual == NULL) return;\n"; - StaticOutput << " {\n"; - StaticOutput << model_output.str(); - // Writing Jacobian - StaticOutput << " /* Jacobian for endogenous variables without lag */\n"; - StaticOutput << " if (g1 == NULL) return;\n"; - StaticOutput << " {\n"; - StaticOutput << jacobian_output.str(); - StaticOutput << " }\n"; - StaticOutput << " }\n"; - StaticOutput << "}\n\n"; + StaticOutput << "void Static(double *y, double *x, double *residual, double *g1)\n"; + StaticOutput << "{\n"; + StaticOutput << " double lhs, rhs;\n\n"; + // Writing residual equations + StaticOutput << " /* Residual equations */\n"; + StaticOutput << " if (residual == NULL) return;\n"; + StaticOutput << " {\n"; + StaticOutput << model_output.str(); + // Writing Jacobian + StaticOutput << " /* Jacobian for endogenous variables without lag */\n"; + StaticOutput << " if (g1 == NULL) return;\n"; + StaticOutput << " {\n"; + StaticOutput << jacobian_output.str(); + StaticOutput << " }\n"; + StaticOutput << " }\n"; + StaticOutput << "}\n\n"; } - current_order = d; - return StaticOutput.str(); + current_order = d; + return StaticOutput.str(); } - - -/*New*/ - -void reverse(char *s) -{ - int c, i, j; - for(i=0,j=strlen(s)-1;i0); - if (sign<0) - i++; - s=(char*)malloc(i); - i=0; - do - { - s[i++]=n % 10+'0'; - } - while((n/=10)>0); - if (sign<0) - s[i++]='-'; - s[i]='\0'; - reverse(s); - return(s); -} - -char* strcopy(char *s,int pos1,int pos2) -{ - int i; - char* st; - st=(char*)malloc(pos2-pos1+1); - for(i=pos1;iSize]; - typedef struct vari - { - int Index; - vari *pNext; - }; - typedef struct variable - { - int Size; - vari *list; - vari *First_list; - }; - string Jacobian[ModelBlock->Size],Jacobian_s[ModelBlock->Size]; - variable *v_Jacobian, *v_Jacobian_s; - int i,j,k,l,l1,n,m,p; - int d = current_order; - bool finish, OK; - int *Table, *leaded; - int TableSize; - v_Jacobian=(variable*)malloc(ModelBlock->Size*sizeof(*v_Jacobian)); - v_Jacobian_s=(variable*)malloc(ModelBlock->Size*sizeof(*v_Jacobian_s)); - leaded=(int*)malloc(ModelBlock->Size*sizeof(int)); - fill(ZeroEqZero->reference_count.begin(), - ZeroEqZero->reference_count.end(),0); - - // Clearing output string - model_output.str(""); - sModel=""; - sOptimize=""; - jacobian_output.str(""); - // Getting equations from model tree - // Starting from the end of equation - // Searching for the next '=' operator, - current_order = 1; - lEquationNBR = 0; - cout << "\tequations .. "; - list_tree_it=(TreeIterator*)malloc(sizeof(*list_tree_it)*(ModelParameters::endo_nbr+1)); - tree_it = BeginModel; - list_tree_it[lEquationNBR]=tree_it; - for (; tree_it != mModelTree.end(); tree_it++) - { - if ((*tree_it)->op_code == EQUAL) - { - if ((*tree_it)->id1->type1 == eLocalParameter) - ; - else if (lEquationNBR < ModelParameters::eq_nbr) - { - - lEquationNBR++; - tree_it_f=tree_it; - tree_it_f++; - list_tree_it[lEquationNBR]=tree_it_f; - } - else - break; - } - else if ((*tree_it)->op_code != NoOpCode) - (*tree_it)->tmp_status = 0; - } - for(k=0;kSize;k++) - { - Jacobian[k]=""; - Jacobian_s[k]=""; - Equationf[k]=""; - leaded[k]=0; - v_Jacobian[k].First_list=NULL; - v_Jacobian[k].Size=0; - v_Jacobian_s[k].First_list=NULL; - v_Jacobian_s[k].Size=0; - } - G_tree_it=tree_it; - G_tree_it--; - - - lEquationNBR=0; - Table=VariableTable::GetVariableTable(&TableSize); - for(j=0;jSize;j++) - { - Equationf[j]="//Block "; - Equationf[j]=Equationf[j]+itoa(j+1)+" "+BlockTriangular::BlockType0(ModelBlock->Block_List[j].Type)+"\n"; - ModelBlock->Block_List[j].Simulation_Type=UNKNOWN; - for(i=0;iBlock_List[j].Size;i++) - { - sModel=SymbolTable::getNameByID(eEndogenous,ModelBlock->Block_List[j].Variable[i]) ; - ModelBlock->Block_List[j].Variable_Sorted[i]=VariableTable::GetVariableID(sModel, 0); - Equationf[j]=Equationf[j]+"//equation "+itoa(ModelBlock->Block_List[j].Equation[i]+1)+" variable : "+ - sModel+" ("+itoa(ModelBlock->Block_List[j].Variable_Sorted[i])+")\n"; - finish=0; - for(tree_it=list_tree_it[ModelBlock->Block_List[j].Equation[i]];/*!finish*/tree_it!=list_tree_it[ModelBlock->Block_List[j].Equation[i]+1];tree_it++) - { - if ((*tree_it)->op_code == EQUAL) - { - if ((*tree_it)->id1->type1 == eLocalParameter) - { - Equationf[j]=Equationf[j]+getExpression((*tree_it)->id1, eStaticEquations, lEquationNBR)+" = "+ - getExpression((*tree_it)->id2, eStaticEquations, lEquationNBR)+";\n"; - } - else if (lEquationNBR < ModelParameters::eq_nbr) - { - if ((ModelBlock->Block_List[j].Type==PROLOGUE)||(ModelBlock->Block_List[j].Type==EPILOGUE)) - { - sModel=getExpression(((*tree_it)->id2), eDynamicEquations, lEquationNBR); - OK=1; - for(k=0;kBlock_List[j].Variable_Sorted[i]) - { - n=Table[k*4]; - break; - } - for(k=0;k0) - { - if((ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)||(Table[k*4+1]==0)) - { - OK=0; - if(ModelBlock->Block_List[j].Simulation_Type!=SOLVE_TWO_BOUNDARIES_SIMPLE) - { - if(ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD) - ModelBlock->Block_List[j].Simulation_Type=SOLVE_BACKWARD_SIMPLE; - else - ModelBlock->Block_List[j].Simulation_Type=SOLVE_FOREWARD_SIMPLE; - } - } - else - { - if(Table[k*4+1]<0) - if((ModelBlock->Block_List[j].Simulation_Type==UNKNOWN)||(ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FOREWARD)) - ModelBlock->Block_List[j].Simulation_Type=EVALUATE_FOREWARD; - else - ModelBlock->Block_List[j].Simulation_Type=SOLVE_TWO_BOUNDARIES_SIMPLE; - if(Table[k*4+1]>0) - if((ModelBlock->Block_List[j].Simulation_Type==UNKNOWN)||(ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD)) - ModelBlock->Block_List[j].Simulation_Type=EVALUATE_BACKWARD; - else - ModelBlock->Block_List[j].Simulation_Type=SOLVE_TWO_BOUNDARIES_SIMPLE; - } - } - } - sModel=getExpression(((*tree_it)->id1), eDynamicEquations, lEquationNBR); - tmp_s=""; - tmp_s=tmp_s+"y["+itoa(ModelBlock->Block_List[j].Variable_Sorted[i])+"]"; - if(tmp_s!=sModel) - { - OK=0; - if((ModelBlock->Block_List[j].Simulation_Type==UNKNOWN)||(ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FOREWARD)) - ModelBlock->Block_List[j].Simulation_Type=SOLVE_FOREWARD_SIMPLE; - else if(ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD) - ModelBlock->Block_List[j].Simulation_Type=SOLVE_BACKWARD_SIMPLE; - } - else - if(ModelBlock->Block_List[j].Simulation_Type==UNKNOWN) - ModelBlock->Block_List[j].Simulation_Type=EVALUATE_FOREWARD; - if (!OK) - Equationf[j]=Equationf[j]+"residual"+lpar+/*itoa(lEquationNBR+1)*/itoa(i+1)+rpar+"= ("+ - sModel+")-("+ - getExpression(((*tree_it)->id2), eDynamicEquations, lEquationNBR)+");\n"; - else - Equationf[j]=Equationf[j]+ - sModel+"="+ - getExpression(((*tree_it)->id2), eDynamicEquations, lEquationNBR)+";\n"; - } - else - { - if((ModelBlock->Block_List[j].Max_Lag>0)&&(ModelBlock->Block_List[j].Max_Lead>0)) - ModelBlock->Block_List[j].Simulation_Type=SOLVE_TWO_BOUNDARIES_COMPLETE; - else if((ModelBlock->Block_List[j].Max_Lag==0)&&(ModelBlock->Block_List[j].Max_Lead>0)) - ModelBlock->Block_List[j].Simulation_Type=SOLVE_BACKWARD_COMPLETE; - else - ModelBlock->Block_List[j].Simulation_Type=SOLVE_FOREWARD_COMPLETE; - Equationf[j]=Equationf[j]+"residual"+lpar+/*itoa(lEquationNBR+1)*/itoa(i+1)+rpar+"= ("+ - getExpression(((*tree_it)->id1), eDynamicEquations, lEquationNBR)+")-("+ - getExpression(((*tree_it)->id2), eDynamicEquations, lEquationNBR)+");\n"; - } - lEquationNBR++; - } - else - break; - } - else if ((*tree_it)->op_code != NoOpCode) - { - if (optimize(*tree_it)) - { - sModel="T"; - sModel=sModel+itoa((*tree_it)->idx); - if (sOptimize=="") - sOptimize=sModel; - else - if(offset==1) - sOptimize=sOptimize+" "+sModel; - else - sOptimize=sOptimize+", "+sModel; - Equationf[j]=Equationf[j]+sModel+"="+getExpression(*tree_it, eDynamicEquations, lEquationNBR)+";\n"; - (*tree_it)->tmp_status = 1; - } - else - { - (*tree_it)->tmp_status = 0; - } - } - finish=(tree_it==list_tree_it[ModelBlock->Block_List[j].Equation[i]+1]); - if(G_tree_it != mModelTree.end()) - { - if ((*G_tree_it)->op_code != NoOpCode && (*G_tree_it)->op_code != EQUAL) - { - if (optimize(*G_tree_it) == 1) - { - sModel="T"; - sModel=sModel+itoa((*G_tree_it)->idx); - if (sOptimize=="") - sOptimize=sModel; - else - if(offset==1) - sOptimize=sOptimize+" "+sModel; - else - sOptimize=sOptimize+", "+sModel; - Equationf[j]=Equationf[j]+sModel+"="+getExpression(*G_tree_it, eDynamicEquations, lEquationNBR)+";\n"; - (*G_tree_it)->tmp_status = 1; - } - else - { - (*G_tree_it)->tmp_status = 0; - } - } - G_tree_it++; - } - } - } - } - for(k = 0; k < mDerivativeIndex[0].size(); k++) - { - if (computeJacobianExo || VariableTable::getType(mDerivativeIndex[0][k].derivators) == eEndogenous) - { - NodeID startJacobian = mDerivativeIndex[0][k].token_id; - if (startJacobian != ZeroEqZero) - { - string exp = getExpression(startJacobian->id1, eDynamicDerivatives); - ostringstream g1; - j=ModelBlock->in_Block_Equ[mDerivativeIndex[0][k].equation_id]; - i=0; - while((mDerivativeIndex[0][k].equation_id!=ModelBlock->Block_List[j].Equation[i])&&(iBlock_List[j].Size)) - { - i++; - } - n=VariableTable::getSortID(mDerivativeIndex[0][k].derivators); - l=0; - while((n!=Table[l*4+2])&&(lBlock_List[j].Size;n++) - if(ModelBlock->Block_List[j].Variable[n]==l1) - { - finish=1; - break; - } - if(finish) - { - g1.str(""); - m=-1; - if(v_Jacobian[j].Size>0) - { - v_Jacobian[j].list=v_Jacobian[j].First_list; - p=0; - while((v_Jacobian[j].list->Index!=(VariableTable::getSortID(mDerivativeIndex[0][k].derivators)))&&(v_Jacobian[j].list->pNext!=NULL)) - { - p++; - v_Jacobian[j].list=v_Jacobian[j].list->pNext; - } - if(v_Jacobian[j].list->Index==(VariableTable::getSortID(mDerivativeIndex[0][k].derivators))) - m= mDerivativeIndex[0][k].derivators; - while(v_Jacobian[j].list->pNext!=NULL) - v_Jacobian[j].list=v_Jacobian[j].list->pNext; - } - if(m<0) - { - if(offset!=2) - g1 << " g1" << lpar << i+1 << "," << v_Jacobian[j].Size+1 << rpar; - else - g1 << " g1" << lpar << i+1 << "*" << itoa(ModelBlock->Block_List[j].Size) << "+" << v_Jacobian[j].Size+1 << rpar; - Jacobian[j]=Jacobian[j]+g1.str()+"="+g1.str()+"+"+exp+"; /*" - +SymbolTable::getNameByID(eEndogenous,VariableTable::/*getSortID*/VariableTable::getSymbolID(mDerivativeIndex[0][k].derivators))+ - +"("+itoa(VariableTable::getLag(mDerivativeIndex[0][k].derivators))+") " - +itoa(VariableTable::getSortID(mDerivativeIndex[0][k].derivators))+"*/\n"; - if(v_Jacobian[j].First_list==NULL) - { - v_Jacobian[j].First_list=(vari*)malloc(sizeof(vari)); - v_Jacobian[j].list=v_Jacobian[j].First_list; - } - else - { - v_Jacobian[j].list->pNext=(vari*)malloc(sizeof(vari)); - v_Jacobian[j].list=v_Jacobian[j].list->pNext; - } - v_Jacobian[j].list->pNext=NULL; - v_Jacobian[j].list->Index=VariableTable::getSortID(mDerivativeIndex[0][k].derivators); - v_Jacobian[j].Size++; - } - else - { - if(offset!=2) - g1 << " g1" << lpar << i+1 << "," << p+1 << rpar; - else - g1 << " g1" << lpar << i+1 << "*" << itoa(ModelBlock->Block_List[j].Size) << "+" << p+1 << rpar; - Jacobian[j]=Jacobian[j]+g1.str()+"="+g1.str()+"+"+exp+"; /*" - +SymbolTable::getNameByID(eEndogenous,VariableTable::/*getSortID*/VariableTable::getSymbolID(m))+ - +"("+itoa(VariableTable::getLag(m))+") " - +itoa(VariableTable::getSortID(m))+"*/\n"; - } - if(Table[l*4+1]==0) - { - g1.str(""); - m=-1; - if(v_Jacobian_s[j].Size>0) - { - v_Jacobian_s[j].list=v_Jacobian_s[j].First_list; - p=0; - while((v_Jacobian_s[j].list->Index!=(VariableTable::getSortID(mDerivativeIndex[0][k].derivators)))&&(v_Jacobian_s[j].list->pNext!=NULL)) - { - p++; - v_Jacobian_s[j].list=v_Jacobian_s[j].list->pNext; - } - if(v_Jacobian_s[j].list->Index==(VariableTable::getSortID(mDerivativeIndex[0][k].derivators))) - m= mDerivativeIndex[0][k].derivators; - while(v_Jacobian_s[j].list->pNext!=NULL) - v_Jacobian_s[j].list=v_Jacobian_s[j].list->pNext; - } - if(m<0) - { - if(offset!=2) - g1 << " g1" << lpar << i+1 << "," << v_Jacobian_s[j].Size+1 << rpar; - else - g1 << " g1" << lpar << i+1 << "*" << itoa(ModelBlock->Block_List[j].Size) << "+" << v_Jacobian_s[j].Size+1 << rpar; - Jacobian_s[j]=Jacobian_s[j]+g1.str()+"="+g1.str()+"+"+exp+"; /*" - +SymbolTable::getNameByID(eEndogenous,VariableTable::/*getSortID*/getSymbolID(mDerivativeIndex[0][k].derivators))+ - +"("+itoa(VariableTable::getLag(mDerivativeIndex[0][k].derivators))+") " - +itoa(VariableTable::getSortID(mDerivativeIndex[0][k].derivators))+"*/\n"; - if(v_Jacobian_s[j].First_list==NULL) - { - v_Jacobian_s[j].First_list=(vari*)malloc(sizeof(vari)); - v_Jacobian_s[j].list=v_Jacobian_s[j].First_list; - } - else - { - v_Jacobian_s[j].list->pNext=(vari*)malloc(sizeof(vari)); - v_Jacobian_s[j].list=v_Jacobian_s[j].list->pNext; - } - v_Jacobian_s[j].list->pNext=NULL; - v_Jacobian_s[j].list->Index=VariableTable::getSortID(mDerivativeIndex[0][k].derivators); - v_Jacobian_s[j].Size++; - } - else - { - if(offset!=2) - g1 << " g1" << lpar << i+1 << "," << p+1 << rpar; - else - g1 << " g1" << lpar << i+1 << "*" << itoa(ModelBlock->Block_List[j].Size) << "+" << p+1 << rpar; - Jacobian_s[j]=Jacobian_s[j]+g1.str()+"="+g1.str()+"+"+exp+"; /*" - +SymbolTable::getNameByID(eEndogenous,VariableTable::/*getSortID*/getSymbolID(m))+ - +"("+itoa(VariableTable::getLag(m))+") " - +itoa(VariableTable::getSortID(m))+"*/\n"; - } - } - if(Table[l*4+1]>0) - leaded[j]=1; - } - } - } - } - finish=0; - while(!finish) - { - if(G_tree_it != mModelTree.end()) - { - if ((*G_tree_it)->op_code != NoOpCode && (*G_tree_it)->op_code != EQUAL) - { - if (optimize(*G_tree_it) == 1) - { - sModel="T"; - sModel=sModel+itoa((*G_tree_it)->idx); - if (sOptimize=="") - sOptimize=sModel; - else - if(offset==1) - sOptimize=sOptimize+" "+sModel; - else - sOptimize=sOptimize+", "+sModel; - Equationf[j]=Equationf[j]+sModel+"="+getExpression(*G_tree_it, eDynamicEquations, lEquationNBR)+";\n"; - (*G_tree_it)->tmp_status = 1; - } - else - { - (*G_tree_it)->tmp_status = 0; - } - } - G_tree_it++; - } - else - finish=1; - } - cout << "done \n"; - if (computeHessian) - { - // Getting Hessian from model tree - // Starting from the end of equation - // Searching for the next '=' operator, - lEquationNBR = 0; - cout << "\tHessian .. "; - for (unsigned int i = 0; i < mDerivativeIndex[1].size(); i++) - { - NodeID startHessian = mDerivativeIndex[1][i].token_id; - //cout << "ID = " << startHessian << " exp = " << exp << "\n"; - if (startHessian != ZeroEqZero) - { - string exp = getExpression(startHessian->id1, eDynamicDerivatives); - - int varID1 = mDerivativeIndex[1][i].derivators/VariableTable::size(); - int varID2 = mDerivativeIndex[1][i].derivators-varID1*VariableTable::size(); - hessian_output << " g2" << lpar << mDerivativeIndex[1][i].equation_id+1 << ", " << - mDerivativeIndex[1][i].derivators+1 << rpar << " = " << exp << ";\n"; - // Treating symetric elements - if (varID1 != varID2) - lsymetric << " g2" << lpar << mDerivativeIndex[1][i].equation_id+1 << ", " << - varID2*VariableTable::size()+varID1+1 << rpar << " = " << - "g2" << lpar << mDerivativeIndex[1][i].equation_id+1 << ", " << - mDerivativeIndex[1][i].derivators+1 << rpar << ";\n"; - } - - } - cout << "done \n"; - } - int nrows = ModelParameters::eq_nbr; - if (offset == 1) - { - DynamicOutput << "global M_ it_\n"; - DynamicOutput << "global "+sOptimize+"\n"; - DynamicOutput << "if M_.param_nbr > 0\n params = M_.params;\nend\n"; - DynamicOutput << "\n\t%\n\t% Model equations\n\t%\n\n"; - DynamicOutput << "residual = zeros(" << nrows << ", 1);\n"; - - DynamicOutput << model_output.str(); - - if (computeJacobian || computeJacobianExo) - { - DynamicOutput << "if nargout >= 2,\n"; - // Writing initialization instruction for matrix g1 - DynamicOutput << " g1 = " << - "zeros(" << nrows << ", " << VariableTable::size() << ");\n" ; - DynamicOutput << "\n\t%\n\t% Jacobian matrix\n\t%\n\n"; - DynamicOutput << jacobian_output.str(); - DynamicOutput << "end\n"; - } - if (computeHessian) - { - DynamicOutput << "if nargout >= 3,\n"; - // Writing initialization instruction for matrix g2 - int ncols = VariableTable::size()*VariableTable::size(); - DynamicOutput << " g2 = " << - "sparse([],[],[]," << nrows << ", " << ncols << ", " << - 5*ncols << ");\n"; - DynamicOutput << "\n\t%\n\t% Hessian matrix\n\t%\n\n"; - DynamicOutput << hessian_output.str() << lsymetric.str(); - DynamicOutput << "end;\n"; - } - } - else - { - if ((offset==2)&&(sOptimize.size()>0)) - DynamicOutput << "double "+sOptimize+";\n"; - for(j=0;jSize;j++) - { - DynamicOutput << "void Dynamic" << j+1 << "(double *y, double *x, double *residual, double *g1, double *g2)\n"; - DynamicOutput << "{\n"; - if((ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FOREWARD)&&(ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD)) - { - v_Jacobian[j].list=v_Jacobian[j].First_list; - v_Jacobian_s[j].list=v_Jacobian_s[j].First_list; - if(leaded[j]==1) - { - ModelBlock->Block_List[j].Sized=v_Jacobian[j].Size; - ModelBlock->Block_List[j].dVariable=(int*)malloc(v_Jacobian[j].Size*sizeof(int)); - for(i=0;iBlock_List[j].dVariable[i]=v_Jacobian[j].list->Index; - v_Jacobian[j].list=v_Jacobian[j].list->pNext; - } - } - else - { - ModelBlock->Block_List[j].Sized=v_Jacobian_s[j].Size; - ModelBlock->Block_List[j].dVariable=(int*)malloc(v_Jacobian[j].Size*sizeof(int)); - for(i=0;iBlock_List[j].dVariable[i]=v_Jacobian_s[j].list->Index; - v_Jacobian_s[j].list=v_Jacobian_s[j].list->pNext; - } - } - } - else - { - ModelBlock->Block_List[j].Sized=0; - } - DynamicOutput << Equationf[j]; - if ((computeJacobian || computeJacobianExo)&&(ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FOREWARD)&&(ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD)) - { - DynamicOutput << " /* Jacobian */\n"; - DynamicOutput << " if (g1 == NULL) return;\n"; - DynamicOutput << " {\n"; - if(leaded[j]==1) - DynamicOutput << Jacobian[j]; - else - DynamicOutput << Jacobian_s[j]; - DynamicOutput << " }\n"; - } - if (computeHessian) - { - DynamicOutput << " /* Hessian for endogenous and exogenous variables */\n"; - DynamicOutput << " if (g2 == NULL) return;\n"; - DynamicOutput << " {\n"; - DynamicOutput << hessian_output.str() << lsymetric.str(); - DynamicOutput << " }\n"; - } - DynamicOutput << "}\n\n"; - } - } - current_order = d; - free(leaded); - return DynamicOutput.str(); -} -/*EndNew*/ - - - - //------------------------------------------------------------------------------ string ModelTree::setDynamicModel(void) { - TreeIterator tree_it; - int lEquationNBR = 0; - ostringstream lsymetric; // Used when writing symetric elements - ostringstream model_output; // Used for storing model equations - ostringstream model_tmp_output; // Used for storing tmp expressions for model equations - ostringstream jacobian_output; // Used for storing jacobian equations - ostringstream jacobian_tmp_output; // Used for storing tmp expressions for jacobian equations - ostringstream hessian_output; // Used for storing Hessian equations - ostringstream hessian_tmp_output; // Used for storing tmp expressions for Hessian equations + TreeIterator tree_it; + int lEquationNBR = 0; + ostringstream lsymetric; // Used when writing symetric elements + ostringstream model_output; // Used for storing model equations + ostringstream model_tmp_output; // Used for storing tmp expressions for model equations + ostringstream jacobian_output; // Used for storing jacobian equations + ostringstream jacobian_tmp_output; // Used for storing tmp expressions for jacobian equations + ostringstream hessian_output; // Used for storing Hessian equations + ostringstream hessian_tmp_output; // Used for storing tmp expressions for Hessian equations + + int d = current_order; + + + + // Reference count of token "0=0" is set to 0 + // Not to be printed as a temp expression + fill(ZeroEqZero->reference_count.begin(), + ZeroEqZero->reference_count.end(),0); - int d = current_order; - - - - // Reference count of token "0=0" is set to 0 - // Not to be printed as a temp expression - fill(ZeroEqZero->reference_count.begin(), - ZeroEqZero->reference_count.end(),0); - - // Clearing output string - model_output.str(""); - jacobian_output.str(""); - // Getting equations from model tree - // Starting from the end of equation - // Searching for the next '=' operator, - current_order = 1; - lEquationNBR = 0; - cout << "\tequations .. "; - tree_it = BeginModel; - for (; tree_it != mModelTree.end(); tree_it++) + // Clearing output string + model_output.str(""); + jacobian_output.str(""); + // Getting equations from model tree + // Starting from the end of equation + // Searching for the next '=' operator, + current_order = 1; + lEquationNBR = 0; + cout << "\tequations .. "; + tree_it = BeginModel; + for (; tree_it != mModelTree.end(); tree_it++) { - if ((*tree_it)->op_code == EQUAL || (*tree_it)->op_code == ASSIGN) - { - if ((*tree_it)->id1->type1 == eLocalParameter) - { - model_output << getExpression((*tree_it)->id1, eStaticEquations, lEquationNBR); - model_output << " = "; - model_output << getExpression((*tree_it)->id2, eStaticEquations, lEquationNBR) << ";" << endl; - } - else if (lEquationNBR < ModelParameters::eq_nbr) - { - model_output << "lhs ="; - model_output << getExpression(((*tree_it)->id1), eDynamicEquations, lEquationNBR) << ";" << endl; - model_output << "rhs ="; - model_output << getExpression(((*tree_it)->id2), eDynamicEquations, lEquationNBR) << ";" << endl; - model_output << "residual" << lpar << lEquationNBR+1 << rpar << "= lhs-rhs;" << endl; - lEquationNBR++; - } - else - break; - } - else if ((*tree_it)->op_code != NoOpCode) - { - if (optimize(*tree_it)) - { - model_output << "T" << (*tree_it)->idx << "=" << getExpression(*tree_it, eDynamicEquations, lEquationNBR) << ";" << endl; - (*tree_it)->tmp_status = 1; - } - else - { - (*tree_it)->tmp_status = 0; - } - } + if ((*tree_it)->op_code == EQUAL || (*tree_it)->op_code == ASSIGN) + { + if ((*tree_it)->id1->type1 == eLocalParameter) + { + model_output << getExpression((*tree_it)->id1, eStaticEquations, lEquationNBR); + model_output << " = "; + model_output << getExpression((*tree_it)->id2, eStaticEquations, lEquationNBR) << ";" << endl; + } + else if (lEquationNBR < ModelParameters::eq_nbr) + { + model_output << "lhs ="; + model_output << getExpression(((*tree_it)->id1), eDynamicEquations, lEquationNBR) << ";" << endl; + model_output << "rhs ="; + model_output << getExpression(((*tree_it)->id2), eDynamicEquations, lEquationNBR) << ";" << endl; + model_output << "residual" << lpar << lEquationNBR+1 << rpar << "= lhs-rhs;" << endl; + lEquationNBR++; + } + else break; + } + else if ((*tree_it)->op_code != NoOpCode) + { + if (optimize(*tree_it)) + { + model_output << "T" << (*tree_it)->idx << "=" << getExpression(*tree_it, eDynamicEquations, lEquationNBR) << ";" << endl; + (*tree_it)->tmp_status = 1; + } + else + { + (*tree_it)->tmp_status = 0; + } + } } - for(; tree_it != mModelTree.end(); tree_it++) + for(; tree_it != mModelTree.end(); tree_it++) { - if ((*tree_it)->op_code != NoOpCode - && (*tree_it)->op_code != EQUAL - && (*tree_it)->op_code != ASSIGN) - { - if (optimize(*tree_it) == 1) - { - jacobian_output << "T" << (*tree_it)->idx << "=" << getExpression(*tree_it, eDynamicEquations, lEquationNBR) << ";" << endl; - (*tree_it)->tmp_status = 1; - } - else - { - (*tree_it)->tmp_status = 0; - } - } + if ((*tree_it)->op_code != NoOpCode + && (*tree_it)->op_code != EQUAL + && (*tree_it)->op_code != ASSIGN) + { + if (optimize(*tree_it) == 1) + { + jacobian_output << "T" << (*tree_it)->idx << "=" << getExpression(*tree_it, eDynamicEquations, lEquationNBR) << ";" << endl; + (*tree_it)->tmp_status = 1; + } + else + { + (*tree_it)->tmp_status = 0; + } + } } - cout << "done \n"; - // Getting Jacobian from model tree - if (computeJacobian || computeJacobianExo) + cout << "done \n"; + // Getting Jacobian from model tree + if (computeJacobian || computeJacobianExo) { - cout << "\tJacobian .. "; - for(; tree_it != mModelTree.end(); tree_it++) - { - if ((*tree_it)->op_code != NoOpCode - && (*tree_it)->op_code != EQUAL - && (*tree_it)->op_code != ASSIGN) - { - if (optimize(*tree_it) == 1) - { - jacobian_output << "T" << (*tree_it)->idx << "=" << getExpression(*tree_it, eDynamicEquations, lEquationNBR) << ";" << endl; - (*tree_it)->tmp_status = 1; - } - else - { - (*tree_it)->tmp_status = 0; - } - } - } + cout << "\tJacobian .. "; + for(; tree_it != mModelTree.end(); tree_it++) + { + if ((*tree_it)->op_code != NoOpCode + && (*tree_it)->op_code != EQUAL + && (*tree_it)->op_code != ASSIGN) + { + if (optimize(*tree_it) == 1) + { + jacobian_output << "T" << (*tree_it)->idx << "=" << getExpression(*tree_it, eDynamicEquations, lEquationNBR) << ";" << endl; + (*tree_it)->tmp_status = 1; + } + else + { + (*tree_it)->tmp_status = 0; + } + } + } - lEquationNBR = 0; - for (unsigned int i = 0; i < mDerivativeIndex[0].size(); i++) - { - if (computeJacobianExo || VariableTable::getType(mDerivativeIndex[0][i].derivators) == eEndogenous) - { - NodeID startJacobian = mDerivativeIndex[0][i].token_id; - if (startJacobian != ZeroEqZero) - { - string exp = getExpression(startJacobian->id1, eDynamicDerivatives); - ostringstream g1; - g1 << " g1" << lpar << mDerivativeIndex[0][i].equation_id+1 << ", " << - VariableTable::getSortID(mDerivativeIndex[0][i].derivators)+1 << rpar; - jacobian_output << g1.str() << "=" << g1.str() << "+" << exp << ";\n"; - } - } - } - cout << "done \n"; + lEquationNBR = 0; + for (unsigned int i = 0; i < mDerivativeIndex[0].size(); i++) + { + if (computeJacobianExo || VariableTable::getType(mDerivativeIndex[0][i].derivators) == eEndogenous) + { + NodeID startJacobian = mDerivativeIndex[0][i].token_id; + if (startJacobian != ZeroEqZero) + { + string exp = getExpression(startJacobian->id1, eDynamicDerivatives); + ostringstream g1; + g1 << " g1" << lpar << mDerivativeIndex[0][i].equation_id+1 << ", " << + VariableTable::getSortID(mDerivativeIndex[0][i].derivators)+1 << rpar; + jacobian_output << g1.str() << "=" << g1.str() << "+" << exp << ";\n"; + } + } + } + cout << "done \n"; } - if (computeHessian) + if (computeHessian) { - // Getting Hessian from model tree - // Starting from the end of equation - // Searching for the next '=' operator, - lEquationNBR = 0; - cout << "\tHessian .. "; - for (unsigned int i = 0; i < mDerivativeIndex[1].size(); i++) - { - NodeID startHessian = mDerivativeIndex[1][i].token_id; - //cout << "ID = " << startHessian << " exp = " << exp << "\n"; - if (startHessian != ZeroEqZero) - { - string exp = getExpression(startHessian->id1, eDynamicDerivatives); + // Getting Hessian from model tree + // Starting from the end of equation + // Searching for the next '=' operator, + lEquationNBR = 0; + cout << "\tHessian .. "; + for (unsigned int i = 0; i < mDerivativeIndex[1].size(); i++) + { + NodeID startHessian = mDerivativeIndex[1][i].token_id; + //cout << "ID = " << startHessian << " exp = " << exp << "\n"; + if (startHessian != ZeroEqZero) + { + string exp = getExpression(startHessian->id1, eDynamicDerivatives); - int varID1 = mDerivativeIndex[1][i].derivators/VariableTable::size(); - int varID2 = mDerivativeIndex[1][i].derivators-varID1*VariableTable::size(); - hessian_output << " g2" << lpar << mDerivativeIndex[1][i].equation_id+1 << ", " << - mDerivativeIndex[1][i].derivators+1 << rpar << " = " << exp << ";\n"; - // Treating symetric elements - if (varID1 != varID2) - lsymetric << " g2" << lpar << mDerivativeIndex[1][i].equation_id+1 << ", " << - varID2*VariableTable::size()+varID1+1 << rpar << " = " << - "g2" << lpar << mDerivativeIndex[1][i].equation_id+1 << ", " << - mDerivativeIndex[1][i].derivators+1 << rpar << ";\n"; - } + int varID1 = mDerivativeIndex[1][i].derivators/VariableTable::size(); + int varID2 = mDerivativeIndex[1][i].derivators-varID1*VariableTable::size(); + hessian_output << " g2" << lpar << mDerivativeIndex[1][i].equation_id+1 << ", " << + mDerivativeIndex[1][i].derivators+1 << rpar << " = " << exp << ";\n"; + // Treating symetric elements + if (varID1 != varID2) + lsymetric << " g2" << lpar << mDerivativeIndex[1][i].equation_id+1 << ", " << + varID2*VariableTable::size()+varID1+1 << rpar << " = " << + "g2" << lpar << mDerivativeIndex[1][i].equation_id+1 << ", " << + mDerivativeIndex[1][i].derivators+1 << rpar << ";\n"; + } - } - cout << "done \n"; + } + cout << "done \n"; } - int nrows = ModelParameters::eq_nbr; - if (offset == 1) + int nrows = ModelParameters::eq_nbr; + if (offset == 1) { - DynamicOutput << "global M_ it_\n"; - DynamicOutput << "if M_.param_nbr > 0\n params = M_.params;\nend\n"; - DynamicOutput << "\n\t"+interfaces::comment()+"\n\t"+interfaces::comment(); - DynamicOutput << "Model equations\n\t"; - DynamicOutput << interfaces::comment() + "\n\n"; - DynamicOutput << "residual = zeros(" << nrows << ", 1);\n"; + DynamicOutput << "global M_ it_\n"; + DynamicOutput << "if M_.param_nbr > 0\n params = M_.params;\nend\n"; + DynamicOutput << "\n\t"+interfaces::comment()+"\n\t"+interfaces::comment(); + DynamicOutput << "Model equations\n\t"; + DynamicOutput << interfaces::comment() + "\n\n"; + DynamicOutput << "residual = zeros(" << nrows << ", 1);\n"; - DynamicOutput << model_output.str(); + DynamicOutput << model_output.str(); - if (computeJacobian || computeJacobianExo) - { - DynamicOutput << "if nargout >= 2,\n"; - // Writing initialization instruction for matrix g1 - DynamicOutput << " g1 = " << - "zeros(" << nrows << ", " << VariableTable::size() << ");\n" ; - DynamicOutput << "\n\t"+interfaces::comment()+"\n\t"+interfaces::comment(); - DynamicOutput << "Jacobian matrix\n\t"; - DynamicOutput << interfaces::comment()+"\n\n"; - DynamicOutput << jacobian_output.str(); - DynamicOutput << "end\n"; - } - if (computeHessian) - { - DynamicOutput << "if nargout >= 3,\n"; - // Writing initialization instruction for matrix g2 - int ncols = VariableTable::size()*VariableTable::size(); - DynamicOutput << " g2 = " << - "sparse([],[],[]," << nrows << ", " << ncols << ", " << - 5*ncols << ");\n"; - DynamicOutput << "\n\t"+interfaces::comment()+"\n\t"+interfaces::comment(); - DynamicOutput << "Hessian matrix\n\t"; - DynamicOutput << interfaces::comment() + "\n\n"; - DynamicOutput << hessian_output.str() << lsymetric.str(); - DynamicOutput << "end;\n"; - } + if (computeJacobian || computeJacobianExo) + { + DynamicOutput << "if nargout >= 2,\n"; + // Writing initialization instruction for matrix g1 + DynamicOutput << " g1 = " << + "zeros(" << nrows << ", " << VariableTable::size() << ");\n" ; + DynamicOutput << "\n\t"+interfaces::comment()+"\n\t"+interfaces::comment(); + DynamicOutput << "Jacobian matrix\n\t"; + DynamicOutput << interfaces::comment()+"\n\n"; + DynamicOutput << jacobian_output.str(); + DynamicOutput << "end\n"; + } + if (computeHessian) + { + DynamicOutput << "if nargout >= 3,\n"; + // Writing initialization instruction for matrix g2 + int ncols = VariableTable::size()*VariableTable::size(); + DynamicOutput << " g2 = " << + "sparse([],[],[]," << nrows << ", " << ncols << ", " << + 5*ncols << ");\n"; + DynamicOutput << "\n\t"+interfaces::comment()+"\n\t"+interfaces::comment(); + DynamicOutput << "Hessian matrix\n\t"; + DynamicOutput << interfaces::comment() + "\n\n"; + DynamicOutput << hessian_output.str() << lsymetric.str(); + DynamicOutput << "end;\n"; + } } - else + else { - DynamicOutput << "void Dynamic(double *y, double *x, double *residual, double *g1, double *g2)\n"; - DynamicOutput << "{\n"; - DynamicOutput << " double lhs, rhs;\n\n"; - DynamicOutput << " /* Residual equations */\n"; - DynamicOutput << model_output.str(); - if (computeJacobian || computeJacobianExo) - { - DynamicOutput << " /* Jacobian */\n"; - DynamicOutput << " if (g1 == NULL) return;\n"; - DynamicOutput << " {\n"; - DynamicOutput << jacobian_output.str(); - DynamicOutput << " }\n"; - } - if (computeHessian) - { - DynamicOutput << " /* Hessian for endogenous and exogenous variables */\n"; - DynamicOutput << " if (g2 == NULL) return;\n"; - DynamicOutput << " {\n"; - DynamicOutput << hessian_output.str() << lsymetric.str(); - DynamicOutput << " }\n"; - } - DynamicOutput << "}\n\n"; + DynamicOutput << "void Dynamic(double *y, double *x, double *residual, double *g1, double *g2)\n"; + DynamicOutput << "{\n"; + DynamicOutput << " double lhs, rhs;\n\n"; + DynamicOutput << " /* Residual equations */\n"; + DynamicOutput << model_output.str(); + if (computeJacobian || computeJacobianExo) + { + DynamicOutput << " /* Jacobian */\n"; + DynamicOutput << " if (g1 == NULL) return;\n"; + DynamicOutput << " {\n"; + DynamicOutput << jacobian_output.str(); + DynamicOutput << " }\n"; + } + if (computeHessian) + { + DynamicOutput << " /* Hessian for endogenous and exogenous variables */\n"; + DynamicOutput << " if (g2 == NULL) return;\n"; + DynamicOutput << " {\n"; + DynamicOutput << hessian_output.str() << lsymetric.str(); + DynamicOutput << " }\n"; + } + DynamicOutput << "}\n\n"; } - current_order = d; - return DynamicOutput.str(); +current_order = d; +return DynamicOutput.str(); } //------------------------------------------------------------------------------ inline string ModelTree::getExpression(NodeID StartID, EquationType iEquationType, int iEquationID) { - // Stack of tokens - stack > stack_token; - ostringstream exp; - NodeID current_token_ID; + // Stack of tokens + stack > stack_token; + ostringstream exp; + NodeID current_token_ID; + + stack_token.push(StartID); + int precedence_last_op = 0; + int last_op_code = 0; + int on_the_right_of_upper_node = 0; - stack_token.push(StartID); - int precedence_last_op = 0; - int last_op_code = 0; - int on_the_right_of_upper_node = 0; - - while (stack_token.size() > 0) + while (stack_token.size() > 0) { - current_token_ID = stack_token.top(); - // defining short hand for current op code - int current_op_code = current_token_ID->op_code; - if ( current_token_ID->tmp_status == 1) - { - exp << "T" << current_token_ID->idx; - // set precedence of terminal token to highest value - precedence_last_op = 100; - stack_token.pop(); - continue; - } - // else if current token is final - else if ( current_op_code == NoOpCode) - { - exp << getArgument(current_token_ID->id1, current_token_ID->type1, iEquationType); - // set precedence of terminal token to highest value - precedence_last_op = 100; - stack_token.pop(); - continue; - } + current_token_ID = stack_token.top(); + // defining short hand for current op code + int current_op_code = current_token_ID->op_code; + if ( current_token_ID->tmp_status == 1) + { + exp << "T" << current_token_ID->idx; + // set precedence of terminal token to highest value + precedence_last_op = 100; + stack_token.pop(); + continue; + } + // else if current token is final + else if ( current_op_code == NoOpCode) + { + exp << getArgument(current_token_ID->id1, current_token_ID->type1, iEquationType); + // set precedence of terminal token to highest value + precedence_last_op = 100; + stack_token.pop(); + continue; + } - int precedence_current_op = operator_table.precedence(current_op_code); - // deal with left argument first - if (current_token_ID->left_done == 0) - { - // if current operator is not a temporary variable and - // of lesser precedence than previous one, insert '(' - if ( precedence_current_op < precedence_last_op || - (on_the_right_of_upper_node == 1 && - (last_op_code == MINUS || last_op_code == DIVIDE) && - (precedence_current_op == precedence_last_op))|| - current_op_code == UMINUS) - { - exp << "("; - current_token_ID->close_parenthesis = 1; - } - // set flag: left argument has been explored - current_token_ID->left_done = 1; - precedence_last_op = precedence_current_op; - last_op_code = current_op_code; - if ( offset == 0 && current_op_code == POWER) - { - exp << "pow("; - precedence_last_op = 0; - current_token_ID->close_parenthesis = 1; - } - else if ( current_op_code == UMINUS) - { - exp << "-"; - current_token_ID->close_parenthesis = 1; - } - else if ( operator_table.isfunction(current_op_code) == true) - { - exp << current_token_ID->op_name << "("; - precedence_last_op = 0; - current_token_ID->close_parenthesis = 1; - } - on_the_right_of_upper_node = 0; - stack_token.push(current_token_ID->id1); - } - // deal with right argument when left branch is entirely explored - else if ( current_token_ID->right_done == 0 ) - { - current_token_ID->right_done = 1; - if ( offset == 0 && current_op_code == POWER) - { - exp << ","; - } + int precedence_current_op = operator_table.precedence(current_op_code); + // deal with left argument first + if (current_token_ID->left_done == 0) + { + // if current operator is not a temporary variable and + // of lesser precedence than previous one, insert '(' + if ( precedence_current_op < precedence_last_op || + (on_the_right_of_upper_node == 1 && + (last_op_code == MINUS || last_op_code == DIVIDE) && + (precedence_current_op == precedence_last_op))|| + current_op_code == UMINUS) + { + exp << "("; + current_token_ID->close_parenthesis = 1; + } + // set flag: left argument has been explored + current_token_ID->left_done = 1; + precedence_last_op = precedence_current_op; + last_op_code = current_op_code; + if ( offset == 0 && current_op_code == POWER) + { + exp << "pow("; + precedence_last_op = 0; + current_token_ID->close_parenthesis = 1; + } + else if ( current_op_code == UMINUS) + { + exp << "-"; + current_token_ID->close_parenthesis = 1; + } + else if ( operator_table.isfunction(current_op_code) == true) + { + exp << current_token_ID->op_name << "("; + precedence_last_op = 0; + current_token_ID->close_parenthesis = 1; + } + on_the_right_of_upper_node = 0; + stack_token.push(current_token_ID->id1); + } + // deal with right argument when left branch is entirely explored + else if ( current_token_ID->right_done == 0 ) + { + current_token_ID->right_done = 1; + if ( offset == 0 && current_op_code == POWER) + { + exp << ","; + } - if ( current_token_ID->id2 != NullID ) - { - exp << current_token_ID->op_name; - precedence_last_op = precedence_current_op; - last_op_code = current_op_code; - on_the_right_of_upper_node = 1; - stack_token.push(current_token_ID->id2); - } - } - else - { - if ( current_token_ID->close_parenthesis == 1) - { - exp << ")"; - } - precedence_last_op = precedence_current_op; - last_op_code = current_op_code; - current_token_ID->left_done=0; - current_token_ID->right_done=0; - current_token_ID->close_parenthesis=0; - stack_token.pop(); - } + if ( current_token_ID->id2 != NullID ) + { + exp << current_token_ID->op_name; + precedence_last_op = precedence_current_op; + last_op_code = current_op_code; + on_the_right_of_upper_node = 1; + stack_token.push(current_token_ID->id2); + } + } + else + { + if ( current_token_ID->close_parenthesis == 1) + { + exp << ")"; + } + precedence_last_op = precedence_current_op; + last_op_code = current_op_code; + current_token_ID->left_done=0; + current_token_ID->right_done=0; + current_token_ID->close_parenthesis=0; + stack_token.pop(); + } } - return exp.str(); + return exp.str(); } //------------------------------------------------------------------------------ /* void ModelTree::RemoveUnref(int iBeginID, int iEndID, int iOrder) { - int id = iEndID; - while (id >= iBeginID) - { - //cout << id; - if (accumulate(mModelTree[id].reference_count.begin(),mModelTree[id].reference_count.end(),0) == 0) - { - //cout << " Removed" << endl; - //Decreasing reference count of arguments model tree - // First argument is a temporary result, - if (mModelTree[id].type1 == eTempResult) - { - //Decreasing reference count of argument 1 in model tree - int arg = mModelTree[id].id1; - mModelTree[arg].reference_count[iOrder]--; - } - // Second argument has id >=0 (temporary result), - if (mModelTree[id].id2 >= 0) - { - //Decreasing reference count of argument 2 in model tree - int arg = mModelTree[id].id2; - mModelTree[arg].reference_count[iOrder]--; - } - //Updating equals ids in mDerivativeIndex - for (int d=0; did) - mDerivativeIndex[iOrder-1][d].token_id--; - } - //cout << "ModelTree size : " << mModelTree.size() << endl; - //Updatting upper token ids in model tree and map - mIndexOfTokens.erase(Key((MToken) mModelTree[id])); - for (int id2 = id+1; id2 <= iEndID; id2++) - { - //cout << " - " << mIndexOfTokens[Key((MToken) mModelTree[id2])]; - mIndexOfTokens.erase(Key((MToken) mModelTree[id2])); - } - //cout << endl; - for (int id2 = id+1; id2 <= iEndID; id2++) - { - // Updating derivative ids - map >::iterator it; - for (it = mModelTree[id2].p1.begin(); it != mModelTree[id2].p1.end(); it++) - { - int p1 = (*it).second; - int var = (*it).first; - //cout << "===========" << mModelTree[p1].d1[var] << "/"; - mModelTree[p1].d1[var] = id2-1; - //cout << mModelTree[p1].d1[var] << endl; - } - // Updating ModelTree map - if (mModelTree[id2].type1 == eTempResult) - { - if (mModelTree[id2].id1>id) - { - mModelTree[id2].id1--; - } - } - if (mModelTree[id2].id2>id) - { - mModelTree[id2].id2--; - } - } - mModelTree.erase(mModelTree.begin()+id); - for (int id2 = id; id2 < iEndID; id2++) - { - mIndexOfTokens[Key((MToken) mModelTree[id2])] = id2; - //cout << " - " << mIndexOfTokens[Key((MToken) mModelTree[id2])]; - } - //Removing token from model tree - //cout << "ModelTree size : " << mModelTree.size() << endl; + int id = iEndID; + while (id >= iBeginID) + { + //cout << id; + if (accumulate(mModelTree[id].reference_count.begin(),mModelTree[id].reference_count.end(),0) == 0) + { + //cout << " Removed" << endl; + //Decreasing reference count of arguments model tree + // First argument is a temporary result, + if (mModelTree[id].type1 == eTempResult) + { + //Decreasing reference count of argument 1 in model tree + int arg = mModelTree[id].id1; + mModelTree[arg].reference_count[iOrder]--; + } + // Second argument has id >=0 (temporary result), + if (mModelTree[id].id2 >= 0) + { + //Decreasing reference count of argument 2 in model tree + int arg = mModelTree[id].id2; + mModelTree[arg].reference_count[iOrder]--; + } + //Updating equals ids in mDerivativeIndex + for (int d=0; did) + mDerivativeIndex[iOrder-1][d].token_id--; + } + //cout << "ModelTree size : " << mModelTree.size() << endl; + //Updatting upper token ids in model tree and map + mIndexOfTokens.erase(Key((MToken) mModelTree[id])); + for (int id2 = id+1; id2 <= iEndID; id2++) + { + //cout << " - " << mIndexOfTokens[Key((MToken) mModelTree[id2])]; + mIndexOfTokens.erase(Key((MToken) mModelTree[id2])); + } + //cout << endl; + for (int id2 = id+1; id2 <= iEndID; id2++) + { + // Updating derivative ids + map >::iterator it; + for (it = mModelTree[id2].p1.begin(); it != mModelTree[id2].p1.end(); it++) + { + int p1 = (*it).second; + int var = (*it).first; + //cout << "===========" << mModelTree[p1].d1[var] << "/"; + mModelTree[p1].d1[var] = id2-1; + //cout << mModelTree[p1].d1[var] << endl; + } + // Updating ModelTree map + if (mModelTree[id2].type1 == eTempResult) + { + if (mModelTree[id2].id1>id) + { + mModelTree[id2].id1--; + } + } + if (mModelTree[id2].id2>id) + { + mModelTree[id2].id2--; + } + } + mModelTree.erase(mModelTree.begin()+id); + for (int id2 = id; id2 < iEndID; id2++) + { + mIndexOfTokens[Key((MToken) mModelTree[id2])] = id2; + //cout << " - " << mIndexOfTokens[Key((MToken) mModelTree[id2])]; + } + //Removing token from model tree + //cout << "ModelTree size : " << mModelTree.size() << endl; - iEndID--; - id--; - } - else - { - id--; - //cout << endl; - } - } + iEndID--; + id--; + } + else + { + id--; + //cout << endl; + } + } } //------------------------------------------------------------------------------ @@ -1973,380 +1249,381 @@ void ModelTree::RemoveUnref(int iBeginID, int iEndID, int iOrder) /* void ModelTree::DecrementUnref(int iBeginID, int iEndID, int iOrder) { - int id = iEndID; - while (id >= iBeginID) - { - //cout << id; - if (accumulate(mModelTree[id].reference_count.begin(),mModelTree[id].reference_count.end(),0) == 0) - { - //Decreasing reference count of arguments model tree - // First argument is a temporary result, - if (mModelTree[id].type1 == eTempResult) - { - //Decreasing reference count of argument 1 in model tree - int arg = mModelTree[id].id1; - mModelTree[arg].reference_count[iOrder]--; - } - // Second argument has id >=0 (temporary result), - if (mModelTree[id].id2 >= 0) - { - //Decreasing reference count of argument 2 in model tree - int arg = mModelTree[id].id2; - mModelTree[arg].reference_count[iOrder]--; - } - id--; - } - else - { - id--; - //cout << endl; - } - } + int id = iEndID; + while (id >= iBeginID) + { + //cout << id; + if (accumulate(mModelTree[id].reference_count.begin(),mModelTree[id].reference_count.end(),0) == 0) + { + //Decreasing reference count of arguments model tree + // First argument is a temporary result, + if (mModelTree[id].type1 == eTempResult) + { + //Decreasing reference count of argument 1 in model tree + int arg = mModelTree[id].id1; + mModelTree[arg].reference_count[iOrder]--; + } + // Second argument has id >=0 (temporary result), + if (mModelTree[id].id2 >= 0) + { + //Decreasing reference count of argument 2 in model tree + int arg = mModelTree[id].id2; + mModelTree[arg].reference_count[iOrder]--; + } + id--; + } + else + { + id--; + //cout << endl; + } + } } */ //------------------------------------------------------------------------------ inline string ModelTree::getArgument(NodeID id, Type type, EquationType iEquationType) { + + stringstream argument; + - stringstream argument; - - - if (type == eParameter) + if (type == eParameter) { - argument << param_name << lpar << (int)id+offset << rpar; + argument << param_name << lpar << (int)id+offset << rpar; } - else if (type == eLocalParameter) + else if (type == eLocalParameter) { - argument << SymbolTable::getNameByID(eLocalParameter,(int)id); + argument << SymbolTable::getNameByID(eLocalParameter,(int)id); } - else if (type == eNumericalConstant) - { - argument << NumericalConstants::get((int) id) - ; - } - else if (type == eEndogenous || type == eExogenous || type == eExogenousDet) - if (iEquationType == eStaticEquations || iEquationType == eStaticDerivatives) - { - int idx = VariableTable::getSymbolID((int) id)+offset; - if (type == eEndogenous) - { - argument << "y" << lpar << idx << rpar; - } - else if (type == eExogenous) - { - argument << "x" << lpar << idx << rpar; - } - else if (type == eExogenousDet) - { - idx += ModelParameters::exo_nbr; - argument << "x" << lpar << idx << rpar; - } - } - else - { - if (type == eEndogenous) - { - int idx = VariableTable::getPrintIndex((int) id)+offset; - argument << "y" << lpar << idx << rpar; - } - else if (type == eExogenous) - { - int idx = VariableTable::getSymbolID((int) id)+offset; - int lag = VariableTable::getLag((int) id); - if (offset == 1) - { - if ( lag != 0) - { - argument << "x" << lpar << "it_ + " << lag - << ", " << idx << rpar; - } - else - { - argument << "x" << lpar << "it_, " << idx << rpar; - } - } - else - { - if ( lag != 0) - { - argument << "x" << lpar << "it_+" << lag - << "+" << idx << "*nb_row_x" << rpar; - } - else - { - argument << "x" << lpar << "it_+" << idx << "*nb_row_x" << rpar; - } - } - } - else if (type == eExogenousDet) - { - int idx = VariableTable::getSymbolID((int) id)+ModelParameters::exo_nbr+offset; - int lag = VariableTable::getLag((int) id); - if (offset == 1) - { - if (lag != 0) - { - argument << "x" << lpar << "it_ + " << lag - << ", " << idx << rpar; - } - else - { - argument << "x" << lpar << "it_, " << idx << rpar; - } - } - else - { - if (lag != 0) - { - argument << "x" << lpar << "it_ + " << lag - << "+" << idx << "*nb_row_xd" << rpar; - } - else - { - argument << "x" << lpar << "it_+" << idx << "*nb_row_xd" << rpar; - } - } + else if (type == eNumericalConstant) + { + argument << NumericalConstants::get((int) id); + } + else if (type == eEndogenous || type == eExogenous || type == eExogenousDet) + if (iEquationType == eStaticEquations || iEquationType == eStaticDerivatives) + { + int idx = VariableTable::getSymbolID((int) id)+offset; + if (type == eEndogenous) + { + argument << "y" << lpar << idx << rpar; + } + else if (type == eExogenous) + { + argument << "x" << lpar << idx << rpar; + } + else if (type == eExogenousDet) + { + idx += ModelParameters::exo_nbr; + argument << "x" << lpar << idx << rpar; + } + } + else + { + if (type == eEndogenous) + { + int idx = VariableTable::getPrintIndex((int) id)+offset; + argument << "y" << lpar << idx << rpar; + } + else if (type == eExogenous) + { + int idx = VariableTable::getSymbolID((int) id)+offset; + int lag = VariableTable::getLag((int) id); + if (offset == 1) + { + if ( lag != 0) + { + argument << "x" << lpar << "it_ + " << lag + << ", " << idx << rpar; + } + else + { + argument << "x" << lpar << "it_, " << idx << rpar; + } + } + else + { + if ( lag != 0) + { + argument << "x" << lpar << "it_+" << lag + << "+" << idx << "*nb_row_x" << rpar; + } + else + { + argument << "x" << lpar << "it_+" << idx << "*nb_row_x" << rpar; + } + } + } + else if (type == eExogenousDet) + { + int idx = VariableTable::getSymbolID((int) id)+ModelParameters::exo_nbr+offset; + int lag = VariableTable::getLag((int) id); + if (offset == 1) + { + if (lag != 0) + { + argument << "x" << lpar << "it_ + " << lag + << ", " << idx << rpar; + } + else + { + argument << "x" << lpar << "it_, " << idx << rpar; + } + } + else + { + if (lag != 0) + { + argument << "x" << lpar << "it_ + " << lag + << "+" << idx << "*nb_row_xd" << rpar; + } + else + { + argument << "x" << lpar << "it_+" << idx << "*nb_row_xd" << rpar; + } + } - } - } - return argument.str(); + } + } + return argument.str(); } //------------------------------------------------------------------------------ void ModelTree::ModelInitialization(void) { - // Exit if there is no equation in model file*/ - if (ModelParameters::eq_nbr == 0) + // Exit if there is no equation in model file*/ + if (ModelParameters::eq_nbr == 0) { - (* error) ("no equations found in model file"); + (* error) ("no equations found in model file"); } - cout << ModelParameters::eq_nbr << " equation(s) found \n"; - // Sorting variable table - VariableTable::Sort(); + cout << ModelParameters::eq_nbr << " equation(s) found \n"; + // Sorting variable table + VariableTable::Sort(); - // Setting number of equations in ModelParameters class - // Here no derivative are computed - BeginModel++; - min_cost = 40*operator_table.cost(PLUS,offset); - // Setting format of parentheses - if (offset == 1) + // Setting number of equations in ModelParameters class + // Here no derivative are computed + BeginModel++; + min_cost = 40*operator_table.cost(PLUS,offset); + // Setting format of parentheses + if (offset == 1) { - lpar = '('; - rpar = ')'; - param_name = "params"; + lpar = '('; + rpar = ')'; + param_name = "params"; } - else + else { - lpar = '['; - rpar = ']'; - param_name = "params"; + lpar = '['; + rpar = ']'; + param_name = "params"; } - /* Writing initialisation for M_.lead_lag_incidence matrix - M_.lead_lag_incidence is a matrix with as many columns as there are - endogenous variables and as many rows as there are periods in the - models (nbr of rows = M_.max_lag+M_.max_lead+1) + /* Writing initialisation for M_.lead_lag_incidence matrix + M_.lead_lag_incidence is a matrix with as many columns as there are + endogenous variables and as many rows as there are periods in the + models (nbr of rows = M_.max_lag+M_.max_lead+1) - The matrix elements are equal to zero if a variable isn't present in the - model at a given period. - */ - // Initializing matrix to zero - output << "M_.lead_lag_incidence = ["; - /* - zeros(" << - ModelParameters::max_lag+ModelParameters::max_lead+1 << ", " << - ModelParameters::endo_nbr << ");\n"; - */ - // Loop on endogenous variables - for (int endoID = 0; endoID < ModelParameters::endo_nbr; endoID++) + The matrix elements are equal to zero if a variable isn't present in the + model at a given period. + */ + // Initializing matrix to zero + output << "M_.lead_lag_incidence = ["; + /* + zeros(" << + ModelParameters::max_lag+ModelParameters::max_lead+1 << ", " << + ModelParameters::endo_nbr << ");\n"; + */ + // Loop on endogenous variables + for (int endoID = 0; endoID < ModelParameters::endo_nbr; endoID++) { - output << "\n\t"; - // Loop on periods - for (int lag = -ModelParameters::max_lag; lag <= ModelParameters::max_lead; lag++) - { - // Getting name of symbol - string name = SymbolTable::getNameByID(eEndogenous, endoID); - // and its variableID if exists with current period - int varID = VariableTable::getID(name, lag); - //cout << name << " " << varID << " " << lag << " " << VariableTable::getPrintIndex(varID)+1 << " " << VariableTable::getSortID(varID)+1 << endl; + output << "\n\t"; + // Loop on periods + for (int lag = -ModelParameters::max_lag; lag <= ModelParameters::max_lead; lag++) + { + // Getting name of symbol + string name = SymbolTable::getNameByID(eEndogenous, endoID); + // and its variableID if exists with current period + int varID = VariableTable::getID(name, lag); + //cout << name << " " << varID << " " << lag << " " << VariableTable::getPrintIndex(varID)+1 << " " << VariableTable::getSortID(varID)+1 << endl; - if (varID >=0) - { - output << " " << VariableTable::getPrintIndex(varID)+1; - } - else - { - output << " 0"; - } - } - output << ";"; + if (varID >=0) + { + output << " " << VariableTable::getPrintIndex(varID)+1; + } + else + { + output << " 0"; + } + } + output << ";"; } - output << "]';\n"; - - - // Writing initialization for some other variables - output << "M_.exo_names_orig_ord = [1:" << ModelParameters::exo_nbr << "];\n"; - output << "M_.maximum_lag = " << ModelParameters::max_lag << ";\n"; - output << "M_.maximum_lead = " << ModelParameters::max_lead<< ";\n"; - if (ModelParameters::exo_nbr > 0) - {} - if (ModelParameters::exo_nbr > 0) - {} - if (ModelParameters::exo_nbr > 0) + output << "]';\n"; + + + // Writing initialization for some other variables + output << "M_.exo_names_orig_ord = [1:" << ModelParameters::exo_nbr << "];\n"; + output << "M_.maximum_lag = " << ModelParameters::max_lag << ";\n"; + output << "M_.maximum_lead = " << ModelParameters::max_lead<< ";\n"; + if (ModelParameters::exo_nbr > 0) { - output << "M_.maximum_exo_lag = " << ModelParameters::max_exo_lag << ";\n"; - output << "M_.maximum_exo_lead = " << ModelParameters::max_exo_lead<< ";\n"; } - if (ModelParameters::endo_nbr) + if (ModelParameters::exo_nbr > 0) { - output << "M_.maximum_endo_lag = " << ModelParameters::max_endo_lag << ";\n"; - output << "M_.maximum_endo_lead = " << ModelParameters::max_endo_lead<< ";\n"; - output << "oo_.steady_state = zeros(" << ModelParameters::endo_nbr << ", 1);\n"; } - if (ModelParameters::exo_nbr) + if (ModelParameters::exo_nbr > 0) { - output << "M_.maximum_exo_lag = " << ModelParameters::max_exo_lag << ";\n"; - output << "M_.maximum_exo_lead = " << ModelParameters::max_exo_lead<< ";\n"; - output << "oo_.exo_steady_state = zeros(" << ModelParameters::exo_nbr << ", 1);\n"; + output << "M_.maximum_exo_lag = " << ModelParameters::max_exo_lag << ";\n"; + output << "M_.maximum_exo_lead = " << ModelParameters::max_exo_lead<< ";\n"; } - if (ModelParameters::exo_det_nbr) + if (ModelParameters::endo_nbr) { - output << "M_.maximum_exo_det_lag = " << ModelParameters::max_exo_det_lag << ";\n"; - output << "M_.maximum_exo_det_lead = " << ModelParameters::max_exo_det_lead<< ";\n"; - output << "oo_.exo_det_steady_state = zeros(" << ModelParameters::exo_det_nbr << ", 1);\n"; + output << "M_.maximum_endo_lag = " << ModelParameters::max_endo_lag << ";\n"; + output << "M_.maximum_endo_lead = " << ModelParameters::max_endo_lead<< ";\n"; + output << "oo_.steady_state = zeros(" << ModelParameters::endo_nbr << ", 1);\n"; } - if (ModelParameters::recur_nbr) + if (ModelParameters::exo_nbr) { - output << "M_.maximum_recur_lag = " << ModelParameters::max_recur_lag << ";\n"; - output << "M_.maximum_recur_lead = " << ModelParameters::max_recur_lead<< ";\n"; - output << "oo_.recur_steady_state = zeros(" << ModelParameters::recur_nbr << ", 1);\n"; + output << "M_.maximum_exo_lag = " << ModelParameters::max_exo_lag << ";\n"; + output << "M_.maximum_exo_lead = " << ModelParameters::max_exo_lead<< ";\n"; + output << "oo_.exo_steady_state = zeros(" << ModelParameters::exo_nbr << ", 1);\n"; } - if (ModelParameters::parameter_nbr) + if (ModelParameters::exo_det_nbr) { - output << "M_.params = zeros(" << ModelParameters::parameter_nbr << ", 1);\n"; + output << "M_.maximum_exo_det_lag = " << ModelParameters::max_exo_det_lag << ";\n"; + output << "M_.maximum_exo_det_lead = " << ModelParameters::max_exo_det_lead<< ";\n"; + output << "oo_.exo_det_steady_state = zeros(" << ModelParameters::exo_det_nbr << ", 1);\n"; + } + if (ModelParameters::recur_nbr) + { + output << "M_.maximum_recur_lag = " << ModelParameters::max_recur_lag << ";\n"; + output << "M_.maximum_recur_lead = " << ModelParameters::max_recur_lead<< ";\n"; + output << "oo_.recur_steady_state = zeros(" << ModelParameters::recur_nbr << ", 1);\n"; + } + if (ModelParameters::parameter_nbr) + { + output << "M_.params = zeros(" << ModelParameters::parameter_nbr << ", 1);\n"; } } //------------------------------------------------------------------------------ string ModelTree::get() { - return output.str(); + return output.str(); } //------------------------------------------------------------------------------ inline int ModelTree::optimize(NodeID node) { - int cost; - int tmp_status = 0; - if (node->op_code != NoOpCode) + int cost; + int tmp_status = 0; + if (node->op_code != NoOpCode) { - cost = operator_table.cost(node->op_code,offset); - if (node->id1 != NullID && node->id1->op_code != NoOpCode) - { - cost += operator_table.cost(node->id1->op_code,offset); - } - if (node->id2 != NullID && node->id2->op_code != NoOpCode) - { - cost += operator_table.cost(node->id2->op_code,offset); - } + cost = operator_table.cost(node->op_code,offset); + if (node->id1 != NullID && node->id1->op_code != NoOpCode) + { + cost += operator_table.cost(node->id1->op_code,offset); + } + if (node->id2 != NullID && node->id2->op_code != NoOpCode) + { + cost += operator_table.cost(node->id2->op_code,offset); + } } - cost *= node->reference_count[current_order]; - if (cost > min_cost) + cost *= node->reference_count[current_order]; + if (cost > min_cost) { - tmp_status = 1; - node->cost = 0; + tmp_status = 1; + node->cost = 0; } - else + else { - tmp_status = 0; - node->cost = cost; + tmp_status = 0; + node->cost = cost; } - node->tmp_status = 0; - return tmp_status; + node->tmp_status = 0; + return tmp_status; } - + //------------------------------------------------------------------------------ #ifdef TEST_MODELTREE int main(void) { - SymbolTable st; - VariableTable vt; - NumericalConstants nc; - ModelTree model; - vector t(20); + SymbolTable st; + VariableTable vt; + NumericalConstants nc; + ModelTree model; + vector t(20); + + //Adding 2 different symbols with AddSymbolDeclar + SymbolTable::AddSymbolDeclar("c",eExogenous); + //SymbolTable::PrintSymbolTable(); + SymbolTable::AddSymbolDeclar("k",eEndogenous); + //SymbolTable::PrintSymbolTable(); + SymbolTable::AddSymbolDeclar("aa",eParameter); + //SymbolTable::PrintSymbolTable(); + SymbolTable::AddSymbolDeclar("x",eExogenous); + SymbolTable::AddSymbolDeclar("alph",eParameter); + SymbolTable::AddSymbolDeclar("delt",eParameter); - //Adding 2 different symbols with AddSymbolDeclar - SymbolTable::AddSymbolDeclar("c",eExogenous); - //SymbolTable::PrintSymbolTable(); - SymbolTable::AddSymbolDeclar("k",eEndogenous); - //SymbolTable::PrintSymbolTable(); - SymbolTable::AddSymbolDeclar("aa",eParameter); - //SymbolTable::PrintSymbolTable(); - SymbolTable::AddSymbolDeclar("x",eExogenous); - SymbolTable::AddSymbolDeclar("alph",eParameter); - SymbolTable::AddSymbolDeclar("delt",eParameter); + VariableTable::AddVariable("k",0); + VariableTable::AddVariable("x",-1); + VariableTable::AddVariable("c",-1); + + + + SymbolTable::AddSymbolDeclar("x1",eEndogenous); + SymbolTable::AddSymbolDeclar("x2",eExogenousDet); + //SymbolTable::AddSymbolDeclar("x3",eExogenous); - VariableTable::AddVariable("k",0); - VariableTable::AddVariable("x",-1); - VariableTable::AddVariable("c",-1); + VariableTable::AddVariable("x1",-1); + VariableTable::AddVariable("x2",1); + //VariableTable::AddVariable("x3",-1); + //VariableTable::AddVariable("k",1); + //VariableTable::AddVariable("y",0); + t[0] = model.AddToken("aa"); + t[1] = model.AddToken("x",-1); + t[2] = model.AddToken("k",0); + t[3] = model.AddToken(Argument(t[0], eTempResult), + Argument(t[1], eTempResult), TIMES); + t[4] = model.AddToken("alph"); + t[5] = model.AddToken(Argument(t[2], eTempResult), + Argument(t[4], eTempResult), POWER); + t[6] = model.AddToken(Argument(t[3], eTempResult), + Argument(t[5], eTempResult), TIMES); + + t[7] = model.AddToken("delt"); + //t[8] = model.AddToken("1"); + t[9] = model.AddToken(Argument(1, eTempResult), + Argument(t[7], eTempResult), MINUS); + t[10] = model.AddToken(Argument(t[9], eTempResult), + Argument(t[2], eTempResult), TIMES); + + t[11] = model.AddToken(Argument(t[2], eTempResult), + UMINUS); - SymbolTable::AddSymbolDeclar("x1",eEndogenous); - SymbolTable::AddSymbolDeclar("x2",eExogenousDet); - //SymbolTable::AddSymbolDeclar("x3",eExogenous); - - VariableTable::AddVariable("x1",-1); - VariableTable::AddVariable("x2",1); - //VariableTable::AddVariable("x3",-1); - //VariableTable::AddVariable("k",1); - //VariableTable::AddVariable("y",0); - - - t[0] = model.AddToken("aa"); - t[1] = model.AddToken("x",-1); - t[2] = model.AddToken("k",0); - t[3] = model.AddToken(Argument(t[0], eTempResult), - Argument(t[1], eTempResult), TIMES); - t[4] = model.AddToken("alph"); - t[5] = model.AddToken(Argument(t[2], eTempResult), - Argument(t[4], eTempResult), POWER); - t[6] = model.AddToken(Argument(t[3], eTempResult), - Argument(t[5], eTempResult), TIMES); - - t[7] = model.AddToken("delt"); - //t[8] = model.AddToken("1"); - t[9] = model.AddToken(Argument(1, eTempResult), - Argument(t[7], eTempResult), MINUS); - t[10] = model.AddToken(Argument(t[9], eTempResult), - Argument(t[2], eTempResult), TIMES); - - t[11] = model.AddToken(Argument(t[2], eTempResult), - UMINUS); - - t[12] = model.AddToken(Argument(t[11], eTempResult), - Argument(t[6], eTempResult), PLUS); - t[13] = model.AddToken(Argument(t[12], eTempResult), - Argument(t[10], eTempResult), PLUS); - t[14] = model.AddToken(Argument(t[13], eTempResult), - Argument(t[10], eTempResult), PLUS); - t[15] = model.AddToken("c",-1); - t[16] = model.AddToken(Argument(t[15], eTempResult), - Argument(t[14], eTempResult), EQUAL); - //try - //{ - model.derive(2); - model.setStaticModel(); - model.setDynamicStochasticModel(); - model.Open("static_model.m", "dynamic_model.m"); - model.Save(); - //cout << model.getStaticModel(); - //} - //catch(Error err) - //{ - // cout << "error---------------------\n"; - // exit(-1); - //} - //cout << model.getDynamicDeterministicModel() << endl; - //cout << model.getDynamicStochasticModel() << endl; - //VariableTable::Sort(); + t[12] = model.AddToken(Argument(t[11], eTempResult), + Argument(t[6], eTempResult), PLUS); + t[13] = model.AddToken(Argument(t[12], eTempResult), + Argument(t[10], eTempResult), PLUS); + t[14] = model.AddToken(Argument(t[13], eTempResult), + Argument(t[10], eTempResult), PLUS); + t[15] = model.AddToken("c",-1); + t[16] = model.AddToken(Argument(t[15], eTempResult), + Argument(t[14], eTempResult), EQUAL); + //try + //{ + model.derive(2); + model.setStaticModel(); + model.setDynamicStochasticModel(); + model.Open("static_model.m", "dynamic_model.m"); + model.Save(); + //cout << model.getStaticModel(); + //} + //catch(Error err) + //{ + // cout << "error---------------------\n"; + // exit(-1); + //} + //cout << model.getDynamicDeterministicModel() << endl; + //cout << model.getDynamicStochasticModel() << endl; + //VariableTable::Sort(); } #endif //------------------------------------------------------------------------------ diff --git a/parser.src/VariableTable.cc b/parser.src/VariableTable.cc index b7a08c73e..0cba635e6 100644 --- a/parser.src/VariableTable.cc +++ b/parser.src/VariableTable.cc @@ -1,4 +1,4 @@ -/*! \file +/*! \file \version 1.0 \date 04/09/2004 \par This file implements the VariableTable class methodes. @@ -12,13 +12,13 @@ using namespace std; #include "VariableTable.h" //------------------------------------------------------------------------------ map VariableTable::mVariableTable = *(new map); -vector VariableTable::mVariableIndex = *(new vector); +vector VariableTable::mVariableIndex = *(new vector); vector VariableTable::mSortedVariableID = *(new vector); vector VariableTable::mPrintFormatIndex = *(new vector); void (* VariableTable::error) (const char* ) = NULL; //------------------------------------------------------------------------------ VariableTable::VariableTable() -{ +{ // Empty } //------------------------------------------------------------------------------ @@ -29,10 +29,10 @@ VariableTable::~VariableTable() //------------------------------------------------------------------------------ int VariableTable::AddVariable(string iName, int iLag) { - int lVariableID; + int lVariableID; //Variable lVariable; varKey key; - // Testing if symbol exists + // Testing if symbol exists if (!SymbolTable::Exist(iName)) { string msg = "unknown symbol: " + iName; @@ -51,7 +51,7 @@ int VariableTable::AddVariable(string iName, int iLag) //lVariable.symbol_id = SymbolTable::getID(iName); //lVariable.variable_id = lVariableID; key = make_pair(iName,iLag); - // Pushing variable on VariableTable + // Pushing variable on VariableTable //mVariableTable[key] = lVariable; mVariableTable[key] = lVariableID; mVariableIndex.push_back(key); @@ -114,7 +114,7 @@ int VariableTable::AddVariable(string iName, int iLag) } break; default: - ; + ; } return mVariableIndex.size()-1; @@ -122,7 +122,7 @@ int VariableTable::AddVariable(string iName, int iLag) //------------------------------------------------------------------------------ void VariableTable::decSymbolID(string iName, int id, int iLag, Type iType) { - int lVariableID; + int lVariableID; Variable lVariable; varKey key; @@ -150,7 +150,7 @@ void VariableTable::Sort(void) vector IDs; vector Lags; vector Types; - + if (mVariableIndex.size() == 1) { mSortedVariableID.push_back(0); @@ -172,20 +172,20 @@ void VariableTable::Sort(void) unsigned long long int type = Types[id]; type = type << 8*sizeof(int); unsigned long long int sort_pound = IDs[id]+lag+type; - VarToSort.push_back(make_pair(sort_pound,id)); + VarToSort.push_back(make_pair(sort_pound,id)); } // Uncomment this to debug /* cout << "Before sorting\n"; cout << "S T L ID pound \n"; for (int id=0; id < VarToSort.size(); id++) - { + { Type type = Types[VarToSort[id].second]; int lag = Lags[VarToSort[id].second]; int ID = IDs[VarToSort[id].second]; - cout << SymbolTable::getNameByID(type, ID) << " " - << type << " " - << lag << " " + cout << SymbolTable::getNameByID(type, ID) << " " + << type << " " + << lag << " " << ID << " " << VarToSort[id].first << "\n"; } @@ -198,7 +198,7 @@ void VariableTable::Sort(void) Type type = Types[VarToSort[0].second]; int index = 0; for (unsigned int id = 0; id < VarToSort.size(); id++) - { + { int id2 = VarToSort[id].second; mSortedVariableID[id2] = id; if (type == Types[id2]) @@ -207,7 +207,7 @@ void VariableTable::Sort(void) index++; } else - { + { mPrintFormatIndex[id2] = 0; type = Types[id2]; index = 1; @@ -218,13 +218,13 @@ void VariableTable::Sort(void) cout << "After sorting\n"; cout << "S T L ID SVID PIDX\n"; for (int id=0; id < VarToSort.size(); id++) - { + { Type type = Types[VarToSort[id].second]; int lag = Lags[VarToSort[id].second]; int ID = IDs[VarToSort[id].second]; - cout << SymbolTable::getNameByID(Types[id], IDs[id]) << " " - << Types[id] << " " - << Lags[id] << " " + cout << SymbolTable::getNameByID(Types[id], IDs[id]) << " " + << Types[id] << " " + << Lags[id] << " " << IDs[id] << " " << mSortedVariableID[id] << " " << mPrintFormatIndex[id] << "\n"; @@ -232,91 +232,3 @@ void VariableTable::Sort(void) */ } //------------------------------------------------------------------------------ -/*New*/ -int* VariableTable::GetVariableTable(int* Size) -{ - int* Table; - varKey key; - int variable,id, ind; - *Size=0; - //cout << "S T L ID SVID PIDX\n"; - //cout << "mVariableIndex.size() : " << mVariableIndex.size() << "\n"; - for (id=0; id < mVariableIndex.size(); id++) - { - key = mVariableIndex[id]; - variable = mVariableTable[key]; - if(getType(variable)==eEndogenous) - (*Size)++; - } - //cout << "*Size : " << (*Size) << "\n"; - Table=(int*)malloc((*Size)*sizeof(*Table)*4); - ind=0; - for (id=0; id < mVariableIndex.size(); id++) - { - //Type type = Types[VarToSort[id].second]; - //int lag = Lags[VarToSort[id].second]; - //int ID = IDs[VarToSort[id].second]; - key = mVariableIndex[id]; - variable = mVariableTable[key]; - if (getType(variable)==eEndogenous) - { - Table[ind*4]= getSymbolID(id); - Table[ind*4+1]= key.second; - Table[ind*4+2]= mPrintFormatIndex[id]; - Table[ind*4+3]= 1; - ind++; - //cout << SymbolTable::getNameByID(Types[id], IDs[id]) << " " - // << Types[id] << " " - // << Lags[id] << " " - // << IDs[id] << " " - // << mSortedVariableID[id] << " " - // << mPrintFormatIndex[id] << "\n"; - } - } - return(Table); -} - -int VariableTable::GetVariableID(std::string name, int lead_lag) - { - int found=-1; - varKey key; - int variable; - for (int id=0; id < mVariableIndex.size(); id++) - { - key=mVariableIndex[id]; - variable = mVariableTable[key]; - if((SymbolTable::getNameByID(getType(id), getSymbolID(variable))==name) && (lead_lag==key.second)) - found=mPrintFormatIndex[id]; - } - return(found); - } - - - -int VariableTable::getIDS(int id, int lead_lag) - { - /*int found=-1;*/ - varKey key; - int variable; - /*for (int id=0; id < mVariableIndex.size(); id++) - {*/ - key=mVariableIndex[id]; - variable = mVariableTable[key]; - /*if((SymbolTable::getNameByID(getType(id), getSymbolID(variable))==name) && (lead_lag==key.second)) - found=mPrintFormatIndex[id]; - }*/ - return(variable); - } - - - -std::string VariableTable::GetVariableName(int id) - { - varKey key; - int variable; - key=mVariableIndex[id]; - variable = mVariableTable[key]; - return SymbolTable::getNameByID(getType(id), getSymbolID(variable)); - } -/*EndNew*/ -//------------------------------------------------------------------------------ diff --git a/parser.src/include/DynareBison.h b/parser.src/include/DynareBison.h index 35ba7a01a..b6e220dbb 100644 --- a/parser.src/include/DynareBison.h +++ b/parser.src/include/DynareBison.h @@ -1,351 +1,349 @@ -/* A Bison parser, made by GNU Bison 2.1. */ - -/* Skeleton parser for Yacc-like parsing with Bison, - Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. */ - -/* As a special exception, when this file is copied by Bison into a - Bison output file, you may use that output file without restriction. - This special exception was added by the Free Software Foundation - in version 1.24 of Bison. */ - -/* Tokens. */ -#ifndef YYTOKENTYPE -# define YYTOKENTYPE - /* Put the tokens into the symbol table, so that GDB and other debuggers - know about them. */ - enum yytokentype { - AR = 258, - AUTOCORR = 259, - BAYESIAN_IRF = 260, - BETA_PDF = 261, - CALIB = 262, - CALIB_VAR = 263, - CHECK = 264, - CONF_SIG = 265, - CORR = 266, - COVAR = 267, - DATAFILE = 268, - DIAGNOSTIC = 269, - DIFFUSE_D = 270, - DLL = 271, - DOLLAR = 272, - DR_ALGO = 273, - DROP = 274, - DSAMPLE = 275, - DYN2VEC = 276, - DYNASAVE = 277, - DYNATYPE = 278, - END = 279, - ENDVAL = 280, - EQUAL = 281, - ESTIMATION = 282, - ESTIMATED_PARAMS = 283, - ESTIMATED_PARAMS_BOUNDS = 284, - ESTIMATED_PARAMS_INIT = 285, - FILTERED_VARS = 286, - FIRST_OBS = 287, - FLOAT_NUMBER = 288, - FORECAST = 289, - FUNCTIONS = 290, - GAMMA_PDF = 291, - GRAPH = 292, - HISTVAL = 293, - HP_FILTER = 294, - HP_NGRID = 295, - INITVAL = 296, - INITVALF = 297, - INT_NUMBER = 298, - INV_GAMMA_PDF = 299, - INV_GAMMA1_PDF = 300, - INV_GAMMA2_PDF = 301, - IRF = 302, - KALMAN_ALGO = 303, - KALMAN_TOL = 304, - CONSTANT = 305, - NOCONSTANT = 306, - LAPLACE = 307, - LIK_ALGO = 308, - LIK_INIT = 309, - LINEAR = 310, - LOAD_MH_FILE = 311, - LOGLINEAR = 312, - MH_DROP = 313, - MH_INIT_SCALE = 314, - MH_JSCALE = 315, - MH_MODE = 316, - MH_NBLOCKS = 317, - MH_REPLIC = 318, - MODE_CHECK = 319, - MODE_COMPUTE = 320, - MODE_FILE = 321, - MODEL = 322, - MODEL_COMPARISON = 323, - MODEL_COMPARISON_APPROXIMATION = 324, - MODIFIEDHARMONICMEAN = 325, - MOMENTS = 326, - MOMENTS_VARENDO = 327, - MSHOCKS = 328, - NAME = 329, - NOBS = 330, - NOCORR = 331, - NODIAGNOSTIC = 332, - NOFUNCTIONS = 333, - NOGRAPH = 334, - XLS_SHEET = 335, - XLS_RANGE = 336, - NOMOMENTS = 337, - NOPRINT = 338, - NORMAL_PDF = 339, - OBSERVATION_TRENDS = 340, - OLR = 341, - OLR_INST = 342, - OLR_BETA = 343, - OPTIM = 344, - OPTIM_WEIGHTS = 345, - ORDER = 346, - OSR = 347, - OSR_PARAMS = 348, - PARAMETERS = 349, - PERIODS = 350, - PREFILTER = 351, - PRESAMPLE = 352, - PRINT = 353, - PRIOR_TRUNC = 354, - FILTER_STEP_AHEAD = 355, - QZ_CRITERIUM = 356, - RELATIVE_IRF = 357, - REPLIC = 358, - RESOL = 359, - RPLOT = 360, - SHOCKS = 361, - SIGMA_E = 362, - SIMUL = 363, - SIMUL_ALGO = 364, - SIMUL_SEED = 365, - SMOOTHER = 366, - SOLVE_ALGO = 367, - STDERR = 368, - STEADY = 369, - STOCH_SIMUL = 370, - TEX = 371, - TEX_NAME = 372, - UNIFORM_PDF = 373, - UNIT_ROOT_VARS = 374, - USE_DLL = 375, - VALUES = 376, - VAR = 377, - VAREXO = 378, - VAREXO_DET = 379, - VAROBS = 380, - XTICK = 381, - XTICKLABEL = 382, - COMMA = 383, - MINUS = 384, - PLUS = 385, - DIVIDE = 386, - TIMES = 387, - UMINUS = 388, - POWER = 389, - FACTORIAL = 390, - EXP = 391, - LOG = 392, - LOG10 = 393, - LN = 394, - SIN = 395, - COS = 396, - TAN = 397, - ASIN = 398, - ACOS = 399, - ATAN = 400, - SINH = 401, - COSH = 402, - TANH = 403, - ASINH = 404, - ACOSH = 405, - ATANH = 406, - SQRT = 407, - ASSIGN = 408 - }; -#endif -/* Tokens. */ -#define AR 258 -#define AUTOCORR 259 -#define BAYESIAN_IRF 260 -#define BETA_PDF 261 -#define CALIB 262 -#define CALIB_VAR 263 -#define CHECK 264 -#define CONF_SIG 265 -#define CORR 266 -#define COVAR 267 -#define DATAFILE 268 -#define DIAGNOSTIC 269 -#define DIFFUSE_D 270 -#define DLL 271 -#define DOLLAR 272 -#define DR_ALGO 273 -#define DROP 274 -#define DSAMPLE 275 -#define DYN2VEC 276 -#define DYNASAVE 277 -#define DYNATYPE 278 -#define END 279 -#define ENDVAL 280 -#define EQUAL 281 -#define ESTIMATION 282 -#define ESTIMATED_PARAMS 283 -#define ESTIMATED_PARAMS_BOUNDS 284 -#define ESTIMATED_PARAMS_INIT 285 -#define FILTERED_VARS 286 -#define FIRST_OBS 287 -#define FLOAT_NUMBER 288 -#define FORECAST 289 -#define FUNCTIONS 290 -#define GAMMA_PDF 291 -#define GRAPH 292 -#define HISTVAL 293 -#define HP_FILTER 294 -#define HP_NGRID 295 -#define INITVAL 296 -#define INITVALF 297 -#define INT_NUMBER 298 -#define INV_GAMMA_PDF 299 -#define INV_GAMMA1_PDF 300 -#define INV_GAMMA2_PDF 301 -#define IRF 302 -#define KALMAN_ALGO 303 -#define KALMAN_TOL 304 -#define CONSTANT 305 -#define NOCONSTANT 306 -#define LAPLACE 307 -#define LIK_ALGO 308 -#define LIK_INIT 309 -#define LINEAR 310 -#define LOAD_MH_FILE 311 -#define LOGLINEAR 312 -#define MH_DROP 313 -#define MH_INIT_SCALE 314 -#define MH_JSCALE 315 -#define MH_MODE 316 -#define MH_NBLOCKS 317 -#define MH_REPLIC 318 -#define MODE_CHECK 319 -#define MODE_COMPUTE 320 -#define MODE_FILE 321 -#define MODEL 322 -#define MODEL_COMPARISON 323 -#define MODEL_COMPARISON_APPROXIMATION 324 -#define MODIFIEDHARMONICMEAN 325 -#define MOMENTS 326 -#define MOMENTS_VARENDO 327 -#define MSHOCKS 328 -#define NAME 329 -#define NOBS 330 -#define NOCORR 331 -#define NODIAGNOSTIC 332 -#define NOFUNCTIONS 333 -#define NOGRAPH 334 -#define XLS_SHEET 335 -#define XLS_RANGE 336 -#define NOMOMENTS 337 -#define NOPRINT 338 -#define NORMAL_PDF 339 -#define OBSERVATION_TRENDS 340 -#define OLR 341 -#define OLR_INST 342 -#define OLR_BETA 343 -#define OPTIM 344 -#define OPTIM_WEIGHTS 345 -#define ORDER 346 -#define OSR 347 -#define OSR_PARAMS 348 -#define PARAMETERS 349 -#define PERIODS 350 -#define PREFILTER 351 -#define PRESAMPLE 352 -#define PRINT 353 -#define PRIOR_TRUNC 354 -#define FILTER_STEP_AHEAD 355 -#define QZ_CRITERIUM 356 -#define RELATIVE_IRF 357 -#define REPLIC 358 -#define RESOL 359 -#define RPLOT 360 -#define SHOCKS 361 -#define SIGMA_E 362 -#define SIMUL 363 -#define SIMUL_ALGO 364 -#define SIMUL_SEED 365 -#define SMOOTHER 366 -#define SOLVE_ALGO 367 -#define STDERR 368 -#define STEADY 369 -#define STOCH_SIMUL 370 -#define TEX 371 -#define TEX_NAME 372 -#define UNIFORM_PDF 373 -#define UNIT_ROOT_VARS 374 -#define USE_DLL 375 -#define VALUES 376 -#define VAR 377 -#define VAREXO 378 -#define VAREXO_DET 379 -#define VAROBS 380 -#define XTICK 381 -#define XTICKLABEL 382 -#define COMMA 383 -#define MINUS 384 -#define PLUS 385 -#define DIVIDE 386 -#define TIMES 387 -#define UMINUS 388 -#define POWER 389 -#define FACTORIAL 390 -#define EXP 391 -#define LOG 392 -#define LOG10 393 -#define LN 394 -#define SIN 395 -#define COS 396 -#define TAN 397 -#define ASIN 398 -#define ACOS 399 -#define ATAN 400 -#define SINH 401 -#define COSH 402 -#define TANH 403 -#define ASINH 404 -#define ACOSH 405 -#define ATANH 406 -#define SQRT 407 -#define ASSIGN 408 - - - - -#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED) -typedef int YYSTYPE; -# define yystype YYSTYPE /* obsolescent; will be withdrawn */ -# define YYSTYPE_IS_DECLARED 1 -# define YYSTYPE_IS_TRIVIAL 1 -#endif - -extern YYSTYPE yylval; - - - +/* A Bison parser, made by GNU Bison 2.1. */ + +/* Skeleton parser for Yacc-like parsing with Bison, + Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. */ + +/* As a special exception, when this file is copied by Bison into a + Bison output file, you may use that output file without restriction. + This special exception was added by the Free Software Foundation + in version 1.24 of Bison. */ + +/* Tokens. */ +#ifndef YYTOKENTYPE +# define YYTOKENTYPE + /* Put the tokens into the symbol table, so that GDB and other debuggers + know about them. */ + enum yytokentype { + AR = 258, + AUTOCORR = 259, + BAYESIAN_IRF = 260, + BETA_PDF = 261, + CALIB = 262, + CALIB_VAR = 263, + CHECK = 264, + CONF_SIG = 265, + CORR = 266, + COVAR = 267, + DATAFILE = 268, + DIAGNOSTIC = 269, + DIFFUSE_D = 270, + DOLLAR = 271, + DR_ALGO = 272, + DROP = 273, + DSAMPLE = 274, + DYN2VEC = 275, + DYNASAVE = 276, + DYNATYPE = 277, + END = 278, + ENDVAL = 279, + EQUAL = 280, + ESTIMATION = 281, + ESTIMATED_PARAMS = 282, + ESTIMATED_PARAMS_BOUNDS = 283, + ESTIMATED_PARAMS_INIT = 284, + FILTERED_VARS = 285, + FIRST_OBS = 286, + FLOAT_NUMBER = 287, + FORECAST = 288, + FUNCTIONS = 289, + GAMMA_PDF = 290, + GRAPH = 291, + HISTVAL = 292, + HP_FILTER = 293, + HP_NGRID = 294, + INITVAL = 295, + INITVALF = 296, + INT_NUMBER = 297, + INV_GAMMA_PDF = 298, + INV_GAMMA1_PDF = 299, + INV_GAMMA2_PDF = 300, + IRF = 301, + KALMAN_ALGO = 302, + KALMAN_TOL = 303, + CONSTANT = 304, + NOCONSTANT = 305, + LAPLACE = 306, + LIK_ALGO = 307, + LIK_INIT = 308, + LINEAR = 309, + LOAD_MH_FILE = 310, + LOGLINEAR = 311, + MH_DROP = 312, + MH_INIT_SCALE = 313, + MH_JSCALE = 314, + MH_MODE = 315, + MH_NBLOCKS = 316, + MH_REPLIC = 317, + MODE_CHECK = 318, + MODE_COMPUTE = 319, + MODE_FILE = 320, + MODEL = 321, + MODEL_COMPARISON = 322, + MODEL_COMPARISON_APPROXIMATION = 323, + MODIFIEDHARMONICMEAN = 324, + MOMENTS = 325, + MOMENTS_VARENDO = 326, + MSHOCKS = 327, + NAME = 328, + NOBS = 329, + NOCORR = 330, + NODIAGNOSTIC = 331, + NOFUNCTIONS = 332, + NOGRAPH = 333, + XLS_SHEET = 334, + XLS_RANGE = 335, + NOMOMENTS = 336, + NOPRINT = 337, + NORMAL_PDF = 338, + OBSERVATION_TRENDS = 339, + OLR = 340, + OLR_INST = 341, + OLR_BETA = 342, + OPTIM = 343, + OPTIM_WEIGHTS = 344, + ORDER = 345, + OSR = 346, + OSR_PARAMS = 347, + PARAMETERS = 348, + PERIODS = 349, + PREFILTER = 350, + PRESAMPLE = 351, + PRINT = 352, + PRIOR_TRUNC = 353, + FILTER_STEP_AHEAD = 354, + QZ_CRITERIUM = 355, + RELATIVE_IRF = 356, + REPLIC = 357, + RESOL = 358, + RPLOT = 359, + SHOCKS = 360, + SIGMA_E = 361, + SIMUL = 362, + SIMUL_ALGO = 363, + SIMUL_SEED = 364, + SMOOTHER = 365, + SOLVE_ALGO = 366, + STDERR = 367, + STEADY = 368, + STOCH_SIMUL = 369, + TEX = 370, + TEX_NAME = 371, + UNIFORM_PDF = 372, + UNIT_ROOT_VARS = 373, + USE_DLL = 374, + VALUES = 375, + VAR = 376, + VAREXO = 377, + VAREXO_DET = 378, + VAROBS = 379, + XTICK = 380, + XTICKLABEL = 381, + COMMA = 382, + MINUS = 383, + PLUS = 384, + DIVIDE = 385, + TIMES = 386, + UMINUS = 387, + POWER = 388, + FACTORIAL = 389, + EXP = 390, + LOG = 391, + LOG10 = 392, + LN = 393, + SIN = 394, + COS = 395, + TAN = 396, + ASIN = 397, + ACOS = 398, + ATAN = 399, + SINH = 400, + COSH = 401, + TANH = 402, + ASINH = 403, + ACOSH = 404, + ATANH = 405, + SQRT = 406, + ASSIGN = 407 + }; +#endif +/* Tokens. */ +#define AR 258 +#define AUTOCORR 259 +#define BAYESIAN_IRF 260 +#define BETA_PDF 261 +#define CALIB 262 +#define CALIB_VAR 263 +#define CHECK 264 +#define CONF_SIG 265 +#define CORR 266 +#define COVAR 267 +#define DATAFILE 268 +#define DIAGNOSTIC 269 +#define DIFFUSE_D 270 +#define DOLLAR 271 +#define DR_ALGO 272 +#define DROP 273 +#define DSAMPLE 274 +#define DYN2VEC 275 +#define DYNASAVE 276 +#define DYNATYPE 277 +#define END 278 +#define ENDVAL 279 +#define EQUAL 280 +#define ESTIMATION 281 +#define ESTIMATED_PARAMS 282 +#define ESTIMATED_PARAMS_BOUNDS 283 +#define ESTIMATED_PARAMS_INIT 284 +#define FILTERED_VARS 285 +#define FIRST_OBS 286 +#define FLOAT_NUMBER 287 +#define FORECAST 288 +#define FUNCTIONS 289 +#define GAMMA_PDF 290 +#define GRAPH 291 +#define HISTVAL 292 +#define HP_FILTER 293 +#define HP_NGRID 294 +#define INITVAL 295 +#define INITVALF 296 +#define INT_NUMBER 297 +#define INV_GAMMA_PDF 298 +#define INV_GAMMA1_PDF 299 +#define INV_GAMMA2_PDF 300 +#define IRF 301 +#define KALMAN_ALGO 302 +#define KALMAN_TOL 303 +#define CONSTANT 304 +#define NOCONSTANT 305 +#define LAPLACE 306 +#define LIK_ALGO 307 +#define LIK_INIT 308 +#define LINEAR 309 +#define LOAD_MH_FILE 310 +#define LOGLINEAR 311 +#define MH_DROP 312 +#define MH_INIT_SCALE 313 +#define MH_JSCALE 314 +#define MH_MODE 315 +#define MH_NBLOCKS 316 +#define MH_REPLIC 317 +#define MODE_CHECK 318 +#define MODE_COMPUTE 319 +#define MODE_FILE 320 +#define MODEL 321 +#define MODEL_COMPARISON 322 +#define MODEL_COMPARISON_APPROXIMATION 323 +#define MODIFIEDHARMONICMEAN 324 +#define MOMENTS 325 +#define MOMENTS_VARENDO 326 +#define MSHOCKS 327 +#define NAME 328 +#define NOBS 329 +#define NOCORR 330 +#define NODIAGNOSTIC 331 +#define NOFUNCTIONS 332 +#define NOGRAPH 333 +#define XLS_SHEET 334 +#define XLS_RANGE 335 +#define NOMOMENTS 336 +#define NOPRINT 337 +#define NORMAL_PDF 338 +#define OBSERVATION_TRENDS 339 +#define OLR 340 +#define OLR_INST 341 +#define OLR_BETA 342 +#define OPTIM 343 +#define OPTIM_WEIGHTS 344 +#define ORDER 345 +#define OSR 346 +#define OSR_PARAMS 347 +#define PARAMETERS 348 +#define PERIODS 349 +#define PREFILTER 350 +#define PRESAMPLE 351 +#define PRINT 352 +#define PRIOR_TRUNC 353 +#define FILTER_STEP_AHEAD 354 +#define QZ_CRITERIUM 355 +#define RELATIVE_IRF 356 +#define REPLIC 357 +#define RESOL 358 +#define RPLOT 359 +#define SHOCKS 360 +#define SIGMA_E 361 +#define SIMUL 362 +#define SIMUL_ALGO 363 +#define SIMUL_SEED 364 +#define SMOOTHER 365 +#define SOLVE_ALGO 366 +#define STDERR 367 +#define STEADY 368 +#define STOCH_SIMUL 369 +#define TEX 370 +#define TEX_NAME 371 +#define UNIFORM_PDF 372 +#define UNIT_ROOT_VARS 373 +#define USE_DLL 374 +#define VALUES 375 +#define VAR 376 +#define VAREXO 377 +#define VAREXO_DET 378 +#define VAROBS 379 +#define XTICK 380 +#define XTICKLABEL 381 +#define COMMA 382 +#define MINUS 383 +#define PLUS 384 +#define DIVIDE 385 +#define TIMES 386 +#define UMINUS 387 +#define POWER 388 +#define FACTORIAL 389 +#define EXP 390 +#define LOG 391 +#define LOG10 392 +#define LN 393 +#define SIN 394 +#define COS 395 +#define TAN 396 +#define ASIN 397 +#define ACOS 398 +#define ATAN 399 +#define SINH 400 +#define COSH 401 +#define TANH 402 +#define ASINH 403 +#define ACOSH 404 +#define ATANH 405 +#define SQRT 406 +#define ASSIGN 407 + + + + +#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED) +typedef int YYSTYPE; +# define yystype YYSTYPE /* obsolescent; will be withdrawn */ +# define YYSTYPE_IS_DECLARED 1 +# define YYSTYPE_IS_TRIVIAL 1 +#endif + +extern YYSTYPE yylval; + + + diff --git a/parser.src/include/DynareParser.h b/parser.src/include/DynareParser.h index f5840f2b1..684ea7d26 100644 --- a/parser.src/include/DynareParser.h +++ b/parser.src/include/DynareParser.h @@ -1,7 +1,7 @@ #ifndef DYNAREPARSER_H #define DYNAREPARSER_H //------------------------------------------------------------------------------ -/*! \file +/*! \file \version 1.0 \date 04/27/2004 \par This file defines the parser class. @@ -18,11 +18,8 @@ #include "SigmaeInitialization.h" #include "ComputingTasks.h" #include "TmpSymbolTable.h" -#include "Objects.h" -/*New*/ -#include "BlockTriangular.h" -/*EndNew*/ -#ifndef YLMM_basic_parser +#include "Objects.h" +#ifndef YLMM_basic_parser #include "ylmm/basic_parser.hh" #endif #ifndef YLMM_basic_scanner @@ -36,13 +33,13 @@ extern int yylineno; /*! \namespace dynare */ -namespace dynare +namespace dynare { /*! \class parser - \brief Member functions of this class are called from DyanreBison.y + \brief Member functions of this class are called from DyanreBison.y */ - class parser : public ylmm::basic_parser + class parser : public ylmm::basic_parser { private: ylmm::basic_scanner& _scanner; @@ -79,21 +76,18 @@ namespace dynare int order; /*! Value of option linear */ int linear; - EstimationParams estim_params; - /*New*/ - BlockTriangular block_triangular; - /*EndNew*/ + EstimationParams estim_params; /*! Prints an arror to stdout */ static void error(const char* m) - { + { std::cout << file_name << " : Error in line " << yylineno << " : " << m << endl; exit(-1); } /*! Constuctor - \param s reference to scanner + \param s reference to scanner */ - parser(ylmm::basic_scanner& s) : _scanner(s) + parser(ylmm::basic_scanner& s) : _scanner(s) { order = -1; linear = -1; @@ -106,17 +100,17 @@ namespace dynare tmp_symbol_table.error = error; } /*! Destructor */ - virtual ~parser() {} + virtual ~parser() {} /*! - Scan input - \param arg Optional argument - \return The next token ID + Scan input + \param arg Optional argument + \return The next token ID */ - int scan(void* arg=0) { - if (need_where()) - return _scanner.next(*_token,*_location); + int scan(void* arg=0) { + if (need_where()) + return _scanner.next(*_token,*_location); return _scanner.next(*_token); - + } /*! Sets output file name */ void set_file_name(string fname); @@ -129,10 +123,7 @@ namespace dynare /*! Initializes the model */ void initialize_model(void); /*! Sets variable offset of ModelTree class to use C output */ - void use_dll(void); - /*New*/ - void dll(void); - /*EndNew*/ + void use_dll(void); /*! Adds an endogenous variable to SymbolTable*/ Objects* add_endogenous(Objects* name, Objects* tex_name = new Objects("",NULL, eUNDEF)); /*! Adds an exogenous variable to SymbolTable*/ diff --git a/parser.src/include/ModelTree.h b/parser.src/include/ModelTree.h index 0dbe5409c..f530080b7 100644 --- a/parser.src/include/ModelTree.h +++ b/parser.src/include/ModelTree.h @@ -1,7 +1,7 @@ #ifndef MODELTREE_H #define MODELTREE_H //------------------------------------------------------------------------------ -/*! \file +/*! \file \version 1.0 \date 04/13/2003 \par This file defines the ModelTree class. @@ -20,9 +20,6 @@ #include "NumericalConstants.h" #include "ModelTypes.h" #include "DataTree.h" -/*New*/ -#include "BlockTriangular.h" -/*EndNew*/ //------------------------------------------------------------------------------ /*! \class ModelTree @@ -71,9 +68,9 @@ class ModelTree : public DataTree inline std::string getExpression(NodeID StartID, EquationType iEquationType, int iEquationID = -1); /*! Return true if node is to be writen as temp result - depending on its time cost and number of times it is referenced in model tree + depending on its time cost and number of times it is referenced in model tree */ - inline bool writeAsTemp(NodeID id); + inline bool writeAsTemp(NodeID id); /*! Remove unreferenced tokens after a derivation */ //void RemoveUnref(int iBeginID, int iEndID, int iOrder); /*! Decrementing reference couter of unreferenced tokens in last derivative */ @@ -96,31 +93,22 @@ class ModelTree : public DataTree void OpenCFiles(std::string iModelFileName1, std::string iModelFileName2 = ""); /*! Saves output string into output M files */ void SaveMFiles(); - /*! Saves output string into output C files */ - /*New*/ - void SaveCFiles(Model_Block* ModelBlock); - /*EndNew*/ + void SaveCFiles(); /*! Computes derivatives of ModelTree */ void derive(int iOrder); /*! Writes output file for static model : - - equations - - 1st order derivatives with respect to endogenous variables (without lags) + - equations + - 1st order derivatives with respect to endogenous variables (without lags) */ std::string setStaticModel(void); - /*! + /*! Writes output file for dynamic stochastic model : - - equations - - 1st order and 2nd order derivatives with respect to endogenous, exogenous, exogenous_det (in specific order) + - equations + - 1st order and 2nd order derivatives with respect to endogenous, exogenous, exogenous_det (in specific order) */ std::string setDynamicModel(void); - - /*New*/ - std::string setDynamicModel_New(Model_Block* ModelBlock, simple* Index_Var_IM); - /*EndNew*/ - - /*! Writes initialization of various Matlab variables */ void ModelInitialization(void); /*! Returns string output for main file */ diff --git a/parser.src/include/VariableTable.h b/parser.src/include/VariableTable.h index 8f87898b2..e08ec3843 100644 --- a/parser.src/include/VariableTable.h +++ b/parser.src/include/VariableTable.h @@ -1,7 +1,7 @@ #ifndef VARIABLETABLE_H #define VARIABLETABLE_H //------------------------------------------------------------------------------ -/** \file +/** \file * \version 1.0 * \date 12/16/2003 * \par This file defines the VariableTable class . @@ -11,11 +11,11 @@ #include #include //------------------------------------------------------------------------------ -#include "SymbolTable.h" +#include "SymbolTable.h" //------------------------------------------------------------------------------ -/*! +/*! \class Variable - \brief Variable struct + \brief Variable struct */ struct Variable { /*! Variable type */ @@ -29,12 +29,12 @@ struct Variable { typedef std::pair varKey; //------------------------------------------------------------------------------ /*! - \class VariableTable - \brief This class is used to store variables as they appear + \class VariableTable + \brief This class is used to store variables as they appear in the model (with their lead or lag) */ class VariableTable -{ +{ private : /*! Variable table data */ //static std::map mVariableTable; @@ -44,19 +44,19 @@ class VariableTable /*! Variable IDs of sorted variable table */ static std::vector mSortedVariableID; /*! Output index for variable table */ - static std::vector mPrintFormatIndex; + static std::vector mPrintFormatIndex; public : /*! */ VariableTable(); /*! */ ~VariableTable(); - /*! Find type and ID in SymbolTable - - Increment variable_id; - - Make variable - - Push variable on variabletable - */ - static int AddVariable(std::string iName, int iLag); - /*! Pointer to error function of parser class */ + /*! Find type and ID in SymbolTable + - Increment variable_id; + - Make variable + - Push variable on variabletable + */ + static int AddVariable(std::string iName, int iLag); + /*! Pointer to error function of parser class */ static void (* error) (const char* m); /*! Decremente a symbol id of a variable */ static void decSymbolID(std::string iName, int id, int iLag, Type iType); @@ -76,12 +76,6 @@ class VariableTable inline static int getPrintIndex(int iVarID); /*! Sorts variable table */ static void Sort(void); - /*New*/ - static int* GetVariableTable(int* Size); - static int GetVariableID(std::string name, int lead_lag); - static std::string GetVariableName(int id); - static int getIDS(int id, int lead_lag); - /*EndNew*/ }; inline int VariableTable::getSortID(int iVarID) { diff --git a/parser.src/include/ylmm/basic_buffer.hh b/parser.src/include/ylmm/basic_buffer.hh index a29a44d80..9c74e79d3 100644 --- a/parser.src/include/ylmm/basic_buffer.hh +++ b/parser.src/include/ylmm/basic_buffer.hh @@ -1,22 +1,22 @@ -// $Id: basic_buffer.hh,v 1.13 2004/03/09 02:38:01 cholm Exp $ -// +// $Id: basic_buffer.hh,v 1.13 2004/03/09 02:38:01 cholm Exp $ +// // basic_buffer.hh -// Copyright (C) 2002 Christian Holm Christensen +// Copyright (C) 2002 Christian Holm Christensen // -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public License -// as published by the Free Software Foundation; either version 2.1 -// of the License, or (at your option) any later version. +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public License +// as published by the Free Software Foundation; either version 2.1 +// of the License, or (at your option) any later version. // -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free -// Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA -// 02111-1307 USA +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free +// Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +// 02111-1307 USA // #ifndef YLMM_basic_buffer #define YLMM_basic_buffer @@ -35,10 +35,10 @@ @date Mon Sep 30 00:08:22 2002 @brief Declaration of scanner ABC. */ -namespace ylmm +namespace ylmm { /** @class basic_buffer basic_buffer.hh - @brief ABC for scanner buffers. + @brief ABC for scanner buffers. This class is used by the ylmm::basic_scanner class to read input. Internally it uses a std::istream to read from. User @@ -48,12 +48,12 @@ namespace ylmm or the standard input (for example via readline), then the client code is much better off making a customised std::streambuf layer - it really isn't as hard as the standard - leaves you thinking it may be, and it's really powerful. + leaves you thinking it may be, and it's really powerful. @see @ref buffer_issues. To do a proper interface to @b Flex notion of buffers, there's an extra data member, and some extra member functions. These - are @e not used by other kinds implmentations of @b Lex. + are @e not used by other kinds implmentations of @b Lex. @ingroup lex */ class basic_buffer @@ -73,22 +73,22 @@ namespace ylmm //@{ /// @name Automatic updates - /** Do an automatic incrementation. + /** Do an automatic incrementation. @param c the character read. */ void increment_it(char c); //@} //@{ - /// @name Actual reading + /// @name Actual reading /** Read at most @p max characters into buffer @p buf. See also - the public input method. + the public input method. @param buf The buffer to read into @param max The maximum number of characters to read @return The number of characters read */ virtual int read_buffered(char* buf, int max); /** Read at most @p max characters from input, or up to the first - occurence of delimiter. See also the public input method. - @param buf The buffer to read into + occurence of delimiter. See also the public input method. + @param buf The buffer to read into @param max The maximum number of characters to read @param delim the delimiter to read to @return The number of characters read */ @@ -97,47 +97,47 @@ namespace ylmm //@{ /// @name Extra functions to help with @b Flex - /** An extra action to take when creating a new buffer. + /** An extra action to take when creating a new buffer. @param size is the size of the buffer */ void new_extra(int size); /** An extra action to take when deallocating the buffer.*/ - void delete_extra(); + void delete_extra(); /** An extra action to take when flushing the buffer. */ - void flush_extra(); - /** An extra action to take when making interactive or buffered. + void flush_extra(); + /** An extra action to take when making interactive or buffered. @param inter Whether it's interactive (ignored) */ void interactive_extra(bool inter); - /** An extra action to take when setting begning-of-line flag + /** An extra action to take when setting begning-of-line flag @param bol ignored */ void at_bol_extra(bool bol); //@} public: - /** Make a new state. + /** Make a new state. @param stream Stream to read from. This could be a @c std::istream like @c std::cin, or a @c std::stringstream refering to an external string buffer. If argument is null (0) then the stream is set to @c std::cin and interactive reads - are enabled. - @param inter Is this stream interactive or not. + are enabled. + @param inter Is this stream interactive or not. @param autoinc Should we do automatic location tracking? That is should we set the _line and _column number automatically by parsing the read stream, or should we let the client code do that job for us. */ basic_buffer(std::istream& stream, bool inter=true, bool autoinc=false); - /** Make a new state. - @param filename Name of a file to read from. If this is `-' + /** Make a new state. + @param filename Name of a file to read from. If this is `-' then std::cin is opened for input. If file can not be found, - then this throws a std::runtime_error. - @param inter Is this stream interactive or not. + then this throws a std::runtime_error. + @param inter Is this stream interactive or not. @param autoinc Should we do automatic location tracking? That is should we set the _line and _column number automatically by parsing the read stream, or should we let the client code do - that job for us. + that job for us. @exception std::runtime_error Thrown if named file cannot be found. */ - basic_buffer(const std::string& filename, + basic_buffer(const std::string& filename, bool inter=false, bool autoinc=true); - /** Free this buffer. + /** Free this buffer. If this buffer is the @e owner of the used input stream, that is, if this buffer opened it because it was constructed using the string constructor, then the underlying stream is closed @@ -147,24 +147,24 @@ namespace ylmm //@{ /// @name Stream - /** Get the input stream + /** Get the input stream @return the input stream */ std::istream* stream() { return _stream; } //@} //@{ - /// @name position handling - /** Get the line number + /// @name position handling + /** Get the line number @return the line number */ int line() const { return _line; } - /** Get the column number + /** Get the column number @return the column number */ int column() const { return _column; } - /** Increment line and possibly column + /** Increment line and possibly column @param l number to add to current line number @param c number to add to current column number */ virtual void increment_line(int l, int c=0); - /** Increment the column + /** Increment the column @param c number to add to current column number */ virtual void increment_column(int c) { _column += c; } //@} @@ -173,54 +173,54 @@ namespace ylmm /// @name Read handling /** Flush the buffer */ void flush() { flush_extra(); } - /** Read one character from input - Note, when EOF is encountered, 0 (and not EOF) is returned. + /** Read one character from input + Note, when EOF is encountered, 0 (and not EOF) is returned. @return the character read */ virtual int read(); - /** Read at most @p max characters into buffer @p buf. - @param buf Buffer of at least size @p max to read into. - @param max Maximum number of characters to read from input. + /** Read at most @p max characters into buffer @p buf. + @param buf Buffer of at least size @p max to read into. + @param max Maximum number of characters to read from input. @return The number of characters read. Returns -1 in case of errors. */ virtual int read(char* buf, int max); - /** Put one character back into the stream. + /** Put one character back into the stream. @param c character to put back. */ virtual void putback(int c); //@} //@{ /// @name Miscellanious - /** Are we doing automatic increments? + /** Are we doing automatic increments? @return true if auto incrementing */ bool auto_increment() const { return _auto_increment; } - /** Set wether we should do automatic increments. - @param ai If true, auto increment, otherwise don't - @return true if auto incrementing */ + /** Set wether we should do automatic increments. + @param ai If true, auto increment, otherwise don't + @return true if auto incrementing */ bool auto_increment(bool ai) { return _auto_increment = ai; } - /** Test if we're at the start of a line + /** Test if we're at the start of a line @return true if last read characer was a newline */ bool at_bol() const { return _last_read == '\n'; } - /** Set wether we're at the start of a line + /** Set wether we're at the start of a line @param bol set the last read character to be a newline @return true if last read characer was a newline */ bool at_bol(bool bol); - /** Check if buffer is interactive + /** Check if buffer is interactive @return true if we're reading interactively */ bool interactive() const { return _interactive; } - /** Set whether buffer is interactive + /** Set whether buffer is interactive @param inter if true, read inteactively @return true if we're reading interactively */ bool interactive(bool inter); - /** Called when this buffer is restored as current buffer. + /** Called when this buffer is restored as current buffer. @return true if this is the current buffer after activation */ bool activate(); //@} }; //__________________________________________________________________ - inline - basic_buffer::basic_buffer(std::istream& stream, bool inter, - bool autoinc) + inline + basic_buffer::basic_buffer(std::istream& stream, bool inter, + bool autoinc) { _interactive = inter; _stream = (!stream ? &std::cin : &stream); @@ -233,9 +233,9 @@ namespace ylmm new_extra(0); } //__________________________________________________________________ - inline - basic_buffer::basic_buffer(const std::string& filename, bool inter, - bool autoinc) + inline + basic_buffer::basic_buffer(const std::string& filename, bool inter, + bool autoinc) { _interactive = inter; if (filename.empty()) throw std::runtime_error("no filename given"); @@ -245,7 +245,7 @@ namespace ylmm } else { _stream = new std::ifstream(filename.data()); - if (!_stream || _stream->bad()) + if (!_stream || _stream->bad()) throw std::runtime_error("failed to open file"); _is_owner = true; } @@ -258,17 +258,17 @@ namespace ylmm } //__________________________________________________________________ - inline - basic_buffer::~basic_buffer() + inline + basic_buffer::~basic_buffer() { - delete_extra(); + delete_extra(); if (_is_owner && _stream) { - std::ifstream* is; + std::ifstream* is; if ((is = dynamic_cast(_stream))) is->close(); delete _stream; } } - + //__________________________________________________________________ inline void basic_buffer::increment_it(char c) { @@ -279,20 +279,20 @@ namespace ylmm } //__________________________________________________________________ - inline int basic_buffer::read_buffered(char* buf, int max) + inline int basic_buffer::read_buffered(char* buf, int max) { if (!_stream || _stream->eof()) return 0; _stream->read(buf, max); if (_stream->bad()) return -1; int c = _stream->gcount(); _last_read = buf[c-1]; - if (_auto_increment) { + if (_auto_increment) { for (int i = 0; i < c; i++) increment_it(buf[i]); } return c; } //__________________________________________________________________ - inline int basic_buffer::read_interactive(char* buf, int max, char delim) + inline int basic_buffer::read_interactive(char* buf, int max, char delim) { if (max <= 0 || !_stream || _stream->eof()) return 0; int i = 0; @@ -306,30 +306,30 @@ namespace ylmm } //__________________________________________________________________ - inline void basic_buffer::increment_line(int l, int c) + inline void basic_buffer::increment_line(int l, int c) { - if (_auto_increment) return; - _line = l; - _column = c; + if (_auto_increment) return; + _line = l; + _column = c; } - + //__________________________________________________________________ - inline bool basic_buffer::at_bol(bool bol) - { + inline bool basic_buffer::at_bol(bool bol) + { at_bol_extra(bol); - _last_read = bol ? '\n' : '\0'; return bol; + _last_read = bol ? '\n' : '\0'; return bol; } - + //__________________________________________________________________ - inline bool basic_buffer::interactive(bool inter) - { + inline bool basic_buffer::interactive(bool inter) + { interactive_extra(inter); - return _interactive = inter; + return _interactive = inter; } //__________________________________________________________________ - inline int basic_buffer::read() - { + inline int basic_buffer::read() + { _last_read = _stream->get(); if (_stream->eof()) return 0; if (_stream->bad()) return -1; @@ -338,17 +338,17 @@ namespace ylmm } //__________________________________________________________________ - inline int basic_buffer::read(char* buf, int max) - { + inline int basic_buffer::read(char* buf, int max) + { if (_interactive) return read_interactive(buf, max, '\n'); - else return read_buffered(buf, max); + else return read_buffered(buf, max); } //__________________________________________________________________ - inline void basic_buffer::putback(int c) - { - _stream->putback(char(c)); - if (!_stream->bad() && _auto_increment) _column--; + inline void basic_buffer::putback(int c) + { + _stream->putback(char(c)); + if (!_stream->bad() && _auto_increment) _column--; } } @@ -357,8 +357,8 @@ namespace ylmm @param o output stream to write to @param b the ylmm::basic_buffer to write out @return @a o */ -inline std::ostream& -operator<<(std::ostream& o, const ylmm::basic_buffer& b) +inline std::ostream& +operator<<(std::ostream& o, const ylmm::basic_buffer& b) { return o << b.line() << "," << b.column(); } @@ -367,69 +367,69 @@ operator<<(std::ostream& o, const ylmm::basic_buffer& b) #define YLMM_flex_buffer_impl //__________________________________________________________________ -/** Create a new Flex buffer. +/** Create a new Flex buffer. @param file The file to associate with the buffer. Can be NULL. @param size The size of the buffer @return A newly allocated buffer. */ -extern YY_BUFFER_STATE yy_create_buffer(FILE *file, int size); +extern YY_BUFFER_STATE yy_create_buffer(FILE *file, int size); -inline void -ylmm::basic_buffer::new_extra(int size) +inline void +ylmm::basic_buffer::new_extra(int size) { - // If size is not given (0 or less), then use the default. + // If size is not given (0 or less), then use the default. if (size < 0) { _extra = 0; return; } if (size == 0) size = YY_BUF_SIZE; _extra = static_cast(yy_create_buffer(0, size)); } //__________________________________________________________________ -/** De-allocate a Flex buffer. +/** De-allocate a Flex buffer. @param b The buffer to de-allocate. */ extern void yy_delete_buffer(YY_BUFFER_STATE b); -inline void -ylmm::basic_buffer::delete_extra() +inline void +ylmm::basic_buffer::delete_extra() { yy_delete_buffer(static_cast(_extra)); } //__________________________________________________________________ -/** Switch to another Flex buffer +/** Switch to another Flex buffer @param b The buffer to switch to. */ extern void yy_switch_to_buffer(YY_BUFFER_STATE b); -inline bool -ylmm::basic_buffer::activate() +inline bool +ylmm::basic_buffer::activate() { yy_switch_to_buffer(static_cast(_extra)); return static_cast(_extra) == YY_CURRENT_BUFFER; } //__________________________________________________________________ -inline void -ylmm::basic_buffer::interactive_extra(bool inter) +inline void +ylmm::basic_buffer::interactive_extra(bool inter) { (static_cast(_extra))->yy_is_interactive = inter ? 1 : 0; } //__________________________________________________________________ -inline void -ylmm::basic_buffer::at_bol_extra(bool inter) +inline void +ylmm::basic_buffer::at_bol_extra(bool inter) { (static_cast(_extra))->yy_at_bol = inter ? 1 : 0; } //__________________________________________________________________ -/** Flush a buffer. +/** Flush a buffer. @param b The buffer to flush. */ extern void yy_flush_buffer(YY_BUFFER_STATE b); -inline void -ylmm::basic_buffer::flush_extra() +inline void +ylmm::basic_buffer::flush_extra() { yy_flush_buffer(static_cast(_extra)); } -#else +#else //__________________________________________________________________ inline void ylmm::basic_buffer::new_extra(int size) {} @@ -443,5 +443,5 @@ inline bool ylmm::basic_buffer::activate() { return true; } #endif - - + +