DynamicModel.cc 274 KB
Newer Older
sebastien's avatar
sebastien committed
1
/*
2
 * Copyright © 2003-2021 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
#include <algorithm>
25
#include <numeric>
26
#include <regex>
sebastien's avatar
sebastien committed
27

28
#include "DynamicModel.hh"
sebastien's avatar
sebastien committed
29

30
31
32
void
DynamicModel::copyHelper(const DynamicModel &m)
{
33
  auto f = [this](const ExprNode *e) { return e->clone(*this); };
34
35
36

  for (const auto &it : m.static_only_equations)
    static_only_equations.push_back(dynamic_cast<BinaryOpNode *>(f(it)));
37
38
39
40
41
42
43
44
45
46
47
48
49
50

    auto convert_block_derivative = [f](const map<tuple<int, int, int>, expr_t> &dt)
                                    {
                                      map<tuple<int, int, int>, expr_t> dt2;
                                      for (const auto &it : dt)
                                        dt2[it.first] = f(it.second);
                                      return dt2;
                                    };
  for (const auto &it : m.blocks_derivatives_other_endo)
    blocks_derivatives_other_endo.emplace_back(convert_block_derivative(it));
  for (const auto &it : m.blocks_derivatives_exo)
    blocks_derivatives_exo.emplace_back(convert_block_derivative(it));
  for (const auto &it : m.blocks_derivatives_exo_det)
    blocks_derivatives_exo_det.emplace_back(convert_block_derivative(it));
51
52
53

  for (const auto &[key, expr] : m.pac_expectation_substitution)
    pac_expectation_substitution.emplace(key, f(expr));
54
55
}

sebastien's avatar
sebastien committed
56
DynamicModel::DynamicModel(SymbolTable &symbol_table_arg,
57
                           NumericalConstants &num_constants_arg,
58
                           ExternalFunctionsTable &external_functions_table_arg,
Houtan Bastani's avatar
Houtan Bastani committed
59
60
                           TrendComponentModelTable &trend_component_model_table_arg,
                           VarModelTable &var_model_table_arg) :
Sébastien Villemot's avatar
Sébastien Villemot committed
61
  ModelTree{symbol_table_arg, num_constants_arg, external_functions_table_arg, true},
62
63
  trend_component_model_table{trend_component_model_table_arg},
  var_model_table{var_model_table_arg}
sebastien's avatar
sebastien committed
64
65
66
{
}

67
DynamicModel::DynamicModel(const DynamicModel &m) :
Sébastien Villemot's avatar
Sébastien Villemot committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
  ModelTree{m},
  trend_component_model_table{m.trend_component_model_table},
  var_model_table{m.var_model_table},
  balanced_growth_test_tol{m.balanced_growth_test_tol},
  static_only_equations_lineno{m.static_only_equations_lineno},
  static_only_equations_equation_tags{m.static_only_equations_equation_tags},
  deriv_id_table{m.deriv_id_table},
  inv_deriv_id_table{m.inv_deriv_id_table},
  dyn_jacobian_cols_table{m.dyn_jacobian_cols_table},
  max_lag{m.max_lag},
  max_lead{m.max_lead},
  max_endo_lag{m.max_endo_lag},
  max_endo_lead{m.max_endo_lead},
  max_exo_lag{m.max_exo_lag},
  max_exo_lead{m.max_exo_lead},
  max_exo_det_lag{m.max_exo_det_lag},
  max_exo_det_lead{m.max_exo_det_lead},
  max_lag_orig{m.max_lag_orig},
  max_lead_orig{m.max_lead_orig},
  max_lag_with_diffs_expanded_orig{m.max_lag_with_diffs_expanded_orig},
  max_endo_lag_orig{m.max_endo_lag_orig},
  max_endo_lead_orig{m.max_endo_lead_orig},
  max_exo_lag_orig{m.max_exo_lag_orig},
  max_exo_lead_orig{m.max_exo_lead_orig},
  max_exo_det_lag_orig{m.max_exo_det_lag_orig},
  max_exo_det_lead_orig{m.max_exo_det_lead_orig},
  xrefs{m.xrefs},
  xref_param{m.xref_param},
  xref_endo{m.xref_endo},
  xref_exo{m.xref_exo},
  xref_exo_det{m.xref_exo_det},
  nonzero_hessian_eqs{m.nonzero_hessian_eqs},
100
101
  dynJacobianColsNbr{m.dynJacobianColsNbr},
  variableMapping{m.variableMapping},
102
103
104
105
106
107
108
  blocks_other_endo{m.blocks_other_endo},
  blocks_exo{m.blocks_exo},
  blocks_exo_det{m.blocks_exo_det},
  blocks_jacob_cols_endo{m.blocks_jacob_cols_endo},
  blocks_jacob_cols_other_endo{m.blocks_jacob_cols_other_endo},
  blocks_jacob_cols_exo{m.blocks_jacob_cols_exo},
  blocks_jacob_cols_exo_det{m.blocks_jacob_cols_exo_det},
109
110
111
112
113
114
115
116
  var_expectation_functions_to_write{m.var_expectation_functions_to_write},
  pac_mce_alpha_symb_ids{m.pac_mce_alpha_symb_ids},
  pac_h0_indices{m.pac_h0_indices},
  pac_h1_indices{m.pac_h1_indices},
  pac_mce_z1_symb_ids{m.pac_mce_z1_symb_ids},
  pac_eqtag_and_lag{m.pac_eqtag_and_lag},
  pac_model_info{m.pac_model_info},
  pac_equation_info{m.pac_equation_info}
sebastien's avatar
sebastien committed
117
{
118
119
120
121
122
123
124
125
126
127
  copyHelper(m);
}

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

  assert(&trend_component_model_table == &m.trend_component_model_table);
  assert(&var_model_table == &m.var_model_table);
128
  balanced_growth_test_tol = m.balanced_growth_test_tol;
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144

  static_only_equations_lineno = m.static_only_equations_lineno;
  static_only_equations_equation_tags = m.static_only_equations_equation_tags;
  deriv_id_table = m.deriv_id_table;
  inv_deriv_id_table = m.inv_deriv_id_table;
  dyn_jacobian_cols_table = m.dyn_jacobian_cols_table;
  max_lag = m.max_lag;
  max_lead = m.max_lead;
  max_endo_lag = m.max_endo_lag;
  max_endo_lead = m.max_endo_lead;
  max_exo_lag = m.max_exo_lag;
  max_exo_lead = m.max_exo_lead;
  max_exo_det_lag = m.max_exo_det_lag;
  max_exo_det_lead = m.max_exo_det_lead;
  max_lag_orig = m.max_lag_orig;
  max_lead_orig = m.max_lead_orig;
145
  max_lag_with_diffs_expanded_orig = m.max_lag_with_diffs_expanded_orig;
146
147
148
149
150
151
152
  max_endo_lag_orig = m.max_endo_lag_orig;
  max_endo_lead_orig = m.max_endo_lead_orig;
  max_exo_lag_orig = m.max_exo_lag_orig;
  max_exo_lead_orig = m.max_exo_lead_orig;
  max_exo_det_lag_orig = m.max_exo_det_lag_orig;
  max_exo_det_lead_orig = m.max_exo_det_lead_orig;
  xrefs = m.xrefs;
Sébastien Villemot's avatar
Sébastien Villemot committed
153
  xref_param = m.xref_param;
154
155
156
157
  xref_endo = m.xref_endo;
  xref_exo = m.xref_exo;
  xref_exo_det = m.xref_exo_det;
  nonzero_hessian_eqs = m.nonzero_hessian_eqs;
158
159
  dynJacobianColsNbr = m.dynJacobianColsNbr;
  variableMapping = m.variableMapping;
160
161
162
  blocks_derivatives_other_endo.clear();
  blocks_derivatives_exo.clear();
  blocks_derivatives_exo_det.clear();
163
164
165
166
167
168
169
  blocks_other_endo = m.blocks_other_endo;
  blocks_exo = m.blocks_exo;
  blocks_exo_det = m.blocks_exo_det;
  blocks_jacob_cols_endo = m.blocks_jacob_cols_endo;
  blocks_jacob_cols_other_endo = m.blocks_jacob_cols_other_endo;
  blocks_jacob_cols_exo = m.blocks_jacob_cols_exo;
  blocks_jacob_cols_exo_det = m.blocks_jacob_cols_exo_det;
170
171
172

  var_expectation_functions_to_write = m.var_expectation_functions_to_write;

173
174
175
176
177
178
179
180
181
  pac_mce_alpha_symb_ids = m.pac_mce_alpha_symb_ids;
  pac_h0_indices = m.pac_h0_indices;
  pac_h1_indices = m.pac_h1_indices;
  pac_mce_z1_symb_ids = m.pac_mce_z1_symb_ids;
  pac_eqtag_and_lag = m.pac_eqtag_and_lag;
  pac_expectation_substitution.clear();
  pac_model_info = m.pac_model_info;
  pac_equation_info = m.pac_equation_info;

182
183
184
  copyHelper(m);

  return *this;
sebastien's avatar
sebastien committed
185
186
}

sebastien's avatar
sebastien committed
187
void
188
DynamicModel::compileDerivative(ofstream &code_file, unsigned int &instruction_number, int eq, int symb_id, int lag, const temporary_terms_t &temporary_terms, const temporary_terms_idxs_t &temporary_terms_idxs) const
189
{
190
191
  if (auto it = derivatives[1].find({ eq, getDerivID(symbol_table.getID(SymbolType::endogenous, symb_id), lag) });
      it != derivatives[1].end())
192
    it->second->compile(code_file, instruction_number, false, temporary_terms, temporary_terms_idxs, true, false);
193
194
195
  else
    {
      FLDZ_ fldz;
196
      fldz.write(code_file, instruction_number);
197
198
    }
}
199
200

void
201
DynamicModel::compileChainRuleDerivative(ofstream &code_file, unsigned int &instruction_number, int blk, int eq, int var, int lag, const temporary_terms_t &temporary_terms, const temporary_terms_idxs_t &temporary_terms_idxs) const
202
{
203
204
  if (auto it = blocks_derivatives[blk].find({ eq, var, lag });
      it != blocks_derivatives[blk].end())
205
    it->second->compile(code_file, instruction_number, false, temporary_terms, temporary_terms_idxs, true, false);
206
  else
207
208
    {
      FLDZ_ fldz;
209
      fldz.write(code_file, instruction_number);
210
    }
211
212
}

sebastien's avatar
sebastien committed
213
void
214
DynamicModel::additionalBlockTemporaryTerms(int blk,
215
216
                                            vector<vector<temporary_terms_t>> &blocks_temporary_terms,
                                            map<expr_t, tuple<int, int, int>> &reference_count) const
sebastien's avatar
sebastien committed
217
{
218
  for (const auto &[ignore, d] : blocks_derivatives_exo[blk])
219
    d->computeBlockTemporaryTerms(blk, blocks[blk].size, blocks_temporary_terms, reference_count);
220
  for (const auto &[ignore, d] : blocks_derivatives_exo_det[blk])
221
    d->computeBlockTemporaryTerms(blk, blocks[blk].size, blocks_temporary_terms, reference_count);
222
  for (const auto &[ignore, d] : blocks_derivatives_other_endo[blk])
223
    d->computeBlockTemporaryTerms(blk, blocks[blk].size, blocks_temporary_terms, reference_count);
224
225
}

226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
void
DynamicModel::writeDynamicPerBlockHelper(int blk, ostream &output, ExprNodeOutputType output_type, temporary_terms_t &temporary_terms, int nze_stochastic, int nze_deterministic, int nze_exo, int nze_exo_det, int nze_other_endo) const
{
  BlockSimulationType simulation_type = blocks[blk].simulation_type;
  int block_size = blocks[blk].size;
  int block_mfs_size = blocks[blk].mfs_size;
  int block_recursive_size = blocks[blk].getRecursiveSize();

  deriv_node_temp_terms_t tef_terms;

  auto write_eq_tt = [&](int eq)
                     {
                       for (auto it : blocks_temporary_terms[blk][eq])
                         {
                           if (dynamic_cast<AbstractExternalFunctionNode *>(it))
                             it->writeExternalFunctionOutput(output, output_type, temporary_terms, blocks_temporary_terms_idxs, tef_terms);

                           output << "  ";
                           it->writeOutput(output, output_type, blocks_temporary_terms[blk][eq], blocks_temporary_terms_idxs, tef_terms);
                           output << '=';
                           it->writeOutput(output, output_type, temporary_terms, blocks_temporary_terms_idxs, tef_terms);
                           temporary_terms.insert(it);
                           output << ';' << endl;
                         }
                     };

  // The equations
  for (int eq = 0; eq < block_size; eq++)
    {
      write_eq_tt(eq);

      EquationType equ_type = getBlockEquationType(blk, eq);
      BinaryOpNode *e = getBlockEquationExpr(blk, eq);
      expr_t lhs = e->arg1, rhs = e->arg2;
      switch (simulation_type)
        {
        case BlockSimulationType::evaluateBackward:
        case BlockSimulationType::evaluateForward:
          evaluation:
          if (equ_type == EquationType::evaluateRenormalized)
            {
              e = getBlockEquationRenormalizedExpr(blk, eq);
              lhs = e->arg1;
              rhs = e->arg2;
            }
          else if (equ_type != EquationType::evaluate)
            {
              cerr << "Type mismatch for equation " << getBlockEquationID(blk, eq)+1  << endl;
              exit(EXIT_FAILURE);
            }
          output << "  ";
          lhs->writeOutput(output, output_type, temporary_terms, blocks_temporary_terms_idxs);
          output << '=';
          rhs->writeOutput(output, output_type, temporary_terms, blocks_temporary_terms_idxs);
          output << ';' << endl;
          break;
        case BlockSimulationType::solveBackwardSimple:
        case BlockSimulationType::solveForwardSimple:
        case BlockSimulationType::solveBackwardComplete:
        case BlockSimulationType::solveForwardComplete:
        case BlockSimulationType::solveTwoBoundariesComplete:
        case BlockSimulationType::solveTwoBoundariesSimple:
          if (eq < block_recursive_size)
            goto evaluation;
          output << "  residual" << LEFT_ARRAY_SUBSCRIPT(output_type)
                 << eq-block_recursive_size+ARRAY_SUBSCRIPT_OFFSET(output_type)
                 << RIGHT_ARRAY_SUBSCRIPT(output_type) << "=(";
          goto end;
        default:
        end:
          lhs->writeOutput(output, output_type, temporary_terms, blocks_temporary_terms_idxs);
          output << ")-(";
          rhs->writeOutput(output, output_type, temporary_terms, blocks_temporary_terms_idxs);
          output << ");" << endl;
        }
    }

  // The Jacobian if we have to solve the block

  // Write temporary terms for derivatives
  write_eq_tt(blocks[blk].size);

308
309
310
311
  if (isCOutput(output_type))
    output << "  if (stochastic_mode) {" << endl;
  else
    output << "  if stochastic_mode" << endl;
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328

  ostringstream i_output, j_output, v_output;
  int line_counter = ARRAY_SUBSCRIPT_OFFSET(output_type);
  for (const auto &[indices, d] : blocks_derivatives[blk])
    {
      auto [eq, var, lag] = indices;
      int jacob_col = blocks_jacob_cols_endo[blk].at({ var, lag });
      i_output << "    g1_i" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
               << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=' << eq+1 << ';' << endl;
      j_output << "    g1_j" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
               << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=' << jacob_col+1 << ';' << endl;
      v_output << "    g1_v" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
               << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=';
      d->writeOutput(v_output, output_type, temporary_terms, blocks_temporary_terms_idxs);
      v_output << ';' << endl;
      line_counter++;
    }
329
  assert(line_counter == nze_stochastic+ARRAY_SUBSCRIPT_OFFSET(output_type));
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
  output << i_output.str() << j_output.str() << v_output.str();

  i_output.str("");
  j_output.str("");
  v_output.str("");
  line_counter = ARRAY_SUBSCRIPT_OFFSET(output_type);
  for (const auto &[indices, d] : blocks_derivatives_exo[blk])
    {
      auto [eq, var, lag] = indices;
      int jacob_col = blocks_jacob_cols_exo[blk].at({ var, lag });
      i_output << "    g1_x_i" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
               << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=' << eq+1 << ';' << endl;
      j_output << "    g1_x_j" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
               << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=' << jacob_col+1 << ';' << endl;
      v_output << "    g1_x_v" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
               << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=';
      d->writeOutput(v_output, output_type, temporary_terms, blocks_temporary_terms_idxs);
      v_output << ';' << endl;
      line_counter++;
    }
350
  assert(line_counter == nze_exo+ARRAY_SUBSCRIPT_OFFSET(output_type));
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
  output << i_output.str() << j_output.str() << v_output.str();

  i_output.str("");
  j_output.str("");
  v_output.str("");
  line_counter = ARRAY_SUBSCRIPT_OFFSET(output_type);
  for (const auto &[indices, d] : blocks_derivatives_exo_det[blk])
    {
      auto [eq, var, lag] = indices;
      int jacob_col = blocks_jacob_cols_exo_det[blk].at({ var, lag });
      i_output << "    g1_xd_i" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
               << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=' << eq+1 << ';' << endl;
      j_output << "    g1_xd_j" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
               << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=' << jacob_col+1 << ';' << endl;
      v_output << "    g1_xd_v" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
               << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=';
      d->writeOutput(v_output, output_type, temporary_terms, blocks_temporary_terms_idxs);
      v_output << ';' << endl;
      line_counter++;
    }
371
  assert(line_counter == nze_exo_det+ARRAY_SUBSCRIPT_OFFSET(output_type));
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
  output << i_output.str() << j_output.str() << v_output.str();

  i_output.str("");
  j_output.str("");
  v_output.str("");
  line_counter = ARRAY_SUBSCRIPT_OFFSET(output_type);
  for (const auto &[indices, d] : blocks_derivatives_other_endo[blk])
    {
      auto [eq, var, lag] = indices;
      int jacob_col = blocks_jacob_cols_other_endo[blk].at({ var, lag });
      i_output << "    g1_o_i" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
               << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=' << eq+1 << ';' << endl;
      j_output << "    g1_o_j" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
               << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=' << jacob_col+1 << ';' << endl;
      v_output << "    g1_o_v" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
               << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=';
      d->writeOutput(v_output, output_type, temporary_terms, blocks_temporary_terms_idxs);
      v_output << ';' << endl;
      line_counter++;
    }
392
  assert(line_counter == nze_other_endo+ARRAY_SUBSCRIPT_OFFSET(output_type));
393
394
395
396
397
398
  output << i_output.str() << j_output.str() << v_output.str();

  // Deterministic mode
  if (simulation_type != BlockSimulationType::evaluateForward
      && simulation_type != BlockSimulationType::evaluateBackward)
    {
399
400
401
402
      if (isCOutput(output_type))
        output << "  } else {" << endl;
      else
        output << "  else" << endl;
403
404
405
406
407
408
409
410
411
412
413
      i_output.str("");
      j_output.str("");
      v_output.str("");
      line_counter = ARRAY_SUBSCRIPT_OFFSET(output_type);
      if (simulation_type == BlockSimulationType::solveBackwardSimple
          || simulation_type == BlockSimulationType::solveForwardSimple
          || simulation_type == BlockSimulationType::solveBackwardComplete
          || simulation_type == BlockSimulationType::solveForwardComplete)
        for (const auto &[indices, d] : blocks_derivatives[blk])
          {
            auto [eq, var, lag] = indices;
414
            if (lag == 0 && eq >= block_recursive_size && var >= block_recursive_size)
415
416
              {
                i_output << "    g1_i" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
417
418
                         << RIGHT_ARRAY_SUBSCRIPT(output_type) << '='
                         << eq+1-block_recursive_size << ';' << endl;
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
445
446
447
448
                j_output << "    g1_j" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
                         << RIGHT_ARRAY_SUBSCRIPT(output_type) << '='
                         << var+1-block_recursive_size << ';' << endl;
                v_output << "    g1_v" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
                         << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=';
                d->writeOutput(v_output, output_type, temporary_terms, blocks_temporary_terms_idxs);
                v_output << ';' << endl;
                line_counter++;
              }
          }
      else // solveTwoBoundariesSimple || solveTwoBoundariesComplete
        for (const auto &[indices, d] : blocks_derivatives[blk])
        {
          auto [eq, var, lag] = indices;
          assert(lag >= -1 && lag <= 1);
          if (eq >= block_recursive_size && var >= block_recursive_size)
            {
              i_output << "    g1_i" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
                       << RIGHT_ARRAY_SUBSCRIPT(output_type) << '='
                       << eq+1-block_recursive_size << ';' << endl;
              j_output << "    g1_j" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
                       << RIGHT_ARRAY_SUBSCRIPT(output_type) << '='
                       << var+1-block_recursive_size+block_mfs_size*(lag+1) << ';' << endl;
              v_output << "    g1_v" << LEFT_ARRAY_SUBSCRIPT(output_type) << line_counter
                       << RIGHT_ARRAY_SUBSCRIPT(output_type) << '=';
              d->writeOutput(v_output, output_type, temporary_terms, blocks_temporary_terms_idxs);
              v_output << ';' << endl;
              line_counter++;
            }
        }
449
      assert(line_counter == nze_deterministic+ARRAY_SUBSCRIPT_OFFSET(output_type));
450
451
      output << i_output.str() << j_output.str() << v_output.str();
    }
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
  if (isCOutput(output_type))
    output << "  }" << endl;
  else
    output << "  end" << endl;
}

int
DynamicModel::nzeDeterministicJacobianForBlock(int blk) const
{
  BlockSimulationType simulation_type = blocks[blk].simulation_type;
  int block_recursive_size = blocks[blk].getRecursiveSize();

  int nze_deterministic = 0;
  if (simulation_type == BlockSimulationType::solveTwoBoundariesComplete
      || simulation_type == BlockSimulationType::solveTwoBoundariesSimple)
    nze_deterministic = count_if(blocks_derivatives[blk].begin(), blocks_derivatives[blk].end(),
                                 [=](const auto &kv) {
                                   auto [eq, var, lag] = kv.first;
                                   return eq >= block_recursive_size && var >= block_recursive_size;
                                 });
  else if (simulation_type == BlockSimulationType::solveBackwardSimple
           || simulation_type == BlockSimulationType::solveForwardSimple
           || simulation_type == BlockSimulationType::solveBackwardComplete
           || simulation_type == BlockSimulationType::solveForwardComplete)
    nze_deterministic = count_if(blocks_derivatives[blk].begin(), blocks_derivatives[blk].end(),
477
                                 [=](const auto &kv) {
478
                                   auto [eq, var, lag] = kv.first;
479
                                   return lag == 0 && eq >= block_recursive_size && var >= block_recursive_size;
480
481
                                 });
  return nze_deterministic;
482
483
}

sebastien's avatar
sebastien committed
484
void
485
DynamicModel::writeDynamicPerBlockMFiles(const string &basename) const
486
{
487
  temporary_terms_t temporary_terms; // Temp terms written so far
488

489
  for (int blk = 0; blk < static_cast<int>(blocks.size()); blk++)
490
    {
491
492
493
494
      BlockSimulationType simulation_type = blocks[blk].simulation_type;
      int block_size = blocks[blk].size;
      int block_mfs_size = blocks[blk].mfs_size;

495
496
      // Number of nonzero derivatives for the various Jacobians
      int nze_stochastic = blocks_derivatives[blk].size();
497
      int nze_deterministic = nzeDeterministicJacobianForBlock(blk);
498
499
500
501
      int nze_other_endo = blocks_derivatives_other_endo[blk].size();
      int nze_exo = blocks_derivatives_exo[blk].size();
      int nze_exo_det = blocks_derivatives_exo_det[blk].size();

502
503
504
      string filename = packageDir(basename + ".block") + "/dynamic_" + to_string(blk+1) + ".m";
      ofstream output;
      output.open(filename, ios::out | ios::binary);
505
506
507
508
509
      if (!output.is_open())
        {
          cerr << "ERROR: Can't open file " << filename << " for writing" << endl;
          exit(EXIT_FAILURE);
        }
510

511
      output << "%" << endl
512
             << "% " << filename << " : Computes dynamic version of one block" << endl
513
514
515
             << "%" << endl
             << "% Warning : this file is generated automatically by Dynare" << endl
             << "%           from model file (.mod)" << endl << endl
516
             << "%" << endl;
517
518
      if (simulation_type == BlockSimulationType::evaluateBackward
          || simulation_type == BlockSimulationType::evaluateForward)
519
        output << "function [y, T, g1, varargout] = dynamic_" << blk+1 << "(y, x, params, steady_state, T, it_, stochastic_mode)" << endl;
520
      else
521
        output << "function [residual, y, T, g1, varargout] = dynamic_" << blk+1 << "(y, x, params, steady_state, T, it_, stochastic_mode)" << endl;
522

523
      output << "  % ////////////////////////////////////////////////////////////////////////" << endl
524
             << "  % //" << string("                     Block ").substr(static_cast<int>(log10(blk + 1))) << blk+1
525
             << "                                        //" << endl
526
527
             << "  % //                     Simulation type "
             << BlockSim(simulation_type) << "  //" << endl
528
             << "  % ////////////////////////////////////////////////////////////////////////" << endl;
529

530
531
      if (simulation_type != BlockSimulationType::evaluateForward
          && simulation_type != BlockSimulationType::evaluateBackward)
532
        output << "  residual=zeros(" << block_mfs_size << ",1);" << endl;
533

534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
      output << "  if stochastic_mode" << endl
             << "    g1_i=zeros(" << nze_stochastic << ",1);" << endl
             << "    g1_j=zeros(" << nze_stochastic << ",1);" << endl
             << "    g1_v=zeros(" << nze_stochastic << ",1);" << endl
             << "    g1_x_i=zeros(" << nze_exo << ",1);" << endl
             << "    g1_x_j=zeros(" << nze_exo << ",1);" << endl
             << "    g1_x_v=zeros(" << nze_exo << ",1);" << endl
             << "    g1_xd_i=zeros(" << nze_exo_det << ",1);" << endl
             << "    g1_xd_j=zeros(" << nze_exo_det << ",1);" << endl
             << "    g1_xd_v=zeros(" << nze_exo_det << ",1);" << endl
             << "    g1_o_i=zeros(" << nze_other_endo << ",1);" << endl
             << "    g1_o_j=zeros(" << nze_other_endo << ",1);" << endl
             << "    g1_o_v=zeros(" << nze_other_endo << ",1);" << endl;
      if (simulation_type != BlockSimulationType::evaluateForward
          && simulation_type != BlockSimulationType::evaluateBackward)
        output << "  else" << endl
               << "    g1_i=zeros(" << nze_deterministic << ",1);" << endl
               << "    g1_j=zeros(" << nze_deterministic << ",1);" << endl
               << "    g1_v=zeros(" << nze_deterministic << ",1);" << endl;
      output << "  end" << endl
             << endl;
555

556
557
      writeDynamicPerBlockHelper(blk, output, ExprNodeOutputType::matlabDynamicModel, temporary_terms,
                                 nze_stochastic, nze_deterministic, nze_exo, nze_exo_det, nze_other_endo);
558

559
      output << endl
560
             << "  if stochastic_mode" << endl
561
             << "    g1=sparse(g1_i, g1_j, g1_v, " << block_size << ", " << blocks_jacob_cols_endo[blk].size() << ");" << endl
562
563
             << "    varargout{1}=sparse(g1_x_i, g1_x_j, g1_x_v, " << block_size << ", " << blocks_jacob_cols_exo[blk].size() << ");" << endl
             << "    varargout{2}=sparse(g1_xd_i, g1_xd_j, g1_xd_v, " << block_size << ", " << blocks_jacob_cols_exo_det[blk].size() << ");" << endl
564
565
             << "    varargout{3}=sparse(g1_o_i, g1_o_j, g1_o_v, " << block_size << ", " << blocks_jacob_cols_other_endo[blk].size() << ");" << endl
             << "  else" << endl;
566
567
      switch (simulation_type)
        {
568
569
        case BlockSimulationType::evaluateForward:
        case BlockSimulationType::evaluateBackward:
570
          output << "    g1=[];" << endl;
571
          break;
572
573
574
575
        case BlockSimulationType::solveBackwardSimple:
        case BlockSimulationType::solveForwardSimple:
        case BlockSimulationType::solveBackwardComplete:
        case BlockSimulationType::solveForwardComplete:
576
          output << "    g1=sparse(g1_i, g1_j, g1_v, " << block_mfs_size
577
                 << ", " << block_mfs_size << ");" << endl;
578
          break;
579
580
        case BlockSimulationType::solveTwoBoundariesSimple:
        case BlockSimulationType::solveTwoBoundariesComplete:
581
          output << "    g1=sparse(g1_i, g1_j, g1_v, " << block_mfs_size
582
                 << ", " << 3*block_mfs_size << ");" << endl;
583
584
585
586
          break;
        default:
          break;
        }
587
588
      output << "  end" << endl
             << "end" << endl;
589
590
591
      output.close();
    }
}
sebastien's avatar
sebastien committed
592

593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
void
DynamicModel::writeDynamicPerBlockCFiles(const string &basename) const
{
  temporary_terms_t temporary_terms; // Temp terms written so far

  for (int blk = 0; blk < static_cast<int>(blocks.size()); blk++)
    {
      BlockSimulationType simulation_type = blocks[blk].simulation_type;
      int block_size = blocks[blk].size;
      int block_mfs_size = blocks[blk].mfs_size;

      // Number of nonzero derivatives for the various Jacobians
      int nze_stochastic = blocks_derivatives[blk].size();
      int nze_deterministic = nzeDeterministicJacobianForBlock(blk);
      int nze_other_endo = blocks_derivatives_other_endo[blk].size();
      int nze_exo = blocks_derivatives_exo[blk].size();
      int nze_exo_det = blocks_derivatives_exo_det[blk].size();

      string filename = basename + "/model/src/dynamic_" + to_string(blk+1) + ".c";
      ofstream output;
      output.open(filename, ios::out | ios::binary);
      if (!output.is_open())
        {
          cerr << "ERROR: Can't open file " << filename << " for writing" << endl;
          exit(EXIT_FAILURE);
        }

      output << "/* Block " << blk+1 << endl
             << "   " << BlockSim(simulation_type) << " */" << endl
             << endl
             << "#include <math.h>" << endl
             << "#include <stdlib.h>" << endl
             << "#include <stdbool.h>" << endl
             << R"(#include "mex.h")" << endl
             << endl;

      // Write function definition if BinaryOpcode::powerDeriv is used
      writePowerDerivHeader(output);

      output << endl;

      if (simulation_type == BlockSimulationType::evaluateBackward
          || simulation_type == BlockSimulationType::evaluateForward)
