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

#include <iostream>
#include <algorithm>
22
#include <cassert>
23
#include <cmath>
24
#include <utility>
25

26 27
#include "ExprNode.hh"
#include "DataTree.hh"
28
#include "ModFile.hh"
29

30
ExprNode::ExprNode(DataTree &datatree_arg, int idx_arg) : datatree{datatree_arg}, idx{idx_arg}
31 32 33
{
}

34
expr_t
35
ExprNode::getDerivative(int deriv_id)
36
{
sebastien's avatar
sebastien committed
37 38
  if (!preparedForDerivation)
    prepareForDerivation();
39

40
  // Return zero if derivative is necessarily null (using symbolic a priori)
41
  auto it = non_null_derivatives.find(deriv_id);
42 43
  if (it == non_null_derivatives.end())
    return datatree.Zero;
44

45
  // If derivative is stored in cache, use the cached value, otherwise compute it (and cache it)
46
  map<int, expr_t>::const_iterator it2 = derivatives.find(deriv_id);
47 48 49 50
  if (it2 != derivatives.end())
    return it2->second;
  else
    {
51
      expr_t d = computeDerivative(deriv_id);
52
      derivatives[deriv_id] = d;
53 54 55 56
      return d;
    }
}

ferhat's avatar
ferhat committed
57
int
58
ExprNode::precedence(ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms) const
59 60 61 62
{
  // For a constant, a variable, or a unary op, the precedence is maximal
  return 100;
}
ferhat's avatar
ferhat committed
63

64 65 66 67 68 69 70
int
ExprNode::precedenceJson(const temporary_terms_t &temporary_terms) const
{
  // For a constant, a variable, or a unary op, the precedence is maximal
  return 100;
}

71
int
72 73 74 75 76 77 78 79 80 81 82 83 84 85
ExprNode::cost(int cost, bool is_matlab) const
{
  // For a terminal node, the cost is null
  return 0;
}

int
ExprNode::cost(const temporary_terms_t &temp_terms_map, bool is_matlab) const
{
  // For a terminal node, the cost is null
  return 0;
}

int
86
ExprNode::cost(const map<pair<int, int>, temporary_terms_t> &temp_terms_map, bool is_matlab) const
87 88 89 90
{
  // For a terminal node, the cost is null
  return 0;
}
91

92 93 94 95 96 97 98 99 100
bool
ExprNode::checkIfTemporaryTermThenWrite(ostream &output, ExprNodeOutputType output_type,
                                        const temporary_terms_t &temporary_terms,
                                        const temporary_terms_idxs_t &temporary_terms_idxs) const
{
  auto it = temporary_terms.find(const_cast<ExprNode *>(this));
  if (it == temporary_terms.end())
    return false;

101
  if (output_type == ExprNodeOutputType::matlabDynamicModelSparse)
102 103
    output << "T" << idx << "(it_)";
  else
104
    if (output_type == ExprNodeOutputType::matlabStaticModelSparse)
105 106 107 108 109 110 111
      output << "T" << idx;
    else
      {
        auto it2 = temporary_terms_idxs.find(const_cast<ExprNode *>(this));
        // It is the responsibility of the caller to ensure that all temporary terms have their index
        assert(it2 != temporary_terms_idxs.end());
        output << "T" << LEFT_ARRAY_SUBSCRIPT(output_type)
112
               << it2->second + ARRAY_SUBSCRIPT_OFFSET(output_type)
113 114 115 116 117
               << RIGHT_ARRAY_SUBSCRIPT(output_type);
      }
  return true;
}

118 119 120
void
ExprNode::collectVariables(SymbolType type, set<int> &result) const
{
121
  set<pair<int, int>> symbs_lags;
122 123
  collectDynamicVariables(type, symbs_lags);
  transform(symbs_lags.begin(), symbs_lags.end(), inserter(result, result.begin()),
124
            [](auto x) { return x.first; });
125 126
}

sebastien's avatar
sebastien committed
127
void
128
ExprNode::collectEndogenous(set<pair<int, int>> &result) const
sebastien's avatar
sebastien committed
129
{
130
  set<pair<int, int>> symb_ids;
131
  collectDynamicVariables(SymbolType::endogenous, symb_ids);
132
  for (const auto & symb_id : symb_ids)
133
    result.emplace(datatree.symbol_table.getTypeSpecificID(symb_id.first), symb_id.second);
sebastien's avatar
sebastien committed
134 135 136
}

void
137
ExprNode::collectExogenous(set<pair<int, int>> &result) const
sebastien's avatar
sebastien committed
138
{
139
  set<pair<int, int>> symb_ids;
140
  collectDynamicVariables(SymbolType::exogenous, symb_ids);
141
  for (const auto & symb_id : symb_ids)
142
    result.emplace(datatree.symbol_table.getTypeSpecificID(symb_id.first), symb_id.second);
sebastien's avatar
sebastien committed
143 144
}

145
void
146 147 148 149
ExprNode::computeTemporaryTerms(const pair<int, int> &derivOrder,
                                map<pair<int, int>, temporary_terms_t> &temp_terms_map,
                                map<expr_t, pair<int, pair<int, int>>> &reference_count,
                                bool is_matlab) const
150 151 152
{
  // Nothing to do for a terminal node
}
153 154

