StaticModel.cc 64 KB
Newer Older
sebastien's avatar
sebastien committed
1
/*
2
 * Copyright (C) 2003-2011 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
21
#include <iostream>
#include <cmath>
22
#include <cstdlib>
23
#include <cassert>
24
25
#include <cstdio>
#include <cerrno>
sebastien's avatar
sebastien committed
26
#include <algorithm>
27
28
29
30
31
32
33
34
35
#include "StaticModel.hh"

// For mkdir() and chdir()
#ifdef _WIN32
# include <direct.h>
#else
# include <unistd.h>
# include <sys/stat.h>
# include <sys/types.h>
36
#endif
sebastien's avatar
sebastien committed
37

38
StaticModel::StaticModel(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
  global_temporary_terms(true)
43
44
{
}
45

46
void
47
StaticModel::compileDerivative(ofstream &code_file, unsigned int &instruction_number, int eq, int symb_id, map_idx_t &map_idx, temporary_terms_t temporary_terms) const
48
{
49
  first_derivatives_t::const_iterator it = first_derivatives.find(make_pair(eq, symbol_table.getID(eEndogenous, symb_id)));
50
  if (it != first_derivatives.end())
51
    (it->second)->compile(code_file, instruction_number, false, temporary_terms, map_idx, false, false);
52
53
54
  else
    {
      FLDZ_ fldz;
55
      fldz.write(code_file, instruction_number);
56
57
    }
}
sebastien's avatar
sebastien committed
58

59
void
60
StaticModel::compileChainRuleDerivative(ofstream &code_file, unsigned int &instruction_number, int eqr, int varr, int lag, map_idx_t &map_idx, temporary_terms_t temporary_terms) const
61
{
62
  map<pair<int, pair<int, int> >, expr_t>::const_iterator it = first_chain_rule_derivatives.find(make_pair(eqr, make_pair(varr, lag)));
63
  if (it != first_chain_rule_derivatives.end())
64
    (it->second)->compile(code_file, instruction_number, false, temporary_terms, map_idx, false, false);
65
66
67
  else
    {
      FLDZ_ fldz;
68
      fldz.write(code_file, instruction_number);
69
70
71
72
73
74
    }
}

void
StaticModel::computeTemporaryTermsOrdered()
{
75
76
  map<expr_t, pair<int, int> > first_occurence;
  map<expr_t, int> reference_count;
77
  BinaryOpNode *eq_node;
78
79
  first_derivatives_t::const_iterator it;
  first_chain_rule_derivatives_t::const_iterator it_chr;
80
81
82
83
84
  ostringstream tmp_s;
  v_temporary_terms.clear();
  map_idx.clear();

  unsigned int nb_blocks = getNbBlocks();
85
  v_temporary_terms = vector< vector<temporary_terms_t> >(nb_blocks);
86
  v_temporary_terms_local = vector< vector<temporary_terms_t> >(nb_blocks);
87

88
  v_temporary_terms_inuse = vector<temporary_terms_inuse_t>(nb_blocks);
89

90
91
  map_idx2 = vector<map_idx_t>(nb_blocks);

92
  temporary_terms.clear();
93
94
95

  //local temporay terms
  for (unsigned int block = 0; block < nb_blocks; block++)
96
    {
97
98
99
100
101
102
      map<expr_t, int> reference_count_local;
      reference_count_local.clear();
      map<expr_t, pair<int, int> > first_occurence_local;
      first_occurence_local.clear();
      temporary_terms_t temporary_terms_l;
      temporary_terms_l.clear();
103

104
105
106
107
108
109
110
111
112
113
      unsigned int block_size = getBlockSize(block);
      unsigned int block_nb_mfs = getBlockMfs(block);
      unsigned int block_nb_recursives = block_size - block_nb_mfs;
      v_temporary_terms_local[block] = vector<temporary_terms_t>(block_size);

      for (unsigned int i = 0; i < block_size; i++)
        {
          if (i < block_nb_recursives && isBlockEquationRenormalized(block, i))
            getBlockEquationRenormalizedExpr(block, i)->computeTemporaryTerms(reference_count_local, temporary_terms_l, first_occurence_local, block, v_temporary_terms_local,  i);
          else
114
            {
115
116
              eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
              eq_node->computeTemporaryTerms(reference_count_local, temporary_terms_l, first_occurence_local, block, v_temporary_terms_local,  i);
117
118
            }
        }
119
120
121
122
123
124
125
126
127
      for (block_derivatives_equation_variable_laglead_nodeid_t::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
        {
          expr_t id = it->second.second;
          id->computeTemporaryTerms(reference_count_local, temporary_terms_l, first_occurence_local, block, v_temporary_terms_local,  block_size-1);
        }
      set<int> temporary_terms_in_use;
      temporary_terms_in_use.clear();
      v_temporary_terms_inuse[block] = temporary_terms_in_use;
      computeTemporaryTermsMapping(temporary_terms_l, map_idx2[block]);
128
    }
129
130
131

  // global temporay terms
  for (unsigned int block = 0; block < nb_blocks; block++)
132
    {
133
134
135
136
137
138
      // 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;
      v_temporary_terms[block] = vector<temporary_terms_t>(block_size);
      for (unsigned int i = 0; i < block_size; i++)
139
        {
140
141
142
          if (i < block_nb_recursives && isBlockEquationRenormalized(block, i))
            getBlockEquationRenormalizedExpr(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  i);
          else
143
            {
144
145
              eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
              eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i);
146
147
            }
        }
148
      for (block_derivatives_equation_variable_laglead_nodeid_t::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
149
        {
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
          expr_t id = it->second.second;
          id->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1);
        }
    }

  for (unsigned int block = 0; block < nb_blocks; block++)
    {
      // Collecte 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++)
        {
          if (i < block_nb_recursives && isBlockEquationRenormalized(block, i))
            getBlockEquationRenormalizedExpr(block, i)->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
          else
167
            {
168
169
              eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
              eq_node->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
170
171
            }
        }
172
173
174
175
176
177
178
179
180
181
      for (block_derivatives_equation_variable_laglead_nodeid_t::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
        {
          expr_t id = it->second.second;
          id->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
        }
      for (int i = 0; i < (int) getBlockSize(block); i++)
        for (temporary_terms_t::const_iterator it = v_temporary_terms[block][i].begin();
             it != v_temporary_terms[block][i].end(); it++)
          (*it)->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
      v_temporary_terms_inuse[block] = temporary_terms_in_use;
182
    }
183
  computeTemporaryTermsMapping(temporary_terms, map_idx);
184
185
186
}

void
187
StaticModel::computeTemporaryTermsMapping(temporary_terms_t &temporary_terms, map_idx_t &map_idx)
188
{
189
  // Add a mapping form node ID to temporary terms order
190
  int j = 0;
191
  for (temporary_terms_t::const_iterator it = temporary_terms.begin();
192
       it != temporary_terms.end(); it++)
193
    map_idx[(*it)->idx] = j++;
194
195
196
197
}

void
StaticModel::writeModelEquationsOrdered_M(const string &static_basename) const
198
199
200
{
  string tmp_s, sps;
  ostringstream tmp_output, tmp1_output, global_output;
201
  expr_t lhs = NULL, rhs = NULL;
202
  BinaryOpNode *eq_node;
203
  map<expr_t, int> reference_count;
204
  temporary_terms_t local_temporary_terms;
205
206
207
  ofstream  output;
  int nze;
  vector<int> feedback_variables;
208
  deriv_node_temp_terms_t tef_terms;
209
  ExprNodeOutputType local_output_type;
210

Sébastien Villemot's avatar
Sébastien Villemot committed
211
  local_output_type = oMatlabStaticModelSparse;
212
  if (global_temporary_terms)
Sébastien Villemot's avatar
Sébastien Villemot committed
213
    local_temporary_terms = temporary_terms;
214
215
216
217
218
219
220
221
222
223
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

  //----------------------------------------------------------------------
  //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();
      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;

      tmp1_output.str("");
      tmp1_output << static_basename << "_" << block+1 << ".m";
      output.open(tmp1_output.str().c_str(), ios::out | ios::binary);
      output << "%\n";
      output << "% " << tmp1_output.str() << " : Computes static 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 = " << static_basename << "_" << block+1 << "(y, x, params)\n";
      else
        output << "function [residual, y, g1] = " << static_basename << "_" << block+1 << "(y, x, params)\n";

      BlockType block_type;
      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)
264
        output << " g1 = spalloc("  << block_mfs << ", " << block_mfs << ", " << derivative_endo[block].size() << ");" << endl;
265
266
267
268

      if (v_temporary_terms_inuse[block].size())
        {
          tmp_output.str("");
269
          for (temporary_terms_inuse_t::const_iterator it = v_temporary_terms_inuse[block].begin();
270
271
272
273
274
275
276
277
278
279
280
281
282
               it != v_temporary_terms_inuse[block].end(); it++)
            tmp_output << " T" << *it;
          output << "  global" << tmp_output.str() << ";\n";
        }

      if (simulation_type != EVALUATE_BACKWARD && simulation_type != EVALUATE_FORWARD)
        output << "  residual=zeros(" << block_mfs << ",1);\n";

      // The equations
      for (unsigned int i = 0; i < block_size; i++)
        {
          if (!global_temporary_terms)
            local_temporary_terms = v_temporary_terms[block][i];
283
          temporary_terms_t tt2;
284
285
286
287
          tt2.clear();
          if (v_temporary_terms[block].size())
            {
              output << "  " << "% //Temporary variables" << endl;
288
              for (temporary_terms_t::const_iterator it = v_temporary_terms[block][i].begin();
289
290
                   it != v_temporary_terms[block][i].end(); it++)
                {
291
292
293
                  if (dynamic_cast<ExternalFunctionNode *>(*it) != NULL)
                    (*it)->writeExternalFunctionOutput(output, local_output_type, tt2, tef_terms);

294
                  output << "  " <<  sps;
295
                  (*it)->writeOutput(output, local_output_type, local_temporary_terms, tef_terms);
296
                  output << " = ";
297
                  (*it)->writeOutput(output, local_output_type, tt2, tef_terms);
298
299
300
301
302
303
304
305
306
307
                  // 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));
308
          eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
          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:
              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("");
336
                      eq_node = (BinaryOpNode *) getBlockEquationRenormalizedExpr(block, i);
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
                      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
                     << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl;
              output << "  " << "residual(" << i+1-block_recursive << ") = (";
              goto end;
            default:
            end:
              output << tmp_output.str();
              output << ") - (";
              rhs->writeOutput(output, local_output_type, local_temporary_terms);
              output << ");\n";
            }
        }
      // The Jacobian if we have to solve the block
      if (simulation_type == SOLVE_BACKWARD_SIMPLE   || simulation_type == SOLVE_FORWARD_SIMPLE
          || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE)
        output << "  " << sps << "% Jacobian  " << endl;
      switch (simulation_type)
        {
        case SOLVE_BACKWARD_SIMPLE:
        case SOLVE_FORWARD_SIMPLE:
        case SOLVE_BACKWARD_COMPLETE:
        case SOLVE_FORWARD_COMPLETE:
380
          for (block_derivatives_equation_variable_laglead_nodeid_t::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
381
382
383
384
385
            {
              unsigned int eq = it->first.first;
              unsigned int var = it->first.second;
              unsigned int eqr = getBlockEquationID(block, eq);
              unsigned int varr = getBlockVariableID(block, var);
386
              expr_t id = it->second.second;
387
388
389
390
391
392
393
394
395
396
397
              output << "    g1(" << eq+1-block_recursive << ", " << var+1-block_recursive << ") = ";
              id->writeOutput(output, local_output_type, local_temporary_terms);
              output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr))
                     << "(" << 0
                     << ") " << varr+1
                     << ", equation=" << eqr+1 << endl;
            }
          break;
        default:
          break;
        }
398
      output << "end" << endl;
399
400
401
      output.close();
    }
}
402
403

void
404
StaticModel::writeModelEquationsCode(const string file_name, const string bin_basename, map_idx_t map_idx) const
405
406
407
408
{

  ostringstream tmp_output;
  ofstream code_file;
409
  unsigned int instruction_number = 0;
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
  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;

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

  //Temporary variables declaration
427
428
  FDIMST_ fdimst(temporary_terms.size());
  fdimst.write(code_file, instruction_number);
429
430
431
432
433
434
435
436
437
438
  FBEGINBLOCK_ fbeginblock(symbol_table.endo_nbr(),
                           SOLVE_FORWARD_COMPLETE,
                           0,
                           symbol_table.endo_nbr(),
                           variable_reordered,
                           equation_reordered,
                           false,
                           symbol_table.endo_nbr(),
                           0,
                           0,
439
440
                           u_count_int,
                           symbol_table.endo_nbr()
441
                           );
442
  fbeginblock.write(code_file, instruction_number);
443
444
445

  // Add a mapping form node ID to temporary terms order
  int j = 0;
446
  for (temporary_terms_t::const_iterator it = temporary_terms.begin();
447
448
       it != temporary_terms.end(); it++)
    map_idx[(*it)->idx] = j++;
449
  compileTemporaryTerms(code_file, instruction_number, temporary_terms, map_idx, false, false);
450

451
  compileModelEquations(code_file, instruction_number, temporary_terms, map_idx, false, false);
452
453

  FENDEQU_ fendequ;
454
  fendequ.write(code_file, instruction_number);
455

456
457
458
459
460
461
  // 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;

462
463
464
  vector<vector<pair<int, int> > > derivatives;
  derivatives.resize(symbol_table.endo_nbr());
  count_u = symbol_table.endo_nbr();
465
  for (first_derivatives_t::const_iterator it = first_derivatives.begin();
466
467
468
469
470
       it != first_derivatives.end(); it++)
    {
      int deriv_id = it->first.second;
      if (getTypeByDerivID(deriv_id) == eEndogenous)
        {
471
          expr_t d1 = it->second;
472
473
474
          unsigned int eq = it->first.first;
          int symb = getSymbIDByDerivID(deriv_id);
          unsigned int var = symbol_table.getTypeSpecificID(symb);
475
          FNUMEXPR_ fnumexpr(FirstEndoDerivative, eq, var);
476
          fnumexpr.write(code_file, instruction_number);
477
478
479
480
          if (!derivatives[eq].size())
            derivatives[eq].clear();
          derivatives[eq].push_back(make_pair(var, count_u));

481
          d1->compile(code_file, instruction_number, false, temporary_terms, map_idx, false, false);
482
483

          FSTPSU_ fstpsu(count_u);
484
          fstpsu.write(code_file, instruction_number);
485
486
487
488
489
490
          count_u++;
        }
    }
  for (int i = 0; i < symbol_table.endo_nbr(); i++)
    {
      FLDR_ fldr(i);
491
      fldr.write(code_file, instruction_number);
492
      if (derivatives[i].size())
493
        {
494
495
          for (vector<pair<int, int> >::const_iterator it = derivatives[i].begin();
               it != derivatives[i].end(); it++)
496
            {
497
498
499
500
501
              FLDSU_ fldsu(it->second);
              fldsu.write(code_file, instruction_number);
              FLDSV_ fldsv(eEndogenous, it->first);
              fldsv.write(code_file, instruction_number);
              FBINARY_ fbinary(oTimes);
502
              fbinary.write(code_file, instruction_number);
503
504
505
506
507
              if (it != derivatives[i].begin())
                {
                  FBINARY_ fbinary(oPlus);
                  fbinary.write(code_file, instruction_number);
                }
508
            }
509
510
          FBINARY_ fbinary(oMinus);
          fbinary.write(code_file, instruction_number);
511
512
        }
      FSTPSU_ fstpsu(i);
513
      fstpsu.write(code_file, instruction_number);
514
    }
515
516
517
518
519
520
521
522
523
524
  // 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);
525
  prev_instruction_number = instruction_number;
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549

  temporary_terms_t tt2;
  tt2.clear();
  temporary_terms_t tt3;
  tt3.clear();

  // The Jacobian if we have to solve the block determinsitic bloc
  for (first_derivatives_t::const_iterator it = first_derivatives.begin();
       it != first_derivatives.end(); it++)
    {
      int deriv_id = it->first.second;
      if (getTypeByDerivID(deriv_id) == eEndogenous)
        {
          expr_t d1 = it->second;
          unsigned int eq = it->first.first;
          int symb = getSymbIDByDerivID(deriv_id);
          unsigned int var = symbol_table.getTypeSpecificID(symb);
          FNUMEXPR_ fnumexpr(FirstEndoDerivative, eq, var);
          fnumexpr.write(code_file, instruction_number);
          if (!derivatives[eq].size())
            derivatives[eq].clear();
          derivatives[eq].push_back(make_pair(var, count_u));

          d1->compile(code_file, instruction_number, false, temporary_terms, map_idx, false, false);
550
          FSTPG2_ fstpg2(eq, var);
551
552
553
554
555
556
557
558
559
560
561
          fstpg2.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);

562
  FENDBLOCK_ fendblock;
563
  fendblock.write(code_file, instruction_number);
564
  FEND_ fend;
565
  fend.write(code_file, instruction_number);
566
  writePowerDeriv(code_file, false);
567
568
569
570
  code_file.close();
}

void
571
StaticModel::writeModelEquationsCode_Block(const string file_name, const string bin_basename, map_idx_t map_idx, vector<map_idx_t> map_idx2) const
572
573
{
  struct Uff_l
574
  {
575
576
577
    int u, var, lag;
    Uff_l *pNext;
  };
578

579
580
581
582
583
584
585
586
587
  struct Uff
  {
    Uff_l *Ufl, *Ufl_First;
  };

  int i, v;
  string tmp_s;
  ostringstream tmp_output;
  ofstream code_file;
588
  unsigned int instruction_number = 0;
589
  expr_t lhs = NULL, rhs = NULL;
590
591
  BinaryOpNode *eq_node;
  Uff Uf[symbol_table.endo_nbr()];
592
  map<expr_t, int> reference_count;
593
  vector<int> feedback_variables;
594
  deriv_node_temp_terms_t tef_terms;
595
596
597
598
599
600
601
602
603
604
605
606
  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

607
608
  FDIMST_ fdimst(temporary_terms.size());
  fdimst.write(code_file, instruction_number);
609
610
611
612
613
614
615

  for (unsigned int block = 0; block < getNbBlocks(); block++)
    {
      feedback_variables.clear();
      if (block > 0)
        {
          FENDBLOCK_ fendblock;
616
          fendblock.write(code_file, instruction_number);
617
618
619
620
621
622
623
624
625
626
627
        }
      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;

      if (simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE
          || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE)
        {
628
          Write_Inf_To_Bin_File_Block(file_name, bin_basename, block, u_count_int, file_open);
629
630
631
632
633
634
635
636
637
638
639
640
641
          file_open = true;
        }

      FBEGINBLOCK_ fbeginblock(block_mfs,
                               simulation_type,
                               getBlockFirstEquation(block),
                               block_size,
                               variable_reordered,
                               equation_reordered,
                               blocks_linear[block],
                               symbol_table.endo_nbr(),
                               0,
                               0,
642
                               u_count_int,
643
                               /*symbol_table.endo_nbr()*/ block_size
