DynamicModel.hh 28.8 KB
Newer Older
sebastien's avatar
sebastien committed
1
/*
2
 * Copyright (C) 2003-2018 Dynare Team
sebastien's avatar
sebastien committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * This file is part of Dynare.
 *
 * Dynare is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Dynare is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef _DYNAMICMODEL_HH
#define _DYNAMICMODEL_HH

using namespace std;

25
#include <fstream>
26
#include <boost/crc.hpp>
27

sebastien's avatar
sebastien committed
28 29 30 31 32
#include "StaticModel.hh"

//! Stores a dynamic model
class DynamicModel : public ModelTree
{
33 34 35 36 37
public:
  //! A reference to the trend component model table
  TrendComponentModelTable &trend_component_model_table;
  //! A reference to the VAR model table
  VarModelTable &var_model_table;
sebastien's avatar
sebastien committed
38
private:
39 40
  constexpr static double zero_band{1e-8};

41 42 43 44
  //! Stores equations declared as [static]
  /*! They will be used in toStatic() to replace equations marked as [dynamic] */
  vector<BinaryOpNode *> static_only_equations;

45 46 47
  //! Stores line numbers of equations declared as [static]
  vector<int> static_only_equations_lineno;

48
  //! Stores the equation tags of equations declared as [static]
49
  vector<vector<pair<string, string>>> static_only_equations_equation_tags;
50

51
  using deriv_id_table_t = map<pair<int, int>, int>;
52 53 54
  //! Maps a pair (symbol_id, lag) to a deriv ID
  deriv_id_table_t deriv_id_table;
  //! Maps a deriv ID to a pair (symbol_id, lag)
55
  vector<pair<int, int>> inv_deriv_id_table;
56 57 58 59 60 61

  //! Maps a deriv_id to the column index of the dynamic Jacobian
  /*! Contains only endogenous, exogenous and exogenous deterministic */
  map<int, int> dyn_jacobian_cols_table;

  //! Maximum lag and lead over all types of variables (positive values)
sebastien's avatar
sebastien committed
62
  /*! Set by computeDerivIDs() */
63 64
  int max_lag, max_lead;
  //! Maximum lag and lead over endogenous variables (positive values)
sebastien's avatar
sebastien committed
65
  /*! Set by computeDerivIDs() */
66 67
  int max_endo_lag, max_endo_lead;
  //! Maximum lag and lead over exogenous variables (positive values)
sebastien's avatar
sebastien committed
68
  /*! Set by computeDerivIDs() */
69 70
  int max_exo_lag, max_exo_lead;
  //! Maximum lag and lead over deterministic exogenous variables (positive values)
sebastien's avatar
sebastien committed
71
  /*! Set by computeDerivIDs() */
72
  int max_exo_det_lag, max_exo_det_lead;
73 74 75 76 77 78 79 80
  //! Maximum lag and lead over all types of variables (positive values) of original model
  int max_lag_orig, max_lead_orig;
  //! Maximum lag and lead over endogenous variables (positive values) of original model
  int max_endo_lag_orig, max_endo_lead_orig;
  //! Maximum lag and lead over exogenous variables (positive values) of original model
  int max_exo_lag_orig, max_exo_lead_orig;
  //! Maximum lag and lead over deterministic exogenous variables (positive values) of original model
  int max_exo_det_lag_orig, max_exo_det_lead_orig;
81

82 83
  //! Cross reference information
  map<int, ExprNode::EquationInfo> xrefs;
84 85 86 87
  map<pair<int, int>, set<int>> xref_param;
  map<pair<int, int>, set<int>> xref_endo;
  map<pair<int, int>, set<int>> xref_exo;
  map<pair<int, int>, set<int>> xref_exo_det;
88

89 90 91
  //! Nonzero equations in the Hessian
  map<int, string> nonzero_hessian_eqs;

92
  //! Number of columns of dynamic jacobian
sebastien's avatar
sebastien committed
93
  /*! Set by computeDerivID()s and computeDynJacobianCols() */
94
  int dynJacobianColsNbr;
95
  //! Temporary terms for block decomposed models
96
  vector< vector<temporary_terms_t>> v_temporary_terms;
