DynamicModel.cc 147 KB
Newer Older
sebastien's avatar
sebastien committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
 * Copyright (C) 2003-2009 Dynare Team
 *
 * This file is part of Dynare.
 *
 * Dynare is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Dynare is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 */

20
#include <iostream>
sebastien's avatar
sebastien committed
21
#include <cmath>
22
#include <cstdlib>
23
#include <cassert>
24
25
#include <cstdio>
#include <cerrno>
sebastien's avatar
sebastien committed
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) :
ferhat's avatar
ferhat committed
39
40
41
42
43
44
45
    ModelTree(symbol_table_arg, num_constants_arg),
    max_lag(0), max_lead(0),
    max_endo_lag(0), max_endo_lead(0),
    max_exo_lag(0), max_exo_lead(0),
    max_exo_det_lag(0), max_exo_det_lead(0),
    dynJacobianColsNbr(0),
    cutoff(1e-15),
46
    mfs(0),
ferhat's avatar
ferhat committed
47
    block_triangular(symbol_table_arg, num_constants_arg)
sebastien's avatar
sebastien committed
48
49
50
{
}

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

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

72
73
74
75
76
77

void
DynamicModel::compileChainRuleDerivative(ofstream &code_file, int eqr, int varr, int lag, map_idx_type &map_idx) const
{
  map<pair<int, pair<int, int> >, NodeID>::const_iterator it = first_chain_rule_derivatives.find(make_pair(eqr, make_pair(varr, lag)));
  if (it != first_chain_rule_derivatives.end())
78
    (it->second)->compile(code_file, false, temporary_terms, map_idx, true, false);
79
  else
80
81
82
83
84
    {
      FLDZ_ fldz;
      fldz.write(code_file);
    }
    //code_file.write(&FLDZ, sizeof(FLDZ));
85
86
87
}


sebastien's avatar
sebastien committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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++)
        {
ferhat's avatar
ferhat committed
102
          block_triangular.incidencematrix.fill_IM(eq, it_endogenous->first, it_endogenous->second, eEndogenous);
sebastien's avatar
sebastien committed
103
104
105
106
107
108
109
110
        }
      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++)
        {
ferhat's avatar
ferhat committed
111
          block_triangular.incidencematrix.fill_IM(eq, it_exogenous->first, it_exogenous->second, eExogenous);
sebastien's avatar
sebastien committed
112
113
114
115
116
        }
    }
}

void
117
DynamicModel::computeTemporaryTermsOrdered(Model_Block *ModelBlock)
sebastien's avatar
sebastien committed
118
119
120
{
  map<NodeID, pair<int, int> > first_occurence;
  map<NodeID, int> reference_count;
121
  int i, j, m, eq, var, eqr, varr, lag;
sebastien's avatar
sebastien committed
122
123
124
125
  temporary_terms_type vect;
  ostringstream tmp_output;
  BinaryOpNode *eq_node;
  first_derivatives_type::const_iterator it;
126
  first_chain_rule_derivatives_type::const_iterator it_chr;
sebastien's avatar
sebastien committed
127
128
129
130
131
132
133
134
135
  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++)
        {
136
          if (ModelBlock->Block_List[j].Equation_Type[i] == E_EVALUATE_S && i<ModelBlock->Block_List[j].Nb_Recursives && ModelBlock->Block_List[j].Equation_Normalized[i])
ferhat's avatar
ferhat committed
137
              ModelBlock->Block_List[j].Equation_Normalized[i]->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, i, map_idx);
138
139
140
141
142
          else
            {
              eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
              eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, i, map_idx);
            }
sebastien's avatar
sebastien committed
143
        }
144
145
146
147
148
149
150
151
152
153
      for(i=0; i<(int)ModelBlock->Block_List[j].Chain_Rule_Derivatives->size();i++)
        {
          pair< pair<int, pair<int, int> >, pair<int, int> > it = ModelBlock->Block_List[j].Chain_Rule_Derivatives->at(i);
          lag=it.first.first;
          int eqr=it.second.first;
          int varr=it.second.second;
          it_chr=first_chain_rule_derivatives.find(make_pair(eqr, make_pair( varr, lag)));
          it_chr->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, ModelBlock->Block_List[j].Size-1, map_idx);
        }

sebastien's avatar
sebastien committed
154
155
156
157
158
159
160
      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];
161
              it=first_derivatives.find(make_pair(eq,getDerivID(symbol_table.getID(eEndogenous, var), lag)));
sebastien's avatar
sebastien committed
162
163
              it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, ModelBlock->Block_List[j].Size-1, map_idx);
            }
164
        }
165
      /*for(i=0; i<(int)ModelBlock->Block_List[j].Chain_Rule_Derivatives->size();i++)
166
        {
167
168
          pair< pair<int, pair<int, int> >, pair<int, int> > it = ModelBlock->Block_List[j].Chain_Rule_Derivatives->at(i);
          lag=it.first.first;
169
170
171
          eqr=it.second.first;
          varr=it.second.second;
          it_chr=first_chain_rule_derivatives.find(make_pair(eqr, make_pair( varr, lag)));
172
          it_chr->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, ModelBlock->Block_List[j].Size-1, map_idx);
173
        }*/
174
      /*for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
sebastien's avatar
sebastien committed
175
176
177
178
179
180
        {
          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];
181
              it=first_derivatives.find(make_pair(eq,getDerivID(symbol_table.getID(eExogenous, var), lag)));
sebastien's avatar
sebastien committed
182
183
              it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, j, ModelBlock, ModelBlock->Block_List[j].Size-1, map_idx);
            }
184
        }*/
sebastien's avatar
sebastien committed
185
186
187
188
189
190
191
192
193
194
      //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];
195
                  it=first_derivatives.find(make_pair(eq,getDerivID(symbol_table.getID(eEndogenous, var), lag)));
