DynamicModel.cc 152 KB
Newer Older
sebastien's avatar
sebastien committed
1
/*
2
 * Copyright (C) 2003-2010 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>
sebastien's avatar
sebastien committed
27
28
29
30
31
32
33
34
35
36
37
38
#include "DynamicModel.hh"

// For mkdir() and chdir()
#ifdef _WIN32
# include <direct.h>
#else
# include <unistd.h>
# include <sys/stat.h>
# include <sys/types.h>
#endif

DynamicModel::DynamicModel(SymbolTable &symbol_table_arg,
39
40
41
                           NumericalConstants &num_constants_arg,
                           ExternalFunctionsTable &external_functions_table_arg) :
  ModelTree(symbol_table_arg, num_constants_arg, external_functions_table_arg),
42
43
44
45
46
47
48
49
  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),
  dynJacobianColsNbr(0),
  global_temporary_terms(true),
  cutoff(1e-15),
  mfs(0)
sebastien's avatar
sebastien committed
50
51
52
{
}

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

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

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

85
86
87
88
89
90
91
92
93
94
95
96
void
DynamicModel::initializeVariablesAndEquations()
{
  for(int j=0; j<equation_number(); j++)
    {
      equation_reordered.push_back(j);
      variable_reordered.push_back(j);
    }
}



sebastien's avatar
sebastien committed
97
void
98
DynamicModel::computeTemporaryTermsOrdered()
sebastien's avatar
sebastien committed
99
{
100
101
  map<expr_t, pair<int, int> > first_occurence;
  map<expr_t, int> reference_count;
sebastien's avatar
sebastien committed
102
  BinaryOpNode *eq_node;
103
104
  first_derivatives_t::const_iterator it;
  first_chain_rule_derivatives_t::const_iterator it_chr;
sebastien's avatar
sebastien committed
105
  ostringstream tmp_s;
106
107
  v_temporary_terms.clear();
  map_idx.clear();
sebastien's avatar
sebastien committed
108

109
  unsigned int nb_blocks = getNbBlocks();
110
111
  v_temporary_terms = vector<vector<temporary_terms_t> >(nb_blocks);
  v_temporary_terms_inuse = vector<temporary_terms_inuse_t>(nb_blocks);
sebastien's avatar
sebastien committed
112
  temporary_terms.clear();
113

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

209
210
211
212
213
void
DynamicModel::computeTemporaryTermsMapping()
{
  // Add a mapping form node ID to temporary terms order
  int j = 0;
214
  for (temporary_terms_t::const_iterator it = temporary_terms.begin();
215
216
217
218
219
      it != temporary_terms.end(); it++)
    map_idx[(*it)->idx] = j++;
}


sebastien's avatar
sebastien committed
220
void
221
DynamicModel::writeModelEquationsOrdered_M(const string &dynamic_basename) const
222
223
224
{
  string tmp_s, sps;
  ostringstream tmp_output, tmp1_output, global_output;
225
  expr_t lhs = NULL, rhs = NULL;
226
227
  BinaryOpNode *eq_node;
  ostringstream Uf[symbol_table.endo_nbr()];
228
  map<expr_t, int> reference_count;
229
  temporary_terms_t local_temporary_terms;
230
231
232
233
  ofstream  output;
  int nze, nze_exo, nze_other_endo;
  vector<int> feedback_variables;
  ExprNodeOutputType local_output_type;
sebastien's avatar
sebastien committed
234

Sébastien Villemot's avatar
Sébastien Villemot committed
235
  local_output_type = oMatlabDynamicModelSparse;
236
  if (global_temporary_terms)
Sébastien Villemot's avatar
Sébastien Villemot committed
237
    local_temporary_terms = temporary_terms;
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257

  //----------------------------------------------------------------------
  //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();
      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;
      unsigned int block_exo_size = exo_block[block].size();
      unsigned int block_exo_det_size = exo_det_block[block].size();
      unsigned int block_other_endo_size = other_endo_block[block].size();
      int block_max_lag = max_leadlag_block[block].first;
Sébastien Villemot's avatar
Sébastien Villemot committed
258
      local_output_type = oMatlabDynamicModelSparse;
259
      if (global_temporary_terms)
Sébastien Villemot's avatar
Sébastien Villemot committed
260
        local_temporary_terms = temporary_terms;
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332

      tmp1_output.str("");
      tmp1_output << dynamic_basename << "_" << block+1 << ".m";
      output.open(tmp1_output.str().c_str(), ios::out | ios::binary);
      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)
        {
          output << "function [y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, jacobian_eval, y_kmin, periods)\n";
        }
      else if (simulation_type == SOLVE_FORWARD_COMPLETE || simulation_type == SOLVE_BACKWARD_COMPLETE)
        output << "function [residual, y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, it_, jacobian_eval)\n";
      else if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE)
        output << "function [residual, y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, it_, jacobian_eval)\n";
      else
        output << "function [residual, y, g1, g2, g3, b, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, periods, jacobian_eval, y_kmin, y_size)\n";
      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;
      output << "  global options_;" << endl;
      //The Temporary terms
      if (simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD)
        {
          output << "  if(jacobian_eval)\n";
          output << "    g1 = spalloc(" << block_mfs  << ", " << block_mfs*(1+getBlockMaxLag(block)+getBlockMaxLead(block)) << ", " << nze << ");\n";
          output << "    g1_x=spalloc(" << block_size << ", " << (block_exo_size + block_exo_det_size)
            *(1+max(exo_det_max_leadlag_block[block].first, exo_max_leadlag_block[block].first)+max(exo_det_max_leadlag_block[block].second, exo_max_leadlag_block[block].second))
                 << ", " << nze_exo << ");\n";
          output << "    g1_o=spalloc(" << block_size << ", " << block_other_endo_size
            *(1+other_endo_max_leadlag_block[block].first+other_endo_max_leadlag_block[block].second)
                 << ", " << nze_other_endo << ");\n";
          output << "  end;\n";
        }
      else
        {
          output << "  if(jacobian_eval)\n";
          output << "    g1 = spalloc(" << block_size << ", " << block_size*(1+getBlockMaxLag(block)+getBlockMaxLead(block)) << ", " << nze << ");\n";
          output << "    g1_x=spalloc(" << block_size << ", " << (block_exo_size + block_exo_det_size)
            *(1+max(exo_det_max_leadlag_block[block].first, exo_max_leadlag_block[block].first)+max(exo_det_max_leadlag_block[block].second, exo_max_leadlag_block[block].second))
                 << ", " << nze_exo << ");\n";
          output << "    g1_o=spalloc(" << block_size << ", " << block_other_endo_size
            *(1+other_endo_max_leadlag_block[block].first+other_endo_max_leadlag_block[block].second)
                 << ", " << nze_other_endo << ");\n";
          output << "  else\n";
          if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
            {
              output << "    g1 = spalloc(" << block_mfs << "*options_.periods, "
                     << block_mfs << "*(options_.periods+" << max_leadlag_block[block].first+max_leadlag_block[block].second+1 << ")"
                     << ", " << nze << "*options_.periods);\n";
            }
ferhat's avatar
ferhat committed
333
          else
334
335
336
337
338
339
340
341
342
343
            {
              output << "    g1 = spalloc(" << block_mfs
                     << ", " << block_mfs << ", " << nze << ");\n";
              output << "    g1_tmp_r = spalloc(" << block_recursive
                     << ", " << block_size << ", " << nze << ");\n";
              output << "    g1_tmp_b = spalloc(" << block_mfs
                     << ", " << block_size << ", " << nze << ");\n";
            }
          output << "  end;\n";
        }
344

345
346
347
348
      output << "  g2=0;g3=0;\n";
      if (v_temporary_terms_inuse[block].size())
        {
          tmp_output.str("");
349
          for (temporary_terms_inuse_t::const_iterator it = v_temporary_terms_inuse[block].begin();
350
351
352
353
354
355
               it != v_temporary_terms_inuse[block].end(); it++)
            tmp_output << " T" << *it;
          output << "  global" << tmp_output.str() << ";\n";
        }
      if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
        {
356
          temporary_terms_t tt2;
357
358
359
360
361
362
363
          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;
364
                  for (temporary_terms_t::const_iterator it = v_temporary_terms[block][i].begin();
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
                       it != v_temporary_terms[block][i].end(); it++)
                    {
                      output << "  ";
                      (*it)->writeOutput(output, oMatlabDynamicModel, local_temporary_terms);
                      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
      for (unsigned int i = 0; i < block_size; i++)
        {
400
          temporary_terms_t tt2;
401
402
403
404
          tt2.clear();
          if (v_temporary_terms[block].size())
            {
              output << "  " << "% //Temporary variables" << endl;
405
              for (temporary_terms_t::const_iterator it = v_temporary_terms[block][i].begin();
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
                   it != v_temporary_terms[block][i].end(); it++)
                {
                  output << "  " <<  sps;
                  (*it)->writeOutput(output, local_output_type, local_temporary_terms);
                  output << " = ";
                  (*it)->writeOutput(output, local_output_type, tt2);
                  // Insert current node into tt2
                  tt2.insert(*it);
                  output << ";" << endl;
                }
            }

          int variable_ID = getBlockVariableID(block, i);
          int equation_ID = getBlockEquationID(block, i);
          EquationType equ_type = getBlockEquationType(block, i);
          string sModel = symbol_table.getName(symbol_table.getID(eEndogenous, variable_ID));
422
          eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
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
449
          lhs = eq_node->get_arg1();
          rhs = eq_node->get_arg2();
          tmp_output.str("");
          lhs->writeOutput(tmp_output, local_output_type, local_temporary_terms);
          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 << " = ";
                  rhs->writeOutput(output, local_output_type, local_temporary_terms);
                }
              else if (equ_type == E_EVALUATE_S)
                {
                  output << "%" << tmp_output.str();
                  output << " = ";
                  if (isBlockEquationRenormalized(block, i))
                    {
                      rhs->writeOutput(output, local_output_type, local_temporary_terms);
                      output << "\n    ";
                      tmp_output.str("");
450
                      eq_node = (BinaryOpNode *) getBlockEquationRenormalizedExpr(block, i);
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
                      lhs = eq_node->get_arg1();
                      rhs = eq_node->get_arg2();
                      lhs->writeOutput(output, local_output_type, local_temporary_terms);
                      output << " = ";
                      rhs->writeOutput(output, local_output_type, local_temporary_terms);
                    }
                }
              else
                {
                  cerr << "Type missmatch for equation " << equation_ID+1  << "\n";
                  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
473
                     << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << " symb_id=" << symbol_table.getID(eEndogenous, variable_ID) << endl;
474
475
476
477
478
479
480
481
              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
482
                     << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << " symb_id=" << symbol_table.getID(eEndogenous, variable_ID) << endl;
483
484
485
486
487
488
489
490
491
              Uf[equation_ID] << "    b(" << i+1-block_recursive << "+Per_J_) = -residual(" << i+1-block_recursive << ", it_)";
              output << "    residual(" << i+1-block_recursive << ", it_) = (";
              goto end;
            default:
            end:
              output << tmp_output.str();
              output << ") - (";
              rhs->writeOutput(output, local_output_type, local_temporary_terms);
              output << ");\n";
sebastien's avatar
sebastien committed
492
#ifdef CONDITION
493
494
              if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
                output << "  condition(" << i+1 << ")=0;\n";
sebastien's avatar
sebastien committed
495
#endif
496
497
498
499
500
501
502
503
504
            }
        }
      // The Jacobian if we have to solve the block
      if (simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE)
        output << "  " << sps << "% Jacobian  " << endl;
      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
505
        else
506
507
508
509
510
          output << "    % Jacobian  " << endl << "    if jacobian_eval" << endl;
      switch (simulation_type)
        {
        case EVALUATE_BACKWARD:
        case EVALUATE_FORWARD:
511
          for (derivative_t::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++)
512
513
514
515
516
517
518
            {
              int lag = it->first.first;
              int eq = it->first.second.first;
              int var = it->first.second.second;
              int eqr = getBlockInitialEquationID(block, eq);
              int varr = getBlockInitialVariableID(block, var);

519
              expr_t id = it->second;
520
521
522
523
524
525
526
527

              output << "      g1(" << eqr+1 << ", " << varr+1+(lag+block_max_lag)*block_size << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                     << "(" << lag
                     << ") " << var+1
                     << ", equation=" << eq+1 << endl;
            }
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
          for (derivative_t::const_iterator it = derivative_exo[block].begin(); it != derivative_exo[block].end(); it++)
            {
              int lag = it->first.first;
              int eq = it->first.second.first;
              int var = it->first.second.second;
              int eqr = getBlockInitialEquationID(block, eq);
              expr_t id = it->second;
              output << "      g1_x(" << eqr+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eExogenous, var))
                     << "(" << lag
                     << ") " << var+1
                     << ", equation=" << eq+1 << endl;
            }
          for (derivative_t::const_iterator it = derivative_exo_det[block].begin(); it != derivative_exo_det[block].end(); it++)
            {
              int lag = it->first.first;
              int eq = it->first.second.first;
              int var = it->first.second.second;
              int eqr = getBlockInitialEquationID(block, eq);
              expr_t id = it->second;
              output << "      g1_x(" << eqr+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eExogenous, var))
                     << "(" << lag
                     << ") " << var+1
                     << ", equation=" << eq+1 << endl;
            }
556
          for (derivative_t::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
557
558
559
560
561
            {
              int lag = it->first.first;
              int eq = it->first.second.first;
              int var = it->first.second.second;
              int eqr = getBlockInitialEquationID(block, eq);
562
              expr_t id = it->second;
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579

              output << "      g1_o(" << eqr+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                     << "(" << lag
                     << ") " << var+1
                     << ", equation=" << eq+1 << endl;
            }
          output << "      varargout{1}=g1_x;\n";
          output << "      varargout{2}=g1_o;\n";
          output << "    end;" << endl;
          output << "  end;" << endl;
          break;
        case SOLVE_BACKWARD_SIMPLE:
        case SOLVE_FORWARD_SIMPLE:
        case SOLVE_BACKWARD_COMPLETE:
        case SOLVE_FORWARD_COMPLETE:
580
          for (derivative_t::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++)
581
582
583
584
            {
              int lag = it->first.first;
              unsigned int eq = it->first.second.first;
              unsigned int var = it->first.second.second;
585
              expr_t id = it->second;
586
587
588
589
590
591
592
593

              output << "    g1(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                     << "(" << lag
                     << ") " << var+1
                     << ", equation=" << eq+1 << endl;
            }
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
          for (derivative_t::const_iterator it = derivative_exo[block].begin(); it != derivative_exo[block].end(); it++)
            {
              int lag = it->first.first;
              int eq = it->first.second.first;
              int var = it->first.second.second;
              int eqr = getBlockInitialEquationID(block, eq);
              expr_t id = it->second;

              output << "      g1_x(" << eqr+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eExogenous, var))
                     << "(" << lag
                     << ") " << var+1
                     << ", equation=" << eq+1 << endl;
            }
          for (derivative_t::const_iterator it = derivative_exo_det[block].begin(); it != derivative_exo_det[block].end(); it++)
            {
              int lag = it->first.first;
              int eq = it->first.second.first;
              int var = it->first.second.second;
              int eqr = getBlockInitialEquationID(block, eq);
              expr_t id = it->second;
616

617
618
619
620
621
622
623
              output << "      g1_x(" << eqr+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eExogenous, var))
                     << "(" << lag
                     << ") " << var+1
                     << ", equation=" << eq+1 << endl;
            }
624
          for (derivative_t::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
625
626
627
628
            {
              int lag = it->first.first;
              unsigned int eq = it->first.second.first;
              unsigned int var = it->first.second.second;
629
              expr_t id = it->second;
630
631
632
633
634
635
636
637
638
639
640

              output << "    g1_o(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                     << "(" << lag
                     << ") " << var+1
                     << ", equation=" << eq+1 << endl;
            }
          output << "    varargout{1}=g1_x;\n";
          output << "    varargout{2}=g1_o;\n";
          output << "  else" << endl;
641
          for (block_derivatives_equation_variable_laglead_nodeid_t::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
642
643
644
645
646
            {
              unsigned int eq = it->first.first;
              unsigned int var = it->first.second;
              unsigned int eqr = getBlockEquationID(block, eq);
              unsigned int varr = getBlockVariableID(block, var);
647
              expr_t id = it->second.second;
648
649
650
651
652
653
654
655
656
657
658
659
660
              int lag = it->second.first;
              output << "    g1(" << eq+1 << ", " << var+1-block_recursive << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr))
                     << "(" << lag
                     << ") " << varr+1
                     << ", equation=" << eqr+1 << endl;
            }
          output << "  end;\n";
          break;
        case SOLVE_TWO_BOUNDARIES_SIMPLE:
        case SOLVE_TWO_BOUNDARIES_COMPLETE:
          output << "    if ~jacobian_eval" << endl;
661
          for (block_derivatives_equation_variable_laglead_nodeid_t::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
662
663
664
665
666
667
            {
              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;
668
              expr_t id = it->second.second;
669
              int lag = it->second.first;
670
              if (eq >= block_recursive && var >= block_recursive)
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
                {
                  if (lag == 0)
                    Uf[eqr] << "+g1(" << eq+1-block_recursive
                            << "+Per_J_, " << var+1-block_recursive
                            << "+Per_K_)*y(it_, " << varr+1 << ")";
                  else if (lag == 1)
                    Uf[eqr] << "+g1(" << eq+1-block_recursive
                            << "+Per_J_, " << var+1-block_recursive
                            << "+Per_y_)*y(it_+1, " << varr+1 << ")";
                  else if (lag > 0)
                    Uf[eqr] << "+g1(" << eq+1-block_recursive
                            << "+Per_J_, " << var+1-block_recursive
                            << "+y_size*(it_+" << lag-1 << "))*y(it_+" << lag << ", " << varr+1 << ")";
                  else if (lag < 0)
                    Uf[eqr] << "+g1(" << eq+1-block_recursive
                            << "+Per_J_, " << var+1-block_recursive
                            << "+y_size*(it_" << lag-1 << "))*y(it_" << lag << ", " << varr+1 << ")";
                  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();
                  id->writeOutput(output, local_output_type, local_temporary_terms);
                  output << ";";
                  output << " %2 variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr))
                         << "(" << lag << ") " << varr+1
                         << ", equation=" << eqr+1 << " (" << eq+1 << ")" << endl;
                }
707

sebastien's avatar
sebastien committed
708
#ifdef CONDITION
709
710
              output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
              output << "    condition(" << eqr << ")=u(" << u << "+Per_u_);\n";
sebastien's avatar
sebastien committed
711
#endif
712
713
714
715
716
            }
          for (unsigned int i = 0; i < block_size; i++)
            {
              if (i >= block_recursive)
                output << "  " << Uf[getBlockEquationID(block, i)].str() << ";\n";
sebastien's avatar
sebastien committed
717
#ifdef CONDITION
718
719
              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
720
#endif
721
            }
sebastien's avatar
sebastien committed
722
#ifdef CONDITION
723
724
725
726
727
728
729
730
731
732
733
734
735
736
          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
737
738
#endif

739
          output << "    else" << endl;
740

741
          for (derivative_t::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++)
742
743
744
745
            {
              int lag = it->first.first;
              unsigned int eq = it->first.second.first;
              unsigned int var = it->first.second.second;
746
              expr_t id = it->second;
747
748
749
750
751
752
753
              output << "      g1(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                     << "(" << lag
                     << ") " << var+1
                     << ", equation=" << eq+1 << endl;
            }
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
          for (derivative_t::const_iterator it = derivative_exo[block].begin(); it != derivative_exo[block].end(); it++)
            {
              int lag = it->first.first;
              int eq = it->first.second.first;
              int var = it->first.second.second;
              int eqr = getBlockInitialEquationID(block, eq);
              expr_t id = it->second;

              output << "      g1_x(" << eqr+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eExogenous, var))
                     << "(" << lag
                     << ") " << var+1
                     << ", equation=" << eq+1 << endl;
            }
          for (derivative_t::const_iterator it = derivative_exo_det[block].begin(); it != derivative_exo_det[block].end(); it++)
            {
              int lag = it->first.first;
              int eq = it->first.second.first;
              int var = it->first.second.second;
              int eqr = getBlockInitialEquationID(block, eq);
              expr_t id = it->second;

              output << "      g1_x(" << eqr+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eExogenous, var))
                     << "(" << lag
                     << ") " << var+1
                     << ", equation=" << eq+1 << endl;
            }
784
          for (derivative_t::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
785
786
787
788
            {
              int lag = it->first.first;
              unsigned int eq = it->first.second.first;
              unsigned int var = it->first.second.second;
789
              expr_t id = it->second;
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808

              output << "      g1_o(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                     << "(" << lag
                     << ") " << var+1
                     << ", equation=" << eq+1 << endl;
            }
          output << "      varargout{1}=g1_x;\n";
          output << "      varargout{2}=g1_o;\n";
          output << "    end;\n";
          output << "  end;\n";
          break;
        default:
          break;
        }
      output.close();
    }
}
sebastien's avatar
sebastien committed
809
810

void
811
DynamicModel::writeModelEquationsCode(string &file_name, const string &bin_basename, const map_idx_t &map_idx) const
812
813
814
{
  ostringstream tmp_output;
  ofstream code_file;
815
  unsigned int instruction_number = 0;
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
  bool file_open = false;
  string main_name = file_name;

  main_name += ".cod";
  code_file.open(main_name.c_str(), ios::out | ios::binary | ios::ate);
  if (!code_file.is_open())
    {
      cout << "Error : Can't open file \"" << main_name << "\" for writing\n";
      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;

  Write_Inf_To_Bin_File(file_name, u_count_int, file_open, simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE, symbol_table.endo_nbr() );
  file_open = true;

  //Temporary variables declaration
  FDIMT_ fdimt(temporary_terms.size());
842
843
844
845
  fdimt.write(code_file, instruction_number);
  int other_endo_size = 0;

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

847
848
849
850
  for(int i = 0; i < symbol_table.exo_det_nbr(); i++)
    exo_det.push_back(i);
  for(int i = 0; i < symbol_table.exo_nbr(); i++)
    exo.push_back(i);
851
852
853
854
855
856
857
858
859
860
  FBEGINBLOCK_ fbeginblock(symbol_table.endo_nbr(),
                           simulation_type,
                           0,
                           symbol_table.endo_nbr(),
                           variable_reordered,
                           equation_reordered,
                           false,
                           symbol_table.endo_nbr(),
                           0,
                           0,
861
862
863
864
865
866
867
868
869
                           u_count_int,
                           0,
                           symbol_table.exo_det_nbr(),
                           symbol_table.exo_nbr(),
                           other_endo_size,
                           0,
                           exo_det,
                           exo,
                           other_endo
870
                           );
871
  fbeginblock.write(code_file, instruction_number);
872

873
  compileTemporaryTerms(code_file, instruction_number, temporary_terms, map_idx, true, false);
874

875
  compileModelEquations(code_file, instruction_number, temporary_terms, map_idx, true, false);
876
877

  FENDEQU_ fendequ;
878
  fendequ.write(code_file, instruction_number);
879
880
881
  vector<vector<pair<pair<int, int>, int > > > derivatives;
  derivatives.resize(symbol_table.endo_nbr());
  count_u = symbol_table.endo_nbr();
882
  for (first_derivatives_t::const_iterator it = first_derivatives.begin();
883
884
885
886
887
       it != first_derivatives.end(); it++)
    {
      int deriv_id = it->first.second;
      if (getTypeByDerivID(deriv_id) == eEndogenous)
        {
888
          expr_t d1 = it->second;
889
890
891
892
          unsigned int eq = it->first.first;
          int symb = getSymbIDByDerivID(deriv_id);
          unsigned int var = symbol_table.getTypeSpecificID(symb);
          int lag = getLagByDerivID(deriv_id);
893
          FNUMEXPR_ fnumexpr(FirstEndoDerivative, eq, var, lag);
894
          fnumexpr.write(code_file, instruction_number);
895
896
897
          if (!derivatives[eq].size())
            derivatives[eq].clear();
          derivatives[eq].push_back(make_pair(make_pair(var, lag), count_u));
898
          d1->compile(code_file, instruction_number, false, temporary_terms, map_idx, true, false);
899
900

          FSTPU_ fstpu(count_u);
901
          fstpu.write(code_file, instruction_number);
902
903
904
905
906
907
          count_u++;
        }
    }
  for (int i = 0; i < symbol_table.endo_nbr(); i++)
    {
      FLDR_ fldr(i);
908
      fldr.write(code_file, instruction_number);
909
910
911
912
      for(vector<pair<pair<int, int>, int> >::const_iterator it = derivatives[i].begin();
          it != derivatives[i].end(); it++)
        {
          FLDU_ fldu(it->second);
913
          fldu.write(code_file, instruction_number);
914
          FLDV_ fldv(eEndogenous, it->first.first, it->first.second);
915
          fldv.write(code_file, instruction_number);
916
          FBINARY_ fbinary(oTimes);
917
          fbinary.write(code_file, instruction_number);
918
919
920
          if (it != derivatives[i].begin())
            {
              FBINARY_ fbinary(oPlus);
921
              fbinary.write(code_file, instruction_number);
922
923
924
            }
        }
      FBINARY_ fbinary(oMinus);
925
      fbinary.write(code_file, instruction_number);
926
      FSTPU_ fstpu(i);
927
      fstpu.write(code_file, instruction_number);
928
929
    }
  FENDBLOCK_ fendblock;
930
  fendblock.write(code_file, instruction_number);
931
  FEND_ fend;
932
  fend.write(code_file, instruction_number);
933
934
935
936
937
938
  code_file.close();
}



void
939
DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin_basename, const map_idx_t &map_idx) const
940
941
{
  struct Uff_l
sebastien's avatar
sebastien committed
942
  {
943
944
945
946
947
948
949
950
951
952
953
954
955
    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;
956
  unsigned int instruction_number = 0;
957
  expr_t lhs = NULL, rhs = NULL;
958
959
  BinaryOpNode *eq_node;
  Uff Uf[symbol_table.endo_nbr()];
960
  map<expr_t, int> reference_count;
961
962
963
964
965
966
967
968
969
970
971
972
973
974
  vector<int> feedback_variables;
  bool file_open = false;

  string main_name = file_name;
  main_name += ".cod";
  code_file.open(main_name.c_str(), ios::out | ios::binary | ios::ate);
  if (!code_file.is_open())
    {
      cout << "Error : Can't open file \"" << main_name << "\" for writing\n";
      exit(EXIT_FAILURE);
    }
  //Temporary variables declaration

  FDIMT_ fdimt(temporary_terms.size());
975
  fdimt.write(code_file, instruction_number);
976
977
978
979
980
981
982

  for (unsigned int block = 0; block < getNbBlocks(); block++)
    {
      feedback_variables.clear();
      if (block > 0)
        {
          FENDBLOCK_ fendblock;
983
          fendblock.write(code_file, instruction_number);
984
985
986
987
988
989
990
        }
      int count_u;
      int u_count_int = 0;
      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;
991
992
      unsigned int block_exo_det_size = exo_det_block[block].size();
      unsigned int block_other_endo_size = other_endo_block[block].size();
993
994
995
996
997
      int block_max_lag = max_leadlag_block[block].first;

      if (simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE
          || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE)
        {
998
          Write_Inf_To_Bin_File_Block(file_name, bin_basename, block, u_count_int, file_open,
999
1000
1001
                                simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE);
          file_open = true;
        }
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
      map<pair<int, pair<int, int> >, expr_t> tmp_block_endo_derivative;
      for (block_derivatives_equation_variable_laglead_nodeid_t::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
        tmp_block_endo_derivative[make_pair(it->second.first, make_pair(it->first.second, it->first.first) )] = it->second.second ;
      map<pair<int, pair<int, int> >, expr_t> tmp_exo_derivative;
      for (derivative_t::const_iterator it = derivative_exo[block].begin(); it != (derivative_exo[block]).end(); it++)
        tmp_exo_derivative[make_pair(it->first.first, make_pair(it->first.second.second, it->first.second.first) )] = it->second ;
      map<pair<int, pair<int, int> >, expr_t> tmp_exo_det_derivative;
      for (derivative_t::const_iterator it = derivative_exo_det[block].begin(); it != (derivative_exo_det[block]).end(); it++)
        tmp_exo_det_derivative[make_pair(it->first.first, make_pair(it->first.second.second, it->first.second.first) )] = it->second;
      map<pair<int, pair<int, int> >, expr_t> tmp_other_endo_derivative;
      for (derivative_t::const_iterator it = derivative_other_endo[block].begin(); it != (derivative_other_endo[block]).end(); it++)
        tmp_other_endo_derivative[make_pair(it->first.first, make_pair(it->first.second.second, it->first.second.first) )] = it->second;
      int prev_var = -1;
      int prev_lag = -999999999;
      int count_col_endo = 0;
      for (map<pair<int, pair<int, int> >, expr_t>::const_iterator it = tmp_block_endo_derivative.begin(); it != tmp_block_endo_derivative.end(); it++)
        {
          int lag = it->first.first;
          int var = it->first.second.first;
          if(prev_var != var || prev_lag != lag)
            {
              prev_var = var;
              prev_lag = lag;
              count_col_endo++;
            }
        }
      vector<unsigned int> exo_det;
      for (lag_var_t::const_iterator it = exo_det_block[block].begin(); it != exo_det_block[block].end(); it++)
        exo_det.push_back(it->first);
      vector<unsigned int> exo;
      for (lag_var_t::const_iterator it = exo_block[block].begin(); it != exo_block[block].end(); it++)
        exo.push_back(it->first);
      vector<unsigned int> other_endo;
      unsigned int count_col_other_endo = 0;
      for (lag_var_t::const_iterator it = other_endo_block[block].begin(); it != other_endo_block[block].end(); it++)
        {
          other_endo.push_back(it->first);
          count_col_other_endo += it->second.size();
        }
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
      FBEGINBLOCK_ fbeginblock(block_mfs,
                               simulation_type,
                               getBlockFirstEquation(block),
                               block_size,
                               variable_reordered,
                               equation_reordered,
                               blocks_linear[block],
                               symbol_table.endo_nbr(),
                               block_max_lag,
                               block_max_lag,
1051
1052
1053
1054
1055
1056
1057
1058
1059
                               u_count_int,
                               count_col_endo,
                               block_exo_det_size,
                               getBlockExoColSize(block),
                               block_other_endo_size,
                               count_col_other_endo,
                               exo_det,
                               exo,
                               other_endo
1060
                               );
1061
      fbeginblock.write(code_file, instruction_number);
1062
1063
1064
1065
1066

      // The equations
      for (i = 0; i < (int) block_size; i++)
        {
          //The Temporary terms
1067
          temporary_terms_t tt2;
1068
1069
1070
          tt2.clear();
          if (v_temporary_terms[block][i].size())
            {
1071
              for (temporary_terms_t::const_iterator it = v_temporary_terms[block][i].begin();
1072
1073
                   it != v_temporary_terms[block][i].end(); it++)
                {
1074
                  FNUMEXPR_ fnumexpr(TemporaryTerm, (int)(map_idx.find((*it)->idx)->second));
1075
1076
                  fnumexpr.write(code_file, instruction_number);
                  (*it)->compile(code_file, instruction_number, false, tt2, map_idx, true, false);
1077
                  FSTPT_ fstpt((int)(map_idx.find((*it)->idx)->second));
1078
                  fstpt.write(code_file, instruction_number);
1079
1080
                  // Insert current node into tt2
                  tt2.insert(*it);
sebastien's avatar
sebastien committed
1081
#ifdef DEBUGC
1082
                  cout << "FSTPT " << v << "\n";
1083
                  instruction_number++;
1084
1085
1086
                  code_file.write(&FOK, sizeof(FOK));
                  code_file.write(reinterpret_cast<char *>(&k), sizeof(k));
                  ki++;
sebastien's avatar
sebastien committed
1087
1088
#endif

1089
1090
                }
            }
sebastien's avatar
sebastien committed
1091
#ifdef DEBUGC
1092
          for (temporary_terms_t::const_iterator it = v_temporary_terms[block][i].begin();
1093
1094
               it != v_temporary_terms[block][i].end(); it++)
            {
1095
              map_idx_t::const_iterator ii = map_idx.find((*it)->idx);
1096
1097
              cout << "map_idx[" << (*it)->idx <<"]=" << ii->second << "\n";
            }
1098
1099
#endif

1100
1101
          int variable_ID, equation_ID;
          EquationType equ_type;
1102

1103
1104
1105
1106
1107
1108
          switch (simulation_type)
            {
            evaluation:
            case EVALUATE_BACKWARD:
            case EVALUATE_FORWARD:
              equ_type = getBlockEquationType(block, i);
1109
1110
              {
                FNUMEXPR_ fnumexpr(ModelEquation, getBlockEquationID(block, i));
1111
                fnumexpr.write(code_file, instruction_number);
1112
              }
1113
1114
              if (equ_type == E_EVALUATE)
                {
1115
                  eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
1116
1117
                  lhs = eq_node->get_arg1();
                  rhs = eq_node->get_arg2();
1118
1119
                  rhs->compile(code_file, instruction_number, false, temporary_terms, map_idx, true, false);
                  lhs->compile(code_file, instruction_number, true, temporary_terms, map_idx, true, false);
1120
1121
1122
                }
              else if (equ_type == E_EVALUATE_S)