DynamicModel.cc 119 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
20
/*
 * 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/>.
 */

#include <cmath>
21
#include <cstdlib>
22
#include <cassert>
sebastien's avatar
sebastien committed
23

24

sebastien's avatar
sebastien committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include "DynamicModel.hh"

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

DynamicModel::DynamicModel(SymbolTable &symbol_table_arg,
                           NumericalConstants &num_constants_arg) :
  ModelTree(symbol_table_arg, num_constants_arg),
sebastien's avatar
sebastien committed
39
40
41
42
  max_lag(0), max_lead(0),
  max_endo_lag(0), max_endo_lead(0),
  max_exo_lag(0), max_exo_lead(0),
  max_exo_det_lag(0), max_exo_det_lead(0),
43
  dynJacobianColsNbr(0),
sebastien's avatar
sebastien committed
44
45
46
47
48
49
  cutoff(1e-15),
  markowitz(0.7),
  block_triangular(symbol_table_arg)
{
}

sebastien's avatar
sebastien committed
50
51
52
53
54
55
NodeID
DynamicModel::AddVariable(const string &name, int lag)
{
  return AddVariableInternal(name, lag);
}

sebastien's avatar
sebastien committed
56
void
sebastien's avatar
sebastien committed
57
DynamicModel::compileDerivative(ofstream &code_file, int eq, int symb_id, int lag, map_idx_type &map_idx) const
sebastien's avatar
sebastien committed
58
{
59
  first_derivatives_type::const_iterator it = first_derivatives.find(make_pair(eq, getDerivID(symb_id, lag)));
sebastien's avatar
sebastien committed
60
  if (it != first_derivatives.end())
sebastien's avatar
sebastien committed
61
    (it->second)->compile(code_file, false, temporary_terms, map_idx);
sebastien's avatar
sebastien committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
  else
    code_file.write(&FLDZ, sizeof(FLDZ));
}

void
DynamicModel::BuildIncidenceMatrix()
{
  set<pair<int, int> > endogenous, exogenous;
  for (int eq = 0; eq < (int) equations.size(); eq++)
    {
      BinaryOpNode *eq_node = equations[eq];
      endogenous.clear();
      NodeID Id = eq_node->get_arg1();
      Id->collectEndogenous(endogenous);
      Id = eq_node->get_arg2();
      Id->collectEndogenous(endogenous);
      for (set<pair<int, int> >::iterator it_endogenous=endogenous.begin();it_endogenous!=endogenous.end();it_endogenous++)
        {
          block_triangular.incidencematrix.fill_IM(eq, symbol_table.getTypeSpecificID(it_endogenous->first), it_endogenous->second, eEndogenous);
        }
      exogenous.clear();
      Id = eq_node->get_arg1();
      Id->collectExogenous(exogenous);
      Id = eq_node->get_arg2();
      Id->collectExogenous(exogenous);
      for (set<pair<int, int> >::iterator it_exogenous=exogenous.begin();it_exogenous!=exogenous.end();it_exogenous++)
        {
          block_triangular.incidencematrix.fill_IM(eq, symbol_table.getTypeSpecificID(it_exogenous->first), it_exogenous->second, eExogenous);
        }
    }
}

void
95
DynamicModel::computeTemporaryTermsOrdered(Model_Block *ModelBlock)
sebastien's avatar
sebastien committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
{
  map<NodeID, pair<int, int> > first_occurence;
  map<NodeID, int> reference_count;
  int i, j, m, eq, var, lag;
  temporary_terms_type vect;
  ostringstream tmp_output;
  BinaryOpNode *eq_node;
  first_derivatives_type::const_iterator it;
  ostringstream tmp_s;

  temporary_terms.clear();
  map_idx.clear();
  for (j = 0;j < ModelBlock->Size;j++)
    {
      // Compute the temporary terms reordered
      for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
        {
          eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
          eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, i, map_idx);
        }
      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
        {
          lag=m-ModelBlock->Block_List[j].Max_Lag;
          for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
            {
              eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
              var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
123
              it=first_derivatives.find(make_pair(eq,getDerivID(symbol_table.getID(eEndogenous, var), lag)));
sebastien's avatar
sebastien committed
124
125
126
127
              //it=first_derivatives.find(make_pair(eq,variable_table.getID(var, lag)));
              it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, ModelBlock->Block_List[j].Size-1, map_idx);
            }
        }
128
      /*for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
sebastien's avatar
sebastien committed
129
130
131
132
133
134
        {
          lag=m-ModelBlock->Block_List[j].Max_Lag;
          for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
            {
              eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
              var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
135
              it=first_derivatives.find(make_pair(eq,getDerivID(symbol_table.getID(eExogenous, var), lag)));
sebastien's avatar
sebastien committed
136
137
              it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, ModelBlock->Block_List[j].Size-1, map_idx);
            }
138
        }*/
sebastien's avatar
sebastien committed
139
140
141
142
143
144
145
146
147
148
      //jacobian_max_exo_col=(variable_table.max_exo_lag+variable_table.max_exo_lead+1)*symbol_table.exo_nbr;
      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
        {
          lag=m-ModelBlock->Block_List[j].Max_Lag;
          if (block_triangular.incidencematrix.Model_Max_Lag_Endo - ModelBlock->Block_List[j].Max_Lag +m >=0)
            {
              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;i++)
                {
                  eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index_other_endo[i];
                  var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index_other_endo[i];
149
                  it=first_derivatives.find(make_pair(eq,getDerivID(symbol_table.getID(eEndogenous, var), lag)));
sebastien's avatar
sebastien committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
                  //it=first_derivatives.find(make_pair(eq,variable_table.getID(var, lag)));
                  it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, ModelBlock->Block_List[j].Size-1, map_idx);
                }
            }
        }
    }
  for (j = 0;j < ModelBlock->Size;j++)
    {
      // Compute the temporary terms reordered
      for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
        {
          eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
          eq_node->collectTemporary_terms(temporary_terms, ModelBlock, j);
        }
      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
        {
          lag=m-ModelBlock->Block_List[j].Max_Lag;
          for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
            {
              eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
              var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
171
              it=first_derivatives.find(make_pair(eq,getDerivID(symbol_table.getID(eEndogenous, var), lag)));
sebastien's avatar
sebastien committed
172
173
174
175
              //it=first_derivatives.find(make_pair(eq,variable_table.getID(var, lag)));
              it->second->collectTemporary_terms(temporary_terms, ModelBlock, j);
            }
        }
176
      /*for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
sebastien's avatar
sebastien committed
177
178
179
180
181
182
        {
          lag=m-ModelBlock->Block_List[j].Max_Lag;
          for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
            {
              eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
              var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
183
              it=first_derivatives.find(make_pair(eq,getDerivID(symbol_table.getID(eExogenous, var), lag)));
sebastien's avatar
sebastien committed
184
185
186
              //it=first_derivatives.find(make_pair(eq,variable_table.getID(var, lag)));
              it->second->collectTemporary_terms(temporary_terms, ModelBlock, j);
            }
187
        }*/
sebastien's avatar
sebastien committed
188
189
190
191
192
193
194
195
196
197
      //jacobian_max_exo_col=(variable_table.max_exo_lag+variable_table.max_exo_lead+1)*symbol_table.exo_nbr;
      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
        {
          lag=m-ModelBlock->Block_List[j].Max_Lag;
          if (block_triangular.incidencematrix.Model_Max_Lag_Endo - ModelBlock->Block_List[j].Max_Lag +m >=0)
            {
              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;i++)
                {
                  eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index_other_endo[i];
                  var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index_other_endo[i];
198
                  it=first_derivatives.find(make_pair(eq,getDerivID(symbol_table.getID(eEndogenous, var), lag)));
sebastien's avatar
sebastien committed
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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
405
406
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
                  //it=first_derivatives.find(make_pair(eq,variable_table.getID(var, lag)));
                  it->second->collectTemporary_terms(temporary_terms, ModelBlock, j);
                }
            }
        }
    }
  // Add a mapping form node ID to temporary terms order
  j=0;
  for (temporary_terms_type::const_iterator it = temporary_terms.begin();
       it != temporary_terms.end(); it++)
    map_idx[(*it)->idx]=j++;
}

