ModelEquationBlock.cc 16.8 KB
Newer Older
1
/*
2
 * Copyright © 2010-2021 Dynare Team
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 *
 * 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 <cassert>
#include <algorithm>

Houtan Bastani's avatar
Houtan Bastani committed
23
#include "ModelEquationBlock.hh"
24

25
26
27
28
SteadyStateModel::SteadyStateModel(SymbolTable &symbol_table_arg,
                                   NumericalConstants &num_constants_arg,
                                   ExternalFunctionsTable &external_functions_table_arg,
                                   const StaticModel &static_model_arg) :
29
30
  DataTree{symbol_table_arg, num_constants_arg, external_functions_table_arg},
  static_model{static_model_arg}
31
32
33
{
}

34
SteadyStateModel::SteadyStateModel(const SteadyStateModel &m) :
Sébastien Villemot's avatar
Sébastien Villemot committed
35
36
  DataTree{m},
  static_model{m.static_model}
37
38
{
  for (const auto &it : m.def_table)
Sébastien Villemot's avatar
Sébastien Villemot committed
39
    def_table.emplace_back(it.first, it.second->clone(*this));
40
41
42
43
44
45
46
47
48
49
50
}

SteadyStateModel &
SteadyStateModel::operator=(const SteadyStateModel &m)
{
  DataTree::operator=(m);

  assert(&static_model == &m.static_model);

  def_table.clear();
  for (const auto &it : m.def_table)
Sébastien Villemot's avatar
Sébastien Villemot committed
51
    def_table.emplace_back(it.first, it.second->clone(*this));
52
53
54
55

  return *this;
}

56
void
57
SteadyStateModel::addDefinition(int symb_id, expr_t expr)
58
{
59
60
  AddVariable(symb_id); // Create the variable node to be used in write method

61
62
63
  assert(symbol_table.getType(symb_id) == SymbolType::endogenous
         || symbol_table.getType(symb_id) == SymbolType::modFileLocalVariable
         || symbol_table.getType(symb_id) == SymbolType::parameter);
64
65

  // Add the variable
66
67
  vector<int> v;
  v.push_back(symb_id);
68
  def_table.emplace_back(v, expr);
69
70
71
72
73
}

void
SteadyStateModel::addMultipleDefinitions(const vector<int> &symb_ids, expr_t expr)
{
74
  for (int symb_id : symb_ids)
75
    {
76
      AddVariable(symb_id); // Create the variable nodes to be used in write method
77
78
79
      assert(symbol_table.getType(symb_id) == SymbolType::endogenous
             || symbol_table.getType(symb_id) == SymbolType::modFileLocalVariable
             || symbol_table.getType(symb_id) == SymbolType::parameter);
80
    }
81
  def_table.emplace_back(symb_ids, expr);
82
83
84
}

void
85
SteadyStateModel::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) const
86
{
87
  if (def_table.size() == 0)
88
89
    return;

90
  mod_file_struct.steady_state_model_present = true;
91
92
  vector<int> so_far_defined;

Sébastien Villemot's avatar
Sébastien Villemot committed
93
  for (const auto &i : def_table)
94
    {
95
      const vector<int> &symb_ids = i.first;
96
97

      // Check that symbols are not already defined
98
99
      for (int symb_id : symb_ids)
        if (find(so_far_defined.begin(), so_far_defined.end(), symb_id)
100
            != so_far_defined.end())
101
          warnings << "WARNING: in the 'steady_state_model' block, variable '" << symbol_table.getName(symb_id) << "' is declared twice" << endl;
102

103
      // Check that expression has no undefined symbol
104
      if (!mod_file_struct.ramsey_model_present)
105
        {
106
          set<int> used_symbols;
107
          const expr_t &expr = i.second;
108
109
          expr->collectVariables(SymbolType::endogenous, used_symbols);
          expr->collectVariables(SymbolType::modFileLocalVariable, used_symbols);
110
111
          for (int used_symbol : used_symbols)
            if (find(so_far_defined.begin(), so_far_defined.end(), used_symbol)
112
                == so_far_defined.end())
113
              {
114
                cerr << "ERROR: in the 'steady_state_model' block, variable '" << symbol_table.getName(used_symbol)
115
                     << "' is undefined in the declaration of variable '" << symbol_table.getName(symb_ids[0]) << "'" << endl;
116
117
118
                exit(EXIT_FAILURE);
              }
        }
119
120

      copy(symb_ids.begin(), symb_ids.end(), back_inserter(so_far_defined));
121
    }
122

123
124
125
126
127
128
129
130
  /* Check that all original endogous are defined (except the instruments of a
     Ramsey model, since the steady_state_block should give the steady state
     *conditional* to those instruments) */
  set<int> should_be_defined = symbol_table.getOrigEndogenous();
  if (mod_file_struct.ramsey_policy_present || mod_file_struct.ramsey_model_present)
    for (const auto &s : mod_file_struct.instruments.getSymbols())
      should_be_defined.erase(symbol_table.getID(s));
  for (int v : should_be_defined)
