StaticModel.cc 52 KB
Newer Older
sebastien's avatar
sebastien committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
 * Copyright (C) 2003-2009 Dynare Team
 *
 * 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
42
43
                         NumericalConstants &num_constants_arg) :
  ModelTree(symbol_table_arg, num_constants_arg),
  global_temporary_terms(true),
  cutoff(1e-15),
  mfs(0)
44
45
{
}
46

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

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

73
74
75
76
77
78
79
80
81
82
void
StaticModel::initializeVariablesAndEquations()
{
  for(int j = 0; j < equation_number(); j++)
    {
      equation_reordered.push_back(j);
      variable_reordered.push_back(j);
    }
}

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
void
StaticModel::computeTemporaryTermsOrdered()
{
  map<NodeID, pair<int, int> > first_occurence;
  map<NodeID, int> reference_count;
  BinaryOpNode *eq_node;
  first_derivatives_type::const_iterator it;
  first_chain_rule_derivatives_type::const_iterator it_chr;
  ostringstream tmp_s;
  v_temporary_terms.clear();
  map_idx.clear();

  unsigned int nb_blocks = getNbBlocks();
  v_temporary_terms = vector< vector<temporary_terms_type> >(nb_blocks);

98
  v_temporary_terms_inuse = vector<temporary_terms_inuse_type>(nb_blocks);
99
100

  temporary_terms.clear();
101
  if (!global_temporary_terms)
102
103
104
105
106
107
108
109
110
111
112
113
    {
      for (unsigned int block = 0; block < nb_blocks; block++)
        {

          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;
          v_temporary_terms[block] = vector<temporary_terms_type>(block_size);
          for (unsigned int i = 0; i < block_size; i++)
            {
114
115
              if (i < block_nb_recursives && isBlockEquationRenormalized(block, i))
                getBlockEquationRenormalizedNodeID(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  i);
116
117
              else
                {
118
                  eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i);
119
120
121
122
123
                  eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  i);
                }
            }
          for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
            {
124
              NodeID id = it->second.second;
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
              id->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;
        }
    }
  else
    {
      for (unsigned int block = 0; block < nb_blocks; block++)
        {
          // 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_type>(block_size);
          for (unsigned int i = 0; i < block_size; i++)
            {
143
144
              if (i < block_nb_recursives && isBlockEquationRenormalized(block, i))
                getBlockEquationRenormalizedNodeID(block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  i);
145
146
              else
                {
147
                  eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i);
148
149
150
151
152
                  eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i);
                }
            }
          for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
            {
153
              NodeID id = it->second.second;
154
155
156
157
158
159
160
161
162
163
164
165
166
              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++)
            {
167
168
              if (i < block_nb_recursives && isBlockEquationRenormalized(block, i))
                getBlockEquationRenormalizedNodeID(block, i)->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
169
170
              else
                {
171
                  eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i);
172
173
174
175
176
                  eq_node->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
                }
            }
          for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
            {
177
              NodeID id = it->second.second;
178
179
              id->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
            }
180
          for (int i = 0; i < (int) getBlockSize(block); i++)
181
            for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin();
182
183
                 it != v_temporary_terms[block][i].end(); it++)
              (*it)->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
184
185
          v_temporary_terms_inuse[block] = temporary_terms_in_use;
        }
186
      computeTemporaryTermsMapping();
187
    }
188
189
190
191
192
}

void
StaticModel::computeTemporaryTermsMapping()
{
193
  // Add a mapping form node ID to temporary terms order
194
  int j = 0;
195
  for (temporary_terms_type::const_iterator it = temporary_terms.begin();
196
      it != temporary_terms.end(); it++)
197
    map_idx[(*it)->idx] = j++;
198
199
200
201
}

void
StaticModel::writeModelEquationsOrdered_M(const string &static_basename) const
202
203
204
205
206
207
208
209
210
211
212
{
  string tmp_s, sps;
  ostringstream tmp_output, tmp1_output, global_output;
  NodeID lhs = NULL, rhs = NULL;
  BinaryOpNode *eq_node;
  map<NodeID, int> reference_count;
  temporary_terms_type local_temporary_terms;
  ofstream  output;
  int nze;
  vector<int> feedback_variables;
  ExprNodeOutputType local_output_type;
213

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
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
333
334
335
336
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
  if (global_temporary_terms)
    {
      local_output_type = oMatlabStaticModelSparse;
      local_temporary_terms = temporary_terms;
    }
  else
    local_output_type = oMatlabDynamicModelSparseLocalTemporaryTerms;

  //----------------------------------------------------------------------
  //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)
        output << "  g1 = zeros(" << block_mfs << ", " << block_mfs << ");" << endl;

      if (v_temporary_terms_inuse[block].size())
        {
          tmp_output.str("");
          for (temporary_terms_inuse_type::const_iterator it = v_temporary_terms_inuse[block].begin();
               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];
          temporary_terms_type tt2;
          tt2.clear();
          if (v_temporary_terms[block].size())
            {
              output << "  " << "% //Temporary variables" << endl;
              for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin();
                   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));
          eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i);
          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("");
                      eq_node = (BinaryOpNode *) getBlockEquationRenormalizedNodeID(block, i);
                      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:
          for (t_block_derivatives_equation_variable_laglead_nodeid::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);
              NodeID id = it->second.second;
              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;
        }
      output.close();
    }
}
405
406