636
        output << "void dynamic_" << blk+1 << "(double *restrict y, const double *restrict x, int nb_row_x, const double *restrict params, const double *restrict steady_state, double *restrict T, int it_, bool stochastic_mode, double *restrict g1_i, double *restrict g1_j, double *restrict g1_v, double *restrict g1_x_i, double *restrict g1_x_j, double *restrict g1_x_v, double *restrict g1_xd_i, double *restrict g1_xd_j, double *restrict g1_xd_v, double *restrict g1_o_i, double *restrict g1_o_j, double *restrict g1_o_v)" << endl;
637
      else
638
        output << "void dynamic_" << blk+1 << "(double *restrict y, const double *restrict x, int nb_row_x, const double *restrict params, const double *restrict steady_state, double *restrict T, int it_, bool stochastic_mode, double *restrict residual, double *restrict g1_i, double *restrict g1_j, double *restrict g1_v, double *restrict g1_x_i, double *restrict g1_x_j, double *restrict g1_x_v, double *restrict g1_xd_i, double *restrict g1_xd_j, double *restrict g1_xd_v, double *restrict g1_o_i, double *restrict g1_o_j, double *restrict g1_o_v)" << endl;
639
640
641
642
643
644
645
646
647
648
649
650
651
      output << '{' << endl;

      writeDynamicPerBlockHelper(blk, output, ExprNodeOutputType::CDynamicModel, temporary_terms,
                                 nze_stochastic, nze_deterministic, nze_exo, nze_exo_det, nze_other_endo);

      output << '}' << endl
             << endl;

      ostringstream header;
      if (simulation_type == BlockSimulationType::evaluateBackward
          || simulation_type == BlockSimulationType::evaluateForward)
        header << "void dynamic_" << blk+1 << "_mx(mxArray *y, const mxArray *x, const mxArray *params, const mxArray *steady_state, mxArray *T, const mxArray *it_, const mxArray *stochastic_mode, mxArray **g1, mxArray **g1_x, mxArray **g1_xd, mxArray **g1_o)";
      else