131
    {
132
      if (find(so_far_defined.begin(), so_far_defined.end(), v)
133
          == so_far_defined.end())
134
        warnings << "WARNING: in the 'steady_state_model' block, variable '" << symbol_table.getName(v) << "' is not assigned a value" << endl;
135
    }
136
137
}

138
139
140
void
SteadyStateModel::writeLatexSteadyStateFile(const string &basename) const
{
141
  filesystem::create_directories(basename + "/latex");
142

143
  ofstream output, content_output;
144
145
  string filename = basename + "/latex/steady_state.tex";
  string content_filename = basename + "/latex/steady_state_content.tex";
146

147
  output.open(filename, ios::out | ios::binary);
148
149
150
151
152
153
  if (!output.is_open())
    {
      cerr << "ERROR: Can't open file " << filename << " for writing" << endl;
      exit(EXIT_FAILURE);
    }

154
  content_output.open(content_filename, ios::out | ios::binary);
155
156
157
158
159
160
161
162
163
164
165
166
167
168
  if (!content_output.is_open())
    {
      cerr << "ERROR: Can't open file " << content_filename << " for writing" << endl;
      exit(EXIT_FAILURE);
    }

  output << "\\documentclass[10pt,a4paper]{article}" << endl
         << "\\usepackage[landscape]{geometry}" << endl
         << "\\usepackage{fullpage}" << endl
         << "\\usepackage{amsfonts}" << endl
         << "\\usepackage{breqn}" << endl
         << "\\begin{document}" << endl
         << "\\footnotesize" << endl;

169
170
  for (const auto & [ids, value] : def_table)
    for (int id : ids)
171
172
173
      {
        content_output << "\\begin{dmath}" << endl
                       << symbol_table.getTeXName(id) << " = ";
174
        value->writeOutput(content_output, ExprNodeOutputType::latexStaticModel);
175
176
177
178
179
        content_output << endl << "\\end{dmath}" << endl;
      }

  static_model.writeLatexAuxVarRecursiveDefinitions(content_output);

180
  output << "\\include{steady_state_content.tex}" << endl
181
182
183
184
185
186
         << "\\end{document}" << endl;

  output.close();
  content_output.close();
}

187
void
Houtan Bastani's avatar
Houtan Bastani committed
188
SteadyStateModel::writeSteadyStateFile(const string &basename, bool ramsey_model, bool julia) const
189
{
190
  if (def_table.size() == 0)
191
192
    return;

193
  string filename = julia ? basename + "SteadyState2.jl" : packageDir(basename) + "/steadystate.m";
194
  ofstream output;
195
  output.open(filename, ios::out | ios::binary);
196
197
198
199
200
201
  if (!output.is_open())
    {
      cerr << "ERROR: Can't open file " << filename << " for writing" << endl;
      exit(EXIT_FAILURE);
    }

202
  ExprNodeOutputType output_type = (julia ? ExprNodeOutputType::juliaSteadyStateFile : ExprNodeOutputType::steadyStateFile);
Houtan Bastani's avatar
Houtan Bastani committed
203
204

  if (!julia)
205
    output << "function [ys_, params, info] = steadystate("
Houtan Bastani's avatar
Houtan Bastani committed
206
207
208
209
           << "ys_, exo_, params)" << endl
           << "% Steady state generated by Dynare preprocessor" << endl
           << "    info = 0;" << endl;
  else
210
211
212
213
214
    output << "module " << basename << "SteadyState2" << endl
           << "#" << endl
           << "# NB: this file was automatically generated by Dynare" << endl
           << "#     from " << basename << ".mod" << endl
           << "#" << endl
215
           << "export steady_state!" << endl << endl
216
217
           << "function steady_state!(ys_::Vector{Float64}, exo_::Vector{Float64}, "
           << "params::Vector{Float64})" << endl;
218

219
  for (const auto & [symb_ids, value] : def_table)
220
221
    {
      output << "    ";
222
223
224
225
      if (symb_ids.size() > 1)
        output << "[";
      for (size_t j = 0; j < symb_ids.size(); j++)
        {
226
          getVariable(symb_ids[j])->ExprNode::writeOutput(output, output_type);
227
228
229
230
231
232
233
          if (j < symb_ids.size()-1)
            output << ",";
        }
      if (symb_ids.size() > 1)
        output << "]";

      output << "=";
234
      value->writeOutput(output, output_type);
235
236
      output << ";" << endl;
    }
Houtan Bastani's avatar
Houtan Bastani committed
237
238
239
240
  if (!julia)
    output << "    % Auxiliary equations" << endl;
  else
    output << "    # Auxiliary equations" << endl;
241
  static_model.writeAuxVarRecursiveDefinitions(output, output_type);
Houtan Bastani's avatar
Houtan Bastani committed
242
243
244
245

  output << "end" << endl;
  if (julia)
    output << "end" << endl;
246
  output.close();
247
248
}