sebastien's avatar
sebastien committed
196
197
198
199
200
201
202
                  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++)
    {
ferhat's avatar
ferhat committed
203
      // Collecte the temporary terms reordered
sebastien's avatar
sebastien committed
204
205
      for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
        {
206
207
208
209
210
211
212
213
214
          if (ModelBlock->Block_List[j].Equation_Type[i] == E_EVALUATE_S && i<ModelBlock->Block_List[j].Nb_Recursives && ModelBlock->Block_List[j].Equation_Normalized[i])
              ModelBlock->Block_List[j].Equation_Normalized[i]->collectTemporary_terms(temporary_terms, ModelBlock, j);
          else
            {
              eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
              eq_node->collectTemporary_terms(temporary_terms, ModelBlock, j);
            }

          /*eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
sebastien's avatar
sebastien committed
215
          eq_node->collectTemporary_terms(temporary_terms, ModelBlock, j);
ferhat's avatar
ferhat committed
216
217
218
219
          if (ModelBlock->Block_List[j].Equation_Type[i] == E_EVALUATE_S)
            if(ModelBlock->Block_List[j].Equation_Normalized[i])
              ModelBlock->Block_List[j].Equation_Normalized[i]->collectTemporary_terms(temporary_terms, ModelBlock, j);
          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++)
220
            (*it)->collectTemporary_terms(temporary_terms, ModelBlock, j);*/
sebastien's avatar
sebastien committed
221
222
223
224
225
226
227
228
        }
      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];
229
              it=first_derivatives.find(make_pair(eq,getDerivID(symbol_table.getID(eEndogenous, var), lag)));
sebastien's avatar
sebastien committed
230
              //it=first_derivatives.find(make_pair(eq,variable_table.getID(var, lag)));
231
              //if(it!=first_derivatives.end())
sebastien's avatar
sebastien committed
232
233
              it->second->collectTemporary_terms(temporary_terms, ModelBlock, j);
            }
234
        }
235
      for(i=0; i<(int)ModelBlock->Block_List[j].Chain_Rule_Derivatives->size();i++)
236
        {
237
238
          pair< pair<int, pair<int, int> >, pair<int, int> > it = ModelBlock->Block_List[j].Chain_Rule_Derivatives->at(i);
          lag=it.first.first;
239
240
241
          eqr=it.second.first;
          varr=it.second.second;
          it_chr=first_chain_rule_derivatives.find(make_pair(eqr, make_pair( varr, lag)));
242
          it_chr->second->collectTemporary_terms(temporary_terms, ModelBlock, j);
sebastien's avatar
sebastien committed
243
        }
244
      /*for (m=0;m<=ModelBlock->Block_List[j].Max_Lead+ModelBlock->Block_List[j].Max_Lag;m++)
sebastien's avatar
sebastien committed
245
246
247
248
249
250
        {
          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];
251
              it=first_derivatives.find(make_pair(eq,getDerivID(symbol_table.getID(eExogenous, var), lag)));
sebastien's avatar
sebastien committed
252
253
254
              //it=first_derivatives.find(make_pair(eq,variable_table.getID(var, lag)));
              it->second->collectTemporary_terms(temporary_terms, ModelBlock, j);
            }
255
        }*/
sebastien's avatar
sebastien committed
256
257
258
259
260
261
262
263
264
265
      //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];
266
                  it=first_derivatives.find(make_pair(eq,getDerivID(symbol_table.getID(eEndogenous, var), lag)));
sebastien's avatar
sebastien committed
267
                  //it=first_derivatives.find(make_pair(eq,variable_table.getID(var, lag)));
268
                  //if(it!=first_derivatives.end())
sebastien's avatar
sebastien committed
269
270
271
272
273
274
275
276
277
278
279
280
281
282
                  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
ferhat's avatar
ferhat committed
283
284
285
286
287
288
289
290
  {
    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;
291
    //int prev_Simulation_Type=-1, count_derivates=0;
ferhat's avatar
ferhat committed
292
293
294
295
    int jacobian_max_endo_col;
    ofstream  output;
    //temporary_terms_type::const_iterator it_temp=temporary_terms.begin();
    int nze, nze_exo, nze_other_endo;
296
    //map<int, NodeID> recursive_variables;
ferhat's avatar
ferhat committed
297
298
299
300
301
    vector<int> feedback_variables;
    //----------------------------------------------------------------------
    //For each block
    for (j = 0;j < ModelBlock->Size;j++)
      {
302
        //recursive_variables.clear();
ferhat's avatar
ferhat committed
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
        feedback_variables.clear();
        //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+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)
              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, y, 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, y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << j+1 << "(y, x, params, it_, jacobian_eval)\n";
        else
          output << "function [residual, y, 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;
346
        output << "  global options_;" << endl;
ferhat's avatar
ferhat committed
347
        //The Temporary terms
348
        //output << "  relax = 1;\n";
ferhat's avatar
ferhat committed
349
        if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD
350
            ||ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD)
ferhat's avatar
ferhat committed
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
          {
            output << "  if(jacobian_eval)\n";
            output << "    g1 = spalloc(" << ModelBlock->Block_List[j].Size-ModelBlock->Block_List[j].Nb_Recursives
            << ", " << (ModelBlock->Block_List[j].Size-ModelBlock->Block_List[j].Nb_Recursives)*(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)
              {
369
370
371
                output << "    g1 = spalloc(" << (ModelBlock->Block_List[j].Size-ModelBlock->Block_List[j].Nb_Recursives) << "*options_.periods, "
                << (ModelBlock->Block_List[j].Size-ModelBlock->Block_List[j].Nb_Recursives) << "*(options_.periods+" << ModelBlock->Block_List[j].Max_Lag+ModelBlock->Block_List[j].Max_Lead+1 << ")"
                << ", " << nze << "*options_.periods);\n";
372
                /*output << "    g1_tmp_r = spalloc(" << (ModelBlock->Block_List[j].Nb_Recursives)
ferhat's avatar
ferhat committed
373
374
375
376
                << ", " << (ModelBlock->Block_List[j].Size)*(ModelBlock->Block_List[j].Max_Lag+ModelBlock->Block_List[j].Max_Lead+1)
                << ", " << nze << ");\n";
                output << "    g1_tmp_b = spalloc(" << (ModelBlock->Block_List[j].Size-ModelBlock->Block_List[j].Nb_Recursives)
                << ", " << (ModelBlock->Block_List[j].Size)*(ModelBlock->Block_List[j].Max_Lag+ModelBlock->Block_List[j].Max_Lead+1)
377
                << ", " << nze << ");\n";*/
ferhat's avatar
ferhat committed
378
379
380
381
382
383
384
385
386
387
388
389
              }
            else
              {
                output << "    g1 = spalloc(" << ModelBlock->Block_List[j].Size-ModelBlock->Block_List[j].Nb_Recursives
                << ", " << ModelBlock->Block_List[j].Size-ModelBlock->Block_List[j].Nb_Recursives << ", " << nze << ");\n";
                output << "    g1_tmp_r = spalloc(" << ModelBlock->Block_List[j].Nb_Recursives
                << ", " << ModelBlock->Block_List[j].Size << ", " << nze << ");\n";
                output << "    g1_tmp_b = spalloc(" << ModelBlock->Block_List[j].Size-ModelBlock->Block_List[j].Nb_Recursives
                << ", " << ModelBlock->Block_List[j].Size << ", " << nze << ");\n";
              }
            output << "  end;\n";
          }
sebastien's avatar
sebastien committed
390

ferhat's avatar
ferhat committed
391
392
393
394
395
396
397
398
399
        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";
          }