652
        header << "void dynamic_" << blk+1 << "_mx(mxArray *y, const mxArray *x, const mxArray *params, const mxArray *steady_state, mxArray *T, const mxArray *it_, const mxArray *stochastic_mode, mxArray **residual, mxArray **g1, mxArray **g1_x, mxArray **g1_xd, mxArray **g1_o)";
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
      output << header.str() << endl
             << '{' << endl
             << "  int nb_row_x = mxGetM(x);" << endl;

      if (simulation_type != BlockSimulationType::evaluateForward
          && simulation_type != BlockSimulationType::evaluateBackward)
        output << "  *residual = mxCreateDoubleMatrix(" << block_mfs_size << ",1,mxREAL);" << endl;

      output << "  mxArray *g1_i = NULL, *g1_j = NULL, *g1_v = NULL;" << endl
             << "  mxArray *g1_x_i = NULL, *g1_x_j = NULL, *g1_x_v = NULL;" << endl
             << "  mxArray *g1_xd_i = NULL, *g1_xd_j = NULL, *g1_xd_v = NULL;" << endl
             << "  mxArray *g1_o_i = NULL, *g1_o_j = NULL, *g1_o_v = NULL;" << endl
             << "  if (mxGetScalar(stochastic_mode)) {" << endl
             << "    g1_i=mxCreateDoubleMatrix(" << nze_stochastic << ",1,mxREAL);" << endl
             << "    g1_j=mxCreateDoubleMatrix(" << nze_stochastic << ",1,mxREAL);" << endl
             << "    g1_v=mxCreateDoubleMatrix(" << nze_stochastic << ",1,mxREAL);" << endl
             << "    g1_x_i=mxCreateDoubleMatrix(" << nze_exo << ",1,mxREAL);" << endl
             << "    g1_x_j=mxCreateDoubleMatrix(" << nze_exo << ",1,mxREAL);" << endl
             << "    g1_x_v=mxCreateDoubleMatrix(" << nze_exo << ",1,mxREAL);" << endl
             << "    g1_xd_i=mxCreateDoubleMatrix(" << nze_exo_det << ",1,mxREAL);" << endl
             << "    g1_xd_j=mxCreateDoubleMatrix(" << nze_exo_det << ",1,mxREAL);" << endl
             << "    g1_xd_v=mxCreateDoubleMatrix(" << nze_exo_det << ",1,mxREAL);" << endl
             << "    g1_o_i=mxCreateDoubleMatrix(" << nze_other_endo << ",1,mxREAL);" << endl
             << "    g1_o_j=mxCreateDoubleMatrix(" << nze_other_endo << ",1,mxREAL);" << endl
             << "    g1_o_v=mxCreateDoubleMatrix(" << nze_other_endo << ",1,mxREAL);" << endl;
      if (simulation_type != BlockSimulationType::evaluateForward
          && simulation_type != BlockSimulationType::evaluateBackward)
        output << "  } else {" << endl
               << "    g1_i=mxCreateDoubleMatrix(" << nze_deterministic << ",1,mxREAL);" << endl
               << "    g1_j=mxCreateDoubleMatrix(" << nze_deterministic << ",1,mxREAL);" << endl
               << "    g1_v=mxCreateDoubleMatrix(" << nze_deterministic << ",1,mxREAL);" << endl;
      output << "  }" << endl
             << endl;