97

98
  vector<temporary_terms_inuse_t> v_temporary_terms_inuse;
99

100
  //! Store the derivatives or the chainrule derivatives:map<pair< equation, pair< variable, lead_lag >, expr_t>
101
  using first_chain_rule_derivatives_t = map< pair< int, pair< int, int>>, expr_t>;
102
  first_chain_rule_derivatives_t first_chain_rule_derivatives;
103

sebastien's avatar
sebastien committed
104
  //! Writes dynamic model file (Matlab version)
105
  void writeDynamicMFile(const string &basename) const;
Houtan Bastani's avatar
Houtan Bastani committed
106 107
  //! Writes dynamic model file (Julia version)
  void writeDynamicJuliaFile(const string &dynamic_basename) const;
sebastien's avatar
sebastien committed
108 109
  //! Writes dynamic model file (C version)
  /*! \todo add third derivatives handling */
110
  void writeDynamicCFile(const string &basename, const int order) const;
sebastien's avatar
sebastien committed
111
  //! Writes dynamic model file when SparseDLL option is on
112
  void writeSparseDynamicMFile(const string &basename) const;
sebastien's avatar
sebastien committed
113 114
  //! Writes the dynamic model equations and its derivatives
  /*! \todo add third derivatives handling in C output */
Houtan Bastani's avatar
Houtan Bastani committed
115
  void writeDynamicModel(ostream &DynamicOutput, bool use_dll, bool julia) const;
116 117
  void writeDynamicModel(const string &basename, bool use_dll, bool julia) const;
  void writeDynamicModel(const string &basename, ostream &DynamicOutput, bool use_dll, bool julia) const;
sebastien's avatar
sebastien committed
118
  //! Writes the Block reordred structure of the model in M output
119
  void writeModelEquationsOrdered_M(const string &basename) const;
sebastien's avatar
sebastien committed
120
  //! Writes the code of the Block reordred structure of the model in virtual machine bytecode
121
  void writeModelEquationsCode_Block(const string &basename, const map_idx_t &map_idx) const;
122
  //! Writes the code of the model in virtual machine bytecode
123
  void writeModelEquationsCode(const string &basename, const map_idx_t &map_idx) const;
124

125 126 127
  void writeSetAuxiliaryVariables(const string &basename, const bool julia) const;
  void writeAuxVarRecursiveDefinitions(ostream &output, ExprNodeOutputType output_type) const;

sebastien's avatar
sebastien committed
128 129 130 131 132
  //! Computes jacobian and prepares for equation normalization
  /*! Using values from initval/endval blocks and parameter initializations:
    - computes the jacobian for the model w.r. to contemporaneous variables
    - removes edges of the incidence matrix when derivative w.r. to the corresponding variable is too close to zero (below the cutoff)
  */
133
  //void evaluateJacobian(const eval_context_t &eval_context, jacob_map *j_m, bool dynamic);
134 135

  //! return a map on the block jacobian
136
  map<pair<pair<int, pair<int, int>>, pair<int, int>>, int> get_Derivatives(int block);
137
  //! Computes chain rule derivatives of the Jacobian w.r. to endogenous variables
138
  void computeChainRuleJacobian(blocks_derivatives_t &blocks_derivatives);
139

sebastien's avatar
sebastien committed
140
  string reform(string name) const;
141
  map_idx_t map_idx;
sebastien's avatar
sebastien committed
142

143
  //! sorts the temporary terms in the blocks order
144
  void computeTemporaryTermsOrdered();
145 146 147

  //! creates a mapping from the index of temporary terms to a natural index
  void computeTemporaryTermsMapping();
sebastien's avatar
sebastien committed
148
  //! Write derivative code of an equation w.r. to a variable
149
  void compileDerivative(ofstream &code_file, unsigned int &instruction_number, int eq, int symb_id, int lag, const map_idx_t &map_idx) const;
150
  //! Write chain rule derivative code of an equation w.r. to a variable
151
  void compileChainRuleDerivative(ofstream &code_file, unsigned int &instruction_number, int eq, int var, int lag, const map_idx_t &map_idx) const;
sebastien's avatar
sebastien committed
152