400
        if (ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FORWARD)
ferhat's avatar
ferhat committed
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
          output << "  residual=zeros(" << ModelBlock->Block_List[j].Size-ModelBlock->Block_List[j].Nb_Recursives << ",1);\n";
        if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD)
          output << "  for it_ = (y_kmin+periods):y_kmin+1\n";
        if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD)
          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 = zeros(periods*y_size,1);\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="  ";
          }
sebastien's avatar
sebastien committed
416
        else
ferhat's avatar
ferhat committed
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
          if (ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD || ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD )
            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(symbol_table.getID(eEndogenous, 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("");
444
            /*if((ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD or ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FORWARD) and (i<ModelBlock->Block_List[j].Nb_Recursives))
445
              lhs->writeOutput(tmp_output, oMatlabDynamicModelSparse, temporary_terms);
446
447
            else*/
						lhs->writeOutput(tmp_output, oMatlabDynamicModelSparse, temporary_terms);
ferhat's avatar
ferhat committed
448
449
450
451
            switch (ModelBlock->Block_List[j].Simulation_Type)
              {
              case EVALUATE_BACKWARD:
              case EVALUATE_FORWARD:
452
453
454
evaluation:     if (ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_COMPLETE || ModelBlock->Block_List[j].Simulation_Type==SOLVE_TWO_BOUNDARIES_SIMPLE)
                  output << "    % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : " << sModel
                  << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ") " << block_triangular.c_Equation_Type(ModelBlock->Block_List[j].Equation_Type[i]) << endl;
ferhat's avatar
ferhat committed
455
456
457
458
459
                output << "    ";
                if (ModelBlock->Block_List[j].Equation_Type[i] == E_EVALUATE)
                  {
                    output << tmp_output.str();
                    output << " = ";
460
461
462
463
464
465
466
467
468
469
                    /*if(!(ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD or ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD))
                      {
                        lhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
                        output << "-relax*(";
                        lhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
                        output << "-(";
                        rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
                        output << "))";
                      }
                    else*/
ferhat's avatar
ferhat committed
470
471
472
473
474
475
476
477
478
479
                    rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
                  }
                else if (ModelBlock->Block_List[j].Equation_Type[i] == E_EVALUATE_S)
                  {
                    output << "%" << tmp_output.str();
                    output << " = ";
                    if (ModelBlock->Block_List[j].Equation_Normalized[i])
                      {
                        rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
                        output << "\n    ";
480
481
482
483
                        tmp_output.str("");
                        eq_node = (BinaryOpNode *)ModelBlock->Block_List[j].Equation_Normalized[i];
                        lhs = eq_node->get_arg1();
                        rhs = eq_node->get_arg2();
484
                        lhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
485
                        output << " = ";
486
487
488
489
490
491
492
493
494
495
496
                        /*if(!(ModelBlock->Block_List[j].Simulation_Type==EVALUATE_BACKWARD or ModelBlock->Block_List[j].Simulation_Type==EVALUATE_FORWARD))
                          {
                            lhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
                            output << "-relax*(";
                            lhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
                            output << "-(";
                            rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
                            output << "))";
                          }
                        else*/
                          rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
ferhat's avatar
ferhat committed
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
                      }
                  }
                else
                  {
                    cerr << "Type missmatch for equation " << ModelBlock->Block_List[j].Equation[i]+1  << "\n";
                    exit(EXIT_FAILURE);
                  }
                output << ";\n";
                break;
              case SOLVE_BACKWARD_SIMPLE:
              case SOLVE_FORWARD_SIMPLE:
              case SOLVE_BACKWARD_COMPLETE:
              case SOLVE_FORWARD_COMPLETE:
                if (i<ModelBlock->Block_List[j].Nb_Recursives)
                  {
512
                    /*if (ModelBlock->Block_List[j].Equation_Type[i] == E_EVALUATE_S)
ferhat's avatar
ferhat committed
513
514
                      recursive_variables[getDerivID(symbol_table.getID(eEndogenous, ModelBlock->Block_List[j].Variable[i]), 0)] = ModelBlock->Block_List[j].Equation_Normalized[i];
                    else
515
                      recursive_variables[getDerivID(symbol_table.getID(eEndogenous, ModelBlock->Block_List[j].Variable[i]), 0)] = equations[ModelBlock->Block_List[j].Equation[i]];*/
ferhat's avatar
ferhat committed
516
517
518
519
520
521
522
523
524
525
526
                    goto evaluation;
                  }
                feedback_variables.push_back(ModelBlock->Block_List[j].Variable[i]);
                output << "  % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : " << sModel
                << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ") " << block_triangular.c_Equation_Type(ModelBlock->Block_List[j].Equation_Type[i]) << endl;
                output << "  " << "residual(" << i+1-ModelBlock->Block_List[j].Nb_Recursives << ") = (";
                goto end;
              case SOLVE_TWO_BOUNDARIES_COMPLETE:
              case SOLVE_TWO_BOUNDARIES_SIMPLE:
                if (i<ModelBlock->Block_List[j].Nb_Recursives)
                  {
527
                    /*if (ModelBlock->Block_List[j].Equation_Type[i] == E_EVALUATE_S)
ferhat's avatar
ferhat committed
528
529
                      recursive_variables[getDerivID(symbol_table.getID(eEndogenous, ModelBlock->Block_List[j].Variable[i]), 0)] = ModelBlock->Block_List[j].Equation_Normalized[i];
                    else
530
                      recursive_variables[getDerivID(symbol_table.getID(eEndogenous, ModelBlock->Block_List[j].Variable[i]), 0)] = equations[ModelBlock->Block_List[j].Equation[i]];*/
ferhat's avatar
ferhat committed
531
532
533
534
535
536
537
538
539
540
541
542
543
544
                    goto evaluation;
                  }
                feedback_variables.push_back(ModelBlock->Block_List[j].Variable[i]);
                output << "    % equation " << ModelBlock->Block_List[j].Equation[i]+1 << " variable : " << sModel
                << " (" << ModelBlock->Block_List[j].Variable[i]+1 << ") " << block_triangular.c_Equation_Type(ModelBlock->Block_List[j].Equation_Type[i]) << endl;
                Uf[ModelBlock->Block_List[j].Equation[i]] << "    b(" << i+1-ModelBlock->Block_List[j].Nb_Recursives << "+Per_J_) = -residual(" << i+1-ModelBlock->Block_List[j].Nb_Recursives << ", it_)";
                output << "    residual(" << i+1-ModelBlock->Block_List[j].Nb_Recursives << ", it_) = (";
                goto end;
              default:
end:
                output << tmp_output.str();
                output << ") - (";
                rhs->writeOutput(output, oMatlabDynamicModelSparse, temporary_terms);
                output << ");\n";
sebastien's avatar
sebastien committed
545
#ifdef CONDITION
ferhat's avatar
ferhat committed
546
547
                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";
sebastien's avatar
sebastien committed
548
#endif
ferhat's avatar
ferhat committed
549
550
551
552
553
554
              }
          }
        // 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;
sebastien's avatar
sebastien committed
555
        else
ferhat's avatar
ferhat committed
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
          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:
            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*/
sebastien's avatar
sebastien committed
575
                    varr+1+m*ModelBlock->Block_List[j].Size << ") = ";
ferhat's avatar
ferhat committed
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
                    writeDerivative(output, eq, symbol_table.getID(eEndogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                    output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, 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 << ", "
                           << varr+1+(m+max_exo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.exo_nbr() << ") = ";
                    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 << ", "
                        << varr+1+(m+max_endo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr() << ") = ";
                        writeDerivative(output, eq, symbol_table.getID(eEndogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                        output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                        << "(" << k << ") " << var+1
                        << ", equation=" << eq+1 << endl;
                      }
                  }
              }
            output << "      varargout{1}=g1_x;\n";
            output << "      varargout{2}=g1_o;\n";
            output << "    end;" << endl;
            //output << "    ya = y;\n";
            output << "  end;" << endl;
            break;
          case SOLVE_BACKWARD_SIMPLE:
          case SOLVE_FORWARD_SIMPLE:
          case SOLVE_BACKWARD_COMPLETE:
          case SOLVE_FORWARD_COMPLETE:
            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++)
                  {
636
637
638
639
640
641
642
643
644
645
                    int eqr=ModelBlock->Block_List[j].IM_lead_lag[m].Equ_Index[i];
                    int varr=ModelBlock->Block_List[j].IM_lead_lag[m].Var_Index[i];
                    int eq=ModelBlock->Block_List[j].IM_lead_lag[m].Equ[i];
                    int var=ModelBlock->Block_List[j].IM_lead_lag[m].Var[i];
                    output << "    g1(" << eq+1 << ", "
                    << var+1 + m*(ModelBlock->Block_List[j].Size) << ") = ";
                    writeDerivative(output, eqr, symbol_table.getID(eEndogenous, varr), k, oMatlabDynamicModelSparse, temporary_terms);
                    output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr))
                    << "(" << k << ") " << varr+1
                    << ", equation=" << eqr+1 << endl;
ferhat's avatar
ferhat committed
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
                  }
              }
            /*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 << ", " << varr+1+(m+max_exo_lag-ModelBlock->Block_List[j].Max_Lag)*ModelBlock->Block_List[j].nb_exo << ") = ";
                    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];
675
                        output << "    g1_o(" << eqr+1/*-ModelBlock->Block_List[j].Nb_Recursives*/ << ", "