void
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
StaticModel::writeModelEquationsCode(const string file_name, const string bin_basename, map_idx_type map_idx) const
{

  ostringstream tmp_output;
  ofstream code_file;
  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
  FDIMT_ fdimt(temporary_terms.size());
  fdimt.write(code_file);

  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,
                           u_count_int
                           );
  fbeginblock.write(code_file);


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

  compileModelEquations(code_file, temporary_terms, map_idx, false, false);

  FENDEQU_ fendequ;
  fendequ.write(code_file);

  vector<vector<pair<int, int> > > derivatives;
  derivatives.resize(symbol_table.endo_nbr());
  count_u = symbol_table.endo_nbr();
  for (first_derivatives_type::const_iterator it = first_derivatives.begin();
       it != first_derivatives.end(); it++)
    {
      int deriv_id = it->first.second;
      if (getTypeByDerivID(deriv_id) == eEndogenous)
        {
          NodeID d1 = it->second;
          unsigned int eq = it->first.first;
          int symb = getSymbIDByDerivID(deriv_id);
          unsigned int var = symbol_table.getTypeSpecificID(symb);
          if (!derivatives[eq].size())
            derivatives[eq].clear();
          derivatives[eq].push_back(make_pair(var, count_u));

          d1->compile(code_file, false, temporary_terms, map_idx, false, false);

          FSTPSU_ fstpsu(count_u);
          fstpsu.write(code_file);
          count_u++;
        }
    }
  for (int i = 0; i < symbol_table.endo_nbr(); i++)
    {
      FLDR_ fldr(i);
      fldr.write(code_file);
      for(vector<pair<int, int> >::const_iterator it = derivatives[i].begin();
          it != derivatives[i].end(); it++)
        {
          FLDSU_ fldsu(it->second);
          fldsu.write(code_file);
          FLDSV_ fldsv(eEndogenous, it->first);
          fldsv.write(code_file);
          FBINARY_ fbinary(oTimes);
          fbinary.write(code_file);
          if (it != derivatives[i].begin())
            {
              FBINARY_ fbinary(oPlus);
              fbinary.write(code_file);
            }
        }
      FBINARY_ fbinary(oMinus);
      fbinary.write(code_file);
      FSTPSU_ fstpsu(i);
      fstpsu.write(code_file);
    }
  FENDBLOCK_ fendblock;
  fendblock.write(code_file);
  FEND_ fend;
  fend.write(code_file);
  code_file.close();
}

void
StaticModel::writeModelEquationsCode_Block(const string file_name, const string bin_basename, map_idx_type map_idx) const
516
517
{
  struct Uff_l
518
  {
519
520
521
    int u, var, lag;
    Uff_l *pNext;
  };
522

523
524
525
526
527
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
  struct Uff
  {
    Uff_l *Ufl, *Ufl_First;
  };

  int i, v;
  string tmp_s;
  ostringstream tmp_output;
  ofstream code_file;
  NodeID lhs = NULL, rhs = NULL;
  BinaryOpNode *eq_node;
  Uff Uf[symbol_table.endo_nbr()];
  map<NodeID, int> reference_count;
  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());
  fdimt.write(code_file);

  for (unsigned int block = 0; block < getNbBlocks(); block++)
    {
      feedback_variables.clear();
      if (block > 0)
        {
          FENDBLOCK_ fendblock;
          fendblock.write(code_file);
        }
      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)
        {
570
          Write_Inf_To_Bin_File_Block(file_name, bin_basename, block, u_count_int, file_open);
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
          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,
                               u_count_int
                               );
      fbeginblock.write(code_file);

      // The equations
      for (i = 0; i < (int) block_size; i++)
        {
          //The Temporary terms
          temporary_terms_type tt2;
          tt2.clear();
          if (v_temporary_terms[block].size())
            {
              for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin();
                   it != v_temporary_terms[block][i].end(); it++)
                {
                  (*it)->compile(code_file, false, tt2, map_idx, false, false);
                  FSTPST_ fstpst((int)(map_idx.find((*it)->idx)->second));
                  fstpst.write(code_file);
                  // Insert current node into tt2
                  tt2.insert(*it);
                }
            }

          int variable_ID, equation_ID;
          EquationType equ_type;
          switch (simulation_type)
            {
            evaluation:
            case EVALUATE_BACKWARD:
            case EVALUATE_FORWARD:
              equ_type = getBlockEquationType(block, i);
              if (equ_type == E_EVALUATE)
                {
                  eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i);
                  lhs = eq_node->get_arg1();
                  rhs = eq_node->get_arg2();
                  rhs->compile(code_file, false, temporary_terms, map_idx, false, false);
                  lhs->compile(code_file, true, temporary_terms, map_idx, false, false);
                }
              else if (equ_type == E_EVALUATE_S)
                {
                  eq_node = (BinaryOpNode *) getBlockEquationRenormalizedNodeID(block, i);
                  lhs = eq_node->get_arg1();
                  rhs = eq_node->get_arg2();
                  rhs->compile(code_file, false, temporary_terms, map_idx, false, false);
                  lhs->compile(code_file, true, temporary_terms, map_idx, false, false);
                }
              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:
              eq_node = (BinaryOpNode *) getBlockEquationNodeID(block, i);
              lhs = eq_node->get_arg1();
              rhs = eq_node->get_arg2();
              lhs->compile(code_file, false, temporary_terms, map_idx, false, false);
              rhs->compile(code_file, false, temporary_terms, map_idx, false, false);

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

              FSTPR_ fstpr(i - block_recursive);
              fstpr.write(code_file);
            }
        }
      FENDEQU_ fendequ;
      fendequ.write(code_file);
      // 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:
sebastien's avatar
sebastien committed
666
              compileDerivative(code_file, getBlockEquationID(block, 0), getBlockVariableID(block, 0), map_idx);
667
              {
668
669
                FSTPG_ fstpg(0);
                fstpg.write(code_file);
670
              }
671
              break;
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
            case SOLVE_BACKWARD_COMPLETE:
            case SOLVE_FORWARD_COMPLETE:
              count_u = feedback_variables.size();
              for (t_block_derivatives_equation_variable_laglead_nodeid::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);
                  if (eq >= block_recursive and var >= block_recursive)
                    {
                      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;
                      compileChainRuleDerivative(code_file, eqr, varr, 0, map_idx);
                      FSTPSU_ fstpsu(count_u);
                      fstpsu.write(code_file);
                      count_u++;
                    }
                }
              for (i = 0; i < (int) block_size; i++)
                {
                  if (i >= (int) block_recursive)
                    {
                      FLDR_ fldr(i-block_recursive);
                      fldr.write(code_file);

                      FLDZ_ fldz;
                      fldz.write(code_file);

                      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);
                          fldsu.write(code_file);
                          FLDSV_ fldsv(eEndogenous, Uf[v].Ufl->var);
                          fldsv.write(code_file);

                          FBINARY_ fbinary(oTimes);
                          fbinary.write(code_file);

                          FCUML_ fcuml;
                          fcuml.write(code_file);
                        }
                      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);
                      fbinary.write(code_file);

                      FSTPSU_ fstpsu(i - block_recursive);
                      fstpsu.write(code_file);

                    }
                }
              break;
            default:
              break;
            }
        }
    }
  FENDBLOCK_ fendblock;
  fendblock.write(code_file);
  FEND_ fend;
  fend.write(code_file);
  code_file.close();
}
754
755

void
756
StaticModel::Write_Inf_To_Bin_File_Block(const string &static_basename, const string &bin_basename, const int &num,
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
                                   int &u_count_int, bool &file_open) const
{
  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);
  unsigned int block_mfs = getBlockMfs(num);
  unsigned int block_recursive = block_size - block_mfs;
  for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[num].begin(); it != (blocks_derivatives[num]).end(); it++)
    {
      unsigned int eq = it->first.first;
      unsigned int var = it->first.second;
      int lag = 0;
      if (eq >= block_recursive and var >= block_recursive)
        {
          int v = eq - block_recursive;
          SaveCode.write(reinterpret_cast<char *>(&v), sizeof(v));
          int varr = var - block_recursive;
          SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr));
          SaveCode.write(reinterpret_cast<char *>(&lag), sizeof(lag));
          int u = u_count_int + block_mfs;
          SaveCode.write(reinterpret_cast<char *>(&u), sizeof(u));
          u_count_int++;
        }
    }

  for (j = block_recursive; j < (int) block_size; j++)
    {
      unsigned int varr = getBlockVariableID(num, j);
      SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr));
    }
  for (j = block_recursive; j < (int) block_size; j++)
    {
      unsigned int eqr = getBlockEquationID(num, j);
      SaveCode.write(reinterpret_cast<char *>(&eqr), sizeof(eqr));
    }
  SaveCode.close();
}
804
805
806