644
                               );
645

646
      fbeginblock.write(code_file, instruction_number);
647

648
649
650
651
652
653
      // 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;

654
655
656
      for (i = 0; i < (int) block_size; i++)
        {
          //The Temporary terms
657
          temporary_terms_t tt2;
658
659
660
          tt2.clear();
          if (v_temporary_terms[block].size())
            {
661
              for (temporary_terms_t::const_iterator it = v_temporary_terms[block][i].begin();
662
663
                   it != v_temporary_terms[block][i].end(); it++)
                {
664
665
666
                  if (dynamic_cast<ExternalFunctionNode *>(*it) != NULL)
                    (*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt2, map_idx, false, false, tef_terms);

667
                  FNUMEXPR_ fnumexpr(TemporaryTerm, (int) (map_idx.find((*it)->idx)->second));
668
                  fnumexpr.write(code_file, instruction_number);
669
                  (*it)->compile(code_file, instruction_number, false, tt2, map_idx, false, false, tef_terms);
670
                  FSTPST_ fstpst((int) (map_idx.find((*it)->idx)->second));
671
                  fstpst.write(code_file, instruction_number);
672
673
674
675
676
                  // Insert current node into tt2
                  tt2.insert(*it);
                }
            }

677
          // The equations
678
679
680
681
682
683
684
685
          int variable_ID, equation_ID;
          EquationType equ_type;
          switch (simulation_type)
            {
            evaluation:
            case EVALUATE_BACKWARD:
            case EVALUATE_FORWARD:
              equ_type = getBlockEquationType(block, i);
686
687
              {
                FNUMEXPR_ fnumexpr(ModelEquation, getBlockEquationID(block, i));
688
                fnumexpr.write(code_file, instruction_number);
689
              }
690
691
              if (equ_type == E_EVALUATE)
                {
692
                  eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
693
694
                  lhs = eq_node->get_arg1();
                  rhs = eq_node->get_arg2();
695
696
                  rhs->compile(code_file, instruction_number, false, temporary_terms, map_idx, false, false);
                  lhs->compile(code_file, instruction_number, true, temporary_terms, map_idx, false, false);
697
698
699
                }
              else if (equ_type == E_EVALUATE_S)
                {
700
                  eq_node = (BinaryOpNode *) getBlockEquationRenormalizedExpr(block, i);
701
702
                  lhs = eq_node->get_arg1();
                  rhs = eq_node->get_arg2();
703
704
                  rhs->compile(code_file, instruction_number, false, temporary_terms, map_idx, false, false);
                  lhs->compile(code_file, instruction_number, true, temporary_terms, map_idx, false, false);
705
706
707
708
709
710
711
712
713
714
715
716
717
                }
              break;
            case SOLVE_BACKWARD_COMPLETE:
            case SOLVE_FORWARD_COMPLETE:
              if (i < (int) block_recursive)
                goto evaluation;
              variable_ID = getBlockVariableID(block, i);
              equation_ID = getBlockEquationID(block, i);
              feedback_variables.push_back(variable_ID);
              Uf[equation_ID].Ufl = NULL;
              goto end;
            default:
            end:
718
              FNUMEXPR_ fnumexpr(ModelEquation, getBlockEquationID(block, i));
719
              fnumexpr.write(code_file, instruction_number);
720
              eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
721
722
              lhs = eq_node->get_arg1();
              rhs = eq_node->get_arg2();
723
724
              lhs->compile(code_file, instruction_number, false, temporary_terms, map_idx, false, false);
              rhs->compile(code_file, instruction_number, false, temporary_terms, map_idx, false, false);
725
726

              FBINARY_ fbinary(oMinus);
727
              fbinary.write(code_file, instruction_number);
728
729

              FSTPR_ fstpr(i - block_recursive);
730
              fstpr.write(code_file, instruction_number);
731
732
733
            }
        }
      FENDEQU_ fendequ;