void
DynamicModel::writeModelEquationsOrdered_M( Model_Block *ModelBlock, const string &dynamic_basename) const
{
  int i,j,k,m;
  string tmp_s, sps;
  ostringstream tmp_output, tmp1_output, global_output;
  NodeID lhs=NULL, rhs=NULL;
  BinaryOpNode *eq_node;
  ostringstream Uf[symbol_table.endo_nbr()];
  map<NodeID, int> reference_count;
  int prev_Simulation_Type=-1, count_derivates=0;
  int jacobian_max_endo_col;
  ofstream  output;
  temporary_terms_type::const_iterator it_temp=temporary_terms.begin();
  int nze, nze_exo, nze_other_endo;
  //----------------------------------------------------------------------
  //For each block
  for (j = 0;j < ModelBlock->Size;j++)
    {
      //For a block composed of a single equation determines wether we have to evaluate or to solve the equation
      nze = nze_exo = nze_other_endo =0;
      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
        nze+=ModelBlock->Block_List[j].IM_lead_lag[m].size;
      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead_Exo+ModelBlock->Block_List[j].Max_Lag_Exo;m++)
        nze_exo+=ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;
      for (m=0;m<=ModelBlock->Block_List[j].Max_Lead_Other_Endo+ModelBlock->Block_List[j].Max_Lag_Other_Endo;m++)
        nze_other_endo+=ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;
      tmp1_output.str("");
      tmp1_output << dynamic_basename << "_" << j+1 << ".m";
      output.open(tmp1_output.str().c_str(), ios::out | ios::binary);
      output << "%\n";
      output << "% " << tmp1_output.str() << " : Computes dynamic model for Dynare\n";
      output << "%\n";
      output << "% Warning : this file is generated automatically by Dynare\n";
      output << "%           from model file (.mod)\n\n";
      output << "%/\n";
      if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
          ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
          ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
          ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R)
        {
          output << "function [y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << j+1 << "(y, x, params, jacobian_eval, y_kmin, periods)\n";
        }
      else if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_COMPLETE
               ||   ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_COMPLETE)
        output << "function [residual, g1, g2, g3, varargout] = " << dynamic_basename << "_" << j+1 << "(y, x, params, it_, jacobian_eval)\n";
      else if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_SIMPLE
               ||   ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_SIMPLE)
        output << "function [residual, g1, g2, g3, varargout] = " << dynamic_basename << "_" << j+1 << "(y, x, params, it_, jacobian_eval)\n";
      else
        output << "function [residual, g1, g2, g3, b, varargout] = " << dynamic_basename << "_" << j+1 << "(y, x, params, periods, jacobian_eval, y_kmin, y_size)\n";
      output << "  % ////////////////////////////////////////////////////////////////////////" << endl
             << "  % //" << string("                     Block ").substr(int(log10(j + 1))) << j + 1 << " " << BlockTriangular::BlockType0(ModelBlock->Block_List[j].Type)
             << "          //" << endl
             << "  % //                     Simulation type "
             << BlockTriangular::BlockSim(ModelBlock->Block_List[j].Simulation_Type) << "  //" << endl
             << "  % ////////////////////////////////////////////////////////////////////////" << endl;
      //The Temporary terms
      if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
          ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
          ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
          ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R)
        {
          output << "  if(jacobian_eval)\n";
          output << "    g1 = spalloc(" << ModelBlock->Block_List[j].Size << ", " << ModelBlock->Block_List[j].Size*(1+ModelBlock->Block_List[j].Max_Lag_Endo+ModelBlock->Block_List[j].Max_Lead_Endo) << ", " << nze << ");\n";
          output << "    g1_x=spalloc(" << ModelBlock->Block_List[j].Size << ", " << (ModelBlock->Block_List[j].nb_exo + ModelBlock->Block_List[j].nb_exo_det)*(1+ModelBlock->Block_List[j].Max_Lag_Exo+ModelBlock->Block_List[j].Max_Lead_Exo) << ", " << nze_exo << ");\n";
          output << "    g1_o=spalloc(" << ModelBlock->Block_List[j].Size << ", " << ModelBlock->Block_List[j].nb_other_endo*(1+ModelBlock->Block_List[j].Max_Lag_Other_Endo+ModelBlock->Block_List[j].Max_Lead_Other_Endo) << ", " << nze_other_endo << ");\n";
          output << "  end;\n";
        }
      else
        {
          output << "  if(jacobian_eval)\n";
          output << "    g1 = spalloc(" << ModelBlock->Block_List[j].Size << ", " << ModelBlock->Block_List[j].Size*(1+ModelBlock->Block_List[j].Max_Lag_Endo+ModelBlock->Block_List[j].Max_Lead_Endo) << ", " << nze << ");\n";
          output << "    g1_x=spalloc(" << ModelBlock->Block_List[j].Size << ", " << (ModelBlock->Block_List[j].nb_exo + ModelBlock->Block_List[j].nb_exo_det)*(1+ModelBlock->Block_List[j].Max_Lag_Exo+ModelBlock->Block_List[j].Max_Lead_Exo) << ", " << nze_exo << ");\n";
          output << "    g1_o=spalloc(" << ModelBlock->Block_List[j].Size << ", " << ModelBlock->Block_List[j].nb_other_endo*(1+ModelBlock->Block_List[j].Max_Lag_Other_Endo+ModelBlock->Block_List[j].Max_Lead_Other_Endo) << ", " << nze_other_endo << ");\n";
          output << "  else\n";
          if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
            output << "    g1 = spalloc(" << ModelBlock->Block_List[j].Size*ModelBlock->Periods << ", " << ModelBlock->Block_List[j].Size*(ModelBlock->Periods+ModelBlock->Block_List[j].Max_Lag+ModelBlock->Block_List[j].Max_Lead) << ", " << nze*ModelBlock->Periods << ");\n";
          else
            output << "    g1 = spalloc(" << ModelBlock->Block_List[j].Size << ", " << ModelBlock->Block_List[j].Size << ", " << nze << ");\n";
          output << "  end;\n";
        }

      output << "  g2=0;g3=0;\n";
      if(ModelBlock->Block_List[j].Temporary_InUse->size())
        {
          tmp_output.str("");
          for (temporary_terms_inuse_type::const_iterator it = ModelBlock->Block_List[j].Temporary_InUse->begin();
               it != ModelBlock->Block_List[j].Temporary_InUse->end(); it++)
            tmp_output << " T" << *it;
          output << "  global" << tmp_output.str() << ";\n";
        }
      output << "  residual=zeros(" << ModelBlock->Block_List[j].Size << ",1);\n";
      if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
          ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
          ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
          ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R)
        output << "  for it_ = y_kmin+1:(y_kmin+periods)\n";


      if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
        {
          output << "  b = [];\n";
          output << "  for it_ = y_kmin+1:(periods+y_kmin)\n";
          output << "    Per_y_=it_*y_size;\n";
          output << "    Per_J_=(it_-y_kmin-1)*y_size;\n";
          output << "    Per_K_=(it_-1)*y_size;\n";
          sps="  ";
        }
      else
        if(ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD || ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD ||
           ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R || ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R)
          sps = "  ";
        else
          sps="";
      // The equations
      for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
        {
          temporary_terms_type tt2;
          tt2.clear();
          if (ModelBlock->Block_List[j].Temporary_Terms_in_Equation[i]->size())
            output << "  " << sps << "% //Temporary variables" << endl;
          for (temporary_terms_type::const_iterator it = ModelBlock->Block_List[j].Temporary_Terms_in_Equation[i]->begin();
               it != ModelBlock->Block_List[j].Temporary_Terms_in_Equation[i]->end(); it++)
            {
              output << "  " <<  sps;
              (*it)->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
              output << " = ";
              (*it)->writeOutput(output, oMatlabDynamicModelSparse, tt2);
              // Insert current node into tt2
              tt2.insert(*it);
              output << ";" << endl;
            }
          string sModel = symbol_table.getName(ModelBlock->Block_List[j].Variable[i]) ;
          eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
          lhs = eq_node->get_arg1();
          rhs = eq_node->get_arg2();
          tmp_output.str("");
          lhs->writeOutput(tmp_output, oMatlabDynamicModelSparse, temporary_terms);
          switch (ModelBlock->Block_List[j].Simulation_Type)
            {
            case EVALUATE_BACKWARD:
            case EVALUATE_FORWARD:
              output << "    % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : " << sModel
                     << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ")" << endl;
              output << "    ";
              output << tmp_output.str();
              output << " = ";
              rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
              output << ";\n";
              break;
            case EVALUATE_BACKWARD_R:
            case EVALUATE_FORWARD_R:
              output << "    % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : " << sModel
                     << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ")" << endl;
              output << "  ";
              rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
              output << " = ";
              lhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
              output << ";\n";
              break;
            case SOLVE_BACKWARD_SIMPLE:
            case SOLVE_FORWARD_SIMPLE:
            case SOLVE_BACKWARD_COMPLETE:
            case SOLVE_FORWARD_COMPLETE:
              output << "  % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : " << sModel
                     << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ")" << endl;
              output << "  " << "residual(" << i+1 << ") = (";
              goto end;
            case SOLVE_TWO_BOUNDARIES_COMPLETE:
            case SOLVE_TWO_BOUNDARIES_SIMPLE:
              output << "    % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : " << sModel
                     << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ")" << endl;
              Uf[ModelBlock->Block_List[j].Equation[i]] << "    b(" << i+1 << "+Per_J_) = -residual(" << i+1 << ", it_)";
              output << "    residual(" << i+1 << ", it_) = (";
              goto end;
            default:
            end:
              output << tmp_output.str();
              output << ") - (";
              rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
              output << ");\n";
#ifdef CONDITION
              if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
                output << "  condition(" << i+1 << ")=0;\n";
#endif
            }
        }
      // The Jacobian if we have to solve the block
      if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE
          ||  ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE)
        output << "  " << sps << "% Jacobian  " << endl;
      else
        if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_SIMPLE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_SIMPLE ||
            ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_COMPLETE)
          output << "  % Jacobian  " << endl << "  if jacobian_eval" << endl;
        else
          output << "    % Jacobian  " << endl << "    if jacobian_eval" << endl;
      switch (ModelBlock->Block_List[j].Simulation_Type)
        {
        case EVALUATE_BACKWARD:
        case EVALUATE_FORWARD:
        case EVALUATE_BACKWARD_R:
        case EVALUATE_FORWARD_R:
          count_derivates++;
          for (m=0;m<ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag+1;m++)
            {
              k=m-ModelBlock->Block_List[j].Max_Lag;
              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
                {
                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
                  int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
                  output << "      g1(" << eqr+1 << ", " << /*varr+1+(m+variable_table.max_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr*/
                    varr+1+m*ModelBlock->Block_List[j].Size << ") = ";
                  writeDerivative(output, eq, symbol_table.getID(eEndogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                  output << "; % variable=" << symbol_table.getName(var)
                         << "(" << k//variable_table.getLag(variable_table.getSymbolID(ModelBlock->Block_List[j].Variable[0]))
                         << ") " << var+1
                         << ", equation=" << eq+1 << endl;
                }
            }
          //jacobian_max_endo_col=(variable_table.max_endo_lag+variable_table.max_endo_lead+1)*symbol_table.endo_nbr;
          for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
            {
              k=m-ModelBlock->Block_List[j].Max_Lag;
              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
                {
                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X[i];
                  int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous[i];
                  output << "      g1_x(" << eqr+1 << ", "
446
                         << varr+1+(m+max_exo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.exo_nbr() << ") = ";
sebastien's avatar
sebastien committed
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
                  writeDerivative(output, eq, symbol_table.getID(eExogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                  output << "; % variable=" << symbol_table.getName(var)
                         << "(" << k << ") " << var+1
                         << ", equation=" << eq+1 << endl;
                }
            }
          for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
            {
              k=m-ModelBlock->Block_List[j].Max_Lag;
              if (block_triangular.incidencematrix.Model_Max_Lag_Endo - ModelBlock->Block_List[j].Max_Lag +m >=0)
                {
                  for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;i++)
                    {
                      int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index_other_endo[i];
                      int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index_other_endo[i];
                      int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_other_endo[i];
                      int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var_other_endo[i];
                      output << "      g1_o(" << eqr+1 << ", "
465
                             << varr+1+(m+max_endo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr() << ") = ";
sebastien's avatar
sebastien committed
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
                      writeDerivative(output, eq, symbol_table.getID(eEndogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                      output << "; % variable=" << symbol_table.getName(var)
                             << "(" << k << ") " << var+1
                             << ", equation=" << eq+1 << endl;
                    }
                }
            }
          output << "      varargout{1}=g1_x;\n";
          output << "      varargout{2}=g1_o;\n";
          output << "    end;" << endl;
          output << "  end;" << endl;
          break;
        case SOLVE_BACKWARD_SIMPLE:
        case SOLVE_FORWARD_SIMPLE:
        case SOLVE_BACKWARD_COMPLETE:
        case SOLVE_FORWARD_COMPLETE:
          count_derivates++;
          for (m=0;m<ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag+1;m++)
            {
              k=m-ModelBlock->Block_List[j].Max_Lag;
              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
                {
                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
                  int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
                  output << "    g1(" << eqr+1 << ", " << /*varr+1+(m+variable_table.max_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr*/
                    varr+1+m*ModelBlock->Block_List[j].Size << ") = ";
                  writeDerivative(output, eq, symbol_table.getID(eEndogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                  output << "; % variable=" << symbol_table.getName(var)
                         << "(" << k
                         << ") " << var+1
                         << ", equation=" << eq+1 << endl;
                }
            }
          for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
            {
              k=m-ModelBlock->Block_List[j].Max_Lag;
              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
                {
                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X[i];
                  int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous[i];
510
                  output << "    g1_x(" << eqr+1 << ", " << varr+1+(m+max_exo_lag-ModelBlock->Block_List[j].Max_Lag)*ModelBlock->Block_List[j].nb_exo << ") = ";
sebastien's avatar
sebastien committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
                  writeDerivative(output, eq, symbol_table.getID(eExogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                  output << "; % variable=" << symbol_table.getName(var)
                         << "(" << k << ") " << var+1
                         << ", equation=" << eq+1 << endl;
                }
            }
          for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
            {
              k=m-ModelBlock->Block_List[j].Max_Lag;
              if (block_triangular.incidencematrix.Model_Max_Lag_Endo - ModelBlock->Block_List[j].Max_Lag +m >=0)
                {
                  for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;i++)
                    {
                      int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index_other_endo[i];
                      int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index_other_endo[i];
                      int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_other_endo[i];
                      int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var_other_endo[i];
                      output << "    g1_o(" << eqr+1 << ", "
529
                             << varr+1+(m+max_endo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr() << ") = ";
sebastien's avatar
sebastien committed
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
                      writeDerivative(output, eq, symbol_table.getID(eEndogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                      output << "; % variable=" << symbol_table.getName(var)
                             << "(" << k << ") " << var+1
                             << ", equation=" << eq+1 << endl;
                    }
                }
            }
          output << "    varargout{1}=g1_x;\n";
          output << "    varargout{2}=g1_o;\n";
          output << "  else" << endl;

          m=ModelBlock->Block_List[j].Max_Lag;
          for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
            {
              int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
              int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
              int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
              int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
              output << "    g1(" << eqr+1 << ", " << varr+1 << ") = ";
              writeDerivative(output, eq, symbol_table.getID(eEndogenous, var), 0, oMatlabDynamicModelSparse, temporary_terms);
              output << "; % variable=" << symbol_table.getName(var)
551
                     << "(0) " << var+1
sebastien's avatar
sebastien committed
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
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
                     << ", equation=" << eq+1 << endl;
            }
          output << "  end;\n";
          break;
        case SOLVE_TWO_BOUNDARIES_SIMPLE:
        case SOLVE_TWO_BOUNDARIES_COMPLETE:
          output << "    if ~jacobian_eval" << endl;
          for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
            {
              k=m-ModelBlock->Block_List[j].Max_Lag;
              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
                {
                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
                  int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
                  if (k==0)
                    Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+Per_K_)*y(it_, " << var+1 << ")";
                  else if (k==1)
                    Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+Per_y_)*y(it_+1, " << var+1 << ")";
                  else if (k>0)
                    Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+y_size*(it_+" << k-1 << "))*y(it_+" << k << ", " << var+1 << ")";
                  else if (k<0)
                    Uf[ModelBlock->Block_List[j].Equation[eqr]] << "+g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+y_size*(it_" << k-1 << "))*y(it_" << k << ", " << var+1 << ")";
                  if (k==0)
                    output << "      g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+Per_K_) = ";
                  else if (k==1)
                    output << "      g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+Per_y_) = ";
                  else if (k>0)
                    output << "      g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+y_size*(it_+" << k-1 << ")) = ";
                  else if (k<0)
                    output << "      g1(" << eqr+1 << "+Per_J_, " << varr+1 << "+y_size*(it_" << k-1 << ")) = ";
                  writeDerivative(output, eq, symbol_table.getID(eEndogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                  output << "; % variable=" << symbol_table.getName(var)
                         << "(" << k << ") " << var+1
                         << ", equation=" << eq+1 << endl;
#ifdef CONDITION
                  output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
                  output << "    condition(" << eqr << ")=u(" << u << "+Per_u_);\n";
#endif
                }
            }
          for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
            {
              output << "  " << Uf[ModelBlock->Block_List[j].Equation[i]].str() << ";\n";
#ifdef CONDITION
              output << "  if (fabs(condition(" << i+1 << "))<fabs(u(" << i << "+Per_u_)))\n";
              output << "    condition(" << i+1 << ")=u(" << i+1 << "+Per_u_);\n";
#endif
            }
#ifdef CONDITION
          for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
            {
              k=m-ModelBlock->Block_List[j].Max_Lag;
              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
                {
                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
                  int u=ModelBlock->Block_List[j].IM_lead_lag[m].u[i];
                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
                  output << "  u(" << u+1 << "+Per_u_) = u(" << u+1 << "+Per_u_) / condition(" << eqr+1 << ");\n";
                }
            }
          for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
            output << "  u(" << i+1 << "+Per_u_) = u(" << i+1 << "+Per_u_) / condition(" << i+1 << ");\n";
#endif

          output << "    else" << endl;
          for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
            {
              k=m-ModelBlock->Block_List[j].Max_Lag;
              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
                {
                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
                  int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
                  output << "      g1(" << eqr+1 << ", " << varr+1+(m-ModelBlock->Block_List[j].Max_Lag+ModelBlock->Block_List[j].Max_Lag_Endo)*ModelBlock->Block_List[j].Size << ") = ";
                  writeDerivative(output, eq, symbol_table.getID(eEndogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                  output << "; % variable=" << symbol_table.getName(var)
                         << "(" << k << ") " << var+1
                         << ", equation=" << eq+1 << endl;
                }
            }
          jacobian_max_endo_col=(ModelBlock->Block_List[j].Max_Lead_Endo+ModelBlock->Block_List[j].Max_Lag_Endo+1)*ModelBlock->Block_List[j].Size;
          for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
            {
              k=m-ModelBlock->Block_List[j].Max_Lag;
              for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_exo;i++)
                {
                  int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X_Index[i];
                  int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_X[i];
                  int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous[i];
                  int var=ModelBlock->Block_List[j].IM_lead_lag[m].Exogenous_Index[i];
                  output << "      g1_x(" << eqr+1 << ", "
                         << jacobian_max_endo_col+(m-(ModelBlock->Block_List[j].Max_Lag-ModelBlock->Block_List[j].Max_Lag_Exo))*ModelBlock->Block_List[j].nb_exo+varr+1 << ") = ";
                  writeDerivative(output, eq, symbol_table.getID(eExogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                  output << "; % variable (exogenous)=" << symbol_table.getName(var)
                         << "(" << k << ") " << var+1 << " " << varr+1
                         << ", equation=" << eq+1 << endl;
                }
            }
          for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
            {
              k=m-ModelBlock->Block_List[j].Max_Lag;
              if (block_triangular.incidencematrix.Model_Max_Lag_Endo - ModelBlock->Block_List[j].Max_Lag +m >=0)
                {
                  for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size_other_endo;i++)
                    {
                      int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index_other_endo[i];
                      int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index_other_endo[i];
                      int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_other_endo[i];
                      int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var_other_endo[i];
                      output << "      g1_o(" << eqr+1 << ", "
666
                             << varr+1+(m+max_endo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr() << ") = ";
sebastien's avatar
sebastien committed
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
                      writeDerivative(output, eq, symbol_table.getID(eEndogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                      output << "; % variable=" << symbol_table.getName(var)
                             << "(" << k << ") " << var+1
                             << ", equation=" << eq+1 << endl;
                    }
                }
            }
          output << "      varargout{1}=g1_x;\n";
          output << "      varargout{2}=g1_o;\n";
          output << "    end;\n";
          output << "  end;\n";
          break;
        default:
          break;
        }
      prev_Simulation_Type=ModelBlock->Block_List[j].Simulation_Type;
      output.close();
    }
}

void
sebastien's avatar
sebastien committed
688
DynamicModel::writeModelEquationsCodeOrdered(const string file_name, const Model_Block *ModelBlock, const string bin_basename, map_idx_type map_idx) const
sebastien's avatar
sebastien committed
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
{
  struct Uff_l
  {
    int u, var, lag;
    Uff_l *pNext;
  };

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

  int i,j,k,m, v, ModelBlock_Aggregated_Count, k0, k1;
  string tmp_s;
  ostringstream tmp_output;
  ofstream code_file;
  NodeID lhs=NULL, rhs=NULL;
  BinaryOpNode *eq_node;
  bool lhs_rhs_done;
  Uff Uf[symbol_table.endo_nbr()];
  map<NodeID, int> reference_count;
  map<int,int> ModelBlock_Aggregated_Size, ModelBlock_Aggregated_Number;
  int prev_Simulation_Type=-1;
  //SymbolicGaussElimination SGE;
  bool file_open=false;
  temporary_terms_type::const_iterator it_temp=temporary_terms.begin();
  //----------------------------------------------------------------------
  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
  code_file.write(&FDIMT, sizeof(FDIMT));
  k=temporary_terms.size();
  code_file.write(reinterpret_cast<char *>(&k),sizeof(k));
  //search for successive and identical blocks
  i=k=k0=0;
  ModelBlock_Aggregated_Count=-1;
  for (j = 0;j < ModelBlock->Size;j++)
    {
      if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(ModelBlock->Block_List[j].Simulation_Type)
          && (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD
              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD_R
              ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD_R ))
        {
        }
      else
        {
          k=k0=0;
          ModelBlock_Aggregated_Count++;
        }
      k0+=ModelBlock->Block_List[j].Size;
      ModelBlock_Aggregated_Number[ModelBlock_Aggregated_Count]=k0;
      ModelBlock_Aggregated_Size[ModelBlock_Aggregated_Count]=++k;
      prev_Simulation_Type=ModelBlock->Block_List[j].Simulation_Type;
    }
  ModelBlock_Aggregated_Count++;
  //For each block
  j=0;
  for (k0 = 0;k0 < ModelBlock_Aggregated_Count;k0++)
    {
      k1=j;
      if (k0>0)
        code_file.write(&FENDBLOCK, sizeof(FENDBLOCK));
      code_file.write(&FBEGINBLOCK, sizeof(FBEGINBLOCK));
      v=ModelBlock_Aggregated_Number[k0];
      code_file.write(reinterpret_cast<char *>(&v),sizeof(v));
      v=ModelBlock->Block_List[j].Simulation_Type;
      code_file.write(reinterpret_cast<char *>(&v),sizeof(v));
      for (k=0; k<ModelBlock_Aggregated_Size[k0]; k++)
        {
          for (i=0; i < ModelBlock->Block_List[j].Size;i++)
            {
              code_file.write(reinterpret_cast<char *>(&ModelBlock->Block_List[j].Variable[i]),sizeof(ModelBlock->Block_List[j].Variable[i]));
              code_file.write(reinterpret_cast<char *>(&ModelBlock->Block_List[j].Equation[i]),sizeof(ModelBlock->Block_List[j].Equation[i]));
              code_file.write(reinterpret_cast<char *>(&ModelBlock->Block_List[j].Own_Derivative[i]),sizeof(ModelBlock->Block_List[j].Own_Derivative[i]));
            }
          j++;
        }
      j=k1;
      if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE ||
          ModelBlock->Block_List[j].Simulation_Type==SOLVE_BACKWARD_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_FORWARD_COMPLETE)
        {
          code_file.write(reinterpret_cast<char *>(&ModelBlock->Block_List[j].is_linear),sizeof(ModelBlock->Block_List[j].is_linear));
          v=block_triangular.ModelBlock->Block_List[j].IM_lead_lag[block_triangular.ModelBlock->Block_List[j].Max_Lag + block_triangular.ModelBlock->Block_List[j].Max_Lead].u_finish + 1;
          code_file.write(reinterpret_cast<char *>(&v),sizeof(v));
          v=symbol_table.endo_nbr();
          code_file.write(reinterpret_cast<char *>(&v),sizeof(v));
          v=block_triangular.ModelBlock->Block_List[j].Max_Lag;
          code_file.write(reinterpret_cast<char *>(&v),sizeof(v));
          v=block_triangular.ModelBlock->Block_List[j].Max_Lead;
          code_file.write(reinterpret_cast<char *>(&v),sizeof(v));
          //if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
          //{
          int u_count_int=0;
          Write_Inf_To_Bin_File(file_name, bin_basename, j, u_count_int,file_open,
                                ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE);
          v=u_count_int;
          code_file.write(reinterpret_cast<char *>(&v),sizeof(v));
          file_open=true;
          //}
        }
      for (k1 = 0; k1 < ModelBlock_Aggregated_Size[k0]; k1++)
        {
          //For a block composed of a single equation determines whether we have to evaluate or to solve the equation
          if (ModelBlock->Block_List[j].Size==1)
            {
              lhs_rhs_done=true;
              eq_node = equations[ModelBlock->Block_List[j].Equation[0]];
              lhs = eq_node->get_arg1();
              rhs = eq_node->get_arg2();
            }
          else
            lhs_rhs_done=false;
          // The equations
          for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
            {
              //ModelBlock->Block_List[j].Variable_Sorted[i] = variable_table.getID(eEndogenous, ModelBlock->Block_List[j].Variable[i], 0);
              //The Temporary terms
              temporary_terms_type tt2;
#ifdef DEBUGC
              k=0;
#endif
              for (temporary_terms_type::const_iterator it = ModelBlock->Block_List[j].Temporary_Terms_in_Equation[i]->begin();
                   it != ModelBlock->Block_List[j].Temporary_Terms_in_Equation[i]->end(); it++)
                {
sebastien's avatar
sebastien committed
821
                  (*it)->compile(code_file, false, tt2, map_idx);
sebastien's avatar
sebastien committed
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
                  code_file.write(&FSTPT, sizeof(FSTPT));
                  map_idx_type::const_iterator ii=map_idx.find((*it)->idx);
                  v=(int)ii->second;
                  code_file.write(reinterpret_cast<char *>(&v), sizeof(v));
                  // Insert current node into tt2
                  tt2.insert(*it);
#ifdef DEBUGC
                  cout << "FSTPT " << v << "\n";
                  code_file.write(&FOK, sizeof(FOK));
                  code_file.write(reinterpret_cast<char *>(&k), sizeof(k));
                  ki++;
#endif

                }
#ifdef DEBUGC
              for (temporary_terms_type::const_iterator it = ModelBlock->Block_List[j].Temporary_terms->begin();
                   it != ModelBlock->Block_List[j].Temporary_terms->end(); it++)
                {
                  map_idx_type::const_iterator ii=map_idx.find((*it)->idx);
                  cout << "map_idx[" << (*it)->idx <<"]=" << ii->second << "\n";
                }
#endif
              if (!lhs_rhs_done)
                {
                  eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
                  lhs = eq_node->get_arg1();
                  rhs = eq_node->get_arg2();
                }
              switch (ModelBlock->Block_List[j].Simulation_Type)
                {
                case EVALUATE_BACKWARD:
                case EVALUATE_FORWARD:
sebastien's avatar
sebastien committed
854
855
                  rhs->compile(code_file, false, temporary_terms, map_idx);
                  lhs->compile(code_file, true, temporary_terms, map_idx);
sebastien's avatar
sebastien committed
856
857
858
                  break;
                case EVALUATE_BACKWARD_R:
                case EVALUATE_FORWARD_R:
sebastien's avatar
sebastien committed
859
860
                  lhs->compile(code_file, false, temporary_terms, map_idx);
                  rhs->compile(code_file, true, temporary_terms, map_idx);
sebastien's avatar
sebastien committed
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
                  break;
                case SOLVE_BACKWARD_COMPLETE:
                case SOLVE_FORWARD_COMPLETE:
                  v=ModelBlock->Block_List[j].Equation[i];
                  Uf[v].eqr=i;
                  Uf[v].Ufl=NULL;
                  goto end;
                case SOLVE_TWO_BOUNDARIES_COMPLETE:
                case SOLVE_TWO_BOUNDARIES_SIMPLE:
                  v=ModelBlock->Block_List[j].Equation[i];
                  Uf[v].eqr=i;
                  Uf[v].Ufl=NULL;
                  goto end;
                default:
                end:
sebastien's avatar
sebastien committed
876
877
                  lhs->compile(code_file, false, temporary_terms, map_idx);
                  rhs->compile(code_file, false, temporary_terms, map_idx);
sebastien's avatar
sebastien committed
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
                  code_file.write(&FBINARY, sizeof(FBINARY));
                  int v=oMinus;
                  code_file.write(reinterpret_cast<char *>(&v),sizeof(v));
                  code_file.write(&FSTPR, sizeof(FSTPR));
                  code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
#ifdef CONDITION
                  if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE)
                    output << "  condition[" << i << "]=0;\n";
#endif
                }
            }
          code_file.write(&FENDEQU, sizeof(FENDEQU));
          // The Jacobian if we have to solve the block
          if (ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD
              && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FORWARD
              && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD_R
              && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FORWARD_R)
            {
              switch (ModelBlock->Block_List[j].Simulation_Type)
                {
                case SOLVE_BACKWARD_SIMPLE:
                case SOLVE_FORWARD_SIMPLE:
sebastien's avatar
sebastien committed
900
                  compileDerivative(code_file, ModelBlock->Block_List[j].Equation[0], ModelBlock->Block_List[j].Variable[0], 0, map_idx);
sebastien's avatar
sebastien committed
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
                  code_file.write(&FSTPG, sizeof(FSTPG));
                  v=0;
                  code_file.write(reinterpret_cast<char *>(&v), sizeof(v));
                  break;
                case SOLVE_BACKWARD_COMPLETE:
                case SOLVE_FORWARD_COMPLETE:
                  m=ModelBlock->Block_List[j].Max_Lag;
                  for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
                    {
                      int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
                      int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
                      int u=ModelBlock->Block_List[j].IM_lead_lag[m].us[i];
                      int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
                      int v=ModelBlock->Block_List[j].Equation[eqr];
                      if (!Uf[v].Ufl)
                        {
                          Uf[v].Ufl=(Uff_l*)malloc(sizeof(Uff_l));
                          Uf[v].Ufl_First=Uf[v].Ufl;
                        }
                      else
                        {
                          Uf[v].Ufl->pNext=(Uff_l*)malloc(sizeof(Uff_l));
                          Uf[v].Ufl=Uf[v].Ufl->pNext;
                        }
                      Uf[v].Ufl->pNext=NULL;
                      Uf[v].Ufl->u=u;
                      Uf[v].Ufl->var=var;
sebastien's avatar
sebastien committed
928
                      compileDerivative(code_file, eq, var, 0, map_idx);
sebastien's avatar
sebastien committed
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
                      code_file.write(&FSTPU, sizeof(FSTPU));
                      code_file.write(reinterpret_cast<char *>(&u), sizeof(u));
                    }
                  for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
                    {
                      code_file.write(&FLDR, sizeof(FLDR));
                      code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
                      code_file.write(&FLDZ, sizeof(FLDZ));
                      int v=ModelBlock->Block_List[j].Equation[i];
                      for (Uf[v].Ufl=Uf[v].Ufl_First;Uf[v].Ufl;Uf[v].Ufl=Uf[v].Ufl->pNext)
                        {
                          code_file.write(&FLDU, sizeof(FLDU));
                          code_file.write(reinterpret_cast<char *>(&Uf[v].Ufl->u), sizeof(Uf[v].Ufl->u));
                          code_file.write(&FLDV, sizeof(FLDV));
                          char vc=eEndogenous;
                          code_file.write(reinterpret_cast<char *>(&vc), sizeof(vc));
                          code_file.write(reinterpret_cast<char *>(&Uf[v].Ufl->var), sizeof(Uf[v].Ufl->var));
                          int v1=0;
                          code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
                          code_file.write(&FBINARY, sizeof(FBINARY));
                          v1=oTimes;
                          code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
                          code_file.write(&FCUML, sizeof(FCUML));
                        }
                      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;
                        }
                      code_file.write(&FBINARY, sizeof(FBINARY));
                      v=oMinus;
                      code_file.write(reinterpret_cast<char *>(&v), sizeof(v));
                      code_file.write(&FSTPU, sizeof(FSTPU));
                      code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
                    }
                  break;
                case SOLVE_TWO_BOUNDARIES_COMPLETE:
                case SOLVE_TWO_BOUNDARIES_SIMPLE:
                  for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
                    {
                      k=m-ModelBlock->Block_List[j].Max_Lag;
                      for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
                        {
                          int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
                          int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
                          int u=ModelBlock->Block_List[j].IM_lead_lag[m].u[i];
                          int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
                          int v=ModelBlock->Block_List[j].Equation[eqr];
                          if (!Uf[v].Ufl)
                            {
                              Uf[v].Ufl=(Uff_l*)malloc(sizeof(Uff_l));
                              Uf[v].Ufl_First=Uf[v].Ufl;
                            }
                          else
                            {
                              Uf[v].Ufl->pNext=(Uff_l*)malloc(sizeof(Uff_l));
                              Uf[v].Ufl=Uf[v].Ufl->pNext;
                            }
                          Uf[v].Ufl->pNext=NULL;
                          Uf[v].Ufl->u=u;
                          Uf[v].Ufl->var=var;
                          Uf[v].Ufl->lag=k;
sebastien's avatar
sebastien committed
993
                          compileDerivative(code_file, eq, var, k, map_idx);
sebastien's avatar
sebastien committed
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
                          code_file.write(&FSTPU, sizeof(FSTPU));
                          code_file.write(reinterpret_cast<char *>(&u), sizeof(u));
#ifdef CONDITION
                          output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
                          output << "    condition[" << eqr << "]=u[" << u << "+Per_u_];\n";
#endif
                        }
                    }
                  for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
                    {
                      code_file.write(&FLDR, sizeof(FLDR));
                      code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
                      code_file.write(&FLDZ, sizeof(FLDZ));
                      int v=ModelBlock->Block_List[j].Equation[i];
                      for (Uf[v].Ufl=Uf[v].Ufl_First;Uf[v].Ufl;Uf[v].Ufl=Uf[v].Ufl->pNext)
                        {
                          code_file.write(&FLDU, sizeof(FLDU));
                          code_file.write(reinterpret_cast<char *>(&Uf[v].Ufl->u), sizeof(Uf[v].Ufl->u));
                          code_file.write(&FLDV, sizeof(FLDV));
                          char vc=eEndogenous;
                          code_file.write(reinterpret_cast<char *>(&vc), sizeof(vc));
                          int v1=Uf[v].Ufl->var;
                          code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
                          v1=Uf[v].Ufl->lag;
                          code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
                          code_file.write(&FBINARY, sizeof(FBINARY));
                          v1=oTimes;
                          code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));
                          code_file.write(&FCUML, sizeof(FCUML));
                        }
                      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;
                        }
                      code_file.write(&FBINARY, sizeof(FBINARY));
                      v=oMinus;
                      code_file.write(reinterpret_cast<char *>(&v), sizeof(v));
                      code_file.write(&FSTPU, sizeof(FSTPU));
                      code_file.write(reinterpret_cast<char *>(&i), sizeof(i));
#ifdef CONDITION
                      output << "  if (fabs(condition[" << i << "])<fabs(u[" << i << "+Per_u_]))\n";
                      output << "    condition[" << i << "]=u[" << i << "+Per_u_];\n";
#endif
                    }
#ifdef CONDITION
                  for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
                    {
                      k=m-ModelBlock->Block_List[j].Max_Lag;
                      for (i=0;i<ModelBlock->Block_List[j].IM_lead_lag[m].size;i++)
                        {
                          int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
                          int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
                          int u=ModelBlock->Block_List[j].IM_lead_lag[m].u[i];
                          int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
                          output << "  u[" << u << "+Per_u_] /= condition[" << eqr << "];\n";
                        }
                    }
                  for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
                    output << "  u[" << i << "+Per_u_] /= condition[" << i << "];\n";
#endif
                  break;
                default:
                  break;
                }

              prev_Simulation_Type=ModelBlock->Block_List[j].Simulation_Type;
            }
          j++;
        }
    }
  code_file.write(&FENDBLOCK, sizeof(FENDBLOCK));
  code_file.write(&FEND, sizeof(FEND));
  code_file.close();
}

void
DynamicModel::writeDynamicMFile(const string &dynamic_basename) const
{
  string filename = dynamic_basename + ".m";

  ofstream mDynamicModelFile;
  mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary);
  if (!mDynamicModelFile.is_open())
    {
      cerr << "Error: Can't open file " << filename << " for writing" << endl;
      exit(EXIT_FAILURE);
    }
  mDynamicModelFile << "function [residual, g1, g2, g3] = " << dynamic_basename << "(y, x, params, it_)" << endl
                    << "%" << endl
                    << "% Status : Computes dynamic model for Dynare" << endl
                    << "%" << endl
                    << "% Warning : this file is generated automatically by Dynare" << endl
                    << "%           from model file (.mod)" << endl << endl;

  writeDynamicModel(mDynamicModelFile);

  mDynamicModelFile.close();
}

void
DynamicModel::writeDynamicCFile(const string &dynamic_basename) const
{
  string filename = dynamic_basename + ".c";
  ofstream mDynamicModelFile;

  mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary);
  if (!mDynamicModelFile.is_open())
    {
      cerr << "Error: Can't open file " << filename << " for writing" << endl;
      exit(EXIT_FAILURE);
    }
  mDynamicModelFile << "/*" << endl
                    << " * " << filename << " : Computes dynamic model for Dynare" << endl
                    << " *" << endl
                    << " * Warning : this file is generated automatically by Dynare" << endl
                    << " *           from model file (.mod)" << endl
                    << endl
                    << " */" << endl
                    << "#include <math.h>" << endl
                    << "#include \"mex.h\"" << endl;

  // Writing the function body
  writeDynamicModel(mDynamicModelFile);

  // Writing the gateway routine
  mDynamicModelFile << "/* The gateway routine */" << endl
                    << "void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])" << endl
                    << "{" << endl
                    << "  double *y, *x, *params;" << endl
                    << "  double *residual, *g1, *g2;" << endl
                    << "  int nb_row_x, it_;" << endl
                    << endl
                    << "  /* Create a pointer to the input matrix y. */" << endl
                    << "  y = mxGetPr(prhs[0]);" << endl
                    << endl
                    << "  /* Create a pointer to the input matrix x. */" << endl
                    << "  x = mxGetPr(prhs[1]);" << endl
                    << endl
                    << "  /* Create a pointer to the input matrix params. */" << endl
                    << "  params = mxGetPr(prhs[2]);" << endl
                    << endl
                    << "  /* Fetch time index */" << endl
                    << "  it_ = (int) mxGetScalar(prhs[3]) - 1;" << endl
                    << endl
                    << "  /* Gets number of rows of matrix x. */" << endl
                    << "  nb_row_x = mxGetM(prhs[1]);" << endl
                    << endl
                    << "  residual = NULL;" << endl
                    << "  if (nlhs >= 1)" << endl
                    << "  {" << endl
                    << "     /* Set the output pointer to the output matrix residual. */" << endl
                    << "     plhs[0] = mxCreateDoubleMatrix(" << equations.size() << ",1, mxREAL);" << endl
                    << "     /* Create a C pointer to a copy of the output matrix residual. */" << endl
                    << "     residual = mxGetPr(plhs[0]);" << endl
                    << "  }" << endl
                    << endl
                    << "  g1 = NULL;" << endl
                    << "  if (nlhs >= 2)" << endl
                    << "  {" << endl
                    << "     /* Set the output pointer to the output matrix g1. */" << endl

1158
                    << "     plhs[1] = mxCreateDoubleMatrix(" << equations.size() << ", " << dynJacobianColsNbr << ", mxREAL);" << endl
sebastien's avatar
sebastien committed
1159
1160
1161
1162
1163
1164
1165
                    << "     /* Create a C pointer to a copy of the output matrix g1. */" << endl
                    << "     g1 = mxGetPr(plhs[1]);" << endl
                    << "  }" << endl
                    << endl
                    << "  g2 = NULL;" << endl
                    << " if (nlhs >= 3)" << endl
                    << "  {" << endl
sebastien's avatar
sebastien committed
1166
                    << "     /* Set the output pointer to the output matrix g2. */" << endl
1167
                    << "     plhs[2] = mxCreateDoubleMatrix(" << equations.size() << ", " << dynJacobianColsNbr*dynJacobianColsNbr
sebastien's avatar
sebastien committed
1168
                    << ", mxREAL);" << endl
sebastien's avatar
sebastien committed
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
                    << "     /* Create a C pointer to a copy of the output matrix g1. */" << endl
                    << "     g2 = mxGetPr(plhs[2]);" << endl
                    << "  }" << endl
                    << endl
                    << "  /* Call the C subroutines. */" << endl
                    << "  Dynamic(y, x, nb_row_x, params, it_, residual, g1, g2);" << endl
                    << "}" << endl;
  mDynamicModelFile.close();
}

string
DynamicModel::reform(const string name1) const
{
  string name=name1;
  int pos = name.find("\\", 0);
  while (pos >= 0)
    {
      if (name.substr(pos + 1, 1) != "\\")
        {
          name = name.insert(pos, "\\");
          pos++;
        }
      pos++;
      pos = name.find("\\", pos);
    }
  return (name);
}

void
DynamicModel::Write_Inf_To_Bin_File(const string &dynamic_basename, const string &bin_basename, const int &num,
                                    int &u_count_int, bool &file_open, bool is_two_boundaries) const
{
  int j;
  std::ofstream SaveCode;
  if (file_open)
    SaveCode.open((bin_basename + ".bin").c_str(), ios::out | ios::in | ios::binary | ios ::ate );
  else
    SaveCode.open((bin_basename + ".bin").c_str(), ios::out | ios::binary);
  if (!SaveCode.is_open())
    {
      cout << "Error : Can't open file \"" << bin_basename << ".bin\" for writing\n";
      exit(EXIT_FAILURE);
    }
  u_count_int=0;
  for (int m=0;m<=block_triangular.ModelBlock->Block_List[num].Max_Lead+block_triangular.ModelBlock->Block_List[num].Max_Lag;m++)
    {
      int k1=m-block_triangular.ModelBlock->Block_List[num].Max_Lag;
      for (j=0;j<block_triangular.ModelBlock->Block_List[num].IM_lead_lag[m].size;j++)
        {
          int varr=block_triangular.ModelBlock->Block_List[num].IM_lead_lag[m].Var[j]+k1*block_triangular.ModelBlock->Block_List[num].Size;
          int u=block_triangular.ModelBlock->Block_List[num].IM_lead_lag[m].u[j];
          int eqr1=block_triangular.ModelBlock->Block_List[num].IM_lead_lag[m].Equ[j];
          SaveCode.write(reinterpret_cast<char *>(&eqr1), sizeof(eqr1));
          SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr));
          SaveCode.write(reinterpret_cast<char *>(&k1), sizeof(k1));
          SaveCode.write(reinterpret_cast<char *>(&u), sizeof(u));
          u_count_int++;
        }
    }
  if(is_two_boundaries)
    {
      for (j=0;j<block_triangular.ModelBlock->Block_List[num].Size;j++)
        {
          int eqr1=j;
          int varr=block_triangular.ModelBlock->Block_List[num].Size*(block_triangular.periods
                                                                      +block_triangular.incidencematrix.Model_Max_Lead_Endo);
          int k1=0;
          SaveCode.write(reinterpret_cast<char *>(&eqr1), sizeof(eqr1));
          SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr));
          SaveCode.write(reinterpret_cast<char *>(&k1), sizeof(k1));
          SaveCode.write(reinterpret_cast<char *>(&eqr1), sizeof(eqr1));
          u_count_int++;
        }
    }
  //cout << "u_count_int=" << u_count_int << "\n";
  for (j=0;j<block_triangular.ModelBlock->Block_List[num].Size;j++)
    {
      int varr=block_triangular.ModelBlock->Block_List[num].Variable[j];
      SaveCode.write(reinterpret_cast<char *>(&varr), sizeof(varr));
    }
  for (j=0;j<block_triangular.ModelBlock->Block_List[num].Size;j++)
    {
      int eqr1=block_triangular.ModelBlock->Block_List[num].Equation[j];
      SaveCode.write(reinterpret_cast<char *>(&eqr1), sizeof(eqr1));
    }
  SaveCode.close();
}

void
DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const string &basename, const int mode) const
{
  string sp;
  ofstream mDynamicModelFile;
  ostringstream tmp, tmp1, tmp_eq;
  int prev_Simulation_Type, tmp_i;
  //SymbolicGaussElimination SGE;
  bool OK;
  chdir(basename.c_str());
  string filename = dynamic_basename + ".m";
  mDynamicModelFile.open(filename.c_str(), ios::out | ios::binary);
  if (!mDynamicModelFile.is_open())
    {
      cerr << "Error: Can't open file " << filename << " for writing" << endl;
      exit(EXIT_FAILURE);
    }
  mDynamicModelFile << "%\n";
  mDynamicModelFile << "% " << filename << " : Computes dynamic model for Dynare\n";
  mDynamicModelFile << "%\n";
  mDynamicModelFile << "% Warning : this file is generated automatically by Dynare\n";
  mDynamicModelFile << "%           from model file (.mod)\n\n";
  mDynamicModelFile << "%/\n";

  int i, k, Nb_SGE=0;
  bool skip_head, open_par=false;
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332

  mDynamicModelFile << "function [varargout] = " << dynamic_basename << "(varargin)\n";
  mDynamicModelFile << "  global oo_ options_ M_ ;\n";
  mDynamicModelFile << "  g2=[];g3=[];\n";
  //Temporary variables declaration
  OK=true;
  ostringstream tmp_output;
  for (temporary_terms_type::const_iterator it = temporary_terms.begin();
       it != temporary_terms.end(); it++)
    {
      if (OK)
        OK=false;
      else
        tmp_output << " ";
      (*it)->writeOutput(tmp_output, oMatlabStaticModelSparse, temporary_terms);
    }
  if (tmp_output.str().length()>0)
    mDynamicModelFile << "  global " << tmp_output.str() << " M_ ;\n";

  mDynamicModelFile << "  T_init=zeros(1,options_.periods+M_.maximum_lag+M_.maximum_lead);\n";
  tmp_output.str("");
  for (temporary_terms_type::const_iterator it = temporary_terms.begin();
       it != temporary_terms.end(); it++)
    {
      tmp_output << "  ";
      (*it)->writeOutput(tmp_output, oMatlabDynamicModel, temporary_terms);
      tmp_output << "=T_init;\n";
    }
  if (tmp_output.str().length()>0)
    mDynamicModelFile << tmp_output.str();

  mDynamicModelFile << "  y_kmin=M_.maximum_lag;\n";
  mDynamicModelFile << "  y_kmax=M_.maximum_lead;\n";
  mDynamicModelFile << "  y_size=M_.endo_nbr;\n";
  mDynamicModelFile << "  if(length(varargin)>0)\n";
  mDynamicModelFile << "    %it is a simple evaluation of the dynamic model for time _it\n";
  mDynamicModelFile << "    params=varargin{3};\n";
  mDynamicModelFile << "    it_=varargin{4};\n";
  /*i = symbol_table.endo_nbr*(variable_table.max_endo_lag+variable_table.max_endo_lead+1)+
    symbol_table.exo_nbr*(variable_table.max_exo_lag+variable_table.max_exo_lead+1);
    mDynamicModelFile << "    g1=spalloc(" << symbol_table.endo_nbr << ", " << i << ", " << i*symbol_table.endo_nbr << ");\n";*/
  mDynamicModelFile << "    Per_u_=0;\n";
  mDynamicModelFile << "    Per_y_=it_*y_size;\n";
  mDynamicModelFile << "    y=varargin{1};\n";
  mDynamicModelFile << "    ys=y(it_,:);\n";
  mDynamicModelFile << "    x=varargin{2};\n";
  prev_Simulation_Type=-1;
  tmp.str("");
  tmp_eq.str("");
  for (int count_call=1, i = 0;i < block_triangular.ModelBlock->Size;i++, count_call++)
sebastien's avatar
sebastien committed
1333
    {
1334
1335
1336
1337
      k=block_triangular.ModelBlock->Block_List[i].Simulation_Type;
      if ((BlockTriangular::BlockSim(prev_Simulation_Type)!=BlockTriangular::BlockSim(k))  &&
          ((prev_Simulation_Type==EVALUATE_FORWARD || prev_Simulation_Type==EVALUATE_BACKWARD || prev_Simulation_Type==EVALUATE_FORWARD_R || prev_Simulation_Type==EVALUATE_BACKWARD_R)
           || (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R)))
sebastien's avatar
sebastien committed
1338
        {
1339
1340
1341
1342
1343
1344
          mDynamicModelFile << "    y_index_eq=[" << tmp_eq.str() << "];\n";
          tmp_eq.str("");
          mDynamicModelFile << "    y_index=[" << tmp.str() << "];\n";
          tmp.str("");
          mDynamicModelFile << tmp1.str();
          tmp1.str("");
sebastien's avatar
sebastien committed
1345
        }
1346
      for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
sebastien's avatar
sebastien committed
1347
        {
1348
1349
          tmp << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
          tmp_eq << " " << block_triangular.ModelBlock->Block_List[i].Equation[ik]+1;
sebastien's avatar
sebastien committed
1350
        }
1351
      if (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R)
sebastien's avatar
sebastien committed
1352
        {
1353
          if (i==block_triangular.ModelBlock->Size-1)
sebastien's avatar
sebastien committed
1354
1355
1356
1357
1358
1359
1360
1361
1362
            {
              mDynamicModelFile << "    y_index_eq=[" << tmp_eq.str() << "];\n";
              tmp_eq.str("");
              mDynamicModelFile << "    y_index=[" << tmp.str() << "];\n";
              tmp.str("");
              mDynamicModelFile << tmp1.str();
              tmp1.str("");
            }
        }
1363
1364
1365
1366
1367
1368
      if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(k) &&
          (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R))
        skip_head=true;
      else
        skip_head=false;
      switch (k)
sebastien's avatar
sebastien committed
1369
        {
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
        case EVALUATE_FORWARD:
        case EVALUATE_BACKWARD:
        case EVALUATE_FORWARD_R:
        case EVALUATE_BACKWARD_R:
          if (!skip_head)
            {
              tmp1 << "    [y, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << i + 1 << "(y, x, params, 1, it_-1, 1);\n";
              tmp1 << "    residual(y_index_eq)=ys(y_index)-y(it_, y_index);\n";
            }
          break;
        case SOLVE_FORWARD_SIMPLE:
        case SOLVE_BACKWARD_SIMPLE:
          mDynamicModelFile << "    y_index_eq = " << block_triangular.ModelBlock->Block_List[i].Equation[0]+1 << ";\n";
          mDynamicModelFile << "    [r, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << i + 1 << "(y, x, params, it_, 1);\n";
          mDynamicModelFile << "    residual(y_index_eq)=r;\n";
          tmp_eq.str("");
          tmp.str("");
          break;
        case SOLVE_FORWARD_COMPLETE:
        case SOLVE_BACKWARD_COMPLETE:
          mDynamicModelFile << "    y_index_eq = [" << tmp_eq.str() << "];\n";
          mDynamicModelFile << "    [r, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" << i + 1 << "(y, x, params, it_, 1);\n";
          mDynamicModelFile << "    residual(y_index_eq)=r;\n";
          break;
        case SOLVE_TWO_BOUNDARIES_COMPLETE:
        case SOLVE_TWO_BOUNDARIES_SIMPLE:
          int j;
          mDynamicModelFile << "    y_index_eq = [" << tmp_eq.str() << "];\n";
          tmp_i=block_triangular.ModelBlock->Block_List[i].Max_Lag_Endo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Endo+1;
          mDynamicModelFile << "    y_index = [";
          for (j=0;j<tmp_i;j++)
            for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
              {
                mDynamicModelFile << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1+j*symbol_table.endo_nbr();
              }
          int tmp_ix=block_triangular.ModelBlock->Block_List[i].Max_Lag_Exo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Exo+1;
          for (j=0;j<tmp_ix;j++)
            for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].nb_exo;ik++)
              mDynamicModelFile << " " << block_triangular.ModelBlock->Block_List[i].Exogenous[ik]+1+j*symbol_table.exo_nbr()+symbol_table.endo_nbr()*tmp_i;
          mDynamicModelFile << " ];\n";
          tmp.str("");
          tmp_eq.str("");
          //mDynamicModelFile << "    ga = [];\n";
          j = block_triangular.ModelBlock->Block_List[i].Size*(block_triangular.ModelBlock->Block_List[i].Max_Lag_Endo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Endo+1)
            + block_triangular.ModelBlock->Block_List[i].nb_exo*(block_triangular.ModelBlock->Block_List[i].Max_Lag_Exo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Exo+1);
          /*mDynamicModelFile << "    ga=spalloc(" << block_triangular.ModelBlock->Block_List[i].Size << ", " << j << ", " <<
            block_triangular.ModelBlock->Block_List[i].Size*j << ");\n";*/
          tmp_i=block_triangular.ModelBlock->Block_List[i].Max_Lag_Endo+block_triangular.ModelBlock->Block_List[i].Max_Lead_Endo+1;
          mDynamicModelFile << "    [r, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, b, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" <<  i + 1 << "(y, x, params, it_-" << max_lag << ", 1, " << max_lag << ", " << block_triangular.ModelBlock->Block_List[i].Size << ");\n";
          /*if(block_triangular.ModelBlock->Block_List[i].Max_Lag==variable_table.max_lag && block_triangular.ModelBlock->Block_List[i].Max_Lead==variable_table.max_lead)
            mDynamicModelFile << "    g1(y_index_eq,y_index) = ga;\n";
            else
            mDynamicModelFile << "    g1(y_index_eq,y_index) = ga(:," << 1+(variable_table.max_lag-block_triangular.ModelBlock->Block_List[i].Max_Lag)*block_triangular.ModelBlock->Block_List[i].Size << ":" << (variable_table.max_lag+1+block_triangular.ModelBlock->Block_List[i].Max_Lead)*block_triangular.ModelBlock->Block_List[i].Size << ");\n";*/
          mDynamicModelFile << "    residual(y_index_eq)=r(:,M_.maximum_lag+1);\n";
          break;
sebastien's avatar
sebastien committed
1425
        }