void
155
ExprNode::computeTemporaryTerms(map<expr_t, int> &reference_count,
156
                                temporary_terms_t &temporary_terms,
157
                                map<expr_t, pair<int, int>> &first_occurence,
158
                                int Curr_block,
159
                                vector<vector<temporary_terms_t>> &v_temporary_terms,
160
                                int equation) const
161 162 163
{
  // Nothing to do for a terminal node
}
164

165 166
pair<int, expr_t>
ExprNode::normalizeEquation(int var_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const
167
{
168
  /* nothing to do */
169
  return { 0, nullptr };
170
}
171

172
void
173
ExprNode::writeOutput(ostream &output) const
174
{
175
  writeOutput(output, ExprNodeOutputType::matlabOutsideModel, {}, {});
176 177
}

178 179 180
void
ExprNode::writeOutput(ostream &output, ExprNodeOutputType output_type) const
{
181
  writeOutput(output, output_type, {}, {});
182 183
}

184
void
Houtan Bastani's avatar
Houtan Bastani committed
185
ExprNode::writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, const temporary_terms_idxs_t &temporary_terms_idxs) const
186
{
187
  writeOutput(output, output_type, temporary_terms, temporary_terms_idxs, {});
188 189
}

190 191
void
ExprNode::compile(ostream &CompileCode, unsigned int &instruction_number,
192 193
                  bool lhs_rhs, const temporary_terms_t &temporary_terms,
                  const map_idx_t &map_idx, bool dynamic, bool steady_dynamic) const
194
{
195
  compile(CompileCode, instruction_number, lhs_rhs, temporary_terms, map_idx, dynamic, steady_dynamic, {});
196 197
}

198 199
void
ExprNode::writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type,
200
                                      const temporary_terms_t &temporary_terms,
Houtan Bastani's avatar
Houtan Bastani committed
201
                                      const temporary_terms_idxs_t &temporary_terms_idxs,
202
                                      deriv_node_temp_terms_t &tef_terms) const
203 204 205 206
{
  // Nothing to do
}

207 208 209
void
ExprNode::writeJsonExternalFunctionOutput(vector<string> &efout,
                                          const temporary_terms_t &temporary_terms,
210 211
                                          deriv_node_temp_terms_t &tef_terms,
                                          const bool isdynamic) const
212 213 214 215
{
  // Nothing to do
}

216 217
void
ExprNode::compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number,
218 219 220
                                        bool lhs_rhs, const temporary_terms_t &temporary_terms,
                                        const map_idx_t &map_idx, bool dynamic, bool steady_dynamic,
                                        deriv_node_temp_terms_t &tef_terms) const
221 222 223 224
{
  // Nothing to do
}

sebastien's avatar
sebastien committed
225
VariableNode *
226
ExprNode::createEndoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const
sebastien's avatar
sebastien committed
227 228 229 230 231 232 233 234
{
  int n = maxEndoLead();
  assert(n >= 2);

  subst_table_t::const_iterator it = subst_table.find(this);
  if (it != subst_table.end())
    return const_cast<VariableNode *>(it->second);

235
  expr_t substexpr = decreaseLeadsLags(n-1);
sebastien's avatar
sebastien committed
236 237 238 239
  int lag = n-2;

  // Each iteration tries to create an auxvar such that auxvar(+1)=expr(-lag)
  // At the beginning (resp. end) of each iteration, substexpr is an expression (possibly an auxvar) equivalent to expr(-lag-1) (resp. expr(-lag))
240
  while (lag >= 0)
sebastien's avatar
sebastien committed
241
    {
242
      expr_t orig_expr = decreaseLeadsLags(lag);
sebastien's avatar
sebastien committed
243 244 245
      it = subst_table.find(orig_expr);
      if (it == subst_table.end())
        {
246
          int symb_id = datatree.symbol_table.addEndoLeadAuxiliaryVar(orig_expr->idx, substexpr);
sebastien's avatar
sebastien committed
247 248
          neweqs.push_back(dynamic_cast<BinaryOpNode *>(datatree.AddEqual(datatree.AddVariable(symb_id, 0), substexpr)));
          substexpr = datatree.AddVariable(symb_id, +1);
249
          assert(dynamic_cast<VariableNode *>(substexpr) != nullptr);
sebastien's avatar
sebastien committed
250 251 252 253 254 255 256 257 258 259 260
          subst_table[orig_expr] = dynamic_cast<VariableNode *>(substexpr);
        }
      else
        substexpr = const_cast<VariableNode *>(it->second);

      lag--;
    }

  return dynamic_cast<VariableNode *>(substexpr);
}