map<pair<int, pair<int, int > >, NodeID>
StaticModel::collect_first_order_derivatives_endogenous()
sebastien's avatar
sebastien committed
807
{
808
809
810
811
  map<pair<int, pair<int, int > >, NodeID> endo_derivatives;
  for (first_derivatives_type::iterator it2 = first_derivatives.begin();
       it2 != first_derivatives.end(); it2++)
    {
812
      if (getTypeByDerivID(it2->first.second) == eEndogenous)
813
814
        {
          int eq = it2->first.first;
815
          int var = symbol_table.getTypeSpecificID(it2->first.second);
816
817
818
819
          int lag = 0;
          endo_derivatives[make_pair(eq, make_pair(var, lag))] = it2->second;
        }
    }
820
  return endo_derivatives;
821
822
823
}

void
824
StaticModel::computingPass(const eval_context_type &eval_context, bool no_tmp_terms, bool hessian, bool block, bool bytecode)
825
{
826
  // Compute derivatives w.r. to all endogenous, and possibly exogenous and exogenous deterministic
827
828
  set<int> vars;

829
  for (int i = 0; i < symbol_table.endo_nbr(); i++)
830
831
832
833
    vars.insert(symbol_table.getID(eEndogenous, i));

  // Launch computations
  cout << "Computing static model derivatives:" << endl
834
       << " - order 1" << endl;
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
  first_derivatives.clear();

  computeJacobian(vars);

  if (hessian)
    {
      cout << " - order 2" << endl;
      computeHessian(vars);
    }

  if (block)
    {
      jacob_map contemporaneous_jacobian, static_jacobian;

      // for each block contains pair<Size, Feddback_variable>
      vector<pair<int, int> > blocks;

      evaluateAndReduceJacobian(eval_context, contemporaneous_jacobian, static_jacobian, dynamic_jacobian, cutoff, false);

sebastien's avatar
sebastien committed
854
      computeNonSingularNormalization(contemporaneous_jacobian, cutoff, static_jacobian, dynamic_jacobian);
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881

      computePrologueAndEpilogue(static_jacobian, equation_reordered, variable_reordered, prologue, epilogue);

      map<pair<int, pair<int, int> >, NodeID> first_order_endo_derivatives = collect_first_order_derivatives_endogenous();

      equation_type_and_normalized_equation = equationTypeDetermination(equations, first_order_endo_derivatives, variable_reordered, equation_reordered, mfs);

      cout << "Finding the optimal block decomposition of the model ...\n";

      if (prologue+epilogue < (unsigned int) equation_number())
        computeBlockDecompositionAndFeedbackVariablesForEachBlock(static_jacobian, dynamic_jacobian, prologue, epilogue, equation_reordered, variable_reordered, blocks, equation_type_and_normalized_equation, false, false, mfs, inv_equation_reordered, inv_variable_reordered);

      block_type_firstequation_size_mfs = reduceBlocksAndTypeDetermination(dynamic_jacobian, prologue, epilogue, blocks, equations, equation_type_and_normalized_equation, variable_reordered, equation_reordered);

      printBlockDecomposition(blocks);

      computeChainRuleJacobian(blocks_derivatives);

      blocks_linear = BlockLinear(blocks_derivatives, variable_reordered);

      collect_block_first_order_derivatives();

      global_temporary_terms = true;
      if (!no_tmp_terms)
        computeTemporaryTermsOrdered();
    }
  else
882
883
884
885
886
887
888
889
    {
      if (!no_tmp_terms)
        {
          computeTemporaryTerms(true);
          if (bytecode)
            computeTemporaryTermsMapping();
        }
    }
sebastien's avatar
sebastien committed
890
891
892
}