249
250
251
252
253
254
void
SteadyStateModel::writeJsonSteadyStateFile(ostream &output, bool transformComputingPass) const
{
  if (def_table.size() == 0)
    return;

255
  vector<pair<string, string>> eqtags;
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271

  output << "{\"steady_state_model\": [";

  for (size_t i = 0; i < def_table.size(); i++)
    {
      const vector<int> &symb_ids = def_table[i].first;
      if (i != 0)
        output << ",";
      output << "{\"lhs\": ";
      if (symb_ids.size() > 1)
        output << "[";
      for (size_t j = 0; j < symb_ids.size(); j++)
        {
          if (j != 0)
            output << ",";
          output << "\"";
272
          getVariable(symb_ids[j])->writeJsonOutput(output, {}, {}, false);
273
274
275
276
          output << "\"";
        }
      if (symb_ids.size() > 1)
        output << "]";
277
      output << R"(, "rhs":")";
278
      def_table[i].second->writeJsonOutput(output, {}, {}, false);
279
280
281
282
283
284
285
286
      output << "\"}" << endl;
    }

  if (transformComputingPass)
    static_model.writeJsonAuxVarRecursiveDefinitions(output);

  output << "]}";
}
Houtan Bastani's avatar
Houtan Bastani committed
287
288
289
290
291
292

Epilogue::Epilogue(SymbolTable &symbol_table_arg,
                   NumericalConstants &num_constants_arg,
                   ExternalFunctionsTable &external_functions_table_arg,
                   TrendComponentModelTable &trend_component_model_table_arg,
                   VarModelTable &var_model_table_arg) :
293
294
  DynamicModel{symbol_table_arg, num_constants_arg, external_functions_table_arg,
               trend_component_model_table_arg, var_model_table_arg}
Houtan Bastani's avatar
Houtan Bastani committed
295
296
297
{
}

298
Epilogue::Epilogue(const Epilogue &m) :
Sébastien Villemot's avatar
Sébastien Villemot committed
299
  DynamicModel{m}
300
{
301
302
  for (const auto &it : m.dynamic_def_table)
    dynamic_def_table.emplace_back(it.first, it.second->clone(*this));
303
304
305
306
307
308
309
}

Epilogue &
Epilogue::operator=(const Epilogue &m)
{
  DynamicModel::operator=(m);

310
311
312
  dynamic_def_table.clear();
  for (const auto &it : m.dynamic_def_table)
    dynamic_def_table.emplace_back(it.first, it.second->clone(*this));
313
314
315
316

  return *this;
}

Houtan Bastani's avatar
Houtan Bastani committed
317
void
318
Epilogue::addDefinition(int symb_id, expr_t expr)
Houtan Bastani's avatar
Houtan Bastani committed
319
{
320
  dynamic_def_table.emplace_back(symb_id, expr);
Houtan Bastani's avatar
Houtan Bastani committed
321
322
323
}