153
  //! Get the type corresponding to a derivation ID
154
  SymbolType getTypeByDerivID(int deriv_id) const noexcept(false) override;
155
  //! Get the lag corresponding to a derivation ID
156
  int getLagByDerivID(int deriv_id) const noexcept(false) override;
157
  //! Get the symbol ID corresponding to a derivation ID
158
  int getSymbIDByDerivID(int deriv_id) const noexcept(false) override;
159
  //! Compute the column indices of the dynamic Jacobian
160
  void computeDynJacobianCols(bool jacobianExo);
161 162
  //! Computes derivatives of the Jacobian w.r. to trend vars and tests that they are equal to zero
  void testTrendDerivativesEqualToZero(const eval_context_t &eval_context);
163
  //! Collect only the first derivatives
164
  map<pair<int, pair<int, int>>, expr_t> collect_first_order_derivatives_endogenous();
165

sebastien's avatar
sebastien committed
166 167 168 169
  //! Allocates the derivation IDs for all dynamic variables of the model
  /*! Also computes max_{endo,exo}_{lead_lag}, and initializes dynJacobianColsNbr to the number of dynamic endos */
  void computeDerivIDs();

170 171 172
  //! Collecte the derivatives w.r. to endogenous of the block, to endogenous of previouys blocks and to exogenous
  void collect_block_first_order_derivatives();

173 174 175
  //! Collecte the informations about exogenous, deterministic exogenous and endogenous from the previous block for each block
  void collectBlockVariables();

176
  //! Factorized code for substitutions of leads/lags
177 178 179 180
  /*! \param[in] type determines which type of variables is concerned
    \param[in] deterministic_model whether we are in a deterministic model (only for exogenous leads/lags)
    \param[in] subset variables to which to apply the transformation (only for diff of forward vars)
  */
181
  void substituteLeadLagInternal(AuxVarType type, bool deterministic_model, const vector<string> &subset);
182

183 184 185 186
private:
  //! Indicate if the temporary terms are computed for the overall model (true) or not (false). Default value true
  bool global_temporary_terms;

187
  //! Vector describing equations: BlockSimulationType, if BlockSimulationType == EVALUATE_s then a expr_t on the new normalized equation
188
  equation_type_and_normalized_equation_t equation_type_and_normalized_equation;
189

190
  //! for each block contains pair< Simulation_Type, pair < Block_Size, Recursive_part_Size >>
191
  block_type_firstequation_size_mfs_t block_type_firstequation_size_mfs;
192 193

  //! for all blocks derivatives description
194
  blocks_derivatives_t blocks_derivatives;
195 196

  //! The jacobian without the elements below the cutoff
197
  dynamic_jacob_map_t dynamic_jacobian;
198 199 200 201

  //! Vector indicating if the block is linear in endogenous variable (true) or not (false)
  vector<bool> blocks_linear;

202
  //! Map the derivatives for a block pair<lag, make_pair(make_pair(eq, var)), expr_t>
203
  using derivative_t = map<pair< int, pair<int, int>>, expr_t>;
204
  //! Vector of derivative for each blocks
205
  vector<derivative_t> derivative_endo, derivative_other_endo, derivative_exo, derivative_exo_det;
206

207
  //!List for each block and for each lag-lead all the other endogenous variables and exogenous variables
208
  using var_t = set<int>;
209
  using lag_var_t = map<int, var_t>;
210
  vector<lag_var_t> other_endo_block, exo_block, exo_det_block;
211

212
  //!List for each block the exogenous variables
213
  vector<pair<var_t, int>> block_var_exo;
214

215
  map< int, map<int, int>> block_exo_index, block_det_exo_index, block_other_endo_index;
216 217

  //! for each block described the number of static, forward, backward and mixed variables in the block
218 219
  /*! pair< pair<static, forward>, pair<backward,mixed>> */
  vector<pair< pair<int, int>, pair<int, int>>> block_col_type;
220

221
  //! Help computeXrefs to compute the reverse references (i.e. param->eqs, endo->eqs, etc)
222
  void computeRevXref(map<pair<int, int>, set<int>> &xrefset, const set<pair<int, int>> &eiref, int eqn);