void
893
StaticModel::writeStaticMFile(const string &func_name) const
sebastien's avatar
sebastien committed
894
895
{
  // Writing comments and function definition command
896
897
898
899
900
901
902
903
904
905
906
  string filename = func_name + "_static.m";

  ofstream output;
  output.open(filename.c_str(), ios::out | ios::binary);
  if (!output.is_open())
    {
      cerr << "ERROR: Can't open file " << filename << " for writing" << endl;
      exit(EXIT_FAILURE);
    }

  output << "function [residual, g1, g2] = " << func_name + "_static(y, x, params)" << endl
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
         << "%" << endl
         << "% Status : Computes static model for Dynare" << endl
         << "%" << endl
         << "% Warning : this file is generated automatically by Dynare" << endl
         << "%           from model file (.mod)" << endl
         << endl
         << "residual = zeros( " << equations.size() << ", 1);" << endl
         << endl
         << "%" << endl
         << "% Model equations" << endl
         << "%" << endl
         << endl;

  writeModelLocalVariables(output, oMatlabStaticModel);

  writeTemporaryTerms(temporary_terms, output, oMatlabStaticModel);

  writeModelEquations(output, oMatlabStaticModel);

  output << "if ~isreal(residual)" << endl
         << "  residual = real(residual)+imag(residual).^2;" << endl
         << "end" << endl
         << "if nargout >= 2," << endl
         << "  g1 = zeros(" << equations.size() << ", " << symbol_table.endo_nbr() << ");" << endl
         << endl
         << "%" << endl
         << "% Jacobian matrix" << endl
         << "%" << endl
         << endl;
sebastien's avatar
sebastien committed
936
937
938
939
940
941

  // Write Jacobian w.r. to endogenous only
  for (first_derivatives_type::const_iterator it = first_derivatives.begin();
       it != first_derivatives.end(); it++)
    {
      int eq = it->first.first;
942
      int symb_id = it->first.second;
sebastien's avatar
sebastien committed
943
944
      NodeID d1 = it->second;

945
      output << "  g1(" << eq+1 << "," << symbol_table.getTypeSpecificID(symb_id)+1 << ")=";
946
947
      d1->writeOutput(output, oMatlabStaticModel, temporary_terms);
      output << ";" << endl;
sebastien's avatar
sebastien committed
948
949
    }

950
951
952
953
954
955
956
957
958
959
960
961
  output << "  if ~isreal(g1)" << endl
         << "    g1 = real(g1)+2*imag(g1);" << endl
         << "  end" << endl
         << "end" << endl
         << "if nargout >= 3," << endl
         << "%" << endl
         << "% Hessian matrix" << endl
         << "%" << endl
         << endl;

  int g2ncols = symbol_table.endo_nbr() * symbol_table.endo_nbr();
  if (second_derivatives.size())
962
    {
963
      output << "  v2 = zeros(" << NNZDerivatives[1] << ",3);" << endl;
964

965
966
967
968
      // Write Hessian w.r. to endogenous only (only if 2nd order derivatives have been computed)
      int k = 0; // Keep the line of a 2nd derivative in v2
      for (second_derivatives_type::const_iterator it = second_derivatives.begin();
           it != second_derivatives.end(); it++)
969
        {
970
971
972
973
974
975
976
          int eq = it->first.first;
          int symb_id1 = it->first.second.first;
          int symb_id2 = it->first.second.second;
          NodeID d2 = it->second;

          int tsid1 = symbol_table.getTypeSpecificID(symb_id1);
          int tsid2 = symbol_table.getTypeSpecificID(symb_id2);
sebastien's avatar
sebastien committed
977

978
979
          int col_nb = tsid1*symbol_table.endo_nbr()+tsid2;
          int col_nb_sym = tsid2*symbol_table.endo_nbr()+tsid1;
sebastien's avatar
sebastien committed
980

981
982
983
984
985
          output << "v2(" << k+1 << ",1)=" << eq + 1 << ";" << endl
                 << "v2(" << k+1 << ",2)=" << col_nb + 1 << ";" << endl
                 << "v2(" << k+1 << ",3)=";
          d2->writeOutput(output, oMatlabStaticModel, temporary_terms);
          output << ";" << endl;
sebastien's avatar
sebastien committed
986
987

          k++;
988
989
990
991
992
993
994
995
996

          // Treating symetric elements
          if (symb_id1 != symb_id2)
            {
              output << "v2(" << k+1 << ",1)=" << eq + 1 << ";" << endl
                     << "v2(" << k+1 << ",2)=" << col_nb_sym + 1 << ";" << endl
                     << "v2(" << k+1 << ",3)=v2(" << k << ",3);" << endl;
              k++;
            }
997
        }
sebastien's avatar
sebastien committed
998

999
      output << "  g2 = sparse(v2(:,1),v2(:,2),v2(:,3)," << equations.size() << "," << g2ncols << ");" << endl;
sebastien's avatar
sebastien committed
1000
    }
1001
1002
1003
1004
1005
  else // Either hessian is all zero, or we didn't compute it
    output << "  g2 = sparse([],[],[]," << equations.size() << "," << g2ncols << ");" << endl;

  output << "end;" << endl; // Close the if nargout >= 3 statement
  output.close();
sebastien's avatar
sebastien committed
1006
1007
}

1008
1009
void
StaticModel::writeStaticFile(const string &basename, bool block, bool bytecode) const
1010
1011
{
  int r;
sebastien's avatar
sebastien committed
1012

1013
  //assert(block);
1014

1015
#ifdef _WIN32
1016
  r = mkdir(basename.c_str());
1017
#else
1018
  r = mkdir(basename.c_str(), 0777);
1019
#endif
1020
1021
1022
1023
1024
1025
  if (r < 0 && errno != EEXIST)
    {
      perror("ERROR");
      exit(EXIT_FAILURE);
    }
  if (block && bytecode)
1026
1027
1028
    writeModelEquationsCode_Block(basename + "_static", basename, map_idx);
  else if (!block && bytecode)
    writeModelEquationsCode(basename + "_static", basename, map_idx);
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
  else if (block && !bytecode)
    {
      chdir(basename.c_str());
      writeModelEquationsOrdered_M(basename + "_static");
      chdir("..");
      writeStaticBlockMFSFile(basename);
    }
  else
    writeStaticMFile(basename);
}
1039
1040

