DynamicModel.cc 270 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
36
37
                           NumericalConstants &num_constants_arg,
                           ExternalFunctionsTable &external_functions_table_arg) :
  ModelTree(symbol_table_arg, num_constants_arg, external_functions_table_arg),
38
39
40
41
  max_lag(0), max_lead(0),
  max_endo_lag(0), max_endo_lead(0),
  max_exo_lag(0), max_exo_lead(0),
  max_exo_det_lag(0), max_exo_det_lead(0),
42
43
44
45
  max_lag_orig(0), max_lead_orig(0),
  max_endo_lag_orig(0), max_endo_lead_orig(0),
  max_exo_lag_orig(0), max_exo_lead_orig(0),
  max_exo_det_lag_orig(0), max_exo_det_lead_orig(0),
46
  dynJacobianColsNbr(0),
47
  global_temporary_terms(true)
sebastien's avatar
sebastien committed
48
49
50
{
}

sebastien's avatar
sebastien committed
51
52
VariableNode *
DynamicModel::AddVariable(int symb_id, int lag)
sebastien's avatar
sebastien committed
53
{
sebastien's avatar
sebastien committed
54
  return AddVariableInternal(symb_id, lag);
sebastien's avatar
sebastien committed
55
56
}

sebastien's avatar
sebastien committed
57
void
58
DynamicModel::compileDerivative(ofstream &code_file, unsigned int &instruction_number, int eq, int symb_id, int lag, const map_idx_t &map_idx) const
59
{
60
  auto it = first_derivatives.find({ eq, getDerivID(symbol_table.getID(eEndogenous, symb_id), lag) });
61
  if (it != first_derivatives.end())
62
    (it->second)->compile(code_file, instruction_number, false, temporary_terms, map_idx, true, false);
63
64
65
  else
    {
      FLDZ_ fldz;
66
      fldz.write(code_file, instruction_number);
67
68
    }
}
69
70

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

sebastien's avatar
sebastien committed
83
void
84
DynamicModel::computeTemporaryTermsOrdered()
sebastien's avatar
sebastien committed
85
{
86
  map<expr_t, pair<int, int>> first_occurence;
87
  map<expr_t, int> reference_count;
sebastien's avatar
sebastien committed
88
  BinaryOpNode *eq_node;
89
90
  first_derivatives_t::const_iterator it;
  first_chain_rule_derivatives_t::const_iterator it_chr;
sebastien's avatar
sebastien committed
91
  ostringstream tmp_s;
92
93
  v_temporary_terms.clear();
  map_idx.clear();
sebastien's avatar
sebastien committed
94

95
  unsigned int nb_blocks = getNbBlocks();
96
  v_temporary_terms = vector<vector<temporary_terms_t>>(nb_blocks);
97
  v_temporary_terms_inuse = vector<temporary_terms_inuse_t>(nb_blocks);
sebastien's avatar
sebastien committed
98
  temporary_terms.clear();
99

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

199
200
201
202
203
void
DynamicModel::computeTemporaryTermsMapping()
{
  // Add a mapping form node ID to temporary terms order
  int j = 0;
204
205
  for (auto temporary_term : temporary_terms)
    map_idx[temporary_term->idx] = j++;
206
207
}

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

Sébastien Villemot's avatar
Sébastien Villemot committed
225
  local_output_type = oMatlabDynamicModelSparse;
226
  if (global_temporary_terms)
Sébastien Villemot's avatar
Sébastien Villemot committed
227
    local_temporary_terms = temporary_terms;
228
229
230
231
232
233
234
235
236
237
238
239

  //----------------------------------------------------------------------
  //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();
240
      nze_exo_det = derivative_exo_det[block].size();
241
242
243
244
      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;
245
      deriv_node_temp_terms_t tef_terms;
Sébastien Villemot's avatar
Sébastien Villemot committed
246
      local_output_type = oMatlabDynamicModelSparse;
247
      if (global_temporary_terms)
Sébastien Villemot's avatar
Sébastien Villemot committed
248
        local_temporary_terms = temporary_terms;
249

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

321
      tmp1_output.str("");
322
      tmp1_output << packageDir(basename + ".block") << "/dynamic_" << block+1 << ".m";
323
      output.open(tmp1_output.str(), ios::out | ios::binary);
324
325
326
327
328
329
330
331
      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)
        {
332
          output << "function [y, g1, g2, g3, varargout] = dynamic_" << block+1 << "(y, x, params, steady_state, jacobian_eval, y_kmin, periods)\n";
333
334
        }
      else if (simulation_type == SOLVE_FORWARD_COMPLETE || simulation_type == SOLVE_BACKWARD_COMPLETE)
335
        output << "function [residual, y, g1, g2, g3, varargout] = dynamic_" << block+1 << "(y, x, params, steady_state, it_, jacobian_eval)\n";
336
      else if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE)