223 224

  //! Write reverse cross references
225
  void writeRevXrefs(ostream &output, const map<pair<int, int>, set<int>> &xrefmap, const string &type) const;
226

227
  //! List for each variable its block number and its maximum lag and lead inside the block
228
  vector<pair<int, pair<int, int>>> variable_block_lead_lag;
229 230 231
  //! List for each equation its block number
  vector<int> equation_block;

232
  //! Used for var_expectation and var_model
233
  map<string, set<int>> var_expectation_functions_to_write;
234

235
  //! Used for pac_expectation operator
236
  set<const PacExpectationNode *> pac_expectation_info; // PacExpectationNode pointers
237

238
  //!Maximum lead and lag for each block on endogenous of the block, endogenous of the previous blocks, exogenous and deterministic exogenous
239
  vector<pair<int, int>> endo_max_leadlag_block, other_endo_max_leadlag_block, exo_max_leadlag_block, exo_det_max_leadlag_block, max_leadlag_block;
240

Houtan Bastani's avatar
Houtan Bastani committed
241
  void writeWrapperFunctions(const string &name, const string &ending) const;
242 243
  void writeDynamicModelHelper(const string &basename,
                               const string &name, const string &retvalname,
Houtan Bastani's avatar
Houtan Bastani committed
244 245 246 247 248 249
                               const string &name_tt, size_t ttlen,
                               const string &previous_tt_name,
                               const ostringstream &init_s,
                               const ostringstream &end_s,
                               const ostringstream &s, const ostringstream &s_tt) const;

250
  //! Create a legacy *_dynamic.m file for Matlab/Octave not yet using the temporary terms array interface
251
  void writeDynamicMatlabCompatLayer(const string &basename) const;
252

253 254 255 256
  void getEquationNumbersFromTags(vector<int> &eqnumber, set<string> &eqtags) const;

  void findPacExpectationEquationNumbers(vector<int> &eqnumber) const;

sebastien's avatar
sebastien committed
257
public:
Houtan Bastani's avatar
Houtan Bastani committed
258 259 260 261 262
  DynamicModel(SymbolTable &symbol_table_arg,
               NumericalConstants &num_constants_arg,
               ExternalFunctionsTable &external_functions_table_arg,
               TrendComponentModelTable &trend_component_model_table_arg,
               VarModelTable &var_model_table_arg);
sebastien's avatar
sebastien committed
263 264
  //! Adds a variable node
  /*! This implementation allows for non-zero lag */
265
  VariableNode *AddVariable(int symb_id, int lag = 0) override;
266 267 268 269 270 271 272

  //! Compute cross references
  void computeXrefs();

  //! Write cross references
  void writeXrefs(ostream &output) const;

sebastien's avatar
sebastien committed
273
  //! Execute computations (variable sorting + derivation)
274 275 276 277
  /*!
    \param jacobianExo whether derivatives w.r. to exo and exo_det should be in the Jacobian (derivatives w.r. to endo are always computed)
    \param hessian whether 2nd derivatives w.r. to exo, exo_det and endo should be computed (implies jacobianExo = true)
    \param thirdDerivatives whether 3rd derivatives w.r. to endo/exo/exo_det should be computed (implies jacobianExo = true)
278
    \param paramsDerivsOrder order of derivatives w.r. to a pair (endo/exo/exo_det, parameter) to be computed (>0 implies jacobianExo = true)
279 280 281
    \param eval_context evaluation context for normalization
    \param no_tmp_terms if true, no temporary terms will be computed in the dynamic files
  */
282
  void computingPass(bool jacobianExo, bool hessian, bool thirdDerivatives, int paramsDerivsOrder,
283
                     const eval_context_t &eval_context, bool no_tmp_terms, bool block, bool use_dll, bool bytecode, const bool nopreprocessoroutput);
sebastien's avatar
sebastien committed
284
  //! Writes model initialization and lead/lag incidence matrix to output
285
  void writeOutput(ostream &output, const string &basename, bool block, bool byte_code, bool use_dll, int order, bool estimation_present, bool compute_xrefs, bool julia) const;
286

287 288 289
  //! Write JSON Output
  void writeJsonOutput(ostream &output) const;

