ModelEquationBlock.cc 13 KB
Newer Older
1
/*
2
 * Copyright © 2010-2019 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
35
36
37
38
SteadyStateModel::SteadyStateModel(const SteadyStateModel &m) :
  DataTree {m},
  static_model {m.static_model}
{
  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;

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

  set<int> orig_endogs = symbol_table.getOrigEndogenous();
124
  for (int orig_endog : orig_endogs)
125
    {
126
      if (find(so_far_defined.begin(), so_far_defined.end(), orig_endog)
127
          == so_far_defined.end())
128
        warnings << "WARNING: in the 'steady_state_model' block, variable '" << symbol_table.getName(orig_endog) << "' is not assigned a value" << endl;
129
    }
130
131
}

132
133
134
void
SteadyStateModel::writeLatexSteadyStateFile(const string &basename) const
{
135
136
  boost::filesystem::create_directories(basename + "/latex");

137
  ofstream output, content_output;
138
139
  string filename = basename + "/latex/steady_state.tex";
  string content_filename = basename + "/latex/steady_state_content.tex";
140

141
  output.open(filename, ios::out | ios::binary);
142
143
144
145
146
147
  if (!output.is_open())
    {
      cerr << "ERROR: Can't open file " << filename << " for writing" << endl;
      exit(EXIT_FAILURE);
    }

148
  content_output.open(content_filename, ios::out | ios::binary);
149
150
151
152
153
154
155
156
157
158
159
160
161
162
  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;

163
  for (const auto & it : def_table)
164
    for (auto it1 = it.first.begin(); it1 != it.first.end(); it1++)
165
166
      {
        int id = *it1;
167
        expr_t value = it.second;
168
169
        content_output << "\\begin{dmath}" << endl
                       << symbol_table.getTeXName(id) << " = ";
170
        value->writeOutput(content_output, ExprNodeOutputType::latexStaticModel);
171
172
173
174
175
        content_output << endl << "\\end{dmath}" << endl;
      }

  static_model.writeLatexAuxVarRecursiveDefinitions(content_output);

176
  output << "\\include{steady_state_content.tex}" << endl
177
178
179
180
181
182
         << "\\end{document}" << endl;

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

183
void
Houtan Bastani's avatar
Houtan Bastani committed
184
SteadyStateModel::writeSteadyStateFile(const string &basename, bool ramsey_model, bool julia) const
185
{
186
  if (def_table.size() == 0)
187
188
    return;

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

198
  ExprNodeOutputType output_type = (julia ? ExprNodeOutputType::juliaSteadyStateFile : ExprNodeOutputType::steadyStateFile);
Houtan Bastani's avatar
Houtan Bastani committed
199
200

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

215
  for (const auto & i : def_table)
216
    {
217
      const vector<int> &symb_ids = i.first;
218
      output << "    ";
219
220
221
222
      if (symb_ids.size() > 1)
        output << "[";
      for (size_t j = 0; j < symb_ids.size(); j++)
        {
223
          getVariable(symb_ids[j])->ExprNode::writeOutput(output, output_type);
224
225
226
227
228
229
230
          if (j < symb_ids.size()-1)
            output << ",";
        }
      if (symb_ids.size() > 1)
        output << "]";

      output << "=";
231
      i.second->writeOutput(output, output_type);
232
233
      output << ";" << endl;
    }
Houtan Bastani's avatar
Houtan Bastani committed
234
235
236
237
  if (!julia)
    output << "    % Auxiliary equations" << endl;
  else
    output << "    # Auxiliary equations" << endl;
238
  static_model.writeAuxVarRecursiveDefinitions(output, output_type);
Houtan Bastani's avatar
Houtan Bastani committed
239

240
241
242
  if (!julia)
    output << "    check_=0;" << endl;

Houtan Bastani's avatar
Houtan Bastani committed
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
277
          output << "\"";
        }
      if (symb_ids.size() > 1)
        output << "]";
      output << ", \"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) :
Houtan Bastani's avatar
Houtan Bastani committed
299
  DynamicModel {m}
300
301
{
  for (const auto &it : m.def_table)
Sébastien Villemot's avatar
Sébastien Villemot committed
302
    def_table.emplace_back(it.first, it.second->clone(*this));
303
304
305
306
307
308
309
310
311
}

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

  def_table.clear();
  for (const auto &it : m.def_table)
Sébastien Villemot's avatar
Sébastien Villemot committed
312
    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
  def_table.emplace_back(symb_id, expr);
Houtan Bastani's avatar
Houtan Bastani committed
321
322
323
324
325
326
327
328
}

void
Epilogue::checkPass(WarningConsolidation &warnings) const
{
  if (def_table.size() == 0)
    return;

329
  vector<int> so_far_defined;
Houtan Bastani's avatar
Houtan Bastani committed
330
  for (const auto & it : def_table)
Houtan Bastani's avatar
Houtan Bastani committed
331
332
333
334
335
336
337
    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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
      so_far_defined.push_back(it.first);
}

void
Epilogue::writeEpilogueFile(const string &basename) const
{
  if (def_table.size() == 0)
    return;

  string filename = packageDir(basename) + "/epilogue.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);
    }

356
  ExprNodeOutputType output_type = ExprNodeOutputType::epilogueFile;
Houtan Bastani's avatar
Houtan Bastani committed
357
358
  output << "function dseries__ = epilogue(params, dseries__)" << endl
         << "% function dseries__ = epilogue(params, dseries__)" << endl
359
360
         << "% Epilogue file generated by Dynare preprocessor" << endl << endl
         << "simul_end_date = lastdate(dseries__);" << endl;
Houtan Bastani's avatar
Houtan Bastani committed
361
362
363
364
365
366

  deriv_node_temp_terms_t tef_terms;
  temporary_terms_t temporary_terms;
  temporary_terms_idxs_t temporary_terms_idxs;
  for (const auto & it : def_table)
    if (it.second->containsExternalFunction())
Houtan Bastani's avatar
Houtan Bastani committed
367
      it.second->writeExternalFunctionOutput(output, output_type, temporary_terms, temporary_terms_idxs, tef_terms);
Houtan Bastani's avatar
Houtan Bastani committed
368
369
370
  output << endl;
  for (const auto & it : def_table)
    {
371
372
373
374
375
      int max_lag = it.second->maxLagWithDiffsExpanded();
      set<int> used_symbols;
      it.second->collectVariables(SymbolType::endogenous, used_symbols);
      it.second->collectVariables(SymbolType::exogenous, used_symbols);
      it.second->collectVariables(SymbolType::epilogue, used_symbols);
376
377
378
379
380
381
382
383
384

      output << "simul_begin_date = firstobservedperiod(dseries__{";
      for (auto it1 = used_symbols.begin(); it1 != used_symbols.end(); it1++)
        {
          if (it1 != used_symbols.begin())
            output << ", ";
          output << "'" << symbol_table.getName(*it1) << "'";
        }
      output << "}) + " << max_lag << " + 1;" << endl
385
386
387
388
389
             << "if ~dseries__.exist('" << symbol_table.getName(it.first) << "')" << endl
             << "    dseries__ = [dseries__ dseries(NaN(dseries__.nobs,1), dseries__.firstdate, '" << symbol_table.getName(it.first)<< "')];" << endl
             << "end" << endl
             << "from simul_begin_date to simul_end_date do "
             << "dseries__." << symbol_table.getName(it.first) << "(t) = ";
Houtan Bastani's avatar
Houtan Bastani committed
390
      it.second->writeOutput(output, output_type, temporary_terms, temporary_terms_idxs, tef_terms);
391
      output << ";" << endl << endl;
Houtan Bastani's avatar
Houtan Bastani committed
392
    }
Houtan Bastani's avatar
Houtan Bastani committed
393
  output << "end" << endl;
Houtan Bastani's avatar
Houtan Bastani committed
394
395
  output.close();
}