ferhat's avatar
ferhat committed
676
677
678
679
680
681
682
683
684
685
686
687
                        << varr+1+(m+max_endo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr() << ") = ";
                        writeDerivative(output, eq, symbol_table.getID(eEndogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                        output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                        << "(" << k << ") " << var+1
                        << ", equation=" << eq+1 << endl;
                      }
                  }
              }
            output << "    varargout{1}=g1_x;\n";
            output << "    varargout{2}=g1_o;\n";
            output << "  else" << endl;

688
            for(i=0; i<(int)ModelBlock->Block_List[j].Chain_Rule_Derivatives->size();i++)
ferhat's avatar
ferhat committed
689
              {
690
691
692
693
694
695
696
697
698
699
700
701
                pair< pair<int, pair<int, int> >, pair<int, int> > it = ModelBlock->Block_List[j].Chain_Rule_Derivatives->at(i);
                k=it.first.first;
                int eq=it.first.second.first;
                int var=it.first.second.second;
                int eqr=it.second.first;
                int varr=it.second.second;
                output << "    g1(" << eq+1-ModelBlock->Block_List[j].Nb_Recursives << ", "
                       << var+1-ModelBlock->Block_List[j].Nb_Recursives  << ") = ";
                writeChainRuleDerivative(output, eqr, varr, k, oMatlabDynamicModelSparse, temporary_terms);
                output << "; %2 variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr))
                       << "(" << k << ") " << varr+1 << ", equation=" << eqr+1 << endl;
              }