void
1041
StaticModel::writeStaticBlockMFSFile(const string &basename) const
1042
{
1043
  string filename = basename + "_static.m";
1044

1045
1046
1047
  ofstream output;
  output.open(filename.c_str(), ios::out | ios::binary);
  if (!output.is_open())
1048
    {
1049
1050
      cerr << "ERROR: Can't open file " << filename << " for writing" << endl;
      exit(EXIT_FAILURE);
1051
1052
    }

1053
  string func_name = basename + "_static";
1054

1055
1056
1057
1058
  output << "function [residual, g1, y] = " << func_name << "(nblock, y, x, params)" << endl
         << "  residual = [];" << endl
         << "  g1 = [];" << endl
         << "  switch nblock" << endl;
1059

1060
  unsigned int nb_blocks = getNbBlocks();
1061

1062
  for (int b = 0; b < (int) nb_blocks; b++)
1063
1064
    {

1065
      set<int> local_var;
1066

1067
      output << "    case " << b+1 << endl;
1068

1069
1070
      BlockSimulationType simulation_type = getBlockSimulationType(b);

1071
1072
1073
1074
      if (simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD)
        output << "      y = " << func_name << "_" << b+1 << "(y, x, params);\n";
      else
        output << "      [residual, y, g1] = " << func_name << "_" << b+1 << "(y, x, params);\n";
sebastien's avatar
sebastien committed
1075
    }
1076
1077
1078
  output << "  end" << endl
         << "end" << endl;
  output.close();
sebastien's avatar
sebastien committed
1079

1080
}
sebastien's avatar
sebastien committed
1081

1082
1083
1084
1085
1086
void
StaticModel::writeOutput(ostream &output, bool block) const
{
  if (!block)
    return;
1087

1088
1089
  unsigned int nb_blocks = getNbBlocks();
  output << "M_.blocksMFS = cell(" << nb_blocks << ", 1);" << endl;
1090
  for (int b = 0; b < (int) nb_blocks; b++)
1091
    {
1092
1093
1094
1095
1096
      output << "M_.blocksMFS{" << b+1 << "} = [ ";
      unsigned int block_size = getBlockSize(b);
      unsigned int block_mfs = getBlockMfs(b);
      unsigned int block_recursive = block_size - block_mfs;
      BlockSimulationType simulation_type = getBlockSimulationType(b);
1097

1098
      if (simulation_type != EVALUATE_BACKWARD && simulation_type != EVALUATE_FORWARD)
1099
        for (int i = block_recursive; i < (int) block_size; i++)
1100
          output << getBlockVariableID(b, i)+1 << "; ";
1101

1102
      output << "];" << endl;
1103
    }
sebastien's avatar
sebastien committed
1104
1105
}

1106
1107
1108
1109
SymbolType
StaticModel::getTypeByDerivID(int deriv_id) const throw (UnknownDerivIDException)
{
  return symbol_table.getType(getSymbIDByDerivID(deriv_id));
1110
}
1111

1112
1113
int
StaticModel::getLagByDerivID(int deriv_id) const throw (UnknownDerivIDException)
1114
{
1115
  return 0;
1116
}
1117

1118
1119
int
StaticModel::getSymbIDByDerivID(int deriv_id) const throw (UnknownDerivIDException)
1120
{
1121
  return deriv_id;
1122
1123
}

1124
1125
int
StaticModel::getDerivID(int symb_id, int lag) const throw (UnknownDerivIDException)
1126
{
1127
1128
1129
1130
1131
  if (symbol_table.getType(symb_id) == eEndogenous)
    return symb_id;
  else
    return -1;
}
1132