sebastien's avatar
sebastien committed
261 262 263 264 265 266 267 268 269 270
VariableNode *
ExprNode::createExoLeadAuxiliaryVarForMyself(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const
{
  int n = maxExoLead();
  assert(n >= 1);

  subst_table_t::const_iterator it = subst_table.find(this);
  if (it != subst_table.end())
    return const_cast<VariableNode *>(it->second);

271
  expr_t substexpr = decreaseLeadsLags(n);
sebastien's avatar
sebastien committed
272 273 274 275
  int lag = n-1;

  // Each iteration tries to create an auxvar such that auxvar(+1)=expr(-lag)
  // At the beginning (resp. end) of each iteration, substexpr is an expression (possibly an auxvar) equivalent to expr(-lag-1) (resp. expr(-lag))
276
  while (lag >= 0)
sebastien's avatar
sebastien committed
277
    {
278
      expr_t orig_expr = decreaseLeadsLags(lag);
sebastien's avatar
sebastien committed
279 280 281
      it = subst_table.find(orig_expr);
      if (it == subst_table.end())
        {
282
          int symb_id = datatree.symbol_table.addExoLeadAuxiliaryVar(orig_expr->idx, substexpr);
sebastien's avatar
sebastien committed
283 284
          neweqs.push_back(dynamic_cast<BinaryOpNode *>(datatree.AddEqual(datatree.AddVariable(symb_id, 0), substexpr)));
          substexpr = datatree.AddVariable(symb_id, +1);
285
          assert(dynamic_cast<VariableNode *>(substexpr) != nullptr);
sebastien's avatar
sebastien committed
286 287 288 289 290 291 292 293 294 295 296
          subst_table[orig_expr] = dynamic_cast<VariableNode *>(substexpr);
        }
      else
        substexpr = const_cast<VariableNode *>(it->second);

      lag--;
    }

  return dynamic_cast<VariableNode *>(substexpr);
}

297 298 299 300 301 302 303 304 305 306 307 308
bool
ExprNode::isNumConstNodeEqualTo(double value) const
{
  return false;
}

bool
ExprNode::isVariableNodeEqualTo(SymbolType type_arg, int variable_id, int lag_arg) const
{
  return false;
}

309 310 311 312 313
void
ExprNode::getEndosAndMaxLags(map<string, int> &model_endos_and_lags) const
{
}

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
void
ExprNode::fillErrorCorrectionRow(int eqn,
                                 const vector<int> &nontarget_lhs,
                                 const vector<int> &target_lhs,
                                 map<tuple<int, int, int>, expr_t> &A0,
                                 map<tuple<int, int, int>, expr_t> &A0star) const
{
  vector<pair<expr_t, int>> terms;
  decomposeAdditiveTerms(terms, 1);

  for (const auto &it : terms)
    {
      pair<int, vector<tuple<int, int, int, double>>> m;
      try
        {
          m = it.first->matchParamTimesLinearCombinationOfVariables();
          for (auto &t : m.second)
            get<3>(t) *= it.second; // Update sign of constants
        }
      catch (MatchFailureException &e)
        {
          /* FIXME: we should not just skip them, but rather verify that they are
             autoregressive terms or residuals (probably by merging the two "fill" procedures) */
          continue;
        }

      // Helper function
      auto one_step_orig = [this](int symb_id) {
        return datatree.symbol_table.isAuxiliaryVariable(symb_id) ?
          datatree.symbol_table.getOrigSymbIdForDiffAuxVar(symb_id) : symb_id;
      };

      /* Verify that all variables belong to the error-correction term.
         FIXME: same remark as above about skipping terms. */
      bool not_ec = false;
      for (const auto &t : m.second)
        {
          int vid = one_step_orig(get<0>(t));
          not_ec = not_ec || (find(target_lhs.begin(), target_lhs.end(), vid) == target_lhs.end()
                              && find(nontarget_lhs.begin(), nontarget_lhs.end(), vid) == nontarget_lhs.end());
        }
      if (not_ec)
        continue;

      // Now fill the matrices
      for (const auto &t : m.second)
        {
          int var_id, lag, param_id;
          double constant;
          tie(var_id, lag, param_id, constant) = t;
          /*
          if (lag != -1)
            {
              cerr << "ERROR in trend component model: variables should appear with a lag of 1 in error correction term" << endl;
              exit(EXIT_FAILURE);
            }
          */
          int orig_vid = one_step_orig(var_id);
          int orig_lag = datatree.symbol_table.isAuxiliaryVariable(var_id) ? -datatree.symbol_table.getOrigLeadLagForDiffAuxVar(var_id) : lag;
          if (find(target_lhs.begin(), target_lhs.end(), orig_vid) == target_lhs.end())
            {
              // This an LHS variable, so fill A0
              if (constant != 1)
                {
                  cerr << "ERROR in trend component model: LHS variable should not appear with a multiplicative constant in error correction term" << endl;
                  exit(EXIT_FAILURE);
                }
              if (param_id != -1)
                {
                  cerr << "ERROR in trend component model: spurious parameter in error correction term" << endl;
                  exit(EXIT_FAILURE);
                }
              int colidx = static_cast<int>(distance(nontarget_lhs.begin(), find(nontarget_lhs.begin(), nontarget_lhs.end(), orig_vid)));
              if (A0.find({eqn, -orig_lag, colidx}) != A0.end())
                {
                  cerr << "ExprNode::fillErrorCorrection: Error filling A0 matrix: "
                       << "lag/symb_id encountered more than once in equation" << endl;
                  exit(EXIT_FAILURE);
                }
              A0[{eqn, -orig_lag, colidx}] = datatree.AddVariable(m.first);
            }
          else
            {
              // This is a target, so fill A0star
              int colidx = static_cast<int>(distance(target_lhs.begin(), find(target_lhs.begin(), target_lhs.end(), orig_vid)));
              expr_t e = datatree.AddTimes(datatree.AddVariable(m.first), datatree.AddPossiblyNegativeConstant(-constant));
              if (param_id != -1)
                e = datatree.AddTimes(e, datatree.AddVariable(param_id));
              auto coor = make_tuple(eqn, -orig_lag, colidx);
              if (A0star.find(coor) == A0star.end())
                A0star[coor] = e;
              else
                A0star[coor] = datatree.AddPlus(e, A0star[coor]);
            }
        }
    }
}

412
NumConstNode::NumConstNode(DataTree &datatree_arg, int idx_arg, int id_arg) :
413 414
  ExprNode{datatree_arg, idx_arg},
  id{id_arg}
415
{
sebastien's avatar
sebastien committed
416
}
417

418 419
int
NumConstNode::countDiffs() const
420
{
421
  return 0;
422 423
}

sebastien's avatar
sebastien committed
424 425 426 427
void
NumConstNode::prepareForDerivation()
{
  preparedForDerivation = true;
428 429 430
  // All derivatives are null, so non_null_derivatives is left empty
}

431
expr_t
432
NumConstNode::computeDerivative(int deriv_id)
433 434 435 436
{
  return datatree.Zero;
}

437
void
438
NumConstNode::collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const
439
{
440
  auto it = temporary_terms.find(const_cast<NumConstNode *>(this));
441 442 443
  if (it != temporary_terms.end())
    temporary_terms_inuse.insert(idx);
}
444

445 446
void
NumConstNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
447
                          const temporary_terms_t &temporary_terms,
Houtan Bastani's avatar
Houtan Bastani committed
448
                          const temporary_terms_idxs_t &temporary_terms_idxs,
449
                          const deriv_node_temp_terms_t &tef_terms) const