void
324
Epilogue::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings) const
Houtan Bastani's avatar
Houtan Bastani committed
325
{
326
  if (dynamic_def_table.size() == 0)
327
328
329
330
331
332
333
334
    {
      if (mod_file_struct.with_epilogue_option)
        {
          cerr << "ERROR: the 'with_epilogue' option cannot be specified when there is no 'epilogue' block" << endl;
          exit(EXIT_FAILURE);
        }
      return;
    }
Houtan Bastani's avatar
Houtan Bastani committed
335

336
  vector<int> so_far_defined;
Sébastien Villemot's avatar
Sébastien Villemot committed
337
  for (const auto &it : dynamic_def_table)
Houtan Bastani's avatar
Houtan Bastani committed
338
339
340
341
342
343
344
    if (find(so_far_defined.begin(), so_far_defined.end(), it.first) != so_far_defined.end())
      {
        cerr << "WARNING: in the 'epilogue' block, variable '" << it.first
             << "' is declared twice" << endl;
        exit(EXIT_FAILURE);
      }
    else
Houtan Bastani's avatar
Houtan Bastani committed
345
346
347
      so_far_defined.push_back(it.first);
}

348
349
350
351
352
353
354
void
Epilogue::toStatic()
{
  for (const auto & [symb_id, expr] : dynamic_def_table)
    static_def_table.emplace_back(make_pair(symb_id, expr->toStatic(*this)));
}

Houtan Bastani's avatar
Houtan Bastani committed
355
void
Sébastien Villemot's avatar
Sébastien Villemot committed
356
357
Epilogue::detrend(const map<int, expr_t> &trend_symbols_map,
                  const nonstationary_symbols_map_t &nonstationary_symbols_map)
Houtan Bastani's avatar
Houtan Bastani committed
358
359
{
  for (auto it = nonstationary_symbols_map.crbegin();
360
       it != nonstationary_symbols_map.crend(); ++it)
361
    for (auto & [symb_id, expr] : dynamic_def_table)
Houtan Bastani's avatar
Houtan Bastani committed
362
363
      {
        expr = expr->detrend(it->first, it->second.first, it->second.second);
364
        assert(expr);
Houtan Bastani's avatar
Houtan Bastani committed
365
366
      }

367
  for (auto & [symb_id, expr] : dynamic_def_table)
Houtan Bastani's avatar
Houtan Bastani committed
368
369
    {
      expr = expr->removeTrendLeadLag(trend_symbols_map);
370
      assert(expr);
Houtan Bastani's avatar
Houtan Bastani committed
371
372
    }

373
  for (auto & [symb_id, expr] : dynamic_def_table)
Houtan Bastani's avatar
Houtan Bastani committed
374
375
    {
      expr = expr->replaceTrendVar();
376
      assert(expr);
Houtan Bastani's avatar
Houtan Bastani committed
377
378
379
    }
}

Houtan Bastani's avatar
Houtan Bastani committed
380
381
382
void
Epilogue::writeEpilogueFile(const string &basename) const
{
383
  if (dynamic_def_table.empty())
Houtan Bastani's avatar
Houtan Bastani committed
384
385
    return;

386
387
  writeDynamicEpilogueFile(basename);
  writeStaticEpilogueFile(basename);
388
389
390
}

void
Sébastien Villemot's avatar
Sébastien Villemot committed
391
Epilogue::writeStaticEpilogueFile(const string &basename) const
392
{
393
  string filename = packageDir(basename) + "/epilogue_static.m";
Houtan Bastani's avatar
Houtan Bastani committed
394
395
396
397
398
399
400
401
  ofstream output;
  output.open(filename, ios::out | ios::binary);
  if (!output.is_open())
    {
      cerr << "ERROR: Can't open file " << filename << " for writing" << endl;
      exit(EXIT_FAILURE);
    }

402
403
404
405
406
407
408
  output << "function ds = epilogue_static(params, ds)" << endl
         << "% function ds = epilogue_static(params, ds)" << endl
         << "% Epilogue file generated by Dynare preprocessor" << endl;

  for (const auto & [symb_id, expr] : static_def_table)
    {
      // Rewrite external function TEF term for every equation as argument values could have been changed
409
      // in between two calls to the same function;
410
411
412
      deriv_node_temp_terms_t tef_terms;
      temporary_terms_t temporary_terms;
      temporary_terms_idxs_t temporary_terms_idxs;
413
      output << endl;
414
415
      if (expr->containsExternalFunction())
        expr->writeExternalFunctionOutput(output, ExprNodeOutputType::matlabDseries, temporary_terms, temporary_terms_idxs, tef_terms);
416
      output << "epilogue_static_tmp_term = ";
417
      expr->writeOutput(output, ExprNodeOutputType::matlabDseries, temporary_terms, temporary_terms_idxs, tef_terms);
418
419
420
421
422
423
      output << ";" << endl
             << "if isdseries(epilogue_static_tmp_term)" << endl
             << "    ds." << symbol_table.getName(symb_id) << " = epilogue_static_tmp_term;" << endl
             << "else" << endl
             << "    ds." << symbol_table.getName(symb_id) << " = dseries(ones(ds.nobs,1)*epilogue_static_tmp_term, ds.firstdate, '" << symbol_table.getName(symb_id) << "');" << endl
             << "end" << endl;
424
425
426
427
428
429
    }
  output << "end" << endl;
  output.close();
}