1133
1134
1135
1136
1137
1138
1139
1140
map<pair<pair<int, pair<int, int> >, pair<int, int> >, int>
StaticModel::get_Derivatives(int block)
{
  map<pair<pair<int, pair<int, int> >, pair<int, int> >, int> Derivatives;
  Derivatives.clear();
  int block_size = getBlockSize(block);
  int block_nb_recursive = block_size - getBlockMfs(block);
  int lag = 0;
1141
  for (int eq = 0; eq < block_size; eq++)
1142
    {
1143
      int eqr = getBlockEquationID(block, eq);
1144
      for (int var = 0; var < block_size; var++)
1145
        {
1146
          int varr = getBlockVariableID(block, var);
1147
          if (dynamic_jacobian.find(make_pair(lag, make_pair(eqr, varr))) != dynamic_jacobian.end())
1148
1149
1150
            {
              bool OK = true;
              map<pair<pair<int, pair<int, int> >, pair<int, int> >, int>::const_iterator its = Derivatives.find(make_pair(make_pair(lag, make_pair(eq, var)), make_pair(eqr, varr)));
1151
              if (its != Derivatives.end())
1152
                {
1153
1154
                  if (its->second == 2)
                    OK = false;
1155
                }
1156

1157
              if (OK)
1158
                {
1159
                  if (getBlockEquationType(block, eq) == E_EVALUATE_S and eq < block_nb_recursive)
1160
1161
1162
1163
1164
1165
                    //It's a normalized equation, we have to recompute the derivative using chain rule derivative function
                    Derivatives[make_pair(make_pair(lag, make_pair(eq, var)), make_pair(eqr, varr))] = 1;
                  else
                    //It's a feedback equation we can use the derivatives
                    Derivatives[make_pair(make_pair(lag, make_pair(eq, var)), make_pair(eqr, varr))] = 0;
                }
1166
              if (var < block_nb_recursive)
1167
1168
                {
                  int eqs = getBlockEquationID(block, var);
1169
                  for (int vars = block_nb_recursive; vars < block_size; vars++)
1170
1171
1172
                    {
                      int varrs = getBlockVariableID(block, vars);
                      //A new derivative needs to be computed using the chain rule derivative function (a feedback variable appears in a recursive equation)
1173
                      if (Derivatives.find(make_pair(make_pair(lag, make_pair(var, vars)), make_pair(eqs, varrs))) != Derivatives.end())
1174
1175
1176
1177
                        Derivatives[make_pair(make_pair(lag, make_pair(eq, vars)), make_pair(eqr, varrs))] = 2;
                    }
                }
            }
1178
1179
        }
    }
1180

1181
  return (Derivatives);
1182
}
1183
1184

void
1185
StaticModel::computeChainRuleJacobian(t_blocks_derivatives &blocks_derivatives)
1186
{
1187
1188
1189
  map<int, NodeID> recursive_variables;
  unsigned int nb_blocks = getNbBlocks();
  blocks_derivatives = t_blocks_derivatives(nb_blocks);
1190
  for (unsigned int block = 0; block < nb_blocks; block++)
1191
    {
1192
1193
1194
1195
1196
1197
      t_block_derivatives_equation_variable_laglead_nodeid tmp_derivatives;
      recursive_variables.clear();
      BlockSimulationType simulation_type = getBlockSimulationType(block);
      int block_size = getBlockSize(block);
      int block_nb_mfs = getBlockMfs(block);
      int block_nb_recursives = block_size - block_nb_mfs;
1198
      if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE or simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
1199
        {
1200
          blocks_derivatives.push_back(t_block_derivatives_equation_variable_laglead_nodeid(0));
1201
          for (int i = 0; i < block_nb_recursives; i++)
1202
1203
1204
1205
1206
1207
1208
1209
            {
              if (getBlockEquationType(block, i) == E_EVALUATE_S)
                recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block, i)), 0)] = getBlockEquationRenormalizedNodeID(block, i);
              else
                recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block, i)), 0)] = getBlockEquationNodeID(block, i);
            }
          map<pair<pair<int, pair<int, int> >, pair<int, int> >, int> Derivatives = get_Derivatives(block);
          map<pair<pair<int, pair<int, int> >, pair<int, int> >, int>::const_iterator it = Derivatives.begin();
1210
          for (int i = 0; i < (int) Derivatives.size(); i++)
1211
            {
1212
1213
1214
1215
1216
1217
1218
1219
              int Deriv_type = it->second;
              pair<pair<int, pair<int, int> >, pair<int, int> > it_l(it->first);
              it++;
              int lag = it_l.first.first;
              int eq = it_l.first.second.first;
              int var = it_l.first.second.second;
              int eqr = it_l.second.first;
              int varr = it_l.second.second;
1220
              if (Deriv_type == 0)
1221
1222
1223
1224
                first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))] = first_derivatives[make_pair(eqr, getDerivID(symbol_table.getID(eEndogenous, varr), lag))];
              else if (Deriv_type == 1)
                first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))] = (equation_type_and_normalized_equation[eqr].second)->getChainRuleDerivative(getDerivID(symbol_table.getID(eEndogenous, varr), lag), recursive_variables);
              else if (Deriv_type == 2)
1225
                {
1226
                  if (getBlockEquationType(block, eq) == E_EVALUATE_S && eq < block_nb_recursives)
1227
1228
1229
                    first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))] = (equation_type_and_normalized_equation[eqr].second)->getChainRuleDerivative(getDerivID(symbol_table.getID(eEndogenous, varr), lag), recursive_variables);
                  else
                    first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))] = equations[eqr]->getChainRuleDerivative(getDerivID(symbol_table.getID(eEndogenous, varr), lag), recursive_variables);
1230
                }
1231
              tmp_derivatives.push_back(make_pair(make_pair(eq, var), make_pair(lag, first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, lag))])));
1232
1233
            }
        }