ferhat's avatar
ferhat committed
702
703
704
705
706
            output << "  end;\n";
            break;
          case SOLVE_TWO_BOUNDARIES_SIMPLE:
          case SOLVE_TWO_BOUNDARIES_COMPLETE:
            output << "    if ~jacobian_eval" << endl;
707
            for(i=0; i<(int)ModelBlock->Block_List[j].Chain_Rule_Derivatives->size();i++)
ferhat's avatar
ferhat committed
708
              {
709
710
711
712
713
714
715
716
                pair< pair<int, pair<int, int> >, pair<int, int> > it = ModelBlock->Block_List[j].Chain_Rule_Derivatives->at(i);
                k=it.first.first;
                int eq=it.first.second.first;
                int var=it.first.second.second;
                int eqr=it.second.first;
                int varr=it.second.second;
                ostringstream tmp_output;
                if(eq>=ModelBlock->Block_List[j].Nb_Recursives and var>=ModelBlock->Block_List[j].Nb_Recursives)
ferhat's avatar
ferhat committed
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
                    if (k==0)
                      Uf[ModelBlock->Block_List[j].Equation[eq]] << "+g1(" << eq+1-ModelBlock->Block_List[j].Nb_Recursives
                        << "+Per_J_, " << var+1-ModelBlock->Block_List[j].Nb_Recursives
                        << "+Per_K_)*y(it_, " << varr+1 << ")";
                    else if (k==1)
                      Uf[ModelBlock->Block_List[j].Equation[eq]] << "+g1(" << eq+1-ModelBlock->Block_List[j].Nb_Recursives
                        << "+Per_J_, " << var+1-ModelBlock->Block_List[j].Nb_Recursives
                        << "+Per_y_)*y(it_+1, " << varr+1 << ")";
                    else if (k>0)
                      Uf[ModelBlock->Block_List[j].Equation[eq]] << "+g1(" << eq+1-ModelBlock->Block_List[j].Nb_Recursives
                        << "+Per_J_, " << var+1-ModelBlock->Block_List[j].Nb_Recursives
                        << "+y_size*(it_+" << k-1 << "))*y(it_+" << k << ", " << varr+1 << ")";
                    else if (k<0)
                      Uf[ModelBlock->Block_List[j].Equation[eq]] << "+g1(" << eq+1-ModelBlock->Block_List[j].Nb_Recursives
                        << "+Per_J_, " << var+1-ModelBlock->Block_List[j].Nb_Recursives
                        << "+y_size*(it_" << k-1 << "))*y(it_" << k << ", " << varr+1 << ")";
                    if (k==0)
                      tmp_output << "     g1(" << eq+1-ModelBlock->Block_List[j].Nb_Recursives << "+Per_J_, "
                        << var+1-ModelBlock->Block_List[j].Nb_Recursives << "+Per_K_) = ";
                    else if (k==1)
                      tmp_output << "     g1(" << eq+1-ModelBlock->Block_List[j].Nb_Recursives << "+Per_J_, "
                        << var+1-ModelBlock->Block_List[j].Nb_Recursives << "+Per_y_) = ";
                    else if (k>0)
                      tmp_output << "     g1(" << eq+1-ModelBlock->Block_List[j].Nb_Recursives << "+Per_J_, "
                        << var+1-ModelBlock->Block_List[j].Nb_Recursives << "+y_size*(it_+" << k-1 << ")) = ";
                    else if (k<0)
                      tmp_output << "     g1(" << eq+1-ModelBlock->Block_List[j].Nb_Recursives << "+Per_J_, "
                        << var+1-ModelBlock->Block_List[j].Nb_Recursives << "+y_size*(it_" << k-1 << ")) = ";
                    output << " " << tmp_output.str();

                    writeChainRuleDerivative(output, eqr, varr, k, oMatlabDynamicModelSparse, temporary_terms);

                    output << ";";
                    output << " %2 variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr))
                      << "(" << k << ") " << varr+1
                      << ", equation=" << eqr+1 << " (" << eq+1 << ")" << endl;
                  }
sebastien's avatar
sebastien committed
755
#ifdef CONDITION
756
757
                output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
                output << "    condition(" << eqr << ")=u(" << u << "+Per_u_);\n";
sebastien's avatar
sebastien committed
758
#endif
759
                  //}
ferhat's avatar
ferhat committed
760
761
762
763
764
              }
            for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
              {
                if (i>=ModelBlock->Block_List[j].Nb_Recursives)
                  output << "  " << Uf[ModelBlock->Block_List[j].Equation[i]].str() << ";\n";
sebastien's avatar
sebastien committed
765
#ifdef CONDITION
ferhat's avatar
ferhat committed
766
767
                output << "  if (fabs(condition(" << i+1 << "))<fabs(u(" << i << "+Per_u_)))\n";
                output << "    condition(" << i+1 << ")=u(" << i+1 << "+Per_u_);\n";
sebastien's avatar
sebastien committed
768
#endif
ferhat's avatar
ferhat committed
769
              }
sebastien's avatar
sebastien committed
770
#ifdef CONDITION
ferhat's avatar
ferhat committed
771
772
773
774
775
776
777
778
779
780
781
782
783
784
            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";
sebastien's avatar
sebastien committed
785
786
#endif

ferhat's avatar
ferhat committed
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
821
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
            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(symbol_table.getID(eEndogenous, 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 << ", "
                        << varr+1+(m+max_endo_lag-ModelBlock->Block_List[j].Max_Lag)*symbol_table.endo_nbr() << ") = ";
                        writeDerivative(output, eq, symbol_table.getID(eEndogenous, var), k, oMatlabDynamicModelSparse, temporary_terms);
                        output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                        << "(" << k << ") " << var+1
                        << ", equation=" << eq+1 << endl;
                      }
                  }
              }
            output << "      varargout{1}=g1_x;\n";
            output << "      varargout{2}=g1_o;\n";
            output << "    end;\n";
            //output << "    ya = y;\n";
            output << "  end;\n";
            break;
          default:
            break;
          }
        output.close();
      }
  }