687
      // N.B.: In the following, it_ is decreased by 1, to follow C convention
688
689
      if (simulation_type == BlockSimulationType::evaluateBackward
          || simulation_type == BlockSimulationType::evaluateForward)
690
        output << "  dynamic_" << blk+1 << "(mxGetPr(y), mxGetPr(x), nb_row_x, mxGetPr(params), mxGetPr(steady_state), mxGetPr(T), mxGetScalar(it_)-1, mxGetScalar(stochastic_mode), g1_i ? mxGetPr(g1_i) : NULL, g1_j ? mxGetPr(g1_j) : NULL, g1_v ? mxGetPr(g1_v) : NULL, g1_x_i ? mxGetPr(g1_x_i) : NULL, g1_x_j ? mxGetPr(g1_x_j) : NULL, g1_x_v ? mxGetPr(g1_x_v) : NULL, g1_xd_i ? mxGetPr(g1_xd_i) : NULL, g1_xd_j ? mxGetPr(g1_xd_j) : NULL, g1_xd_v ? mxGetPr(g1_xd_v) : NULL, g1_o_i ? mxGetPr(g1_o_i) : NULL, g1_o_j ? mxGetPr(g1_o_j) : NULL, g1_o_v ? mxGetPr(g1_o_v) : NULL);" << endl;