290 291 292
  //! Write JSON Output representation of original dynamic model
  void writeJsonOriginalModelOutput(ostream &output) const;

293 294 295
  //! Write JSON Output representation of model info (useful stuff from M_)
  void writeJsonDynamicModelInfo(ostream &output) const;

296
  //! Write JSON Output representation of dynamic model after computing pass
297
  void writeJsonComputingPassOutput(ostream &output, bool writeDetails) const;
298 299

  //! Write JSON prams derivatives file
300
  void writeJsonParamsDerivativesFile(ostream &output, bool writeDetails) const;
301

302 303
  //! Write cross reference output if the xref maps have been filed
  void writeJsonXrefs(ostream &output) const;
304
  void writeJsonXrefsHelper(ostream &output, const map<pair<int, int>, set<int>> &xrefs) const;
305

306 307
  //! Print equations that have non-zero second derivatives
  void printNonZeroHessianEquations(ostream &output) const;
308

309 310
  //! Set the equations that have non-zero second derivatives
  void setNonZeroHessianEquations(map<int, string> &eqs);
311

312
  //! Fill Autoregressive Matrix for var_model/trend_component_model
313
  void fillAutoregressiveMatrix(map<string, map<tuple<int, int, int>, expr_t>> &ARr, bool is_trend_component_model) const;
Houtan Bastani's avatar
Houtan Bastani committed
314

315
  //! Fill Error Component Matrix for trend_component_model
316
  void fillErrorComponentMatrix(map<string, map<tuple<int, int, int>, expr_t>> &ECr, ExprNode::subst_table_t &diff_subst_table) const;
317

318 319 320
  //! Fill the Trend Component Model Table
  void fillTrendComponentModelTable() const;
  void fillTrendComponentModelTableFromOrigModel(StaticModel &static_model) const;
321
  void fillTrendComponentmodelTableAREC(ExprNode::subst_table_t &diff_subst_table) const;
322

Houtan Bastani's avatar
Houtan Bastani committed
323 324 325 326
  //! Fill the Var Model Table
  void fillVarModelTable() const;
  void fillVarModelTableFromOrigModel(StaticModel &static_model) const;

327
  //! Update the rhs references in the var model and trend component tables
328 329 330
  //! after substitution of auxiliary variables and find the trend variables
  //! in the trend_component model
  void updateVarAndTrendModel() const;
331

Houtan Bastani's avatar
Houtan Bastani committed
332 333 334 335
  //! Add aux equations (and aux variables) for variables declared in var_model
  //! at max order if they don't already exist
  void addEquationsForVar();

336 337
  //! Get Pac equation parameter info
  void walkPacParameters();
338
  //! Add var_model info to pac_expectation nodes
Houtan Bastani's avatar
Houtan Bastani committed
339
  void fillPacExpectationVarInfo(string &pac_model_name,
340
                                 vector<int> &lhs,
Houtan Bastani's avatar
Houtan Bastani committed
341
                                 int max_lag,
342
                                 int pac_max_lag,
Houtan Bastani's avatar
Houtan Bastani committed
343 344 345
                                 vector<bool> &nonstationary,
                                 int growth_symb_id);

346 347 348
  //! Substitutes pac_expectation operator
  void substitutePacExpectation();

sebastien's avatar
sebastien committed
349
  //! Adds informations for simulation in a binary file
350
  void Write_Inf_To_Bin_File_Block(const string &basename,
351
                                   const int &num, int &u_count_int, bool &file_open, bool is_two_boundaries) const;
sebastien's avatar
sebastien committed
352
  //! Writes dynamic model file
Houtan Bastani's avatar
Houtan Bastani committed
353
  void writeDynamicFile(const string &basename, bool block, bool bytecode, bool use_dll, int order, bool julia) const;
sebastien's avatar
sebastien committed
354
  //! Writes file containing parameters derivatives
355
  void writeParamsDerivativesFile(const string &basename, bool julia) const;
MichelJuillard's avatar
MichelJuillard committed
356

sebastien's avatar
sebastien committed
357 358 359
  //! Converts to static model (only the equations)
  /*! It assumes that the static model given in argument has just been allocated */
  void toStatic(StaticModel &static_model) const;