450
{
451
  if (!checkIfTemporaryTermThenWrite(output, output_type, temporary_terms, temporary_terms_idxs))
452 453
    output << datatree.num_constants.get(id);
}
454

Houtan Bastani's avatar
Houtan Bastani committed
455 456 457
void
NumConstNode::writeJsonAST(ostream &output) const
{
458
  output << R"({"node_type" : "NumConstNode", "value" : )";
459 460 461 462
  double testval = datatree.num_constants.getDouble(id);
  if (testval < 1.0 && testval > -1.0 && testval != 0.0)
    output << "0";
  output << datatree.num_constants.get(id) << "}";
Houtan Bastani's avatar
Houtan Bastani committed
463 464
}

465
void
466
NumConstNode::writeJsonOutput(ostream &output,
467
                              const temporary_terms_t &temporary_terms,
468
                              const deriv_node_temp_terms_t &tef_terms,
469
                              const bool isdynamic) const
470 471 472 473
{
  output << datatree.num_constants.get(id);
}

474 475 476 477 478 479
bool
NumConstNode::containsExternalFunction() const
{
  return false;
}

480
double
481
NumConstNode::eval(const eval_context_t &eval_context) const noexcept(false)
482
{
483
  return (datatree.num_constants.getDouble(id));
484 485 486
}

void
487 488 489
NumConstNode::compile(ostream &CompileCode, unsigned int &instruction_number,
                      bool lhs_rhs, const temporary_terms_t &temporary_terms,
                      const map_idx_t &map_idx, bool dynamic, bool steady_dynamic,
490
                      const deriv_node_temp_terms_t &tef_terms) const
491 492
{
  FLDC_ fldc(datatree.num_constants.getDouble(id));
493
  fldc.write(CompileCode, instruction_number);
494
}
495

496 497 498
void
NumConstNode::collectVARLHSVariable(set<expr_t> &result) const
{
499 500
  cerr << "ERROR: you can only have variables or unary ops on LHS of VAR" << endl;
  exit(EXIT_FAILURE);
501 502
}

503
void
504
NumConstNode::collectDynamicVariables(SymbolType type_arg, set<pair<int, int>> &result) const
505 506 507
{
}

508 509
pair<int, expr_t>
NumConstNode::normalizeEquation(int var_endo, vector<tuple<int, expr_t, expr_t>> &List_of_Op_RHS) const
510
{
511
  /* return the numercial constant */
512
  return { 0, datatree.AddNonNegativeConstant(datatree.num_constants.get(id)) };
513
}
ferhat's avatar
ferhat committed
514

515 516
expr_t
NumConstNode::getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables)
ferhat's avatar
ferhat committed
517
{
ferhat's avatar
ferhat committed
518
  return datatree.Zero;
ferhat's avatar
ferhat committed
519 520
}

521
expr_t
sebastien's avatar
sebastien committed
522
NumConstNode::toStatic(DataTree &static_datatree) const
523
{
524
  return static_datatree.AddNonNegativeConstant(datatree.num_constants.get(id));
525
}
sebastien's avatar
sebastien committed
526

527 528 529 530 531
void
NumConstNode::computeXrefs(EquationInfo &ei) const
{
}

532
expr_t
533
NumConstNode::clone(DataTree &datatree) const
534
{
535
  return datatree.AddNonNegativeConstant(datatree.num_constants.get(id));
536 537
}

sebastien's avatar
sebastien committed
538 539 540 541 542
int
NumConstNode::maxEndoLead() const
{
  return 0;
}
ferhat's avatar
ferhat committed
543

sebastien's avatar
sebastien committed
544 545 546 547 548 549
int
NumConstNode::maxExoLead() const
{
  return 0;
}

550 551 552 553 554 555 556 557 558 559 560 561
int
NumConstNode::maxEndoLag() const
{
  return 0;
}

int
NumConstNode::maxExoLag() const
{
  return 0;
}

562 563 564 565 566 567
int
NumConstNode::maxLead() const
{
  return 0;
}

568 569 570 571 572 573
int
NumConstNode::maxLag() const
{
  return 0;
}

