DynamicModel.cc 290 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),
42
43
44
45
  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),
46
47
48
49
  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),
50
  dynJacobianColsNbr(0),
51
  global_temporary_terms(true)
sebastien's avatar
sebastien committed
52
53
54
{
}

sebastien's avatar
sebastien committed
55
56
VariableNode *
DynamicModel::AddVariable(int symb_id, int lag)
sebastien's avatar
sebastien committed
57
{
sebastien's avatar
sebastien committed
58
  return AddVariableInternal(symb_id, lag);
sebastien's avatar
sebastien committed
59
60
}

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

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

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

99
  unsigned int nb_blocks = getNbBlocks();
100
  v_temporary_terms = vector<vector<temporary_terms_t>>(nb_blocks);
101
  v_temporary_terms_inuse = vector<temporary_terms_inuse_t>(nb_blocks);
sebastien's avatar
sebastien committed
102
  temporary_terms.clear();
103

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

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

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

229
  local_output_type = ExprNodeOutputType::matlabDynamicModelSparse;
230
  if (global_temporary_terms)
Sébastien Villemot's avatar
Sébastien Villemot committed
231
    local_temporary_terms = temporary_terms;
232
233
234
235
236
237
238
239
240
241
242
243

  //----------------------------------------------------------------------
  //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();
244
      nze_exo_det = derivative_exo_det[block].size();
245
246
247
248
      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;
249
      deriv_node_temp_terms_t tef_terms;
250
      local_output_type = ExprNodeOutputType::matlabDynamicModelSparse;
251
      if (global_temporary_terms)
Sébastien Villemot's avatar
Sébastien Villemot committed
252
        local_temporary_terms = temporary_terms;
253

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

325
      tmp1_output.str("");
326
      tmp1_output << packageDir(basename + ".block") << "/dynamic_" << block+1 << ".m";
327
      output.open(tmp1_output.str(), ios::out | ios::binary);
328
329
330
331
332
333
334
335
      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)
        {
336
          output << "function [y, g1, g2, g3, varargout] = dynamic_" << block+1 << "(y, x, params, steady_state, jacobian_eval, y_kmin, periods)\n";
337
338
        }
      else if (simulation_type == SOLVE_FORWARD_COMPLETE || simulation_type == SOLVE_BACKWARD_COMPLETE)
339
        output << "function [residual, y, g1, g2, g3, varargout] = dynamic_" << block+1 << "(y, x, params, steady_state, it_, jacobian_eval)\n";
340
      else if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE)
341
        output << "function [residual, y, g1, g2, g3, varargout] = dynamic_" << block+1 << "(y, x, params, steady_state, it_, jacobian_eval)\n";
342
      else
343
        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";
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
      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";
369
370
          output << "    g1 = spalloc(" << block_mfs  << ", " << count_col_endo << ", " << nze << ");\n";
          output << "    g1_x=spalloc(" << block_size << ", " << count_col_exo  << ", " << nze_exo << ");\n";
371
          output << "    g1_xd=spalloc(" << block_size << ", " << count_col_exo_det  << ", " << nze_exo_det << ");\n";
372
          output << "    g1_o=spalloc(" << block_size << ", " << count_col_other_endo << ", " << nze_other_endo << ");\n";
373
374
375
376
377
          output << "  end;\n";
        }
      else
        {
          output << "  if(jacobian_eval)\n";
378
379
          output << "    g1 = spalloc(" << block_size << ", " << count_col_endo << ", " << nze << ");\n";
          output << "    g1_x=spalloc(" << block_size << ", " << count_col_exo  << ", " << nze_exo << ");\n";
380
          output << "    g1_xd=spalloc(" << block_size << ", " << count_col_exo_det  << ", " << nze_exo_det << ");\n";
381
          output << "    g1_o=spalloc(" << block_size << ", " << count_col_other_endo << ", " << nze_other_endo << ");\n";
382
383
384
          output << "  else\n";
          if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
            {
385
386
387
              output << "    g1 = spalloc(" << block_mfs << "*Periods, "
                     << block_mfs << "*(Periods+" << max_leadlag_block[block].first+max_leadlag_block[block].second+1 << ")"
                     << ", " << nze << "*Periods);\n";
388
            }
ferhat's avatar
ferhat committed
389
          else
390
391
392
393
394
395
            {
              output << "    g1 = spalloc(" << block_mfs
                     << ", " << block_mfs << ", " << nze << ");\n";
            }
          output << "  end;\n";
        }
396

397
398
399
400
      output << "  g2=0;g3=0;\n";
      if (v_temporary_terms_inuse[block].size())
        {
          tmp_output.str("");
401
402
          for (int it : v_temporary_terms_inuse[block])
            tmp_output << " T" << it;
403
404
405
406
          output << "  global" << tmp_output.str() << ";\n";
        }
      if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
        {
407
          temporary_terms_t tt2;
408
409
410
411
412
413
414
          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;
415
                  for (auto it : v_temporary_terms[block][i])
416
417
                    {
                      output << "  ";
418
                      // In the following, "Static" is used to avoid getting the "(it_)" subscripting
419
                      it->writeOutput(output, ExprNodeOutputType::matlabStaticModelSparse, local_temporary_terms, {});
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
445
446
447
448
                      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
449
      temporary_terms_idxs_t temporary_terms_idxs;
450
451
      for (unsigned int i = 0; i < block_size; i++)
        {
452
          temporary_terms_t tt2;
453
454
455
456
          tt2.clear();
          if (v_temporary_terms[block].size())
            {
              output << "  " << "% //Temporary variables" << endl;
457
              for (auto it : v_temporary_terms[block][i])
458
                {
459
                  if (dynamic_cast<AbstractExternalFunctionNode *>(it) != nullptr)
460
                    it->writeExternalFunctionOutput(output, local_output_type, tt2, temporary_terms_idxs, tef_terms);
461

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

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

580
          expr_t id = it->second;
581

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

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

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

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

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

void
791
DynamicModel::writeModelEquationsCode(const string &basename, const map_idx_t &map_idx) const
792
{
793

794
795
  ostringstream tmp_output;
  ofstream code_file;
796
  unsigned int instruction_number = 0;
797
798
  bool file_open = false;

799
800
801
  boost::filesystem::create_directories(basename + "/model/bytecode");

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

819
  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());
820
821
822
823
  file_open = true;

  //Temporary variables declaration
  FDIMT_ fdimt(temporary_terms.size());
824
825
826
  fdimt.write(code_file, instruction_number);

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

828
  for (int i = 0; i < symbol_table.exo_det_nbr(); i++)
829
    exo_det.push_back(i);
830
  for (int i = 0; i < symbol_table.exo_nbr(); i++)
831
    exo.push_back(i);
832

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