691
      else
692
        output << "  dynamic_" << blk+1 << "(mxGetPr(y), mxGetPr(x), nb_row_x, mxGetPr(params), mxGetPr(steady_state), mxGetPr(T), mxGetScalar(it_)-1, mxGetScalar(stochastic_mode), mxGetPr(*residual), g1_i ? mxGetPr(g1_i) : NULL, g1_j ? mxGetPr(g1_j) : NULL, g1_v ? mxGetPr(g1_v) : NULL, g1_x_i ? mxGetPr(g1_x_i) : NULL, g1_x_j ? mxGetPr(g1_x_j) : NULL, g1_x_v ? mxGetPr(g1_x_v) : NULL, g1_xd_i ? mxGetPr(g1_xd_i) : NULL, g1_xd_j ? mxGetPr(g1_xd_j) : NULL, g1_xd_v ? mxGetPr(g1_xd_v) : NULL, g1_o_i ? mxGetPr(g1_o_i) : NULL, g1_o_j ? mxGetPr(g1_o_j) : NULL, g1_o_v ? mxGetPr(g1_o_v) : NULL);" << endl;
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790

      output << endl
             << "  if (mxGetScalar(stochastic_mode)) {" << endl
             << "    mxArray *m = mxCreateDoubleScalar(" << block_size << ");" << endl
             << "    mxArray *n = mxCreateDoubleScalar(" << blocks_jacob_cols_endo[blk].size() << ");" << endl
             << "    mxArray *plhs[1];" << endl
             << "    mxArray *prhs[5] = { g1_i, g1_j, g1_v, m, n };" << endl
             << R"(    mexCallMATLAB(1, plhs, 5, prhs, "sparse");)" << endl
             << "    *g1=plhs[0];" << endl
             << "    mxDestroyArray(g1_i);" << endl
             << "    mxDestroyArray(g1_j);" << endl
             << "    mxDestroyArray(g1_v);" << endl
             << "    mxDestroyArray(n);" << endl
             << "    n = mxCreateDoubleScalar(" << blocks_jacob_cols_exo[blk].size() << ");" << endl
             << "    mxArray *prhs_x[5] = { g1_x_i, g1_x_j, g1_x_v, m, n };" << endl
             << R"(    mexCallMATLAB(1, plhs, 5, prhs_x, "sparse");)" << endl
             << "    *g1_x=plhs[0];" << endl
             << "    mxDestroyArray(g1_x_i);" << endl
             << "    mxDestroyArray(g1_x_j);" << endl
             << "    mxDestroyArray(g1_x_v);" << endl
             << "    mxDestroyArray(n);" << endl
             << "    n = mxCreateDoubleScalar(" << blocks_jacob_cols_exo_det[blk].size() << ");" << endl
             << "    mxArray *prhs_xd[5] = { g1_xd_i, g1_xd_j, g1_xd_v, m, n };" << endl
             << R"(    mexCallMATLAB(1, plhs, 5, prhs_xd, "sparse");)" << endl
             << "    *g1_xd=plhs[0];" << endl
             << "    mxDestroyArray(g1_xd_i);" << endl
             << "    mxDestroyArray(g1_xd_j);" << endl
             << "    mxDestroyArray(g1_xd_v);" << endl
             << "    mxDestroyArray(n);" << endl
             << "    n = mxCreateDoubleScalar(" << blocks_jacob_cols_other_endo[blk].size() << ");" << endl
             << "    mxArray *prhs_o[5] = { g1_o_i, g1_o_j, g1_o_v, m, n };" << endl
             << R"(    mexCallMATLAB(1, plhs, 5, prhs_o, "sparse");)" << endl
             << "    *g1_o=plhs[0];" << endl
             << "    mxDestroyArray(g1_o_i);" << endl
             << "    mxDestroyArray(g1_o_j);" << endl
             << "    mxDestroyArray(g1_o_v);" << endl
             << "    mxDestroyArray(n);" << endl
             << "    mxDestroyArray(m);" << endl
             << "  } else {" << endl;
      switch (simulation_type)
        {
        case BlockSimulationType::evaluateForward:
        case BlockSimulationType::evaluateBackward:
          output << "    *g1=mxCreateDoubleMatrix(0,0,mxREAL);" << endl;
          break;
        case BlockSimulationType::solveBackwardSimple:
        case BlockSimulationType::solveForwardSimple:
        case BlockSimulationType::solveBackwardComplete:
        case BlockSimulationType::solveForwardComplete:
          output << "    mxArray *m = mxCreateDoubleScalar(" << block_mfs_size << ");" << endl
                 << "    mxArray *n = mxCreateDoubleScalar(" << block_mfs_size << ");" << endl
                 << "    mxArray *plhs[1];" << endl
                 << "    mxArray *prhs[5] = { g1_i, g1_j, g1_v, m, n };" << endl
                 << R"(    mexCallMATLAB(1, plhs, 5, prhs, "sparse");)" << endl
                 << "    *g1=plhs[0];" << endl
                 << "    mxDestroyArray(g1_i);" << endl
                 << "    mxDestroyArray(g1_j);" << endl
                 << "    mxDestroyArray(g1_v);" << endl
                 << "    mxDestroyArray(n);" << endl
                 << "    mxDestroyArray(m);" << endl;
          break;
        case BlockSimulationType::solveTwoBoundariesSimple:
        case BlockSimulationType::solveTwoBoundariesComplete:
          output << "    mxArray *m = mxCreateDoubleScalar(" << block_mfs_size << ");" << endl
                 << "    mxArray *n = mxCreateDoubleScalar(" << 3*block_mfs_size << ");" << endl
                 << "    mxArray *plhs[1];" << endl
                 << "    mxArray *prhs[5] = { g1_i, g1_j, g1_v, m, n };" << endl
                 << R"(    mexCallMATLAB(1, plhs, 5, prhs, "sparse");)" << endl
                 << "    *g1=plhs[0];" << endl
                 << "    mxDestroyArray(g1_i);" << endl
                 << "    mxDestroyArray(g1_j);" << endl
                 << "    mxDestroyArray(g1_v);" << endl
                 << "    mxDestroyArray(n);" << endl
                 << "    mxDestroyArray(m);" << endl;
          break;
        default:
          break;
        }
      output << "    *g1_x=mxCreateDoubleMatrix(0,0,mxREAL);" << endl
             << "    *g1_xd=mxCreateDoubleMatrix(0,0,mxREAL);" << endl
             << "    *g1_o=mxCreateDoubleMatrix(0,0,mxREAL);" << endl
             << "  }" << endl
             << "}" << endl;
      output.close();

      filename = basename + "/model/src/dynamic_" + to_string(blk+1) + ".h";
      ofstream header_output;
      header_output.open(filename, ios::out | ios::binary);
      if (!header_output.is_open())
        {
          cerr << "ERROR: Can't open file " << filename << " for writing" << endl;
          exit(EXIT_FAILURE);
        }
      header_output << header.str() << ';' << endl;
      header_output.close();
    }
}

