DynamicModel.cc 289 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
 *
 * 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/>.
 */

20
#include <iostream>
sebastien's avatar
sebastien committed
21
#include <cmath>
22
#include <cstdlib>
23
#include <cassert>
24
25
#include <cstdio>
#include <cerrno>
26
#include <algorithm>
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
27
#include <iterator>
28
#include <numeric>
sebastien's avatar
sebastien committed
29

30
31
32
#include <boost/filesystem.hpp>

#include "DynamicModel.hh"
sebastien's avatar
sebastien committed
33
34

DynamicModel::DynamicModel(SymbolTable &symbol_table_arg,
35
                           NumericalConstants &num_constants_arg,
36
                           ExternalFunctionsTable &external_functions_table_arg,
Houtan Bastani's avatar
Houtan Bastani committed
37
38
                           TrendComponentModelTable &trend_component_model_table_arg,
                           VarModelTable &var_model_table_arg) :
39
40
41
  ModelTree{symbol_table_arg, num_constants_arg, external_functions_table_arg},
  trend_component_model_table{trend_component_model_table_arg},
  var_model_table{var_model_table_arg}
sebastien's avatar
sebastien committed
42
43
44
{
}

sebastien's avatar
sebastien committed
45
46
VariableNode *
DynamicModel::AddVariable(int symb_id, int lag)
sebastien's avatar
sebastien committed
47
{
sebastien's avatar
sebastien committed
48
  return AddVariableInternal(symb_id, lag);
sebastien's avatar
sebastien committed
49
50
}

sebastien's avatar
sebastien committed
51
void
52
DynamicModel::compileDerivative(ofstream &code_file, unsigned int &instruction_number, int eq, int symb_id, int lag, const map_idx_t &map_idx) const
53
{
54
  auto it = first_derivatives.find({ eq, getDerivID(symbol_table.getID(SymbolType::endogenous, symb_id), lag) });
55
  if (it != first_derivatives.end())
56
    (it->second)->compile(code_file, instruction_number, false, temporary_terms, map_idx, true, false);
57
58
59
  else
    {
      FLDZ_ fldz;
60
      fldz.write(code_file, instruction_number);
61
62
    }
}
63
64

void
65
DynamicModel::compileChainRuleDerivative(ofstream &code_file, unsigned int &instruction_number, int eqr, int varr, int lag, const map_idx_t &map_idx) const
66
{
67
  auto it = first_chain_rule_derivatives.find({ eqr, { varr, lag } });
68
  if (it != first_chain_rule_derivatives.end())
69
    (it->second)->compile(code_file, instruction_number, false, temporary_terms, map_idx, true, false);
70
  else
71
72
    {
      FLDZ_ fldz;
73
      fldz.write(code_file, instruction_number);
74
    }
75
76
}

sebastien's avatar
sebastien committed
77
void
78
DynamicModel::computeTemporaryTermsOrdered()
sebastien's avatar
sebastien committed
79
{
80
  map<expr_t, pair<int, int>> first_occurence;
81
  map<expr_t, int> reference_count;
sebastien's avatar
sebastien committed
82
  BinaryOpNode *eq_node;
83
84
  first_derivatives_t::const_iterator it;
  first_chain_rule_derivatives_t::const_iterator it_chr;
sebastien's avatar
sebastien committed
85
  ostringstream tmp_s;
86
87
  v_temporary_terms.clear();
  map_idx.clear();
sebastien's avatar
sebastien committed
88

89
  unsigned int nb_blocks = getNbBlocks();
90
  v_temporary_terms = vector<vector<temporary_terms_t>>(nb_blocks);
91
  v_temporary_terms_inuse = vector<temporary_terms_inuse_t>(nb_blocks);
sebastien's avatar
sebastien committed
92
  temporary_terms.clear();
93

94
  if (!global_temporary_terms)
95
96
    {
      for (unsigned int block = 0; block < nb_blocks; block++)
sebastien's avatar
sebastien committed
97
        {
98
99
100
101
102
          reference_count.clear();
          temporary_terms.clear();
          unsigned int block_size = getBlockSize(block);
          unsigned int block_nb_mfs = getBlockMfs(block);
          unsigned int block_nb_recursives = block_size - block_nb_mfs;
103
          v_temporary_terms[block] = vector<temporary_terms_t>(block_size);
104
          for (unsigned int i = 0; i < block_size; i++)
sebastien's avatar
sebastien committed
105
            {
106
              if (i < block_nb_recursives && isBlockEquationRenormalized(block, i))
107
                getBlockEquationRenormalizedExpr(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  i);
108
              else
sebastien's avatar
sebastien committed
109
                {
110
                  eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
111
                  eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  i);
sebastien's avatar
sebastien committed
112
113
                }
            }
114
          for (block_derivatives_equation_variable_laglead_nodeid_t::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
115
            {
116
              expr_t id = it->second.second;
117
118
              id->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  block_size-1);
            }
119
          for (derivative_t::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++)
120
            it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  block_size-1);
121
          for (derivative_t::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
122
123
124
125
            it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  block_size-1);
          set<int> temporary_terms_in_use;
          temporary_terms_in_use.clear();
          v_temporary_terms_inuse[block] = temporary_terms_in_use;
sebastien's avatar
sebastien committed
126
127
        }
    }