337
        output << "function [residual, y, g1, g2, g3, varargout] = dynamic_" << block+1 << "(y, x, params, steady_state, it_, jacobian_eval)\n";
338
      else
339
        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";
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
      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";
365
366
          output << "    g1 = spalloc(" << block_mfs  << ", " << count_col_endo << ", " << nze << ");\n";
          output << "    g1_x=spalloc(" << block_size << ", " << count_col_exo  << ", " << nze_exo << ");\n";
367
          output << "    g1_xd=spalloc(" << block_size << ", " << count_col_exo_det  << ", " << nze_exo_det << ");\n";
368
          output << "    g1_o=spalloc(" << block_size << ", " << count_col_other_endo << ", " << nze_other_endo << ");\n";
369
370
371
372
373
          output << "  end;\n";
        }
      else
        {
          output << "  if(jacobian_eval)\n";
374
375
          output << "    g1 = spalloc(" << block_size << ", " << count_col_endo << ", " << nze << ");\n";
          output << "    g1_x=spalloc(" << block_size << ", " << count_col_exo  << ", " << nze_exo << ");\n";
376
          output << "    g1_xd=spalloc(" << block_size << ", " << count_col_exo_det  << ", " << nze_exo_det << ");\n";
377
          output << "    g1_o=spalloc(" << block_size << ", " << count_col_other_endo << ", " << nze_other_endo << ");\n";
378
379
380
          output << "  else\n";
          if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
            {
381
382
383
              output << "    g1 = spalloc(" << block_mfs << "*Periods, "
                     << block_mfs << "*(Periods+" << max_leadlag_block[block].first+max_leadlag_block[block].second+1 << ")"
                     << ", " << nze << "*Periods);\n";
384
            }
ferhat's avatar
ferhat committed
385
          else
386
387
388
389
390
391
            {
              output << "    g1 = spalloc(" << block_mfs
                     << ", " << block_mfs << ", " << nze << ");\n";
            }
          output << "  end;\n";
        }
392

393
394
395
396
      output << "  g2=0;g3=0;\n";
      if (v_temporary_terms_inuse[block].size())
        {
          tmp_output.str("");
397
398
          for (int it : v_temporary_terms_inuse[block])
            tmp_output << " T" << it;
399
400
401
402
          output << "  global" << tmp_output.str() << ";\n";
        }
      if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
        {
403
          temporary_terms_t tt2;
404
405
406
407
408
409
410
          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;
411
                  for (auto it : v_temporary_terms[block][i])
412
413
                    {
                      output << "  ";
414
                      // In the following, "Static" is used to avoid getting the "(it_)" subscripting
415
                      it->writeOutput(output, oMatlabStaticModelSparse, local_temporary_terms, {});
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
                      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
445
      temporary_terms_idxs_t temporary_terms_idxs;
446
447
      for (unsigned int i = 0; i < block_size; i++)
        {
448
          temporary_terms_t tt2;
449
450
451
452
          tt2.clear();
          if (v_temporary_terms[block].size())
            {
              output << "  " << "% //Temporary variables" << endl;
453
              for (auto it : v_temporary_terms[block][i])
454
                {
455
                  if (dynamic_cast<AbstractExternalFunctionNode *>(it) != nullptr)
456
                    it->writeExternalFunctionOutput(output, local_output_type, tt2, temporary_terms_idxs, tef_terms);
457

458
                  output << "  " <<  sps;
459
                  it->writeOutput(output, local_output_type, local_temporary_terms, {}, tef_terms);
460
                  output << " = ";
461
                  it->writeOutput(output, local_output_type, tt2, {}, tef_terms);
462
                  // Insert current node into tt2
463
                  tt2.insert(it);
464
465
466
467
468
469
470
471
                  output << ";" << endl;
                }
            }

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

576
          expr_t id = it->second;
577

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

648
          output << "      g1_o(" << eqr+1 << ", " << /*var+1+(lag+block_max_lag)*block_size*/ count_col << ") = ";
649
          id->writeOutput(output, local_output_type, local_temporary_terms, {});
650
651
652
653
654
655
656
657
658
659
660
661
662
          output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                 << "(" << 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:
663
664
665
666
667
668
669
670
          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;
671
          for (auto it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
672
673
674
675
676
            {
              unsigned int eq = it->first.first;
              unsigned int var = it->first.second;
              unsigned int eqr = getBlockEquationID(block, eq);
              unsigned int varr = getBlockVariableID(block, var);
677
              expr_t id = it->second.second;
678
              int lag = it->second.first;
679
680
681
              if (lag == 0)
                {
                  output << "    g1(" << eq+1 << ", " << var+1-block_recursive << ") = ";
682
                  id->writeOutput(output, local_output_type, local_temporary_terms, {});
683
684
685
686
687
688
                  output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr))
                         << "(" << lag
                         << ") " << varr+1
                         << ", equation=" << eqr+1 << endl;
                }

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

725
726
727
728
729
730
731
732
733
734
735
736
737
                  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();
738
                  id->writeOutput(output, local_output_type, local_temporary_terms, {});
739
740
741
742
743
                  output << ";";
                  output << " %2 variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr))
                         << "(" << lag << ") " << varr+1
                         << ", equation=" << eqr+1 << " (" << eq+1 << ")" << endl;
                }
744

sebastien's avatar
sebastien committed
745
#ifdef CONDITION
746
747
              output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
              output << "    condition(" << eqr << ")=u(" << u << "+Per_u_);\n";
sebastien's avatar
sebastien committed
748
#endif
749
750
751
752
            }
          for (unsigned int i = 0; i < block_size; i++)
            {
              if (i >= block_recursive)
753
                output << "  " << Uf[getBlockEquationID(block, i)] << ";\n";
sebastien's avatar
sebastien committed
754
#ifdef CONDITION
755
756
              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
757
#endif
758
            }
sebastien's avatar
sebastien committed
759
#ifdef CONDITION
760
761
762
763
764
765
766
767
768
769
770
771
772
773
          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
774
#endif
775
776
          output << "    end;" << endl;
          output << "  end;" << endl;
777
778
779
780
          break;
        default:
          break;
        }