360

361
  //! Find endogenous variables not used in model
362
  set<int> findUnusedEndogenous();
363 364
  //! Find exogenous variables not used in model
  set<int> findUnusedExogenous();
365

366 367 368
  //! Set the max leads/lags of the original model
  void setLeadsLagsOrig();

369 370 371 372
  //! Copies a dynamic model (only the equations)
  /*! It assumes that the dynamic model given in argument has just been allocated */
  void cloneDynamic(DynamicModel &dynamic_model) const;

373 374 375
  //! update equations after variable type change in model block
  void updateAfterVariableChange(DynamicModel &dynamic_model);

376
  //! Replaces model equations with derivatives of Lagrangian w.r.t. endogenous
377
  void computeRamseyPolicyFOCs(const StaticModel &static_model, const bool nopreprocessoroutput);
Houtan Bastani's avatar
Houtan Bastani committed
378
  //! Replaces the model equations in dynamic_model with those in this model
379 380
  void replaceMyEquations(DynamicModel &dynamic_model) const;

381
  //! Adds an equation marked as [static]
382
  void addStaticOnlyEquation(expr_t eq, int lineno, const vector<pair<string, string>> &eq_tags);
383 384 385

  //! Returns number of static only equations
  size_t staticOnlyEquationsNbr() const;
386

387 388 389
  //! Returns number of dynamic only equations
  size_t dynamicOnlyEquationsNbr() const;

390
  //! Writes LaTeX file with the equations of the dynamic model
391
  void writeLatexFile(const string &basename, const bool write_equation_tags) const;
392

393
  //! Writes LaTeX file with the equations of the dynamic model (for the original model)
394
  void writeLatexOriginalFile(const string &basename, const bool write_equation_tags) const;
395

396 397 398
  int getDerivID(int symb_id, int lag) const noexcept(false) override;
  int getDynJacobianCol(int deriv_id) const noexcept(false) override;
  void addAllParamDerivId(set<int> &deriv_id_set) override;
399

400
  //! Returns true indicating that this is a dynamic model
401 402
  bool
  isDynamic() const override
403 404 405
  {
    return true;
  };
sebastien's avatar
sebastien committed
406

407 408 409
  //! Drive test of detrended equations
  void runTrendTest(const eval_context_t &eval_context);

410
  //! Transforms the model by removing all leads greater or equal than 2 on endos
sebastien's avatar
sebastien committed
411
  /*! Note that this can create new lags on endos and exos */
412
  void substituteEndoLeadGreaterThanTwo(bool deterministic_model);
sebastien's avatar
sebastien committed
413

414
  //! Transforms the model by removing all lags greater or equal than 2 on endos
415
  void substituteEndoLagGreaterThanTwo(bool deterministic_model);
416

sebastien's avatar
sebastien committed
417 418
  //! Transforms the model by removing all leads on exos
  /*! Note that this can create new lags on endos and exos */
419
  void substituteExoLead(bool deterministic_model);
sebastien's avatar
sebastien committed
420 421

  //! Transforms the model by removing all lags on exos
422
  void substituteExoLag(bool deterministic_model);
sebastien's avatar
sebastien committed
423

424
  //! Transforms the model by removing all UnaryOpcode::expectation
425 426
  void substituteExpectation(bool partial_information_model);

427 428 429
  //! Transforms the model by decreasing the lead/lag of predetermined variables in model equations by one
  void transformPredeterminedVariables();

430 431 432
  //! Transforms the model by removing trends specified by the user
  void detrendEquations();

433 434 435
  //! Substitutes adl operator
  void substituteAdl();

436 437 438
  //! Creates aux vars for all unary operators
  void substituteUnaryOps(StaticModel &static_model);

439
  //! Creates aux vars for certain unary operators: originally implemented for support of VARs
440
  void substituteUnaryOps(StaticModel &static_model, set<string> &eq_tags);
441

442 443 444
  //! Creates aux vars for certain unary operators: originally implemented for support of VARs
  void substituteUnaryOps(StaticModel &static_model, vector<int> &eqnumbers);

445
  //! Substitutes diff operator