sebastien's avatar
sebastien committed
854
855

void
sebastien's avatar
sebastien committed
856
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
857
  {
ferhat's avatar
ferhat committed
858
859
860
861
862
863
864
865
866
867
868
    struct Uff_l
      {
        int u, var, lag;
        Uff_l *pNext;
      };

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

869
    int i,j,k,v;
ferhat's avatar
ferhat committed
870
871
872
873
874
875
876
    string tmp_s;
    ostringstream tmp_output;
    ofstream code_file;
    NodeID lhs=NULL, rhs=NULL;
    BinaryOpNode *eq_node;
    Uff Uf[symbol_table.endo_nbr()];
    map<NodeID, int> reference_count;
877
    vector<int> feedback_variables;
ferhat's avatar
ferhat committed
878
879
880
881
882
883
884
885
886
887
    bool file_open=false;
    string main_name=file_name;
    main_name+=".cod";
    code_file.open(main_name.c_str(), ios::out | ios::binary | ios::ate );
    if (!code_file.is_open())
      {
        cout << "Error : Can't open file \"" << main_name << "\" for writing\n";
        exit(EXIT_FAILURE);
      }
    //Temporary variables declaration
888
    /*code_file.write(&FDIMT, sizeof(FDIMT));
ferhat's avatar
ferhat committed
889
    k=temporary_terms.size();
890
891
892
    code_file.write(reinterpret_cast<char *>(&k),sizeof(k));*/
    FDIMT_ fdimt(temporary_terms.size());
    fdimt.write(code_file);
893
894

    for (j = 0; j < ModelBlock->Size ;j++)
ferhat's avatar
ferhat committed
895
      {
896
897
        feedback_variables.clear();
        if (j>0)
ferhat's avatar
ferhat committed
898
          {
899
900
901
            FENDBLOCK_ fendblock;
            fendblock.write(code_file);
            //code_file.write(&FENDBLOCK, sizeof(FENDBLOCK));
ferhat's avatar
ferhat committed
902
          }
903
904
        int count_u;
        int u_count_int=0;
ferhat's avatar
ferhat committed
905
906
907
        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)
          {
908
909
910
            //cout << "ModelBlock->Block_List[j].Nb_Recursives = " << ModelBlock->Block_List[j].Nb_Recursives << "\n";
            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);
911
            //cout << "u_count_int=" << u_count_int << "\n";
912
913
914


            /*code_file.write(reinterpret_cast<char *>(&ModelBlock->Block_List[j].is_linear),sizeof(ModelBlock->Block_List[j].is_linear));
915
            //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;
ferhat's avatar
ferhat committed
916
917
918
919
920
921
            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));
922

ferhat's avatar
ferhat committed
923
            v=u_count_int;
924
            code_file.write(reinterpret_cast<char *>(&v),sizeof(v));*/
ferhat's avatar
ferhat committed
925
926
            file_open=true;
          }
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
        FBEGINBLOCK_ fbeginblock(ModelBlock->Block_List[j].Size - ModelBlock->Block_List[j].Nb_Recursives,
                                 ModelBlock->Block_List[j].Simulation_Type,
                                 ModelBlock->Block_List[j].Variable,
                                 ModelBlock->Block_List[j].Equation,
                                 ModelBlock->Block_List[j].Own_Derivative,
                                 ModelBlock->Block_List[j].is_linear,
                                 symbol_table.endo_nbr(),
                                 ModelBlock->Block_List[j].Max_Lag,
                                 ModelBlock->Block_List[j].Max_Lead,
                                 u_count_int
                                 );
        fbeginblock.write(code_file);
        /*code_file.write(&FBEGINBLOCK, sizeof(FBEGINBLOCK));
        v=ModelBlock->Block_List[j].Size - ModelBlock->Block_List[j].Nb_Recursives;
        //cout << "v (Size) = " << v  << "\n";
        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 (i=ModelBlock->Block_List[j].Nb_Recursives; 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]));
          }*/

ferhat's avatar
ferhat committed
953
954
955
956
957
            // The equations
            for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
              {
                //The Temporary terms
                temporary_terms_type tt2;
958
                tt2.clear();
sebastien's avatar
sebastien committed
959
#ifdef DEBUGC
ferhat's avatar
ferhat committed
960
                k=0;
sebastien's avatar
sebastien committed
961
#endif
ferhat's avatar
ferhat committed
962
963
964
                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++)
                  {
965
                    (*it)->compile(code_file, false, tt2, map_idx, true, false);
966
967
968
969
970

                    FSTPT_ fstpt((int)(map_idx.find((*it)->idx)->second));
                    fstpt.write(code_file);

                    /*code_file.write(&FSTPT, sizeof(FSTPT));
ferhat's avatar
ferhat committed
971
972
                    map_idx_type::const_iterator ii=map_idx.find((*it)->idx);
                    v=(int)ii->second;
973
974
                    code_file.write(reinterpret_cast<char *>(&v), sizeof(v));*/

ferhat's avatar
ferhat committed
975
976
                    // Insert current node into tt2
                    tt2.insert(*it);
sebastien's avatar
sebastien committed
977
#ifdef DEBUGC
ferhat's avatar
ferhat committed
978
979
980
981
                    cout << "FSTPT " << v << "\n";
                    code_file.write(&FOK, sizeof(FOK));
                    code_file.write(reinterpret_cast<char *>(&k), sizeof(k));
                    ki++;
sebastien's avatar
sebastien committed
982
983
#endif

ferhat's avatar
ferhat committed
984
                  }
sebastien's avatar
sebastien committed
985
#ifdef DEBUGC
ferhat's avatar
ferhat committed
986
987
988
989
990
991
                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";
                  }