void
Sébastien Villemot's avatar
Sébastien Villemot committed
430
Epilogue::writeDynamicEpilogueFile(const string &basename) const
431
432
433
434
435
436
437
438
439
440
441
442
{
  string filename = packageDir(basename) + "/epilogue_dynamic.m";
  ofstream output;
  output.open(filename, ios::out | ios::binary);
  if (!output.is_open())
    {
      cerr << "ERROR: Can't open file " << filename << " for writing" << endl;
      exit(EXIT_FAILURE);
    }

  output << "function ds = epilogue_dynamic(params, ds)" << endl
         << "% function ds = epilogue_dynamic(params, ds)" << endl
443
         << "% Epilogue file generated by Dynare preprocessor" << endl << endl
444
         << "simul_end_date = lastdate(ds);" << endl;
Houtan Bastani's avatar
Houtan Bastani committed
445
446
447
448

  deriv_node_temp_terms_t tef_terms;
  temporary_terms_t temporary_terms;
  temporary_terms_idxs_t temporary_terms_idxs;
449
  for (const auto & [symb_id, expr] : dynamic_def_table)
Houtan Bastani's avatar
Houtan Bastani committed
450
    {
451
      int max_lag = expr->maxLagWithDiffsExpanded();
452
      set<int> used_symbols;
453
454
455
      expr->collectVariables(SymbolType::endogenous, used_symbols);
      expr->collectVariables(SymbolType::exogenous, used_symbols);
      expr->collectVariables(SymbolType::epilogue, used_symbols);
456

457
458
459
460
461
462
      output << endl
             << "if ~ds.exist('" << symbol_table.getName(symb_id) << "')" << endl
             << "    ds = [ds dseries(NaN(ds.nobs,1), ds.firstdate, '" << symbol_table.getName(symb_id)<< "')];" << endl
             << "end" << endl
             << "try" << endl
             << "    simul_begin_date = firstobservedperiod(ds{";
463
      for (auto it1 = used_symbols.begin(); it1 != used_symbols.end(); ++it1)
464
465
466
467
468
        {
          if (it1 != used_symbols.begin())
            output << ", ";
          output << "'" << symbol_table.getName(*it1) << "'";
        }
Houtan Bastani's avatar
Houtan Bastani committed
469
      output << "}) + " << max_lag << ";" << endl
470
             << "    from simul_begin_date to simul_end_date do "
471
             << "ds." << symbol_table.getName(symb_id) << "(t) = ";
472
      expr->writeOutput(output, ExprNodeOutputType::epilogueFile, temporary_terms, temporary_terms_idxs, tef_terms);
473
474
475
      output << ";" << endl
             << "catch" << endl
             << "end" << endl;
Houtan Bastani's avatar
Houtan Bastani committed
476
    }
Houtan Bastani's avatar
Houtan Bastani committed
477
  output << "end" << endl;
Houtan Bastani's avatar
Houtan Bastani committed
478
479
  output.close();
}
480
481
482
483

void
Epilogue::writeOutput(ostream &output) const
{
484
  if (dynamic_def_table.empty())
485
486
487
488
489
    {
      output << "M_.epilogue_names = {};" << endl
             << "M_.epilogue_var_list_ = {};" << endl;
      return;
    }
490
491

  int idx = 1;
492
493
  output << "M_.epilogue_names = cell(" << dynamic_def_table.size() << ",1);" << endl;
  for (const auto & [symb_id, expr] : dynamic_def_table)
494
495
    output << "M_.epilogue_names{" << idx++ << "} = '"
           << symbol_table.getName(symb_id) << "';" << endl;
496
497

  set<int> endogs;
498
  for (const auto & [symb_id, expr] : dynamic_def_table)
499
500
501
502
503
504
    expr->collectVariables(SymbolType::endogenous, endogs);

  SymbolList symbol_list;
  for (auto symb_id : endogs)
    symbol_list.addSymbol(symbol_table.getName(symb_id));
  symbol_list.writeOutput("M_.epilogue_var_list_", output);
505
}