446
  void substituteDiff(StaticModel &static_model, ExprNode::subst_table_t &diff_subst_table);
Houtan Bastani's avatar
Houtan Bastani committed
447

448 449 450
  //! Substitute VarExpectation operators
  void substituteVarExpectation(const map<string, expr_t> &subst_table);

451 452 453
  //! Return max lag of pac equation
  int getPacMaxLag(const string &pac_model_name) const;

Houtan Bastani's avatar
Houtan Bastani committed
454
  //! Table to undiff LHS variables for pac vector z
455
  vector<int> getUndiffLHSForPac(const string &aux_model_name,
456
                                 ExprNode::subst_table_t &diff_subst_table) const;
457

458 459 460
  //! Transforms the model by replacing trend variables with a 1
  void removeTrendVariableFromEquations();

461
  //! Transforms the model by creating aux vars for the diff of forward vars
462
  /*! If subset is empty, does the transformation for all fwrd vars; otherwise
463
    restrict it to the vars in subset */
464
  void differentiateForwardVars(const vector<string> &subset);
465

sebastien's avatar
sebastien committed
466
  //! Fills eval context with values of model local variables and auxiliary variables
467
  void fillEvalContext(eval_context_t &eval_context) const;
468 469

  //! Return the number of blocks
470 471
  unsigned int
  getNbBlocks() const override
472 473 474
  {
    return (block_type_firstequation_size_mfs.size());
  };
475
  //! Determine the simulation type of each block
476 477
  BlockSimulationType
  getBlockSimulationType(int block_number) const override
478 479 480
  {
    return (block_type_firstequation_size_mfs[block_number].first.first);
  };
481
  //! Return the first equation number of a block
482 483
  unsigned int
  getBlockFirstEquation(int block_number) const override
484 485 486
  {
    return (block_type_firstequation_size_mfs[block_number].first.second);
  };
487
  //! Return the size of the block block_number
488 489
  unsigned int
  getBlockSize(int block_number) const override
490 491 492
  {
    return (block_type_firstequation_size_mfs[block_number].second.first);
  };
493
  //! Return the number of exogenous variable in the block block_number
494 495
  unsigned int
  getBlockExoSize(int block_number) const override
496 497 498 499
  {
    return (block_var_exo[block_number].first.size());
  };
  //! Return the number of colums in the jacobian matrix for exogenous variable in the block block_number
500 501
  unsigned int
  getBlockExoColSize(int block_number) const override
502 503 504
  {
    return (block_var_exo[block_number].second);
  };
505
  //! Return the number of feedback variable of the block block_number
506 507
  unsigned int
  getBlockMfs(int block_number) const override
508 509 510
  {
    return (block_type_firstequation_size_mfs[block_number].second.second);
  };
511
  //! Return the maximum lag in a block
512 513
  unsigned int
  getBlockMaxLag(int block_number) const override
514 515 516
  {
    return (block_lag_lead[block_number].first);
  };
517
  //! Return the maximum lead in a block
518 519
  unsigned int
  getBlockMaxLead(int block_number) const override
520 521 522
  {
    return (block_lag_lead[block_number].second);
  };
523
  //! Return the type of equation (equation_number) belonging to the block block_number
524 525
  EquationType
  getBlockEquationType(int block_number, int equation_number) const override
526 527 528
  {
    return (equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].first);
  };
529
  //! Return true if the equation has been normalized
530 531
  bool
  isBlockEquationRenormalized(int block_number, int equation_number) const override
532 533 534
  {
    return (equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].first == E_EVALUATE_S);
  };
535
  //! Return the expr_t of the equation equation_number belonging to the block block_number
536 537
  expr_t
  getBlockEquationExpr(int block_number, int equation_number) const override
538 539 540
  {
    return (equations[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]]);
  };
541
  //! Return the expr_t of the renormalized equation equation_number belonging to the block block_number
542 543
  expr_t
  getBlockEquationRenormalizedExpr(int block_number, int equation_number) const override
544 545 546
  {
    return (equation_type_and_normalized_equation[equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]].second);
  };
547
  //! Return the original number of equation equation_number belonging to the block block_number
548 549
  int
  getBlockEquationID(int block_number, int equation_number) const override