1426
1427
1428
1429
1430
1431
      prev_Simulation_Type=k;
    }
  if (tmp1.str().length())
    {
      mDynamicModelFile << tmp1.str();
      tmp1.str("");
sebastien's avatar
sebastien committed
1432
    }
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
  mDynamicModelFile << "    varargout{1}=residual;\n";
  mDynamicModelFile << "    varargout{2}=dr;\n";
  mDynamicModelFile << "    return;\n";
  mDynamicModelFile << "  end;\n";
  mDynamicModelFile << "  %it is the deterministic simulation of the block decomposed dynamic model\n";
  mDynamicModelFile << "  if(options_.simulation_method==0)\n";
  mDynamicModelFile << "    mthd='Sparse LU';\n";
  mDynamicModelFile << "  elseif(options_.simulation_method==2)\n";
  mDynamicModelFile << "    mthd='GMRES';\n";
  mDynamicModelFile << "  elseif(options_.simulation_method==3)\n";
  mDynamicModelFile << "    mthd='BICGSTAB';\n";
  mDynamicModelFile << "  else\n";
  mDynamicModelFile << "    mthd='UNKNOWN';\n";
  mDynamicModelFile << "  end;\n";
  mDynamicModelFile << "  disp (['-----------------------------------------------------']) ;\n";
  mDynamicModelFile << "  disp (['MODEL SIMULATION: (method=' mthd ')']) ;\n";
  mDynamicModelFile << "  fprintf('\\n') ;\n";
  mDynamicModelFile << "  periods=options_.periods;\n";
  mDynamicModelFile << "  maxit_=options_.maxit_;\n";
  mDynamicModelFile << "  solve_tolf=options_.solve_tolf;\n";
  mDynamicModelFile << "  y=oo_.endo_simul';\n";
  mDynamicModelFile << "  x=oo_.exo_simul;\n";