1234
1235
      else if (simulation_type == SOLVE_BACKWARD_SIMPLE or simulation_type == SOLVE_FORWARD_SIMPLE
               or simulation_type == SOLVE_BACKWARD_COMPLETE or simulation_type == SOLVE_FORWARD_COMPLETE)
1236
        {
1237
          blocks_derivatives.push_back(t_block_derivatives_equation_variable_laglead_nodeid(0));
1238
          for (int i = 0; i < block_nb_recursives; i++)
1239
            {
1240
              if (getBlockEquationType(block, i) == E_EVALUATE_S)
1241
                recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block, i)), 0)] = getBlockEquationRenormalizedNodeID(block, i);
1242
              else
1243
                recursive_variables[getDerivID(symbol_table.getID(eEndogenous, getBlockVariableID(block, i)), 0)] = getBlockEquationNodeID(block, i);
1244
            }
1245
          for (int eq = block_nb_recursives; eq < block_size; eq++)
1246
1247
            {
              int eqr = getBlockEquationID(block, eq);
1248
              for (int var = block_nb_recursives; var < block_size; var++)
1249
1250
1251
1252
1253
1254
1255
                {
                  int varr = getBlockVariableID(block, var);
                  NodeID d1 = equations[eqr]->getChainRuleDerivative(getDerivID(symbol_table.getID(eEndogenous, varr), 0), recursive_variables);
                  if (d1 == Zero)
                    continue;
                  first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, 0))] = d1;
                  tmp_derivatives.push_back(
1256
                                            make_pair(make_pair(eq, var), make_pair(0, first_chain_rule_derivatives[make_pair(eqr, make_pair(varr, 0))])));
1257
                }
1258
            }
1259
        }
1260
      blocks_derivatives[block] = tmp_derivatives;
1261
1262
1263
1264
    }
}

void
1265
StaticModel::collect_block_first_order_derivatives()
1266
{
1267
1268
1269
1270
1271
  //! vector for an equation or a variable indicates the block number
  vector<int> equation_2_block, variable_2_block;
  unsigned int nb_blocks = getNbBlocks();
  equation_2_block = vector<int>(equation_reordered.size());
  variable_2_block = vector<int>(variable_reordered.size());
1272
  for (unsigned int block = 0; block < nb_blocks; block++)
1273
    {
1274
      unsigned int block_size = getBlockSize(block);
1275
      for (unsigned int i = 0; i < block_size; i++)
1276
1277
1278
1279
        {
          equation_2_block[getBlockEquationID(block, i)] = block;
          variable_2_block[getBlockVariableID(block, i)] = block;
        }
1280
    }
1281
  derivative_endo = vector<t_derivative>(nb_blocks);
1282
1283
  endo_max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair(0, 0));
  max_leadlag_block = vector<pair<int, int> >(nb_blocks, make_pair(0, 0));
1284
1285
  for (first_derivatives_type::iterator it2 = first_derivatives.begin();
       it2 != first_derivatives.end(); it2++)
1286
    {
1287
1288
1289
1290
1291
1292
1293
1294
1295
      int eq = it2->first.first;
      int var = symbol_table.getTypeSpecificID(getSymbIDByDerivID(it2->first.second));
      int lag = 0;
      int block_eq = equation_2_block[eq];
      int block_var = variable_2_block[var];
      max_leadlag_block[block_eq] = make_pair(0, 0);
      max_leadlag_block[block_eq] = make_pair(0, 0);
      endo_max_leadlag_block[block_eq] = make_pair(0, 0);
      endo_max_leadlag_block[block_eq] = make_pair(0, 0);
1296
      t_derivative tmp_derivative;
1297
1298
1299
1300
1301
1302
1303
      t_lag_var lag_var;
      if (getTypeByDerivID(it2->first.second) == eEndogenous && block_eq == block_var)
        {
          tmp_derivative = derivative_endo[block_eq];
          tmp_derivative[make_pair(lag, make_pair(eq, var))] = first_derivatives[make_pair(eq, getDerivID(symbol_table.getID(eEndogenous, var), lag))];
          derivative_endo[block_eq] = tmp_derivative;
        }
1304
1305
1306
    }
}

1307
void
1308
StaticModel::writeChainRuleDerivative(ostream &output, int eqr, int varr, int lag,
1309
1310
                                      ExprNodeOutputType output_type,
                                      const temporary_terms_type &temporary_terms) const
1311
{
1312
1313
1314
1315
1316
1317
  map<pair<int, pair<int, int> >, NodeID>::const_iterator it = first_chain_rule_derivatives.find(make_pair(eqr, make_pair(varr, lag)));
  if (it != first_chain_rule_derivatives.end())
    (it->second)->writeOutput(output, output_type, temporary_terms);
  else
    output << 0;
}
1318

1319
1320
void
StaticModel::writeLatexFile