sebastien's avatar
sebastien committed
992
#endif
ferhat's avatar
ferhat committed
993
994
                switch (ModelBlock->Block_List[j].Simulation_Type)
                  {
995
evaluation:
ferhat's avatar
ferhat committed
996
997
998
999
                  case EVALUATE_BACKWARD:
                  case EVALUATE_FORWARD:
                    if (ModelBlock->Block_List[j].Equation_Type[i] == E_EVALUATE)
                      {
1000
1001
1002
                        eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
                        lhs = eq_node->get_arg1();
                        rhs = eq_node->get_arg2();
1003
1004
                        rhs->compile(code_file, false, temporary_terms, map_idx, true, false);
                        lhs->compile(code_file, true, temporary_terms, map_idx, true, false);
ferhat's avatar
ferhat committed
1005
1006
1007
1008
1009
1010
                      }
                    else if (ModelBlock->Block_List[j].Equation_Type[i] == E_EVALUATE_S)
                      {
                        eq_node = (BinaryOpNode*)ModelBlock->Block_List[j].Equation_Normalized[i];
                        lhs = eq_node->get_arg1();
                        rhs = eq_node->get_arg2();
1011
1012
                        rhs->compile(code_file, false, temporary_terms, map_idx, true, false);
                        lhs->compile(code_file, true, temporary_terms, map_idx, true, false);
ferhat's avatar
ferhat committed
1013
1014
1015
1016
1017
1018
                      }
                    break;
                  case SOLVE_BACKWARD_COMPLETE:
                  case SOLVE_FORWARD_COMPLETE:
                  case SOLVE_TWO_BOUNDARIES_COMPLETE:
                  case SOLVE_TWO_BOUNDARIES_SIMPLE:
1019
1020
1021
                    if (i<ModelBlock->Block_List[j].Nb_Recursives)
                      goto evaluation;
                    feedback_variables.push_back(ModelBlock->Block_List[j].Variable[i]);
ferhat's avatar
ferhat committed
1022
1023
1024
1025
1026
                    v=ModelBlock->Block_List[j].Equation[i];
                    Uf[v].Ufl=NULL;
                    goto end;
                  default:
end:
1027
1028
1029
                    eq_node = equations[ModelBlock->Block_List[j].Equation[i]];
                    lhs = eq_node->get_arg1();
                    rhs = eq_node->get_arg2();
1030
1031
                    lhs->compile(code_file, false, temporary_terms, map_idx, true, false);
                    rhs->compile(code_file, false, temporary_terms, map_idx, true, false);
1032
1033
1034
1035

                    FBINARY_ fbinary(oMinus);
                    fbinary.write(code_file);
                    /*code_file.write(&FBINARY, sizeof(FBINARY));
ferhat's avatar
ferhat committed
1036
                    int v=oMinus;
1037
1038
1039
1040
                    code_file.write(reinterpret_cast<char *>(&v),sizeof(v));*/
                    FSTPR_ fstpr(i - ModelBlock->Block_List[j].Nb_Recursives);
                    fstpr.write(code_file);
                    /*code_file.write(&FSTPR, sizeof(FSTPR));
1041
                    v = i - ModelBlock->Block_List[j].Nb_Recursives;
1042
                    code_file.write(reinterpret_cast<char *>(&v), sizeof(v));*/
ferhat's avatar
ferhat committed
1043
1044
                  }
              }
1045
1046
1047
            FENDEQU_ fendequ;
            fendequ.write(code_file);
            //code_file.write(&FENDEQU, sizeof(FENDEQU));
ferhat's avatar
ferhat committed
1048
1049
            // The Jacobian if we have to solve the block
            if (ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_BACKWARD
1050
                && ModelBlock->Block_List[j].Simulation_Type!=EVALUATE_FORWARD)