574 575 576 577 578 579
int
NumConstNode::maxLagWithDiffsExpanded() const
{
  return 0;
}

Houtan Bastani's avatar
Houtan Bastani committed
580 581 582 583 584 585
expr_t
NumConstNode::undiff() const
{
  return const_cast<NumConstNode *>(this);
}

586 587 588 589 590 591
int
NumConstNode::VarMinLag() const
{
  return 1;
}

Houtan Bastani's avatar
Houtan Bastani committed
592 593
int
NumConstNode::VarMaxLag(DataTree &static_datatree, set<expr_t> &static_lhs) const
594
{
Houtan Bastani's avatar
Houtan Bastani committed
595
  return 0;
596 597
}

Houtan Bastani's avatar
Houtan Bastani committed
598
int
599
NumConstNode::PacMaxLag(int lhs_symb_id) const
Houtan Bastani's avatar
Houtan Bastani committed
600 601 602 603
{
  return 0;
}

604 605 606 607 608 609
int
NumConstNode::getPacTargetSymbId(int lhs_symb_id, int undiff_lhs_symb_id) const
{
  return -1;
}

610
expr_t
sebastien's avatar
sebastien committed
611 612 613 614 615
NumConstNode::decreaseLeadsLags(int n) const
{
  return const_cast<NumConstNode *>(this);
}

616
expr_t
sebastien's avatar
sebastien committed
617
NumConstNode::decreaseLeadsLagsPredeterminedVariables() const
618
{
sebastien's avatar
sebastien committed
619
  return const_cast<NumConstNode *>(this);
620 621
}

622
expr_t
623
NumConstNode::substituteEndoLeadGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const
sebastien's avatar
sebastien committed
624 625 626 627
{
  return const_cast<NumConstNode *>(this);
}

628
expr_t
629 630 631 632 633
NumConstNode::substituteEndoLagGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const
{
  return const_cast<NumConstNode *>(this);
}