128
  else
sebastien's avatar
sebastien committed
129
    {
130
      for (unsigned int block = 0; block < nb_blocks; block++)
sebastien's avatar
sebastien committed
131
        {
132
133
134
135
          // Compute the temporary terms reordered
          unsigned int block_size = getBlockSize(block);
          unsigned int block_nb_mfs = getBlockMfs(block);
          unsigned int block_nb_recursives = block_size - block_nb_mfs;
136
          v_temporary_terms[block] = vector<temporary_terms_t>(block_size);
137
          for (unsigned int i = 0; i < block_size; i++)
138
            {
139
              if (i < block_nb_recursives && isBlockEquationRenormalized(block, i))
140
                getBlockEquationRenormalizedExpr(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  i);
141
142
              else
                {
143
                  eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
144
145
                  eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i);
                }
146
            }
147
          for (block_derivatives_equation_variable_laglead_nodeid_t::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
sebastien's avatar
sebastien committed
148
            {
149
              expr_t id = it->second.second;
150
              id->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1);
sebastien's avatar
sebastien committed
151
            }
152
          for (derivative_t::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++)
153
            it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1);
154
          for (derivative_t::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
155
            it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1);
156
        }
157
      for (unsigned int block = 0; block < nb_blocks; block++)
158
        {
159
160
161
162
163
164
          // Collect the temporary terms reordered
          unsigned int block_size = getBlockSize(block);
          unsigned int block_nb_mfs = getBlockMfs(block);
          unsigned int block_nb_recursives = block_size - block_nb_mfs;
          set<int> temporary_terms_in_use;
          for (unsigned int i = 0; i < block_size; i++)
sebastien's avatar
sebastien committed
165
            {
166
              if (i < block_nb_recursives && isBlockEquationRenormalized(block, i))
167
                getBlockEquationRenormalizedExpr(block, i)->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
168
              else
sebastien's avatar
sebastien committed
169
                {
170
                  eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
171
                  eq_node->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
sebastien's avatar
sebastien committed
172
173
                }
            }
174
          for (block_derivatives_equation_variable_laglead_nodeid_t::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
175
            {
176
              expr_t id = it->second.second;
177
178
              id->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
            }
179
          for (derivative_t::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++)
180
            it->second->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
181
          for (derivative_t::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
182
            it->second->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
183
184
185
186
          for (derivative_t::const_iterator it = derivative_exo[block].begin(); it != derivative_exo[block].end(); it++)
            it->second->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
          for (derivative_t::const_iterator it = derivative_exo_det[block].begin(); it != derivative_exo_det[block].end(); it++)
            it->second->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
187
          v_temporary_terms_inuse[block] = temporary_terms_in_use;
sebastien's avatar
sebastien committed
188
        }
189
      computeTemporaryTermsMapping();
sebastien's avatar
sebastien committed
190
191
192
    }
}

193
194
195
196
197
void
DynamicModel::computeTemporaryTermsMapping()
{
  // Add a mapping form node ID to temporary terms order
  int j = 0;
198
199
  for (auto temporary_term : temporary_terms)
    map_idx[temporary_term->idx] = j++;
200
201
}