sebastien's avatar
sebastien committed
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
  prev_Simulation_Type=-1;
  mDynamicModelFile << "  params=M_.params;\n";
  mDynamicModelFile << "  oo_.deterministic_simulation.status = 0;\n";
  for (i = 0;i < block_triangular.ModelBlock->Size;i++)
    {
      k = block_triangular.ModelBlock->Block_List[i].Simulation_Type;
      if (BlockTriangular::BlockSim(prev_Simulation_Type)==BlockTriangular::BlockSim(k) &&
          (k==EVALUATE_FORWARD || k==EVALUATE_BACKWARD || k==EVALUATE_FORWARD_R || k==EVALUATE_BACKWARD_R))
        skip_head=true;
      else
        skip_head=false;
      if ((k == EVALUATE_FORWARD || k == EVALUATE_FORWARD_R) && (block_triangular.ModelBlock->Block_List[i].Size))
        {
          if (!skip_head)
            {
              if (open_par)
                {
                  mDynamicModelFile << "  end\n";
                }
              mDynamicModelFile << "  oo_.deterministic_simulation.status = 1;\n";
              mDynamicModelFile << "  oo_.deterministic_simulation.error = 0;\n";
              mDynamicModelFile << "  oo_.deterministic_simulation.iterations = 0;\n";
              mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
              mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
              mDynamicModelFile << "  else\n";
              mDynamicModelFile << "    blck_num = 1;\n";
              mDynamicModelFile << "  end;\n";
              mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).status = 1;\n";
              mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).error = 0;\n";
              mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).iterations = 0;\n";
              mDynamicModelFile << "  g1=[];g2=[];g3=[];\n";
              //mDynamicModelFile << "  for it_ = y_kmin+1:(periods+y_kmin)\n";
              mDynamicModelFile << "    y=" << dynamic_basename << "_" << i + 1 << "(y, x, params, 0, y_kmin, periods);\n";
            }
          //open_par=true;
        }
      else if ((k == EVALUATE_BACKWARD || k == EVALUATE_BACKWARD_R) && (block_triangular.ModelBlock->Block_List[i].Size))
        {
          if (!skip_head)
            {
              if (open_par)
                {
                  mDynamicModelFile << "  end\n";
                }
              mDynamicModelFile << "  oo_.deterministic_simulation.status = 1;\n";
              mDynamicModelFile << "  oo_.deterministic_simulation.error = 0;\n";
              mDynamicModelFile << "  oo_.deterministic_simulation.iterations = 0;\n";
              mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
              mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
              mDynamicModelFile << "  else\n";
              mDynamicModelFile << "    blck_num = 1;\n";
              mDynamicModelFile << "  end;\n";
              mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).status = 1;\n";
              mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).error = 0;\n";
              mDynamicModelFile << "  oo_.deterministic_simulation.block(blck_num).iterations = 0;\n";
              mDynamicModelFile << "  g1=[];g2=[];g3=[];\n";
              mDynamicModelFile << "    " << dynamic_basename << "_" << i + 1 << "(y, x, params, 0, y_kmin, periods);\n";
            }
        }
      else if ((k == SOLVE_FORWARD_COMPLETE || k == SOLVE_FORWARD_SIMPLE) && (block_triangular.ModelBlock->Block_List[i].Size))
        {
          if (open_par)
            mDynamicModelFile << "  end\n";
          open_par=false;
          mDynamicModelFile << "  g1=0;\n";
          mDynamicModelFile << "  r=0;\n";
          tmp.str("");
          for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
            {
              tmp << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
            }
          mDynamicModelFile << "  y_index = [" << tmp.str() << "];\n";
          int nze, m;
          for (nze=0,m=0;m<=block_triangular.ModelBlock->Block_List[i].Max_Lead+block_triangular.ModelBlock->Block_List[i].Max_Lag;m++)
            nze+=block_triangular.ModelBlock->Block_List[i].IM_lead_lag[m].size;
          mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
          mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
          mDynamicModelFile << "  else\n";
          mDynamicModelFile << "    blck_num = 1;\n";
          mDynamicModelFile << "  end;\n";
          mDynamicModelFile << "  y = solve_one_boundary('"  << dynamic_basename << "_" <<  i + 1 << "'" <<
            ", y, x, params, y_index, " << nze <<
            ", options_.periods, " << block_triangular.ModelBlock->Block_List[i].is_linear <<
            ", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, options_.cutoff, options_.simulation_method, 1, 1, 0);\n";

        }
      else if ((k == SOLVE_BACKWARD_COMPLETE || k == SOLVE_BACKWARD_SIMPLE) && (block_triangular.ModelBlock->Block_List[i].Size))
        {
          if (open_par)
            mDynamicModelFile << "  end\n";
          open_par=false;
          mDynamicModelFile << "  g1=0;\n";
          mDynamicModelFile << "  r=0;\n";
          tmp.str("");
          for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
            {
              tmp << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
            }
          mDynamicModelFile << "  y_index = [" << tmp.str() << "];\n";
          int nze, m;
          for (nze=0,m=0;m<=block_triangular.ModelBlock->Block_List[i].Max_Lead+block_triangular.ModelBlock->Block_List[i].Max_Lag;m++)
            nze+=block_triangular.ModelBlock->Block_List[i].IM_lead_lag[m].size;
          mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
          mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
          mDynamicModelFile << "  else\n";
          mDynamicModelFile << "    blck_num = 1;\n";
          mDynamicModelFile << "  end;\n";
          mDynamicModelFile << "  y = solve_one_boundary('"  << dynamic_basename << "_" <<  i + 1 << "'" <<
            ", y, x, params, y_index, " << nze <<
            ", options_.periods, " << block_triangular.ModelBlock->Block_List[i].is_linear <<
            ", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, options_.cutoff, options_.simulation_method, 1, 1, 0);\n";
        }
      else if ((k == SOLVE_TWO_BOUNDARIES_COMPLETE || k == SOLVE_TWO_BOUNDARIES_SIMPLE) && (block_triangular.ModelBlock->Block_List[i].Size))
        {
          if (open_par)
            mDynamicModelFile << "  end\n";
          open_par=false;
          Nb_SGE++;
          int nze, m;
          for (nze=0,m=0;m<=block_triangular.ModelBlock->Block_List[i].Max_Lead+block_triangular.ModelBlock->Block_List[i].Max_Lag;m++)
            nze+=block_triangular.ModelBlock->Block_List[i].IM_lead_lag[m].size;
          mDynamicModelFile << "  y_index=[";
          for (int ik=0;ik<block_triangular.ModelBlock->Block_List[i].Size;ik++)
            {
              mDynamicModelFile << " " << block_triangular.ModelBlock->Block_List[i].Variable[ik]+1;
            }
          mDynamicModelFile << "  ];\n";
          mDynamicModelFile << "  if(isfield(oo_.deterministic_simulation,'block'))\n";
          mDynamicModelFile << "    blck_num = length(oo_.deterministic_simulation.block)+1;\n";
          mDynamicModelFile << "  else\n";
          mDynamicModelFile << "    blck_num = 1;\n";
          mDynamicModelFile << "  end;\n";
          mDynamicModelFile << "  y = solve_two_boundaries('" << dynamic_basename << "_" <<  i + 1 << "'" <<
            ", y, x, params, y_index, " << nze <<
            ", options_.periods, " << block_triangular.ModelBlock->Block_List[i].Max_Lag <<
            ", " << block_triangular.ModelBlock->Block_List[i].Max_Lead <<
            ", " << block_triangular.ModelBlock->Block_List[i].is_linear <<
            ", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, options_.cutoff, options_.simulation_method);\n";

        }
      prev_Simulation_Type=k;
    }
  if (open_par)
    mDynamicModelFile << "  end;\n";
  open_par=false;
  mDynamicModelFile << "  oo_.endo_simul = y';\n";
  mDynamicModelFile << "return;\n";

  mDynamicModelFile.close();

  writeModelEquationsOrdered_M( block_triangular.ModelBlock, dynamic_basename);

  chdir("..");
}