634
expr_t
635
NumConstNode::substituteExoLead(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const
sebastien's avatar
sebastien committed
636 637 638 639
{
  return const_cast<NumConstNode *>(this);
}

640
expr_t
sebastien's avatar
sebastien committed
641
NumConstNode::substituteExoLag(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const
sebastien's avatar
sebastien committed
642 643 644 645
{
  return const_cast<NumConstNode *>(this);
}

646
expr_t
647 648 649 650 651
NumConstNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool partial_information_model) const
{
  return const_cast<NumConstNode *>(this);
}

652
expr_t
653 654 655 656 657
NumConstNode::substituteAdl() const
{
  return const_cast<NumConstNode *>(this);
}

658 659 660 661 662 663
expr_t
NumConstNode::substituteVarExpectation(const map<string, expr_t> &subst_table) const
{
  return const_cast<NumConstNode *>(this);
}

664 665 666 667 668
void
NumConstNode::findDiffNodes(DataTree &static_datatree, diff_table_t &diff_table) const
{
}

669 670 671 672 673
void
NumConstNode::findUnaryOpNodesForAuxVarCreation(DataTree &static_datatree, diff_table_t &nodes) const
{
}

674
int
675
NumConstNode::findTargetVariable(int lhs_symb_id) const
676 677 678 679
{
  return -1;
}

680
expr_t
Houtan Bastani's avatar
Houtan Bastani committed
681
NumConstNode::substituteDiff(DataTree &static_datatree, diff_table_t &diff_table, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const
682 683 684 685
{
  return const_cast<NumConstNode *>(this);
}

686 687 688 689 690 691
expr_t
NumConstNode::substituteUnaryOpNodes(DataTree &static_datatree, diff_table_t &nodes, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const
{
  return const_cast<NumConstNode *>(this);
}

692
expr_t
693
NumConstNode::substitutePacExpectation(const string & name, expr_t subexpr)
694 695 696 697
{
  return const_cast<NumConstNode *>(this);
}

698
expr_t
699
NumConstNode::differentiateForwardVars(const vector<string> &subset, subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs) const
700 701 702 703
{
  return const_cast<NumConstNode *>(this);
}

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
bool
NumConstNode::isNumConstNodeEqualTo(double value) const
{
  if (datatree.num_constants.getDouble(id) == value)
    return true;
  else
    return false;
}

bool
NumConstNode::isVariableNodeEqualTo(SymbolType type_arg, int variable_id, int lag_arg) const
{
  return false;
}

719 720 721 722 723
void
NumConstNode::getEndosAndMaxLags(map<string, int> &model_endos_and_lags) const
{
}

724
bool
725
NumConstNode::containsPacExpectation(const string &pac_model_name) const
726 727 728 729
{
  return false;
}

730
bool
731
NumConstNode::containsEndogenous() const
732 733 734 735
{
  return false;
}

736 737 738 739 740 741
bool
NumConstNode::containsExogenous() const
{
  return false;
}

742 743 744 745 746 747 748
expr_t
NumConstNode::replaceTrendVar() const
{
  return const_cast<NumConstNode *>(this);
}

expr_t
749
NumConstNode::detrend(int symb_id, bool log_trend, expr_t trend) const
750 751 752 753 754 755 756 757 758 759
{
  return const_cast<NumConstNode *>(this);
}

expr_t
NumConstNode::removeTrendLeadLag(map<int, expr_t> trend_symbols_map) const
{
  return const_cast<NumConstNode *>(this);
}

760 761 762 763 764 765
bool
NumConstNode::isInStaticForm() const
{
  return true;
}

766 767 768 769 770 771
bool
NumConstNode::isParamTimesEndogExpr() const
{
  return false;
}

772 773 774 775 776 777
bool
NumConstNode::isVarModelReferenced(const string &model_info_name) const
{
  return false;
}

778 779 780 781 782 783
expr_t
NumConstNode::substituteStaticAuxiliaryVariable() const
{
  return const_cast<NumConstNode *>(this);
}

784
void
785
NumConstNode::findConstantEquations(map<VariableNode *, NumConstNode *> &table) const
786 787 788 789 790
{
  return;
}

expr_t
791
NumConstNode::replaceVarsInEquation(map<VariableNode *, NumConstNode *> &table) const
792 793 794 795
{
  return const_cast<NumConstNode *>(this);
}

796
VariableNode::VariableNode(DataTree &datatree_arg, int idx_arg, int symb_id_arg, int lag_arg) :
797 798 799
  ExprNode{datatree_arg, idx_arg},
  symb_id{symb_id_arg},
  lag{lag_arg}
Houtan Bastani's avatar
Houtan Bastani committed
800 801
{
  // It makes sense to allow a lead/lag on parameters: during steady state calibration, endogenous and parameters can be swapped
802 803
  assert(get_type() != SymbolType::externalFunction
         && (lag == 0 || (get_type() != SymbolType::modelLocalVariable && get_type() != SymbolType::modFileLocalVariable)));
Houtan Bastani's avatar
Houtan Bastani committed
804 805
}

sebastien's avatar
sebastien committed
806 807 808 809 810
void
VariableNode::prepareForDerivation()
{
  if (preparedForDerivation)
    return;
811

sebastien's avatar
sebastien committed
812
  preparedForDerivation = true;
sebastien's avatar
sebastien committed
813

814
  // Fill in non_null_derivatives
815
  switch (get_type())
816
    {
817 818 819 820 821 822
    case SymbolType::endogenous:
    case SymbolType::exogenous:
    case SymbolType::exogenousDet:
    case SymbolType::parameter:
    case SymbolType::trend:
    case SymbolType::logTrend:
sebastien's avatar
sebastien committed
823
      // For a variable or a parameter, the only non-null derivative is with respect to itself
824
      non_null_derivatives.insert(datatree.getDerivID(symb_id, lag));
825
      break;
826
    case SymbolType::modelLocalVariable:
827
      datatree.getLocalVariable(symb_id)->prepareForDerivation();
828
      // Non null derivatives are those of the value of the local parameter
829
      non_null_derivatives = datatree.getLocalVariable(symb_id)->non_null_derivatives;
830
      break;
831 832 833
    case SymbolType::modFileLocalVariable:
    case SymbolType::statementDeclaredVariable:
    case SymbolType::unusedEndogenous:
834 835
      // Such a variable is never derived
      break;
836 837
    case SymbolType::externalFunction:
    case SymbolType::endogenousVAR:
838
    case SymbolType::epilogue:
sebastien's avatar
sebastien committed
839
      cerr << "VariableNode::prepareForDerivation: impossible case" << endl;
840
      exit(EXIT_FAILURE);
841 842 843
    }
}

844
expr_t
sebastien's avatar
sebastien committed
845
VariableNode::computeDerivative(int deriv_id)
846
{
847
  switch (get_type())
848
    {
849 850 851 852 853 854
    case SymbolType::endogenous:
    case SymbolType::exogenous:
    case SymbolType::exogenousDet:
    case SymbolType::parameter:
    case SymbolType::trend:
    case SymbolType::logTrend:
sebastien's avatar
sebastien committed
855
      if (deriv_id == datatree.getDerivID(symb_id, lag))
856 857 858
        return datatree.One;
      else
        return datatree.Zero;
859
    case SymbolType::modelLocalVariable:
860
      return datatree.getLocalVariable(symb_id)->getDerivative(deriv_id);
861
    case SymbolType::modFileLocalVariable:
862
      cerr << "ModFileLocalVariable is not derivable" << endl;
863
      exit(EXIT_FAILURE);
864
    case SymbolType::statementDeclaredVariable:
865 866
      cerr << "eStatementDeclaredVariable is not derivable" << endl;
      exit(EXIT_FAILURE);
867
    case SymbolType::unusedEndogenous:
868 869
      cerr << "eUnusedEndogenous is not derivable" << endl;
      exit(EXIT_FAILURE);
870 871
    case SymbolType::externalFunction:
    case SymbolType::endogenousVAR:
872
    case SymbolType::epilogue:
Houtan Bastani's avatar
Houtan Bastani committed
873
      cerr << "VariableNode::computeDerivative: Impossible case!" << endl;
874
      exit(EXIT_FAILURE);
875
    }
sebastien's avatar
sebastien committed
876
  // Suppress GCC warning
877
  exit(EXIT_FAILURE);
878 879
}

880
void
881
VariableNode::collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const
882
{
883
  auto it = temporary_terms.find(const_cast<VariableNode *>(this));
884 885
  if (it != temporary_terms.end())
    temporary_terms_inuse.insert(idx);
886
  if (get_type() == SymbolType::modelLocalVariable)
887
    datatree.getLocalVariable(symb_id)->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block);
888
}
889

890 891 892 893 894 895
bool
VariableNode::containsExternalFunction() const
{
  return false;
}

Houtan Bastani's avatar
Houtan Bastani committed
896 897 898
void
VariableNode::writeJsonAST(ostream &output) const
{
899 900
  output << R"({"node_type" : "VariableNode", )"
         << R"("name" : ")" << datatree.symbol_table.getName(symb_id) << R"(", "type" : ")";
901
  switch (get_type())
Houtan Bastani's avatar
Houtan Bastani committed
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
    {
    case SymbolType::endogenous:
      output << "endogenous";
      break;
    case SymbolType::exogenous:
      output << "exogenous";
      break;
    case SymbolType::exogenousDet:
      output << "exogenousDet";
      break;
    case SymbolType::parameter:
      output << "parameter";
      break;
    case SymbolType::modelLocalVariable:
      output << "modelLocalVariable";
      break;
    case SymbolType::modFileLocalVariable:
      output << "modFileLocalVariable";
      break;
    case SymbolType::externalFunction:
      output << "externalFunction";
      break;
    case SymbolType::trend:
      output << "trend";
      break;
    case SymbolType::statementDeclaredVariable:
      output << "statementDeclaredVariable";
      break;
    case SymbolType::logTrend:
      output << "logTrend:";
      break;
    case SymbolType::unusedEndogenous:
      output << "unusedEndogenous";
      break;
    case SymbolType::endogenousVAR:
      output << "endogenousVAR";
      break;
939 940 941
    case SymbolType::epilogue:
      output << "epilogue";
      break;
Houtan Bastani's avatar
Houtan Bastani committed
942
    }
943
  output << R"(", "lag" : )" << lag << "}";