ferhat's avatar
ferhat committed
1051
1052
1053
1054
1055
1056
              {
                switch (ModelBlock->Block_List[j].Simulation_Type)
                  {
                  case SOLVE_BACKWARD_SIMPLE:
                  case SOLVE_FORWARD_SIMPLE:
                    compileDerivative(code_file, ModelBlock->Block_List[j].Equation[0], ModelBlock->Block_List[j].Variable[0], 0, map_idx);
1057
1058
1059
1060
1061
                      {
                        FSTPG_ fstpg(0);
                        fstpg.write(code_file);
                      }
                    /*code_file.write(&FSTPG, sizeof(FSTPG));
ferhat's avatar
ferhat committed
1062
                    v=0;
1063
                    code_file.write(reinterpret_cast<char *>(&v), sizeof(v));*/
ferhat's avatar
ferhat committed
1064
                    break;
1065

ferhat's avatar
ferhat committed
1066
1067
                  case SOLVE_BACKWARD_COMPLETE:
                  case SOLVE_FORWARD_COMPLETE:
1068
1069
                  case SOLVE_TWO_BOUNDARIES_COMPLETE:
                  case SOLVE_TWO_BOUNDARIES_SIMPLE:
1070
1071
1072
1073
                    //count_u=ModelBlock->Block_List[j].Size - ModelBlock->Block_List[j].Nb_Recursives;
                    count_u = feedback_variables.size();
                    for(i=0; i<(int)ModelBlock->Block_List[j].Chain_Rule_Derivatives->size();i++)
                      {
1074
1075
1076
1077
1078
1079
1080
1081
                        pair< pair<int, pair<int, int> >, pair<int, int> > it = ModelBlock->Block_List[j].Chain_Rule_Derivatives->at(i);
                        k=it.first.first;
                        int eq=it.first.second.first;
                        int var=it.first.second.second;
                        int eqr=it.second.first;
                        int varr=it.second.second;
                        //cout << "k=" << k << " eq=" << eq << " (" << eq-ModelBlock->Block_List[j].Nb_Recursives << ") var=" << var << " (" << var-ModelBlock->Block_List[j].Nb_Recursives << ") eqr=" << eqr << " varr=" << varr << " count_u=" << count_u << "\n";
                        int v=ModelBlock->Block_List[j].Equation[eq];
1082
                        /*m = ModelBlock->Block_List[j].Max_Lag + k;
1083
1084
                        int u=ModelBlock->Block_List[j].IM_lead_lag[m].u[i];*/
                        if(eq>=ModelBlock->Block_List[j].Nb_Recursives and var>=ModelBlock->Block_List[j].Nb_Recursives)
1085
1086
                          {
                            if (!Uf[v].Ufl)
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
                              {
                                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;
1097
1098
1099
1100
                            Uf[v].Ufl->u=count_u;
                            Uf[v].Ufl->var=varr;
                            Uf[v].Ufl->lag=k;
                            compileChainRuleDerivative(code_file, eqr, varr, k, map_idx);
1101
1102
1103
1104
1105
1106

                            FSTPU_ fstpu(count_u);
                            fstpu.write(code_file);

                            /*code_file.write(&FSTPU, sizeof(FSTPU));
                            code_file.write(reinterpret_cast<char *>(&count_u), sizeof(count_u));*/
1107
1108
1109
                            count_u++;
												  }
											}
ferhat's avatar
ferhat committed
1110
1111
                    for (i = 0;i < ModelBlock->Block_List[j].Size;i++)
                      {
1112
1113
                        if(i>=ModelBlock->Block_List[j].Nb_Recursives)
                          {
1114
1115
1116
                            FLDR_ fldr(i-ModelBlock->Block_List[j].Nb_Recursives);
                            fldr.write(code_file);
                            /*code_file.write(&FLDR, sizeof(FLDR));
1117
                            v = i-ModelBlock->Block_List[j].Nb_Recursives;
1118
1119
1120
1121
1122
1123
                            code_file.write(reinterpret_cast<char *>(&v), sizeof(v));*/

                            FLDZ_ fldz;
                            fldz.write(code_file);
                            //code_file.write(&FLDZ, sizeof(FLDZ));

1124
                            v=ModelBlock->Block_List[j].Equation[i];
1125
1126
                            for (Uf[v].Ufl=Uf[v].Ufl_First; Uf[v].Ufl; Uf[v].Ufl=Uf[v].Ufl->pNext)
                              {
1127
1128
1129
1130
1131
1132
1133
1134
                                FLDU_ fldu(Uf[v].Ufl->u);
                                fldu.write(code_file);
                                /*code_file.write(&FLDU, sizeof(FLDU));
                                code_file.write(reinterpret_cast<char *>(&Uf[v].Ufl->u), sizeof(Uf[v].Ufl->u));*/
                                FLDV_ fldv(eEndogenous, Uf[v].Ufl->var, Uf[v].Ufl->lag);
                                fldv.write(code_file);

                                /*code_file.write(&FLDV, sizeof(FLDV));
1135
1136
1137
1138
1139
                                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;
1140
1141
1142
1143
                                code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));*/
                                FBINARY_ fbinary(oTimes);
                                fbinary.write(code_file);
                                /*code_file.write(&FBINARY, sizeof(FBINARY));
1144
                                v1=oTimes;
1145
1146
1147
1148
1149
                                code_file.write(reinterpret_cast<char *>(&v1), sizeof(v1));*/

                                FCUML_ fcuml;
                                fcuml.write(code_file);
                                //code_file.write(&FCUML, sizeof(FCUML));
1150
                              }
ferhat's avatar
ferhat committed
1151
                            Uf[v].Ufl=Uf[v].Ufl_First;
1152
1153
1154
1155
1156
1157
                            while (Uf[v].Ufl)
                              {
                                Uf[v].Ufl_First=Uf[v].Ufl->pNext;
                                free(Uf[v].Ufl);
                                Uf[v].Ufl=Uf[v].Ufl_First;
                              }
1158
1159
1160
                            FBINARY_ fbinary(oMinus);
                            fbinary.write(code_file);
                            /*code_file.write(&FBINARY, sizeof(FBINARY));
1161
                            v=oMinus;
1162
1163
1164
1165
1166
                            code_file.write(reinterpret_cast<char *>(&v), sizeof(v));*/

                            FSTPU_ fstpu(i - ModelBlock->Block_List[j].Nb_Recursives);
                            fstpu.write(code_file);
                            /*code_file.write(&FSTPU, sizeof(FSTPU));
1167
                            v = i - ModelBlock->Block_List[j].Nb_Recursives;
1168
                            code_file.write(reinterpret_cast<char *>(&v), sizeof(v));*/
ferhat's avatar
ferhat committed
1169
1170
1171
1172
1173
1174
1175
1176
                          }
                      }
                    break;
                  default:
                    break;
                  }
              }
      }
1177
1178
1179
1180
1181
1182
    FENDBLOCK_ fendblock;
    fendblock.write(code_file);
    //code_file.write(&FENDBLOCK, sizeof(FENDBLOCK));
    FEND_ fend;
    fend.write(code_file);
    //code_file.write(&FEND, sizeof(FEND));
ferhat's avatar
ferhat committed
1183
1184
    code_file.close();
  }
sebastien's avatar
sebastien committed
1185
1186
1187

void
DynamicModel::writeDynamicMFile(const string &dynamic_basename) const
ferhat's avatar
ferhat committed
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
  {
    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;

1205
1206
1207
    if (containsSteadyStateOperator())
      mDynamicModelFile << "global oo_;" << endl << endl;

1208
    writeDynamicModel(mDynamicModelFile, false);
ferhat's avatar
ferhat committed
1209
1210
1211

    mDynamicModelFile.close();
  }
sebastien's avatar
sebastien committed
1212
1213
1214

void
DynamicModel::writeDynamicCFile(const string &dynamic_basename) const
ferhat's avatar
ferhat committed
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
  {
    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
1236
    writeDynamicModel(mDynamicModelFile, true);
ferhat's avatar
ferhat committed
1237
1238
1239
1240
1241
1242

    // 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
1243
    << "  double *residual, *g1, *v2, *v3;" << endl
ferhat's avatar
ferhat committed
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
    << "  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

    << "     plhs[1] = mxCreateDoubleMatrix(" << equations.size() << ", " << dynJacobianColsNbr << ", mxREAL);" << endl
    << "     /* Create a C pointer to a copy of the output matrix g1. */" << endl
    << "     g1 = mxGetPr(plhs[1]);" << endl
    << "  }" << endl
    <