sebastien's avatar
sebastien committed
791
void
792
DynamicModel::writeDynamicBytecode(const string &basename) const
793
794
795
{
  ostringstream tmp_output;
  ofstream code_file;
796
  unsigned int instruction_number = 0;
797
798
  bool file_open = false;

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

  int count_u;
  int u_count_int = 0;
  BlockSimulationType simulation_type;
  if ((max_endo_lag > 0) && (max_endo_lead > 0))
811
    simulation_type = BlockSimulationType::solveTwoBoundariesComplete;
812
  else if ((max_endo_lag >= 0) && (max_endo_lead == 0))
813
    simulation_type = BlockSimulationType::solveForwardComplete;
814
  else
815
    simulation_type = BlockSimulationType::solveBackwardComplete;
816

817
  writeBytecodeBinFile(basename + "/model/bytecode/dynamic.bin", u_count_int, file_open, simulation_type == BlockSimulationType::solveTwoBoundariesComplete);
818
819
820
  file_open = true;

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

824
  vector<int> exo, exo_det, other_endo;
825

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

831
832
  map<tuple<int, int, int>, expr_t> first_derivatives_reordered_endo;
  map<tuple<int, SymbolType, int, int>, expr_t> first_derivatives_reordered_exo;
833
  for (const auto & [indices, d1] : derivatives[1])
834
    {
835
      int deriv_id = indices[1];
836
      int eq = indices[0];
837
      int symb = getSymbIDByDerivID(deriv_id);
838
      int var = symbol_table.getTypeSpecificID(symb);
839
      int lag = getLagByDerivID(deriv_id);
840
      if (getTypeByDerivID(deriv_id) == SymbolType::endogenous)
841
        first_derivatives_reordered_endo[{ lag, var, eq }] = d1;
842
      else if (getTypeByDerivID(deriv_id) == SymbolType::exogenous || getTypeByDerivID(deriv_id) == SymbolType::exogenousDet)
843
        first_derivatives_reordered_exo[{ lag, getTypeByDerivID(deriv_id), var, eq }] = d1;
844
845
846
847
    }
  int prev_var = -1;
  int prev_lag = -999999999;
  int count_col_endo = 0;
848
  for (const auto &it : first_derivatives_reordered_endo)
849
    {
850
851
      int var, lag;
      tie(lag, var, ignore) = it.first;
852
      if (prev_var != var || prev_lag != lag)
853
854
855
856
857
858
        {
          prev_var = var;
          prev_lag = lag;
          count_col_endo++;
        }
    }
859
860
  prev_var = -1;
  prev_lag = -999999999;
861
  SymbolType prev_type{SymbolType::unusedEndogenous}; // Any non-exogenous type would do here
862
  int count_col_exo = 0;
863
  int count_col_det_exo = 0;
864

Sébastien Villemot's avatar
Sébastien Villemot committed
865
  for (const auto &it : first_derivatives_reordered_exo)
866
    {
867
868
869
      int var, lag;
      SymbolType type;
      tie(lag, type, var, ignore) = it.first;
870
      if (prev_var != var || prev_lag != lag || prev_type != type)
871
872
873
        {
          prev_var = var;
          prev_lag = lag;
874
          prev_type = type;
875
          if (type == SymbolType::exogenous)
876
            count_col_exo++;
877
          else if (type == SymbolType::exogenousDet)
878
            count_col_det_exo++;
879
880
        }
    }
881

882
883
884
885
  FBEGINBLOCK_ fbeginblock(symbol_table.endo_nbr(),
                           simulation_type,
                           0,
                           symbol_table.endo_nbr(),
886
887
                           endo_idx_block2orig,
                           eq_idx_block2orig,
888
889
                           false,
                           symbol_table.endo_nbr(),
890
891
                           max_endo_lag,
                           max_endo_lead,
892
                           u_count_int,
893
                           count_col_endo,
894
                           symbol_table.exo_det_nbr(),
895
896
                           count_col_det_exo,
                           symbol_table.exo_nbr(),
897
                           count_col_exo,
898
                           0,
899
900
901
                           0,
                           exo_det,
                           exo,
902
                           other_endo);
903
  fbeginblock.write(code_file, instruction_number);
904

905
906
  temporary_terms_t temporary_terms_union;
  compileTemporaryTerms(code_file, instruction_number, true, false, temporary_terms_union, temporary_terms_idxs);
907

908
  compileModelEquations(code_file, instruction_number, true, false, temporary_terms_union, temporary_terms_idxs);
909
910

  FENDEQU_ fendequ;
911
  fendequ.write(code_file, instruction_number);
912
913
914
915
916
917
918

  // Get the current code_file position and jump if eval = true
  streampos pos1 = code_file.tellp();
  FJMPIFEVAL_ fjmp_if_eval(0);
  fjmp_if_eval.write(code_file, instruction_number);
  int prev_instruction_number = instruction_number;

919
  vector<vector<tuple<int, int, int>>> my_derivatives(symbol_table.endo_nbr());;
920
  count_u = symbol_table.endo_nbr();
921
  for (const auto & [indices, d1] : derivatives[1])
922
    {
923
      int deriv_id = indices[1];
924
      if (getTypeByDerivID(deriv_id) == SymbolType::endogenous)
925
        {
926
          int eq = indices[0];
927
          int symb = getSymbIDByDerivID(deriv_id);
928
          int var = symbol_table.getTypeSpecificID(symb);
929
          int lag = getLagByDerivID(deriv_id);
930
          FNUMEXPR_ fnumexpr(ExpressionType::FirstEndoDerivative, eq, var, lag);
931
          fnumexpr.write(code_file, instruction_number);
932
933
          if (!my_derivatives[eq].size())
            my_derivatives[eq].clear();
934
          my_derivatives[eq].emplace_back(var, lag, count_u);
935
          d1->compile(code_file, instruction_number, false, temporary_terms_union, temporary_terms_idxs, true, false);
936
937

          FSTPU_ fstpu(count_u);
938
          fstpu.write(code_file, instruction_number);
939
940
941
942
943
944
          count_u++;
        }
    }
  for (int i = 0; i < symbol_table.endo_nbr(); i++)
    {
      FLDR_ fldr(i);
945
      fldr.write(code_file, instruction_number);
946
      if (my_derivatives[i].size())
947
        {
948
          for (auto it = my_derivatives[i].begin(); it != my_derivatives[i].end(); ++it)
949
            {
950
              FLDU_ fldu(get<2>(*it));
951
              fldu.write(code_file, instruction_number);
952
              FLDV_ fldv{static_cast<int>(SymbolType::endogenous), static_cast<unsigned int>(get<0>(*it)), get<1>(*it)};
953
              fldv.write(code_file, instruction_number);
954
              FBINARY_ fbinary{static_cast<int>(BinaryOpcode::times)};
955
              fbinary.write(code_file, instruction_number);
956
              if (it != my_derivatives[i].begin())
957
                {
958
                  FBINARY_ fbinary{static_cast<int>(BinaryOpcode::plus)};
959
960
                  fbinary.write(code_file, instruction_number);
                }
961
            }
962
          FBINARY_ fbinary{static_cast<int>(BinaryOpcode::minus)};
963
          fbinary.write(code_file, instruction_number);
964
965
        }
      FSTPU_ fstpu(i);
966
      fstpu.write(code_file, instruction_number);
967
    }
968
969
970
971
972
973
974
975
976
977
978

  // Get the current code_file position and jump = true
  streampos pos2 = code_file.tellp();
  FJMP_ fjmp(0);
  fjmp.write(code_file, instruction_number);
  // Set code_file position to previous JMPIFEVAL_ and set the number of instructions to jump
  streampos pos3 = code_file.tellp();
  code_file.seekp(pos1);
  FJMPIFEVAL_ fjmp_if_eval1(instruction_number - prev_instruction_number);
  fjmp_if_eval1.write(code_file, instruction_number);
  code_file.seekp(pos3);
979
  prev_instruction_number = instruction_number;
980
981
982
983
984

  // The Jacobian
  prev_var = -1;
  prev_lag = -999999999;
  count_col_endo = 0;
985
  for (const auto &it : first_derivatives_reordered_endo)
986
    {
987
      auto [lag, var, eq] = it.first;
988
      expr_t d1 = it.second;
989
      FNUMEXPR_ fnumexpr(ExpressionType::FirstEndoDerivative, eq, var, lag);
990
      fnumexpr.write(code_file, instruction_number);
991
      if (prev_var != var || prev_lag != lag)
992
993
994
995
996
        {
          prev_var = var;
          prev_lag = lag;
          count_col_endo++;
        }
997
      d1->compile(code_file, instruction_number, false, temporary_terms_union, temporary_terms_idxs, true, false);
998
999
1000
1001
1002
      FSTPG3_ fstpg3(eq, var, lag, count_col_endo-1);
      fstpg3.write(code_file, instruction_number);
    }
  prev_var = -1;
  prev_lag = -999999999;
1003
  count_col_exo = 0;
Sébastien Villemot's avatar
Sébastien Villemot committed
1004
  for (const auto &it : first_derivatives_reordered_exo)
1005
    {
1006
      auto [lag, ignore, var, eq] = it.first;
1007
      expr_t d1 = it.second;
1008
      FNUMEXPR_ fnumexpr(ExpressionType::FirstExoDerivative, eq, var, lag);
1009
      fnumexpr.write(code_file, instruction_number);
1010
      if (prev_var != var || prev_lag != lag)
1011
1012
1013
1014
1015
        {
          prev_var = var;
          prev_lag = lag;
          count_col_exo++;
        }
1016
      d1->compile(code_file, instruction_number, false, temporary_terms_union, temporary_terms_idxs, true, false);
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
      FSTPG3_ fstpg3(eq, var, lag, count_col_exo-1);
      fstpg3.write(code_file, instruction_number);
    }
  // Set codefile position to previous JMP_ and set the number of instructions to jump
  pos1 = code_file.tellp();
  code_file.seekp(pos2);
  FJMP_ fjmp1(instruction_number - prev_instruction_number);
  fjmp1.write(code_file, instruction_number);
  code_file.seekp(pos1);

1027
  FENDBLOCK_ fendblock;
1028
  fendblock.write(code_file, instruction_number);
1029
  FEND_ fend;
1030
  fend.write(code_file, instruction_number);
1031
1032
1033
1034
  code_file.close();
}