Houtan Bastani's avatar
Houtan Bastani committed
944 945
}

946
void
947
VariableNode::writeJsonOutput(ostream &output,
948
                              const temporary_terms_t &temporary_terms,
949
                              const deriv_node_temp_terms_t &tef_terms,
950
                              const bool isdynamic) const
951
{
952
  auto it = temporary_terms.find(const_cast<VariableNode *>(this));
953 954 955 956 957 958
  if (it != temporary_terms.end())
    {
      output << "T" << idx;
      return;
    }

959
  output << datatree.symbol_table.getName(symb_id);
960
  if (isdynamic && lag != 0)
961 962 963
    output << "(" << lag << ")";
}

964 965
void
VariableNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
966
                          const temporary_terms_t &temporary_terms,
Houtan Bastani's avatar
Houtan Bastani committed
967
                          const temporary_terms_idxs_t &temporary_terms_idxs,
968
                          const deriv_node_temp_terms_t &tef_terms) const
969
{
970
  auto type = get_type();
971 972
  if (checkIfTemporaryTermThenWrite(output, output_type, temporary_terms, temporary_terms_idxs))
    return;
973

974
  if (isLatexOutput(output_type))
975
    {
976
      if (output_type == ExprNodeOutputType::latexDynamicSteadyStateOperator)
977
        output << R"(\bar)";
978
      output << "{" << datatree.symbol_table.getTeXName(symb_id);
979
      if (output_type == ExprNodeOutputType::latexDynamicModel
980
          && (type == SymbolType::endogenous || type == SymbolType::exogenous || type == SymbolType::exogenousDet || type == SymbolType::modelLocalVariable || type == SymbolType::trend || type == SymbolType::logTrend))
981 982 983 984 985 986 987 988
        {
          output << "_{t";
          if (lag != 0)
            {
              if (lag > 0)
                output << "+";
              output << lag;
            }
989
          output << "}";
990
        }
991
      output << "}";
992 993
      return;
    }
994

995 996 997 998
  int i;
  int tsid = datatree.symbol_table.getTypeSpecificID(symb_id);
  switch (type)
    {
999
    case SymbolType::parameter:
1000
      if (output_type == ExprNodeOutputType::matlabOutsideModel)
1001 1002 1003 1004
        output << "M_.params" << "(" << tsid + 1 << ")";
      else
        output << "params" << LEFT_ARRAY_SUBSCRIPT(output_type) << tsid + ARRAY_SUBSCRIPT_OFFSET(output_type) << RIGHT_ARRAY_SUBSCRIPT(output_type);
      break;
ferhat's avatar
ferhat committed
1005

1006
    case SymbolType::modelLocalVariable:
1007 1008 1009
      if (output_type == ExprNodeOutputType::matlabDynamicModelSparse || output_type == ExprNodeOutputType::matlabStaticModelSparse
          || output_type == ExprNodeOutputType::matlabDynamicSteadyStateOperator || output_type == ExprNodeOutputType::matlabDynamicSparseSteadyStateOperator
          || output_type == ExprNodeOutputType::CDynamicSteadyStateOperator)
1010 1011
        {
          output << "(";
1012
          datatree.getLocalVariable(symb_id)->writeOutput(output, output_type, temporary_terms, temporary_terms_idxs, tef_terms);
1013 1014 1015
          output << ")";
        }
      else
Sébastien Villemot's avatar
Sébastien Villemot committed
1016 1017
        /* We append underscores to avoid name clashes with "g1" or "oo_".
           But we probably never arrive here because MLV are temporary terms… */
1018
        output << datatree.symbol_table.getName(symb_id) << "__";
1019
      break;
ferhat's avatar
ferhat committed
1020

1021
    case SymbolType::modFileLocalVariable:
1022 1023 1024
      output << datatree.symbol_table.getName(symb_id);
      break;

1025
    case SymbolType::endogenous:
1026 1027
      switch (output_type)
        {
1028 1029 1030
        case ExprNodeOutputType::juliaDynamicModel:
        case ExprNodeOutputType::matlabDynamicModel:
        case ExprNodeOutputType::CDynamicModel:
1031 1032 1033
          i = datatree.getDynJacobianCol(datatree.getDerivID(symb_id, lag)) + ARRAY_SUBSCRIPT_OFFSET(output_type);
          output <<  "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << i << RIGHT_ARRAY_SUBSCRIPT(output_type);
          break;
1034 1035 1036 1037
        case ExprNodeOutputType::CStaticModel:
        case ExprNodeOutputType::juliaStaticModel:
        case ExprNodeOutputType::matlabStaticModel:
        case ExprNodeOutputType::matlabStaticModelSparse:
1038 1039 1040
          i = tsid + ARRAY_SUBSCRIPT_OFFSET(output_type);
          output <<  "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << i << RIGHT_ARRAY_SUBSCRIPT(output_type);
          break;
1041
        case ExprNodeOutputType::matlabDynamicModelSparse:
1042 1043 1044 1045 1046 1047 1048 1049
          i = tsid + ARRAY_SUBSCRIPT_OFFSET(output_type);
          if (lag > 0)
            output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << "it_+" << lag << ", " << i << RIGHT_ARRAY_SUBSCRIPT(output_type);
          else if (lag < 0)
            output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << "it_" << lag << ", " << i << RIGHT_ARRAY_SUBSCRIPT(output_type);
          else
            output << "y" << LEFT_ARRAY_SUBSCRIPT(output_type) << "it_, " << i << RIGHT_ARRAY_SUBSCRIPT(output_type);
          break;
1050
        case ExprNodeOutputType::matlabOutsideModel:
1051 1052
          output << "oo_.steady_state(" << tsid + 1 << ")";
          break;
1053 1054 1055
        case ExprNodeOutputType::juliaDynamicSteadyStateOperator:
        case ExprNodeOutputType::matlabDynamicSteadyStateOperator:
        case ExprNodeOutputType::matlabDynamicSparseSteadyStateOperator:
Houtan Bastani's avatar
Houtan Bastani committed
1056
          output << "steady_state" << LEFT_ARRAY_SUBSCRIPT(output_type) << tsid + 1 << RIGHT_ARRAY_SUBSCRIPT(output_type);
1057
          break;
1058
        case ExprNodeOutputType::CDynamicSteadyStateOperator:
1059 1060
          output << "steady_state[" << tsid << "]";
          break;
1061 1062
        case ExprNodeOutputType::juliaSteadyStateFile:
        case ExprNodeOutputType::steadyStateFile:
Houtan Bastani's avatar
Houtan Bastani committed
1063
          output << "ys_" << LEFT_ARRAY_SUBSCRIPT(output_type) << tsid + 1 << RIGHT_ARRAY_SUBSCRIPT(output_type);
1064
          break;
1065
        case ExprNodeOutputType::matlabDseries:
1066 1067 1068 1069
          output << "ds." << datatree.symbol_table.getName(symb_id);
          if (lag != 0)
            output << LEFT_ARRAY_SUBSCRIPT(output_type) << lag << RIGHT_ARRAY_SUBSCRIPT(output_type);
          break;
1070
        case ExprNodeOutputType::epilogueFile:
Houtan Bastani's avatar
Houtan Bastani committed
1071
          output << "dseries__." << datatree.symbol_table.getName(symb_id);
1072 1073 1074 1075
          output << LEFT_ARRAY_SUBSCRIPT(output_type) << "t";
          if (lag != 0)
            output << lag;
          output << RIGHT_ARRAY_SUBSCRIPT(output_type);
Houtan Bastani's avatar
Houtan Bastani committed
1076
          break;
1077
        default:
1078 1079
          cerr << "VariableNode::writeOutput: should not reach this point" << endl;
          exit(EXIT_FAILURE);
1080 1081
        }
      break;
ferhat's avatar
ferhat committed
1082

1083
    case SymbolType::exogenous:
1084 1085 1086
      i = tsid + ARRAY_SUBSCRIPT_OFFSET(output_type);
      switch (output_type)
        {
1087 1088 1089
        case ExprNodeOutputType::juliaDynamicModel:
        case ExprNodeOutputType::matlabDynamicModel:
        case ExprNodeOutputType::matlabDynamicModelSparse:
1090
          if (lag > 0)
Houtan Bastani's avatar
Houtan Bastani committed
1091 1092
            output <<  "x" << LEFT_ARRAY_SUBSCRIPT(output_type) << "it_+" << lag << ", " << i
                   << RIGHT_ARRAY_SUBSCRIPT(output_type);
1093
          else if (lag < 0)
Houtan Bastani's avatar
Houtan Bastani committed
1094 1095
            output <<  "x" << LEFT_ARRAY_SUBSCRIPT(output_type) << "it_" << lag << ", " << i
                   << RIGHT_ARRAY_SUBSCRIPT(output_type);
1096
          else
Houtan Bastani's avatar
Houtan Bastani committed
1097 1098
            output <<  "x" << LEFT_ARRAY_SUBSCRIPT(output_type) << "it_, " << i
                   << RIGHT_ARRAY_SUBSCRIPT(output_type);
sebastien's avatar