sebastien's avatar
sebastien committed
202
void
203
DynamicModel::writeModelEquationsOrdered_M(const string &basename) const
204
205
206
{
  string tmp_s, sps;
  ostringstream tmp_output, tmp1_output, global_output;
207
  expr_t lhs = nullptr, rhs = nullptr;
208
  BinaryOpNode *eq_node;
209
210
  ostringstream Ufoss;
  vector<string> Uf(symbol_table.endo_nbr(), "");
211
  map<expr_t, int> reference_count;
212
  temporary_terms_t local_temporary_terms;
213
  ofstream  output;
214
  int nze, nze_exo, nze_exo_det, nze_other_endo;
215
216
  vector<int> feedback_variables;
  ExprNodeOutputType local_output_type;
217
  Ufoss.str("");
sebastien's avatar
sebastien committed
218

219
  local_output_type = ExprNodeOutputType::matlabDynamicModelSparse;
220
  if (global_temporary_terms)
Sébastien Villemot's avatar
Sébastien Villemot committed
221
    local_temporary_terms = temporary_terms;
222
223
224
225
226
227
228
229
230
231
232
233

  //----------------------------------------------------------------------
  //For each block
  for (unsigned int block = 0; block < getNbBlocks(); block++)
    {

      //recursive_variables.clear();
      feedback_variables.clear();
      //For a block composed of a single equation determines wether we have to evaluate or to solve the equation
      nze = derivative_endo[block].size();
      nze_other_endo = derivative_other_endo[block].size();
      nze_exo = derivative_exo[block].size();
234
      nze_exo_det = derivative_exo_det[block].size();
235
236
237
238
      BlockSimulationType simulation_type = getBlockSimulationType(block);
      unsigned int block_size = getBlockSize(block);
      unsigned int block_mfs = getBlockMfs(block);
      unsigned int block_recursive = block_size - block_mfs;
239
      deriv_node_temp_terms_t tef_terms;
240
      local_output_type = ExprNodeOutputType::matlabDynamicModelSparse;
241
      if (global_temporary_terms)
Sébastien Villemot's avatar
Sébastien Villemot committed
242
        local_temporary_terms = temporary_terms;
243

244
245
      int prev_lag;
      unsigned int prev_var, count_col, count_col_endo, count_col_exo, count_col_exo_det, count_col_other_endo;
246
      map<pair<int, pair<int, int>>, expr_t> tmp_block_endo_derivative;
247
      for (auto it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
248
        tmp_block_endo_derivative[{ it->second.first, { it->first.second, it->first.first } }] = it->second.second;
249
250
251
      prev_var = 999999999;
      prev_lag = -9999999;
      count_col_endo = 0;
252
      for (map<pair<int, pair<int, int>>, expr_t>::const_iterator it = tmp_block_endo_derivative.begin(); it != tmp_block_endo_derivative.end(); it++)
253
254
255
256
257
258
259
260
261
262
        {
          int lag = it->first.first;
          unsigned int var = it->first.second.first;
          if (var != prev_var || lag != prev_lag)
            {
              prev_var = var;
              prev_lag = lag;
              count_col_endo++;
            }
        }
263
      map<pair<int, pair<int, int>>, expr_t> tmp_block_exo_derivative;
264
      for (auto it = derivative_exo[block].begin(); it != (derivative_exo[block]).end(); it++)
265
        tmp_block_exo_derivative[{ it->first.first, { it->first.second.second, it->first.second.first } }] = it->second;
266
267
268
      prev_var = 999999999;
      prev_lag = -9999999;
      count_col_exo = 0;
269
      for (map<pair<int, pair<int, int>>, expr_t>::const_iterator it = tmp_block_exo_derivative.begin(); it != tmp_block_exo_derivative.end(); it++)
270
271
272
273
274
275
276
277
278
279
        {
          int lag = it->first.first;
          unsigned int var = it->first.second.first;
          if (var != prev_var || lag != prev_lag)
            {
              prev_var = var;
              prev_lag = lag;
              count_col_exo++;
            }
        }
280
      map<pair<int, pair<int, int>>, expr_t> tmp_block_exo_det_derivative;
281
      for (auto it = derivative_exo_det[block].begin(); it != (derivative_exo_det[block]).end(); it++)
282
        tmp_block_exo_det_derivative[{ it->first.first, { it->first.second.second, it->first.second.first } }] = it->second;
283
284
285
      prev_var = 999999999;
      prev_lag = -9999999;
      count_col_exo_det = 0;
286
      for (map<pair<int, pair<int, int>>, expr_t>::const_iterator it = tmp_block_exo_derivative.begin(); it != tmp_block_exo_derivative.end(); it++)
287
288
289
290
291
292
293
294
295
296
        {
          int lag = it->first.first;
          unsigned int var = it->first.second.first;
          if (var != prev_var || lag != prev_lag)
            {
              prev_var = var;
              prev_lag = lag;
              count_col_exo_det++;
            }
        }
297
      map<pair<int, pair<int, int>>, expr_t> tmp_block_other_endo_derivative;
298
      for (auto it = derivative_other_endo[block].begin(); it != (derivative_other_endo[block]).end(); it++)
299
        tmp_block_other_endo_derivative[{ it->first.first, { it->first.second.second, it->first.second.first } }] = it->second;
300
301
302
      prev_var = 999999999;
      prev_lag = -9999999;
      count_col_other_endo = 0;
303
      for (map<pair<int, pair<int, int>>, expr_t>::const_iterator it = tmp_block_other_endo_derivative.begin(); it != tmp_block_other_endo_derivative.end(); it++)
304
305
306
307
308
309
310
311
312
313
314
        {
          int lag = it->first.first;
          unsigned int var = it->first.second.first;
          if (var != prev_var || lag != prev_lag)
            {
              prev_var = var;
              prev_lag = lag;
              count_col_other_endo++;
            }
        }

315
      tmp1_output.str("");
316
      tmp1_output << packageDir(basename + ".block") << "/dynamic_" << block+1 << ".m";
317
      output.open(tmp1_output.str(), ios::out | ios::binary);
318
319
320
321
322
323
324
325
      output << "%\n";
      output << "% " << tmp1_output.str() << " : Computes dynamic model for Dynare\n";
      output << "%\n";
      output << "% Warning : this file is generated automatically by Dynare\n";
      output << "%           from model file (.mod)\n\n";
      output << "%/\n";
      if (simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD)
        {
326
          output << "function [y, g1, g2, g3, varargout] = dynamic_" << block+1 << "(y, x, params, steady_state, jacobian_eval, y_kmin, periods)\n";
327
328
        }
      else if (simulation_type == SOLVE_FORWARD_COMPLETE || simulation_type == SOLVE_BACKWARD_COMPLETE)
329
        output << "function [residual, y, g1, g2, g3, varargout] = dynamic_" << block+1 << "(y, x, params, steady_state, it_, jacobian_eval)\n";
330
      else if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE)
331
        output << "function [residual, y, g1, g2, g3, varargout] = dynamic_" << block+1 << "(y, x, params, steady_state, it_, jacobian_eval)\n";
332
      else
333
        output << "function [residual, y, g1, g2, g3, b, varargout] = dynamic_" << block+1 << "(y, x, params, steady_state, periods, jacobian_eval, y_kmin, y_size, Periods)\n";
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
      BlockType block_type;
      if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
        block_type = SIMULTAN;
      else if (simulation_type == SOLVE_FORWARD_COMPLETE || simulation_type == SOLVE_BACKWARD_COMPLETE)
        block_type = SIMULTANS;
      else if ((simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_SIMPLE
                || simulation_type == EVALUATE_BACKWARD    || simulation_type == EVALUATE_FORWARD)
               && getBlockFirstEquation(block) < prologue)
        block_type = PROLOGUE;
      else if ((simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_SIMPLE
                || simulation_type == EVALUATE_BACKWARD    || simulation_type == EVALUATE_FORWARD)
               && getBlockFirstEquation(block) >= equations.size() - epilogue)
        block_type = EPILOGUE;
      else
        block_type = SIMULTANS;
      output << "  % ////////////////////////////////////////////////////////////////////////" << endl
             << "  % //" << string("                     Block ").substr(int (log10(block + 1))) << block + 1 << " " << BlockType0(block_type)
             << "          //" << endl
             << "  % //                     Simulation type "
             << BlockSim(simulation_type) << "  //" << endl
             << "  % ////////////////////////////////////////////////////////////////////////" << endl;
      //The Temporary terms
      if (simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD)
        {
          output << "  if(jacobian_eval)\n";
359
360
          output << "    g1 = spalloc(" << block_mfs  << ", " << count_col_endo << ", " << nze << ");\n";
          output << "    g1_x=spalloc(" << block_size << ", " << count_col_exo  << ", " << nze_exo << ");\n";
361
          output << "    g1_xd=spalloc(" << block_size << ", " << count_col_exo_det  << ", " << nze_exo_det << ");\n";
362
          output << "    g1_o=spalloc(" << block_size << ", " << count_col_other_endo << ", " << nze_other_endo << ");\n";
363
364
365
366
367
          output << "  end;\n";
        }
      else
        {
          output << "  if(jacobian_eval)\n";
368
369
          output << "    g1 = spalloc(" << block_size << ", " << count_col_endo << ", " << nze << ");\n";
          output << "    g1_x=spalloc(" << block_size << ", " << count_col_exo  << ", " << nze_exo << ");\n";
370
          output << "    g1_xd=spalloc(" << block_size << ", " << count_col_exo_det  << ", " << nze_exo_det << ");\n";
371
          output << "    g1_o=spalloc(" << block_size << ", " << count_col_other_endo << ", " << nze_other_endo << ");\n";
372
373
374
          output << "  else\n";
          if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
            {
375
376
377
              output << "    g1 = spalloc(" << block_mfs << "*Periods, "
                     << block_mfs << "*(Periods+" << max_leadlag_block[block].first+max_leadlag_block[block].second+1 << ")"
                     << ", " << nze << "*Periods);\n";
378
            }
ferhat's avatar
ferhat committed
379
          else
380
381
382
383
384
385
            {
              output << "    g1 = spalloc(" << block_mfs
                     << ", " << block_mfs << ", " << nze << ");\n";
            }
          output << "  end;\n";
        }
386

387
388
389
390
      output << "  g2=0;g3=0;\n";
      if (v_temporary_terms_inuse[block].size())
        {
          tmp_output.str("");
391
392
          for (int it : v_temporary_terms_inuse[block])
            tmp_output << " T" << it;
393
394
395
396
          output << "  global" << tmp_output.str() << ";\n";
        }
      if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
        {
397
          temporary_terms_t tt2;
398
399
400
401
402
403
404
          tt2.clear();
          for (int i = 0; i < (int) block_size; i++)
            {
              if (v_temporary_terms[block][i].size() && global_temporary_terms)
                {
                  output << "  " << "% //Temporary variables initialization" << endl
                         << "  " << "T_zeros = zeros(y_kmin+periods, 1);" << endl;
405
                  for (auto it : v_temporary_terms[block][i])
406
407
                    {
                      output << "  ";
408
                      // In the following, "Static" is used to avoid getting the "(it_)" subscripting
409
                      it->writeOutput(output, ExprNodeOutputType::matlabStaticModelSparse, local_temporary_terms, {});
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
                      output << " = T_zeros;" << endl;
                    }
                }
            }
        }
      if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE)
        output << "  residual=zeros(" << block_mfs << ",1);\n";
      else if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
        output << "  residual=zeros(" << block_mfs << ",y_kmin+periods);\n";
      if (simulation_type == EVALUATE_BACKWARD)
        output << "  for it_ = (y_kmin+periods):y_kmin+1\n";
      if (simulation_type == EVALUATE_FORWARD)
        output << "  for it_ = y_kmin+1:(y_kmin+periods)\n";

      if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
        {
          output << "  b = zeros(periods*y_size,1);" << endl
                 << "  for it_ = y_kmin+1:(periods+y_kmin)" << endl
                 << "    Per_y_=it_*y_size;" << endl
                 << "    Per_J_=(it_-y_kmin-1)*y_size;" << endl
                 << "    Per_K_=(it_-1)*y_size;" << endl;
          sps = "  ";
        }
      else
        if (simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD)
          sps = "  ";
        else
          sps = "";
      // The equations
Houtan Bastani's avatar
Houtan Bastani committed
439
      temporary_terms_idxs_t temporary_terms_idxs;
440
441
      for (unsigned int i = 0; i < block_size; i++)
        {
442
          temporary_terms_t tt2;
443
444
445
446
          tt2.clear();
          if (v_temporary_terms[block].size())
            {
              output << "  " << "% //Temporary variables" << endl;
447
              for (auto it : v_temporary_terms[block][i])
448
                {
449
                  if (dynamic_cast<AbstractExternalFunctionNode *>(it) != nullptr)
450
                    it->writeExternalFunctionOutput(output, local_output_type, tt2, temporary_terms_idxs, tef_terms);
451

452
                  output << "  " <<  sps;
453
                  it->writeOutput(output, local_output_type, local_temporary_terms, {}, tef_terms);
454
                  output << " = ";
455
                  it->writeOutput(output, local_output_type, tt2, {}, tef_terms);
456
                  // Insert current node into tt2
457
                  tt2.insert(it);
458
459
460
461
462
463
464
                  output << ";" << endl;
                }
            }

          int variable_ID = getBlockVariableID(block, i);
          int equation_ID = getBlockEquationID(block, i);
          EquationType equ_type = getBlockEquationType(block, i);
465
          string sModel = symbol_table.getName(symbol_table.getID(SymbolType::endogenous, variable_ID));
466
          eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
467
468
469
          lhs = eq_node->get_arg1();
          rhs = eq_node->get_arg2();
          tmp_output.str("");
470
          lhs->writeOutput(tmp_output, local_output_type, local_temporary_terms, {});
471
472
473
474
475
476
477
478
479
480
481
482
          switch (simulation_type)
            {
            case EVALUATE_BACKWARD:
            case EVALUATE_FORWARD:
            evaluation:     if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
                output << "    % equation " << getBlockEquationID(block, i)+1 << " variable : " << sModel
                       << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl;
              output << "    ";
              if (equ_type == E_EVALUATE)
                {
                  output << tmp_output.str();
                  output << " = ";
483
                  rhs->writeOutput(output, local_output_type, local_temporary_terms, {});
484
485
486
487
488
489
490
                }
              else if (equ_type == E_EVALUATE_S)
                {
                  output << "%" << tmp_output.str();
                  output << " = ";
                  if (isBlockEquationRenormalized(block, i))
                    {
491
                      rhs->writeOutput(output, local_output_type, local_temporary_terms, {});
492
493
                      output << "\n    ";
                      tmp_output.str("");
494
                      eq_node = (BinaryOpNode *) getBlockEquationRenormalizedExpr(block, i);
495
496
                      lhs = eq_node->get_arg1();
                      rhs = eq_node->get_arg2();
497
                      lhs->writeOutput(output, local_output_type, local_temporary_terms, {});
498
                      output << " = ";
499
                      rhs->writeOutput(output, local_output_type, local_temporary_terms, {});
500
501
502
503
                    }
                }
              else
                {
504
                  cerr << "Type mismatch for equation " << equation_ID+1  << "\n";
505
506
507
508
509
510
511
512
513
514
515
516
                  exit(EXIT_FAILURE);
                }
              output << ";\n";
              break;
            case SOLVE_BACKWARD_SIMPLE:
            case SOLVE_FORWARD_SIMPLE:
            case SOLVE_BACKWARD_COMPLETE:
            case SOLVE_FORWARD_COMPLETE:
              if (i < block_recursive)
                goto evaluation;
              feedback_variables.push_back(variable_ID);
              output << "  % equation " << equation_ID+1 << " variable : " << sModel
517
                     << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << " symb_id=" << symbol_table.getID(SymbolType::endogenous, variable_ID) << endl;
518
519
520
521
522
523
524
525
              output << "  " << "residual(" << i+1-block_recursive << ") = (";
              goto end;
            case SOLVE_TWO_BOUNDARIES_COMPLETE:
            case SOLVE_TWO_BOUNDARIES_SIMPLE:
              if (i < block_recursive)
                goto evaluation;
              feedback_variables.push_back(variable_ID);
              output << "    % equation " << equation_ID+1 << " variable : " << sModel
526
                     << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << " symb_id=" << symbol_table.getID(SymbolType::endogenous, variable_ID) << endl;
527
              Ufoss << "    b(" << i+1-block_recursive << "+Per_J_) = -residual(" << i+1-block_recursive << ", it_)";
528
              Uf[equation_ID] += Ufoss.str();
529
              Ufoss.str("");
530
531
532
533
534
535
              output << "    residual(" << i+1-block_recursive << ", it_) = (";
              goto end;
            default:
            end:
              output << tmp_output.str();
              output << ") - (";
536
              rhs->writeOutput(output, local_output_type, local_temporary_terms, {});
537
              output << ");\n";
sebastien's avatar
sebastien committed
538
#ifdef CONDITION
539
540
              if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
                output << "  condition(" << i+1 << ")=0;\n";
sebastien's avatar
sebastien committed
541
#endif
542
543
544
545
            }
        }
      // The Jacobian if we have to solve the block
      if (simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE)
546
        output << "  " << sps << "% Jacobian  " << endl << "    if jacobian_eval" << endl;
547
548
549
550
      else
        if (simulation_type == SOLVE_BACKWARD_SIMPLE   || simulation_type == SOLVE_FORWARD_SIMPLE
            || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE)
          output << "  % Jacobian  " << endl << "  if jacobian_eval" << endl;
sebastien's avatar
sebastien committed
551
        else
552
          output << "    % Jacobian  " << endl << "    if jacobian_eval" << endl;
553
554
555
      prev_var = 999999999;
      prev_lag = -9999999;
      count_col = 0;
556
      for (map<pair<int, pair<int, int>>, expr_t>::const_iterator it = tmp_block_endo_derivative.begin(); it != tmp_block_endo_derivative.end(); it++)
557
        {
558
559
560
          int lag = it->first.first;
          unsigned int var = it->first.second.first;
          unsigned int eq = it->first.second.second;
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
561
562
          int eqr = getBlockEquationID(block, eq);
          int varr = getBlockVariableID(block, var);
563
          if (var != prev_var || lag != prev_lag)
564
            {
565
566
567
568
              prev_var = var;
              prev_lag = lag;
              count_col++;
            }
569

570
          expr_t id = it->second;
571

572
          output << "      g1(" << eq+1 << ", " << count_col << ") = ";
573
          id->writeOutput(output, local_output_type, local_temporary_terms, {});
574
          output << "; % variable=" << symbol_table.getName(symbol_table.getID(SymbolType::endogenous, varr))
575
                 << "(" << lag
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
576
577
                 << ") " << varr+1 << ", " << var+1
                 << ", equation=" << eqr+1 << ", " << eq+1 << endl;
578
579
580
581
        }
      prev_var = 999999999;
      prev_lag = -9999999;
      count_col = 0;
582
      for (map<pair<int, pair<int, int>>, expr_t>::const_iterator it = tmp_block_exo_derivative.begin(); it != tmp_block_exo_derivative.end(); it++)
583
584
585
586
587
588
        {
          int lag = it->first.first;
          unsigned int var = it->first.second.first;
          unsigned int eq = it->first.second.second;
          int eqr = getBlockInitialEquationID(block, eq);
          if (var != prev_var || lag != prev_lag)
589
            {
590
591
592
              prev_var = var;
              prev_lag = lag;
              count_col++;
593
            }
594
595
          expr_t id = it->second;
          output << "      g1_x(" << eqr+1 << ", " << count_col << ") = ";
596
          id->writeOutput(output, local_output_type, local_temporary_terms, {});
597
          output << "; % variable=" << symbol_table.getName(symbol_table.getID(SymbolType::exogenous, var))
598
599
600
601
602
603
604
                 << "(" << lag
                 << ") " << var+1
                 << ", equation=" << eq+1 << endl;
        }
      prev_var = 999999999;
      prev_lag = -9999999;
      count_col = 0;
605
      for (map<pair<int, pair<int, int>>, expr_t>::const_iterator it = tmp_block_exo_det_derivative.begin(); it != tmp_block_exo_det_derivative.end(); it++)
606
607
608
609
610
611
        {
          int lag = it->first.first;
          unsigned int var = it->first.second.first;
          unsigned int eq = it->first.second.second;
          int eqr = getBlockInitialEquationID(block, eq);
          if (var != prev_var || lag != prev_lag)
612
            {
613
614
615
              prev_var = var;
              prev_lag = lag;
              count_col++;
616
            }
617
618
          expr_t id = it->second;
          output << "      g1_xd(" << eqr+1 << ", " << count_col << ") = ";
619
          id->writeOutput(output, local_output_type, local_temporary_terms, {});
620
          output << "; % variable=" << symbol_table.getName(symbol_table.getID(SymbolType::exogenous, var))
621
622
623
624
625
626
627
                 << "(" << lag
                 << ") " << var+1
                 << ", equation=" << eq+1 << endl;
        }
      prev_var = 999999999;
      prev_lag = -9999999;
      count_col = 0;
628
      for (map<pair<int, pair<int, int>>, expr_t>::const_iterator it = tmp_block_other_endo_derivative.begin(); it != tmp_block_other_endo_derivative.end(); it++)
629
630
631
632
633
634
        {
          int lag = it->first.first;
          unsigned int var = it->first.second.first;
          unsigned int eq = it->first.second.second;
          int eqr = getBlockInitialEquationID(block, eq);
          if (var != prev_var || lag != prev_lag)
635
            {
636
637
638
              prev_var = var;
              prev_lag = lag;
              count_col++;
639
            }
640
641
          expr_t id = it->second;

642
          output << "      g1_o(" << eqr+1 << ", " << /*var+1+(lag+block_max_lag)*block_size*/ count_col << ") = ";
643
          id->writeOutput(output, local_output_type, local_temporary_terms, {});
644
          output << "; % variable=" << symbol_table.getName(symbol_table.getID(SymbolType::endogenous, var))
645
646
647
648
649
650
651
652
653
654
655
656
                 << "(" << lag
                 << ") " << var+1
                 << ", equation=" << eq+1 << endl;
        }
      output << "      varargout{1}=g1_x;\n";
      output << "      varargout{2}=g1_xd;\n";
      output << "      varargout{3}=g1_o;\n";

      switch (simulation_type)
        {
        case EVALUATE_FORWARD:
        case EVALUATE_BACKWARD:
657
658
659
660
661
662
663
664
          output << "    end;" << endl;
          output << "  end;" << endl;
          break;
        case SOLVE_BACKWARD_SIMPLE:
        case SOLVE_FORWARD_SIMPLE:
        case SOLVE_BACKWARD_COMPLETE:
        case SOLVE_FORWARD_COMPLETE:
          output << "  else" << endl;
665
          for (auto it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
666
667
668
669
670
            {
              unsigned int eq = it->first.first;
              unsigned int var = it->first.second;
              unsigned int eqr = getBlockEquationID(block, eq);
              unsigned int varr = getBlockVariableID(block, var);
671
              expr_t id = it->second.second;
672
              int lag = it->second.first;
673
674
675
              if (lag == 0)
                {
                  output << "    g1(" << eq+1 << ", " << var+1-block_recursive << ") = ";
676
                  id->writeOutput(output, local_output_type, local_temporary_terms, {});
677
                  output << "; % variable=" << symbol_table.getName(symbol_table.getID(SymbolType::endogenous, varr))
678
679
680
681
682
                         << "(" << lag
                         << ") " << varr+1
                         << ", equation=" << eqr+1 << endl;
                }

683
684
685
686
687
            }
          output << "  end;\n";
          break;
        case SOLVE_TWO_BOUNDARIES_SIMPLE:
        case SOLVE_TWO_BOUNDARIES_COMPLETE:
688
          output << "    else" << endl;
689
          for (auto it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
690
691
692
693
694
695
            {
              unsigned int eq = it->first.first;
              unsigned int var = it->first.second;
              unsigned int eqr = getBlockEquationID(block, eq);
              unsigned int varr = getBlockVariableID(block, var);
              ostringstream tmp_output;
696
              expr_t id = it->second.second;
697
              int lag = it->second.first;
698
              if (eq >= block_recursive && var >= block_recursive)
699
700
                {
                  if (lag == 0)
701
702
703
                    Ufoss << "+g1(" << eq+1-block_recursive
                          << "+Per_J_, " << var+1-block_recursive
                          << "+Per_K_)*y(it_, " << varr+1 << ")";
704
                  else if (lag == 1)
705
706
707
                    Ufoss << "+g1(" << eq+1-block_recursive
                          << "+Per_J_, " << var+1-block_recursive
                          << "+Per_y_)*y(it_+1, " << varr+1 << ")";
708
                  else if (lag > 0)
709
710
711
                    Ufoss << "+g1(" << eq+1-block_recursive
                          << "+Per_J_, " << var+1-block_recursive
                          << "+y_size*(it_+" << lag-1 << "))*y(it_+" << lag << ", " << varr+1 << ")";
712
                  else
713
714
715
                    Ufoss << "+g1(" << eq+1-block_recursive
                          << "+Per_J_, " << var+1-block_recursive
                          << "+y_size*(it_" << lag-1 << "))*y(it_" << lag << ", " << varr+1 << ")";
716
                  Uf[eqr] += Ufoss.str();
717
718
                  Ufoss.str("");

719
720
721
722
723
724
725
726
727
728
729
730
731
                  if (lag == 0)
                    tmp_output << "     g1(" << eq+1-block_recursive << "+Per_J_, "
                               << var+1-block_recursive << "+Per_K_) = ";
                  else if (lag == 1)
                    tmp_output << "     g1(" << eq+1-block_recursive << "+Per_J_, "
                               << var+1-block_recursive << "+Per_y_) = ";
                  else if (lag > 0)
                    tmp_output << "     g1(" << eq+1-block_recursive << "+Per_J_, "
                               << var+1-block_recursive << "+y_size*(it_+" << lag-1 << ")) = ";
                  else if (lag < 0)
                    tmp_output << "     g1(" << eq+1-block_recursive << "+Per_J_, "
                               << var+1-block_recursive << "+y_size*(it_" << lag-1 << ")) = ";
                  output << " " << tmp_output.str();
732
                  id->writeOutput(output, local_output_type, local_temporary_terms, {});
733
                  output << ";";
734
                  output << " %2 variable=" << symbol_table.getName(symbol_table.getID(SymbolType::endogenous, varr))
735
736
737
                         << "(" << lag << ") " << varr+1
                         << ", equation=" << eqr+1 << " (" << eq+1 << ")" << endl;
                }
738

sebastien's avatar
sebastien committed
739
#ifdef CONDITION
740
741
              output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
              output << "    condition(" << eqr << ")=u(" << u << "+Per_u_);\n";
sebastien's avatar
sebastien committed
742
#endif
743
744
745
746
            }
          for (unsigned int i = 0; i < block_size; i++)
            {
              if (i >= block_recursive)
747
                output << "  " << Uf[getBlockEquationID(block, i)] << ";\n";
sebastien's avatar
sebastien committed
748
#ifdef CONDITION
749
750
              output << "  if (fabs(condition(" << i+1 << "))<fabs(u(" << i << "+Per_u_)))\n";
              output << "    condition(" << i+1 << ")=u(" << i+1 << "+Per_u_);\n";
sebastien's avatar
sebastien committed
751
#endif
752
            }
sebastien's avatar
sebastien committed
753
#ifdef CONDITION
754
755
756
757
758
759
760
761
762
763
764
765
766
767
          for (m = 0; m <= ModelBlock->Block_List[block].Max_Lead+ModelBlock->Block_List[block].Max_Lag; m++)
            {
              k = m-ModelBlock->Block_List[block].Max_Lag;
              for (i = 0; i < ModelBlock->Block_List[block].IM_lead_lag[m].size; i++)
                {
                  unsigned int eq = ModelBlock->Block_List[block].IM_lead_lag[m].Equ_Index[i];
                  unsigned int var = ModelBlock->Block_List[block].IM_lead_lag[m].Var_Index[i];
                  unsigned int u = ModelBlock->Block_List[block].IM_lead_lag[m].u[i];
                  unsigned int eqr = ModelBlock->Block_List[block].IM_lead_lag[m].Equ[i];
                  output << "  u(" << u+1 << "+Per_u_) = u(" << u+1 << "+Per_u_) / condition(" << eqr+1 << ");\n";
                }
            }
          for (i = 0; i < ModelBlock->Block_List[block].Size; i++)
            output << "  u(" << i+1 << "+Per_u_) = u(" << i+1 << "+Per_u_) / condition(" << i+1 << ");\n";
sebastien's avatar
sebastien committed
768
#endif
769
770
          output << "    end;" << endl;
          output << "  end;" << endl;
771
772
773
774
          break;
        default:
          break;
        }
775
      output << "end" << endl;
776
777
778
      output.close();
    }
}
sebastien's avatar
sebastien committed
779
780

void
781
DynamicModel::writeModelEquationsCode(const string &basename, const map_idx_t &map_idx) const
782
{
783

784
785
  ostringstream tmp_output;
  ofstream code_file;
786
  unsigned int instruction_number = 0;
787
788
  bool file_open = false;

789
790
791
  boost::filesystem::create_directories(basename + "/model/bytecode");

  string main_name = basename + "/model/bytecode/dynamic.cod";
792
  code_file.open(main_name, ios::out | ios::binary | ios::ate);
793
794
  if (!code_file.is_open())
    {
795
      cerr << "Error : Can't open file \"" << main_name << "\" for writing" << endl;
796
797
798
799
800
801
802
803
804
805
806
807
808
      exit(EXIT_FAILURE);
    }

  int count_u;
  int u_count_int = 0;
  BlockSimulationType simulation_type;
  if ((max_endo_lag > 0) && (max_endo_lead > 0))
    simulation_type = SOLVE_TWO_BOUNDARIES_COMPLETE;
  else if ((max_endo_lag >= 0) && (max_endo_lead == 0))
    simulation_type = SOLVE_FORWARD_COMPLETE;
  else
    simulation_type = SOLVE_BACKWARD_COMPLETE;

809
  Write_Inf_To_Bin_File(basename + "/model/bytecode/dynamic.bin", u_count_int, file_open, simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE, symbol_table.endo_nbr());
810
811
812
813
  file_open = true;

  //Temporary variables declaration
  FDIMT_ fdimt(temporary_terms.size());
814
815
816
  fdimt.write(code_file, instruction_number);

  vector<unsigned int> exo, exo_det, other_endo;
817

818
  for (int i = 0; i < symbol_table.exo_det_nbr(); i++)
819
    exo_det.push_back(i);
820
  for (int i = 0; i < symbol_table.exo_nbr(); i++)
821
    exo.push_back(i);
822

823
  map<pair< int, pair<int, int>>, expr_t> first_derivatives_reordered_endo;
824
  map<pair< pair<int, SymbolType>, pair<int, int>>, expr_t>  first_derivatives_reordered_exo;
825
  for (const auto & first_derivative : first_derivatives)
826
    {
827
828
      int deriv_id = first_derivative.first.second;
      unsigned int eq = first_derivative.first.first;
829
830
831
      int symb = getSymbIDByDerivID(deriv_id);
      unsigned int var = symbol_table.getTypeSpecificID(symb);
      int lag = getLagByDerivID(deriv_id);
832
      if (getTypeByDerivID(deriv_id) == SymbolType::endogenous)
833
        first_derivatives_reordered_endo[{ lag, make_pair(var, eq) }] = first_derivative.second;
834
      else if (getTypeByDerivID(deriv_id) == SymbolType::exogenous || getTypeByDerivID(deriv_id) == SymbolType::exogenousDet)
835
        first_derivatives_reordered_exo[{ { lag, getTypeByDerivID(deriv_id) }, { var, eq } }] = first_derivative.second;
836
837
838
839
    }
  int prev_var = -1;
  int prev_lag = -999999999;
  int count_col_endo = 0;
840
  for (map<pair< int, pair<int, int>>, expr_t>::const_iterator it = first_derivatives_reordered_endo.begin();
841
842
843
844
       it != first_derivatives_reordered_endo.end(); it++)
    {
      int var = it->first.second.first;
      int lag = it->first.first;
845
      if (prev_var != var || prev_lag != lag)
846
847
848
849
850
851
        {
          prev_var = var;
          prev_lag = lag;
          count_col_endo++;
        }
    }
852
853
  prev_var = -1;
  prev_lag = -999999999;
854
  SymbolType prev_type{SymbolType::unusedEndogenous}; // Any non-exogenous type would do here
855
  int count_col_exo = 0;
856
  int count_col_det_exo = 0;
857