781
      output << "end" << endl;
782
783
784
      output.close();
    }
}
sebastien's avatar
sebastien committed
785
786

void
787
DynamicModel::writeModelEquationsCode(const string &basename, const map_idx_t &map_idx) const
788
{
789

790
791
  ostringstream tmp_output;
  ofstream code_file;
792
  unsigned int instruction_number = 0;
793
794
  bool file_open = false;

795
796
797
  boost::filesystem::create_directories(basename + "/model/bytecode");

  string main_name = basename + "/model/bytecode/dynamic.cod";
798
  code_file.open(main_name, ios::out | ios::binary | ios::ate);
799
800
  if (!code_file.is_open())
    {
801
      cerr << "Error : Can't open file \"" << main_name << "\" for writing" << endl;
802
803
804
805
806
807
808
809
810
811
812
813
814
      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;

815
  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());
816
817
818
819
  file_open = true;

  //Temporary variables declaration
  FDIMT_ fdimt(temporary_terms.size());
820
821
822
  fdimt.write(code_file, instruction_number);

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

824
  for (int i = 0; i < symbol_table.exo_det_nbr(); i++)
825
    exo_det.push_back(i);
826
  for (int i = 0; i < symbol_table.exo_nbr(); i++)
827
    exo.push_back(i);
828

829
830
  map<pair< int, pair<int, int>>, expr_t> first_derivatives_reordered_endo;
  map<pair< pair<int, int>, pair<int, int>>, expr_t>  first_derivatives_reordered_exo;
831
  for (const auto & first_derivative : first_derivatives)
832
    {
833
834
      int deriv_id = first_derivative.first.second;
      unsigned int eq = first_derivative.first.first;
835
836
837
838
      int symb = getSymbIDByDerivID(deriv_id);
      unsigned int var = symbol_table.getTypeSpecificID(symb);
      int lag = getLagByDerivID(deriv_id);
      if (getTypeByDerivID(deriv_id) == eEndogenous)
839
        first_derivatives_reordered_endo[{ lag, make_pair(var, eq) }] = first_derivative.second;
840
      else if (getTypeByDerivID(deriv_id) == eExogenous || getTypeByDerivID(deriv_id) == eExogenousDet)
841
        first_derivatives_reordered_exo[{ { lag, getTypeByDerivID(deriv_id) }, { var, eq } }] = first_derivative.second;
842
843
844
845
    }
  int prev_var = -1;
  int prev_lag = -999999999;
  int count_col_endo = 0;
846
  for (map<pair< int, pair<int, int>>, expr_t>::const_iterator it = first_derivatives_reordered_endo.begin();
847
848
849
850
       it != first_derivatives_reordered_endo.end(); it++)
    {
      int var = it->first.second.first;
      int lag = it->first.first;
851
      if (prev_var != var || prev_lag != lag)
852
853
854
855
856
857
        {
          prev_var = var;
          prev_lag = lag;
          count_col_endo++;
        }
    }
858
859
  prev_var = -1;
  prev_lag = -999999999;
860
  int prev_type = -1;
861
  int count_col_exo = 0;
862
  int count_col_det_exo = 0;
863

864
  for (map<pair< pair<int, int>, pair<int, int>>, expr_t>::const_iterator it = first_derivatives_reordered_exo.begin();
865
866
867
       it != first_derivatives_reordered_exo.end(); it++)
    {
      int var = it->first.second.first;
868
869
870
      int lag = it->first.first.first;
      int type = it->first.first.second;
      if (prev_var != var || prev_lag != lag || prev_type != type)
871
872
873
        {
          prev_var = var;
          prev_lag =<