void
1035
DynamicModel::writeDynamicBlockBytecode(const string &basename) const
1036
1037
{
  struct Uff_l
sebastien's avatar
sebastien committed
1038
  {
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
    int u, var, lag;
    Uff_l *pNext;
  };

  struct Uff
  {
    Uff_l *Ufl, *Ufl_First;
  };

  int i, v;
  string tmp_s;
  ostringstream tmp_output;
  ofstream code_file;
1052
  unsigned int instruction_number = 0;
1053
  expr_t lhs = nullptr, rhs = nullptr;
1054
1055
  BinaryOpNode *eq_node;
  Uff Uf[symbol_table.endo_nbr()];
1056
  map<expr_t, int> reference_count;
1057
1058
  vector<int> feedback_variables;
  bool file_open = false;
1059
  string main_name = basename + "/model/bytecode/dynamic.cod";
1060
  code_file.open(main_name, ios::out | ios::binary | ios::ate);
1061
1062
  if (!code_file.is_open())
    {
1063
      cerr << R"(Error : Can't open file ")" << main_name << R"(" for writing)" << endl;
1064
1065
1066
1067
      exit(EXIT_FAILURE);
    }
  //Temporary variables declaration

1068
  FDIMT_ fdimt(blocks_temporary_terms_idxs.size());
1069
  fdimt.write(code_file, instruction_number);
1070

1071
  for (int block = 0; block < static_cast<int>(blocks.size()); block++)
1072
1073
1074
1075
1076
    {
      feedback_variables.clear();
      if (block > 0)
        {
          FENDBLOCK_ fendblock;
1077
          fendblock.write(code_file, instruction_number);
1078
1079
1080
        }
      int count_u;
      int u_count_int = 0;
1081
1082
1083
1084
      BlockSimulationType simulation_type = blocks[block].simulation_type;
      int block_size = blocks[block].size;
      int block_mfs = blocks[block].mfs_size;
      int block_recursive = blocks[block].getRecursiveSize();
1085
1086
      int block_max_lag = blocks[block].max_lag;
      int block_max_lead = blocks[block].max_lead;
1087

1088
1089
1090
1091
      if (simulation_type == BlockSimulationType::solveTwoBoundariesSimple
          || simulation_type == BlockSimulationType::solveTwoBoundariesComplete
          || simulation_type == BlockSimulationType::solveBackwardComplete
          || simulation_type == BlockSimulationType::solveForwardComplete)
1092
        {
1093
          writeBlockBytecodeBinFile(basename, block, u_count_int, file_open,
1094
                                    simulation_type == BlockSimulationType::solveTwoBoundariesComplete || simulation_type == BlockSimulationType::solveTwoBoundariesSimple);
1095
1096
          file_open = true;
        }
1097

1098
1099
      FBEGINBLOCK_ fbeginblock(block_mfs,
                               simulation_type,
1100
                               blocks[block].first_equation,
1101
                               block_size,
1102
1103
                               endo_idx_block2orig,
                               eq_idx_block2orig,
1104
                               blocks[block].linear,
1105
1106
                               symbol_table.endo_nbr(),
                               block_max_lag,
1107
                               block_max_lead,
1108
                               u_count_int,
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
                               blocks_jacob_cols_endo[block].size(),
                               blocks_exo_det[block].size(),
                               blocks_jacob_cols_exo_det[block].size(),
                               blocks_exo[block].size(),
                               blocks_jacob_cols_exo[block].size(),
                               blocks_other_endo[block].size(),
                               blocks_jacob_cols_other_endo[block].size(),
                               vector<int>(blocks_exo_det[block].begin(), blocks_exo_det[block].end()),
                               vector<int>(blocks_exo[block].begin(), blocks_exo[block].end()),
                               vector<int>(blocks_other_endo[block].begin(), blocks_other_endo[block].end()));
1119
      fbeginblock.write(code_file, instruction_number);
1120

1121
      temporary_terms_t temporary_terms_union;
sebastien's avatar
sebastien committed
1122

1123
1124
      //The Temporary terms
      deriv_node_temp_terms_t tef_terms;
1125
1126
1127
1128
1129
1130
1131
1132

      auto write_eq_tt = [&](int eq)
                         {
                           for (auto it : blocks_temporary_terms[block][eq])
                             {
                               if (dynamic_cast<AbstractExternalFunctionNode *>(it))
                                 it->compileExternalFunctionOutput(code_file, instruction_number, false, temporary_terms_union, blocks_temporary_terms_idxs, true, false, tef_terms);

1133
                               FNUMEXPR_ fnumexpr(ExpressionType::TemporaryTerm, static_cast<int>(blocks_temporary_terms_idxs.at(it)));
1134
1135
1136
1137
1138
                               fnumexpr.write(code_file, instruction_number);
                               it->compile(code_file, instruction_number, false, temporary_terms_union, blocks_temporary_terms_idxs, true, false, tef_terms);
                               FSTPT_ fstpt(static_cast<int>(blocks_temporary_terms_idxs.at(it)));
                               fstpt.write(code_file, instruction_number);
                               temporary_terms_union.insert(it);
sebastien's avatar
sebastien committed
1139
#ifdef DEBUGC
1140
1141
1142
1143
1144
                               cout << "FSTPT " << v << endl;
                               instruction_number++;
                               code_file.write(&FOK, sizeof(FOK));
                               code_file.write(reinterpret_cast<char *>(&k), sizeof(k));
                               ki++;
1145
#endif
1146
1147
                             }
                         };
1148

1149
1150
1151
      // The equations
      for (i = 0; i < block_size; i++)
        {
1152
          write_eq_tt(i);
1153

1154
1155
          int variable_ID, equation_ID;
          EquationType equ_type;
1156

1157
1158
1159
          switch (simulation_type)
            {
            evaluation:
1160
1161
            case BlockSimulationType::evaluateBackward:
            case BlockSimulationType::evaluateForward:
1162
              equ_type = getBlockEquationType(block, i);
1163
              {
1164
                FNUMEXPR_ fnumexpr(ExpressionType::ModelEquation, getBlockEquationID(block, i));
1165
                fnumexpr.write(code_file, instruction_number);
1166
              }
1167
              if (equ_type == EquationType::evaluate)
1168
                {
1169
                  eq_node = getBlockEquationExpr(block, i);
1170
1171
                  lhs = eq_node->arg1;
                  rhs = eq_node->arg2;
1172
1173
                  rhs->compile(code_file, instruction_number, false, temporary_terms_union, blocks_temporary_terms_idxs, true, false);
                  lhs->compile(code_file, instruction_number, true, temporary_terms_union, blocks_temporary_terms_idxs, true, false);
1174
                }
1175
              else if (equ_type == EquationType::evaluateRenormalized)
1176
                {
1177
                  eq_node = getBlockEquationRenormalizedExpr(block, i);
1178
1179
                  lhs = eq_node->arg1;
                  rhs = eq_node->arg2;
1180
1181
                  rhs->compile(code_file, instruction_number, false, temporary_terms_union, blocks_temporary_terms_idxs, true, false);
                  lhs->compile(code_file, instruction_number, true, temporary_terms_union, blocks_temporary_terms_idxs, true, false);
1182
1183
                }
              break;
1184
1185
1186
1187
            case BlockSimulationType::solveBackwardComplete:
            case BlockSimulationType::solveForwardComplete:
            case BlockSimulationType::solveTwoBoundariesComplete:
            case BlockSimulationType::solveTwoBoundariesSimple:
1188
              if (i < block_recursive)
1189
1190
1191
1192
                goto evaluation;
              variable_ID = getBlockVariableID(block, i);
              equation_ID = getBlockEquationID(block, i);
              feedback_variables.push_back(variable_ID);
1193
              Uf[equation_ID].Ufl = nullptr;
1194
1195
1196
              goto end;
            default:
            end:
1197
              FNUMEXPR_ fnumexpr(ExpressionType::ModelEquation, getBlockEquationID(block, i));
1198
              fnumexpr.write(code_file, instruction_number);
1199
              eq_node = getBlockEquationExpr(block, i);
1200
1201
              lhs = eq_node->arg1;
              rhs = eq_node->arg2;
1202
1203
              lhs->compile(code_file, instruction_number, false, temporary_terms_union, blocks_temporary_terms_idxs, true, false);
              rhs->compile(code_file, instruction_number, false, temporary_terms_union, blocks_temporary_terms_idxs, true, false);
1204

1205
              FBINARY_ fbinary{static_cast<int>(BinaryOpcode::minus)};
1206
              fbinary.write(code_file, instruction_number);
1207
              FSTPR_ fstpr(i - block_recursive);
1208
              fstpr.write(code_file, instruction_number);
1209
1210
1211
            }
        }
      FENDEQU_ fendequ;
1212
1213
1214
1215
1216
1217
1218
      fendequ.write(code_file, instruction_number);

      // Get the current code_file position and jump if eval = true
      streampos pos1 = code_file.tellp();
      FJMPIFEVAL_ fjmp_if_eval(0);
      fjmp_if_eval.write(code_file, instruction_number);
      int prev_instruction_number = instruction_number;
1219
      // The Jacobian if we have to solve the block determinsitic block
1220
1221
      if (simulation_type != BlockSimulationType::evaluateBackward
          && simulation_type != BlockSimulationType::evaluateForward)
1222
        {
1223
          // Write temporary terms for derivatives
1224
          write_eq_tt(blocks[block].size);
1225

1226
1227
          switch (simulation_type)
            {
1228
1229
            case BlockSimulationType::solveBackwardSimple:
            case BlockSimulationType::solveForwardSimple:
1230
              {
1231
                FNUMEXPR_ fnumexpr(ExpressionType::FirstEndoDerivative, getBlockEquationID(block, 0), getBlockVariableID(block, 0), 0);
1232
                fnumexpr.write(code_file, instruction_number);