550 551 552
  {
    return (equation_reordered[block_type_firstequation_size_mfs[block_number].first.second+equation_number]);
  };
553
  //! Return the original number of variable variable_number belonging to the block block_number
554 555
  int
  getBlockVariableID(int block_number, int variable_number) const override
556 557 558
  {
    return (variable_reordered[block_type_firstequation_size_mfs[block_number].first.second+variable_number]);
  };
559
  //! Return the original number of the exogenous variable varexo_number belonging to the block block_number
560 561
  int
  getBlockVariableExoID(int block_number, int variable_number) const override
562
  {
563
    auto it = exo_block[block_number].find(variable_number);
564 565
    return (it->first);
  };
566
  //! Return the position of equation_number in the block number belonging to the block block_number
567 568
  int
  getBlockInitialEquationID(int block_number, int equation_number) const override
569 570 571
  {
    return ((int) inv_equation_reordered[equation_number] - (int) block_type_firstequation_size_mfs[block_number].first.second);
  };
572
  //! Return the position of variable_number in the block number belonging to the block block_number
573 574
  int
  getBlockInitialVariableID(int block_number, int variable_number) const override
575 576 577
  {
    return ((int) inv_variable_reordered[variable_number] - (int) block_type_firstequation_size_mfs[block_number].first.second);
  };
578 579 580 581
  //! Return the block number containing the endogenous variable variable_number
  int
  getBlockVariableID(int variable_number) const
  {
582
    return (variable_block_lead_lag[variable_number].first);
583 584
  };
  //! Return the position of the exogenous variable_number in the block number belonging to the block block_number
585 586
  int
  getBlockInitialExogenousID(int block_number, int variable_number) const override
587
  {
588
    auto it = block_exo_index.find(block_number);
589 590
    if (it != block_exo_index.end())
      {
591
        auto it1 = it->second.find(variable_number);
592
        if (it1 != it->second.end())
593 594 595 596 597 598 599 600
          return it1->second;
        else
          return -1;
      }
    else
      return (-1);
  };
  //! Return the position of the deterministic exogenous variable_number in the block number belonging to the block block_number
601 602
  int
  getBlockInitialDetExogenousID(int block_number, int variable_number) const override
603
  {
604
    auto it = block_det_exo_index.find(block_number);
605 606
    if (it != block_det_exo_index.end())
      {
607
        auto it1 = it->second.find(variable_number);
608
        if (it1 != it->second.end())
609 610 611 612 613 614 615 616
          return it1->second;
        else
          return -1;
      }
    else
      return (-1);
  };
  //! Return the position of the other endogenous variable_number in the block number belonging to the block block_number
617 618
  int
  getBlockInitialOtherEndogenousID(int block_number, int variable_number) const override
619
  {
620
    auto it = block_other_endo_index.find(block_number);
621 622
    if (it != block_other_endo_index.end())
      {
623
        auto it1 = it->second.find(variable_number);
624
        if (it1 != it->second.end())
625 626 627 628 629 630 631
          return it1->second;
        else
          return -1;
      }
    else
      return (-1);
  };
632
  bool isModelLocalVariableUsed() const;
633

634 635 636
  //! Returns true if a parameter was used in the model block with a lead or lag
  bool ParamUsedWithLeadLag() const;

637
  bool isChecksumMatching(const string &basename) const;
sebastien's avatar
sebastien committed
638 639
};

640
//! Classes to re-order derivatives for various sparse storage formats
641
class derivative
642 643
{
public:
644 645 646 647
  long unsigned int linear_address;
  long unsigned int col_nbr;
  unsigned int row_nbr;
  expr_t value;
648 649 650 651
  derivative(long unsigned int arg1, long unsigned int arg2, int arg3, expr_t arg4) :
    linear_address(arg1), col_nbr(arg2), row_nbr(arg3), value(arg4)
  {
  };
652 653 654 655 656
};

class derivative_less_than
{
public:
657 658
  bool
  operator()(const derivative &d1, const derivative &d2) const
659 660 661
  {
    return d1.linear_address < d2.linear_address;
  }
662
};
sebastien's avatar
sebastien committed
663
#endif