734
      fendequ.write(code_file, instruction_number);
735

736
737
738
739
740
741
742
743
      // The Jacobian if we have to solve the block
      if    (simulation_type != EVALUATE_BACKWARD
             && simulation_type != EVALUATE_FORWARD)
        {
          switch (simulation_type)
            {
            case SOLVE_BACKWARD_SIMPLE:
            case SOLVE_FORWARD_SIMPLE:
744
745
              {
                FNUMEXPR_ fnumexpr(FirstEndoDerivative, 0, 0);
746
                fnumexpr.write(code_file, instruction_number);
747
              }
748
              compileDerivative(code_file, instruction_number, getBlockEquationID(block, 0), getBlockVariableID(block, 0), map_idx, temporary_terms);
749
              {
750
                FSTPG_ fstpg(0);
751
                fstpg.write(code_file, instruction_number);
752
              }
753
              break;
754

755
756
757
            case SOLVE_BACKWARD_COMPLETE:
            case SOLVE_FORWARD_COMPLETE:
              count_u = feedback_variables.size();
758
              for (block_derivatives_equation_variable_laglead_nodeid_t::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
759
760
761
762
763
                {
                  unsigned int eq = it->first.first;
                  unsigned int var = it->first.second;
                  unsigned int eqr = getBlockEquationID(block, eq);
                  unsigned int varr = getBlockVariableID(block, var);
764
                  if (eq >= block_recursive && var >= block_recursive)
765
766
767
768
769
770
771
772
773
774
775
776
777
778
                    {
                      if (!Uf[eqr].Ufl)
                        {
                          Uf[eqr].Ufl = (Uff_l *) malloc(sizeof(Uff_l));
                          Uf[eqr].Ufl_First = Uf[eqr].Ufl;
                        }
                      else
                        {
                          Uf[eqr].Ufl->pNext = (Uff_l *) malloc(sizeof(Uff_l));
                          Uf[eqr].Ufl = Uf[eqr].Ufl->pNext;
                        }
                      Uf[eqr].Ufl->pNext = NULL;
                      Uf[eqr].Ufl->u = count_u;
                      Uf[eqr].Ufl->var = varr;
779
                      FNUMEXPR_ fnumexpr(FirstEndoDerivative, eqr, varr);
780
                      fnumexpr.write(code_file, instruction_number);
781
                      compileChainRuleDerivative(code_file, instruction_number, eqr, varr, 0, map_idx, temporary_terms);
782
                      FSTPSU_ fstpsu(count_u);
783
                      fstpsu.write(code_file, instruction_number);
784
785
786
787
788
789
790
791
                      count_u++;
                    }
                }
              for (i = 0; i < (int) block_size; i++)
                {
                  if (i >= (int) block_recursive)
                    {
                      FLDR_ fldr(i-block_recursive);
792
                      fldr.write(code_file, instruction_number);
793
794

                      FLDZ_ fldz;
795
                      fldz.write(code_file, instruction_number);
796
797
798
799
800

                      v = getBlockEquationID(block, i);
                      for (Uf[v].Ufl = Uf[v].Ufl_First; Uf[v].Ufl; Uf[v].Ufl = Uf[v].Ufl->pNext)
                        {
                          FLDSU_ fldsu(Uf[v].Ufl->u);
801
                          fldsu.write(code_file, instruction_number);
802
                          FLDSV_ fldsv(eEndogenous, Uf[v].Ufl->var);
803
                          fldsv.write(code_file, instruction_number);
804
805

                          FBINARY_ fbinary(oTimes);
806
                          fbinary.write(code_file, instruction_number);
807
808

                          FCUML_ fcuml;
809
                          fcuml.write(code_file, instruction_number);
810
811
812
813
814
815
816
817
818
                        }
                      Uf[v].Ufl = Uf[v].Ufl_First;
                      while (Uf[v].Ufl)
                        {
                          Uf[v].Ufl_First = Uf[v].Ufl->pNext;
                          free(Uf[v].Ufl);
                          Uf[v].Ufl = Uf[v].Ufl_First;
                        }
                      FBINARY_ fbinary(oMinus);
819
                      fbinary.write(code_file, instruction_number);
820
821

                      FSTPSU_ fstpsu(i - block_recursive);
822
                      fstpsu.write(code_file, instruction_number);
823
824
825
826
827
828
829
830

                    }
                }
              break;
            default:
              break;
            }
        }
831
832
833
834
835
836
837
838
839
840
841

      // 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);
842
      prev_instruction_number = instruction_number;
843
844
845
846
847

      temporary_terms_t tt2;
      tt2.clear();
      temporary_terms_t tt3;
      tt3.clear();
848
      deriv_node_temp_terms_t tef_terms2;
849
850
851
852
853
854
855
856

      for (i = 0; i < (int) block_size; i++)
        {
          if (v_temporary_terms_local[block].size())
            {
              for (temporary_terms_t::const_iterator it = v_temporary_terms_local[block][i].begin();
                   it != v_temporary_terms_local[block][i].end(); it++)
                {
857
                  if (dynamic_cast<ExternalFunctionNode *>(*it) != NULL)
858
                    (*it)->compileExternalFunctionOutput(code_file, instruction_number, false, tt3, map_idx2[block], false, false, tef_terms2);
859

860
                  FNUMEXPR_ fnumexpr(TemporaryTerm, (int) (map_idx2[block].find((*it)->idx)->second));
861
                  fnumexpr.write(code_file, instruction_number);
862
863
864

                  (*it)->compile(code_file, instruction_number, false, tt3, map_idx2[block], false, false, tef_terms);

865
                  FSTPST_ fstpst((int) (map_idx2[block].find((*it)->idx)->second));
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
                  fstpst.write(code_file, instruction_number);
                  // Insert current node into tt2
                  tt3.insert(*it);
                  tt2.insert(*it);
                }
            }

          // The equations
          int variable_ID, equation_ID;
          EquationType equ_type;
          switch (simulation_type)
            {
            evaluation_l:
            case EVALUATE_BACKWARD:
            case EVALUATE_FORWARD:
              equ_type = getBlockEquationType(block, i);
              {
                FNUMEXPR_ fnumexpr(ModelEquation, getBlockEquationID(block, i));
                fnumexpr.write(code_file, instruction_number);
              }
              if (equ_type == E_EVALUATE)
                {
                  eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
                  lhs = eq_node->get_arg1();
                  rhs = eq_node->get_arg2();
891
892
                  rhs->compile(code_file, instruction_number, false, tt2, map_idx2[block], false, false);
                  lhs->compile(code_file, instruction_number, true, tt2, map_idx2[block], false, false);
893
894
895
896
897
898
                }
              else if (equ_type == E_EVALUATE_S)
                {
                  eq_node = (BinaryOpNode *) getBlockEquationRenormalizedExpr(block, i);
                  lhs = eq_node->get_arg1();
                  rhs = eq_node->get_arg2();
899
900
                  rhs->compile(code_file, instruction_number, false, tt2, map_idx2[block], false, false);
                  lhs->compile(code_file, instruction_number, true, tt2, map_idx2[block], false, false);
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
                }
              break;
            case SOLVE_BACKWARD_COMPLETE:
            case SOLVE_FORWARD_COMPLETE:
              if (i < (int) block_recursive)
                goto evaluation_l;
              variable_ID = getBlockVariableID(block, i);
              equation_ID = getBlockEquationID(block, i);
              feedback_variables.push_back(variable_ID);
              Uf[equation_ID].Ufl = NULL;
              goto end_l;
            default:
            end_l:
              FNUMEXPR_ fnumexpr(ModelEquation, getBlockEquationID(block, i));
              fnumexpr.write(code_file, instruction_number);
              eq_node = (BinaryOpNode *) getBlockEquationExpr(block, i);
              lhs = eq_node->get_arg1();
              rhs = eq_node->get_arg2();
919
920
              lhs->compile(code_file, instruction_number, false, tt2, map_idx2[block], false, false);
              rhs->compile(code_file, instruction_number, false, tt2, map_idx2[block], false, false);
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940

              FBINARY_ fbinary(oMinus);
              fbinary.write(code_file, instruction_number);

              FSTPR_ fstpr(i - block_recursive);
              fstpr.write(code_file, instruction_number);
            }
        }
      FENDEQU_ fendequ_l;
      fendequ_l.write(code_file, instruction_number);

      // The Jacobian if we have to solve the block determinsitic bloc
      switch (simulation_type)
        {
        case SOLVE_BACKWARD_SIMPLE:
        case SOLVE_FORWARD_SIMPLE:
          {
            FNUMEXPR_ fnumexpr(FirstEndoDerivative, 0, 0);
            fnumexpr.write(code_file, instruction_number);
          }
941
          compileDerivative(code_file, instruction_number, getBlockEquationID(block, 0), getBlockVariableID(block, 0), map_idx2[block], tt2 /*temporary_terms*/);
942
          {
943
            FSTPG2_ fstpg2(0, 0);
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
            fstpg2.write(code_file, instruction_number);
          }
          break;
        case EVALUATE_BACKWARD:
        case EVALUATE_FORWARD:
        case SOLVE_BACKWARD_COMPLETE:
        case SOLVE_FORWARD_COMPLETE:
          count_u = feedback_variables.size();
          for (block_derivatives_equation_variable_laglead_nodeid_t::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
            {
              unsigned int eq = it->first.first;
              unsigned int var = it->first.second;
              unsigned int eqr = getBlockEquationID(block, eq);
              unsigned int varr = getBlockVariableID(block, var);
              FNUMEXPR_ fnumexpr(FirstEndoDerivative, eqr, varr, 0);
              fnumexpr.write(code_file, instruction_number);

961
              compileChainRuleDerivative(code_file, instruction_number, eqr, varr, 0, map_idx2[block], tt2 /*temporary_terms*/);
962

963
              FSTPG2_ fstpg2(eq, var);
964
965
966
967
968
969
970
971
972
973
974
975
              fstpg2.write(code_file, instruction_number);
            }
          break;
        default:
          break;
        }
      // 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);
976
977
    }
  FENDBLOCK_ fendblock;
978
  fendblock.write(code_file, instruction_number);
979
  FEND_ fend;
980
  fend.write(code_file, instruction_number);
981
982
  code_file.close();
}
983
984

void
985
StaticModel::Write_Inf_To_Bin_File_Block(const string &static_basename, const string &bin_basename, const int &num,
986
                                         int &u_count_int, bool &file_open) const
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
  int j;
  std::ofstream SaveCode;
  if (file_open)
    SaveCode.open((bin_basename + "_static.bin").c_str(), ios::out | ios::in | ios::binary | ios::ate);
  else
    SaveCode.open((bin_basename + "_static.bin").c_str(), ios::out | ios::binary);
  if (!SaveCode.is_open())
    {
      cout << "Error : Can't open file \"" << bin_basename << "_static.bin\" for writing\n";
      exit(EXIT_FAILURE);
    }
  u_count_int = 0;
  unsigned int block_size = getBlockSize(num);