void
DynamicModel::writeDynamicModel(ostream &DynamicOutput) const
{
  ostringstream lsymetric;       // Used when writing symetric elements in Hessian
  ostringstream model_output;    // Used for storing model equations
  ostringstream jacobian_output; // Used for storing jacobian equations
  ostringstream hessian_output;  // Used for storing Hessian equations
  ostringstream third_derivatives_output;

  ExprNodeOutputType output_type = (mode == eStandardMode || mode==eSparseMode ? oMatlabDynamicModel : oCDynamicModel);

  writeModelLocalVariables(model_output, output_type);

sebastien's avatar
sebastien committed
1624
  writeTemporaryTerms(temporary_terms, model_output, output_type);
sebastien's avatar
sebastien committed
1625
1626
1627
1628

  writeModelEquations(model_output, output_type);

  int nrows = equations.size();
1629
  int hessianColsNbr = dynJacobianColsNbr * dynJacobianColsNbr;
sebastien's avatar
sebastien committed
1630
1631

  // Writing Jacobian
1632
1633
1634
1635
1636
1637
  for (first_derivatives_type::const_iterator it = first_derivatives.begin();
       it != first_derivatives.end(); it++)
    {
      int eq = it->first.first;
      int var = it->first.second;
      NodeID d1 = it->second;
sebastien's avatar
sebastien committed
1638

1639
1640
1641
1642
1643
1644
1645
1646
      ostringstream g1;
      g1 << "  g1";
      matrixHelper(g1, eq, getDynJacobianCol(var), output_type);

      jacobian_output << g1.str() << "=" << g1.str() << "+";
      d1->writeOutput(jacobian_output, output_type, temporary_terms);
      jacobian_output << ";" << endl;
    }
sebastien's avatar
sebastien committed
1647
1648

  // Writing Hessian
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
  for (second_derivatives_type::const_iterator it = second_derivatives.begin();
       it != second_derivatives.end(); it++)
    {
      int eq = it->first.first;
      int var1 = it->first.second.first;
      int var2 = it->first.second.second;
      NodeID d2 = it->second;

      int id1 = getDynJacobianCol(var1);
      int id2 = getDynJacobianCol(var2);

      int col_nb = id1 * dynJacobianColsNbr + id2;
      int col_nb_sym = id2 * dynJacobianColsNbr + id1;

      hessian_output << "  g2";
      matrixHelper(hessian_output, eq, col_nb, output_type);
      hessian_output << " = ";
      d2->writeOutput(hessian_output, output_type, temporary_terms);
      hessian_output << ";" << endl;

      // Treating symetric elements
      if (id1 != id2)
        {
          lsymetric <<  "  g2";
          matrixHelper(lsymetric, eq, col_nb_sym, output_type);
          lsymetric << " = " <<  "g2";
          matrixHelper(lsymetric, eq, col_nb, output_type);
          lsymetric << ";" << endl;
        }
    }
sebastien's avatar
sebastien committed
1679
1680

  // Writing third derivatives
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
  for (third_derivatives_type::const_iterator it = third_derivatives.begin();
       it != third_derivatives.end(); it++)
    {
      int eq = it->first.first;
      int var1 = it->first.second.first;
      int var2 = it->first.second.second.first;
      int var3 = it->first.second.second.second;
      NodeID d3 = it->second;

      int id1 = getDynJacobianCol(var1);
      int id2 = getDynJacobianCol(var2);
      int id3 = getDynJacobianCol(var3);

      // Reference column number for the g3 matrix
      int ref_col = id1 * hessianColsNbr + id2 * dynJacobianColsNbr + id3;

      third_derivatives_output << "  g3";
      matrixHelper(third_derivatives_output, eq, ref_col, output_type);
      third_derivatives_output << " = ";
      d3->writeOutput(third_derivatives_output, output_type, temporary_terms);
      third_derivatives_output << ";" << endl;

      // Compute the column numbers for the 5 other permutations of (id1,id2,id3) and store them in a set (to avoid duplicates if two indexes are equal)
      set<int> cols;
      cols.insert(id1 * hessianColsNbr + id3 * dynJacobianColsNbr + id2);
      cols.insert(id2 * hessianColsNbr + id1 * dynJacobianColsNbr + id3);
      cols.insert(id2 * hessianColsNbr + id3 * dynJacobianColsNbr + id1);
      cols.insert(id3 * hessianColsNbr + id1 * dynJacobianColsNbr + id2);
      cols.insert(id3 * hessianColsNbr + id2 * dynJacobianColsNbr + id1);

      for (set<int>::iterator it2 = cols.begin(); it2 != cols.end(); it2++)
        if (*it2 != ref_col)
          {
            third_derivatives_output << "  g3";
            matrixHelper(third_derivatives_output, eq, *it2, output_type);
            third_derivatives_output << " = " << "g3";
            matrixHelper(third_derivatives_output, eq, ref_col, output_type);
            third_derivatives_output << ";" << endl;
          }
    }
sebastien's avatar
sebastien committed
1721
1722
1723
1724
1725
1726
1727
1728

  if (mode == eStandardMode)
    {
      DynamicOutput << "%" << endl
                    << "% Model equations" << endl
                    << "%" << endl
                    << endl
                    << "residual = zeros(" << nrows << ", 1);" << endl
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
                    << model_output.str()
        // Writing initialization instruction for matrix g1
                    << "if nargout >= 2," << endl
                    << "  g1 = zeros(" << nrows << ", " << dynJacobianColsNbr << ");" << endl
                    << endl
                    << "%" << endl
                    << "% Jacobian matrix" << endl
                    << "%" << endl
                    << endl
                    << jacobian_output.str()
                    << "end" << endl;
1740

1741
      if (second_derivatives.size())
sebastien's avatar
sebastien committed
1742
1743
1744
        {
          // Writing initialization instruction for matrix g2
          DynamicOutput << "if nargout >= 3," << endl
1745
                        << "  g2 = sparse([],[],[], " << nrows << ", " << hessianColsNbr << ", " << NNZDerivatives[1] << ");" << endl
sebastien's avatar
sebastien committed
1746
1747
1748
1749
1750
1751
1752
1753
1754
                        << endl
                        << "%" << endl
                        << "% Hessian matrix" << endl
                        << "%" << endl
                        << endl
                        << hessian_output.str()
                        << lsymetric.str()
                        << "end;" << endl;
        }
1755
      if (third_derivatives.size())
sebastien's avatar
sebastien committed
1756
        {
1757
          int ncols = hessianColsNbr * dynJacobianColsNbr;
sebastien's avatar
sebastien committed
1758
          DynamicOutput << "if nargout >= 4," << endl
1759
                        << "  g3 = sparse([],[],[], " << nrows << ", " << ncols << ", " << NNZDerivatives[2] << ");" << endl
sebastien's avatar
sebastien committed
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
                        << endl
                        << "%" << endl
                        << "% Third order derivatives" << endl
                        << "%" << endl
                        << endl
                        << third_derivatives_output.str()
                        << "end;" << endl;
        }
    }
  else
    {
      DynamicOutput << "void Dynamic(double *y, double *x, int nb_row_x, double *params, int it_, double *residual, double *g1, double *g2)" << endl
                    << "{" << endl
                    << "  double lhs, rhs;" << endl
                    << endl
                    << "  /* Residual equations */" << endl
1776
1777
1778
1779
1780
1781
1782
1783
                    << model_output.str()
                    << "  /* Jacobian  */" << endl
                    << "  if (g1 == NULL)" << endl
                    << "    return;" << endl
                    << "  else" << endl
                    << "    {" << endl
                    << jacobian_output.str()
                    << "    }" << endl;
ferhat's avatar