DynamicModel.cc 123 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>
26
#include <algorithm>
sebastien's avatar
sebastien committed
27
28
29
30
31
32
33
34
35
36
37
38
39
#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
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),
46
    global_temporary_terms(true),
ferhat's avatar
ferhat committed
47
    cutoff(1e-15),
48
    mfs(0)
sebastien's avatar
sebastien committed
49
50
51
{
}

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

sebastien's avatar
sebastien committed
58
void
sebastien's avatar
sebastien committed
59
DynamicModel::compileDerivative(ofstream &code_file, int eq, int symb_id, int lag, map_idx_type &map_idx) const
ferhat's avatar
ferhat committed
60
61
62
  {
    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
      {
        FLDZ_ fldz;
        fldz.write(code_file);
      }
ferhat's avatar
ferhat committed
69
  }
sebastien's avatar
sebastien committed
70

71
72
73
74
75
76

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())
77
    (it->second)->compile(code_file, false, temporary_terms, map_idx, true, false);
78
  else
79
80
81
82
    {
      FLDZ_ fldz;
      fldz.write(code_file);
    }
83
84
85
}


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

98
99
100
  unsigned int nb_blocks = getNbBlocks();
  v_temporary_terms = vector<vector<temporary_terms_type> >(nb_blocks);
  v_temporary_terms_inuse = vector<temporary_terms_inuse_type> (nb_blocks);
sebastien's avatar
sebastien committed
101
  temporary_terms.clear();
102

103
104
105
  if(!global_temporary_terms)
    {
      for (unsigned int block = 0; block < nb_blocks; block++)
sebastien's avatar
sebastien committed
106
        {
107
108
109
110
111
112
113
          reference_count.clear();
          temporary_terms.clear();
          unsigned int block_size = getBlockSize(block);
          unsigned int block_nb_mfs = getBlockMfs(block);
          unsigned int block_nb_recursives = block_size - block_nb_mfs;
          v_temporary_terms[block] = vector<temporary_terms_type>(block_size);
          for (unsigned int i = 0; i < block_size; i++)
sebastien's avatar
sebastien committed
114
            {
115
116
117
              if (i<block_nb_recursives && isBlockEquationRenormalized( block, i))
                getBlockEquationRenormalizedNodeID( block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  i);
              else
sebastien's avatar
sebastien committed
118
                {
119
120
                  eq_node = (BinaryOpNode*)getBlockEquationNodeID(block, i);
                  eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  i);
sebastien's avatar
sebastien committed
121
122
                }
            }
123
124
125
126
127
128
129
130
131
132
133
134
135
          for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
            {
              NodeID id=it->second.second;
              id->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  block_size-1);
            }
          for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++)
            it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  block_size-1);
          for (t_derivative::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
            it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  block_size-1);

          set<int> temporary_terms_in_use;
          temporary_terms_in_use.clear();
          v_temporary_terms_inuse[block] = temporary_terms_in_use;
sebastien's avatar
sebastien committed
136
137
        }
    }
138
  else
sebastien's avatar
sebastien committed
139
    {
140
      for (unsigned int block = 0; block < nb_blocks; block++)
sebastien's avatar
sebastien committed
141
        {
142
143
144
145
146
147
          // Compute the temporary terms reordered
          unsigned int block_size = getBlockSize(block);
          unsigned int block_nb_mfs = getBlockMfs(block);
          unsigned int block_nb_recursives = block_size - block_nb_mfs;
          v_temporary_terms[block] = vector<temporary_terms_type>(block_size);
          for (unsigned int i = 0; i < block_size; i++)
148
            {
149
150
151
152
153
154
155
              if (i<block_nb_recursives && isBlockEquationRenormalized( block, i))
                getBlockEquationRenormalizedNodeID( block, i)->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms,  i);
              else
                {
                  eq_node = (BinaryOpNode*)getBlockEquationNodeID(block, i);
                  eq_node->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, i);
                }
156
            }
157
          for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
sebastien's avatar
sebastien committed
158
            {
159
160
              NodeID id=it->second.second;
              id->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1);
sebastien's avatar
sebastien committed
161
            }
162
163
164
165
          for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++)
            it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1);
          for (t_derivative::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
            it->second->computeTemporaryTerms(reference_count, temporary_terms, first_occurence, block, v_temporary_terms, block_size-1);
166
        }
167
      for (unsigned int block = 0; block < nb_blocks; block++)
168
        {
169
170
171
172
173
174
          // Collect the temporary terms reordered
          unsigned int block_size = getBlockSize(block);
          unsigned int block_nb_mfs = getBlockMfs(block);
          unsigned int block_nb_recursives = block_size - block_nb_mfs;
          set<int> temporary_terms_in_use;
          for (unsigned int i = 0; i < block_size; i++)
sebastien's avatar
sebastien committed
175
            {
176
177
178
              if (i<block_nb_recursives && isBlockEquationRenormalized( block, i))
                  getBlockEquationRenormalizedNodeID( block, i)->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
              else
sebastien's avatar
sebastien committed
179
                {
180
181
                  eq_node = (BinaryOpNode*)getBlockEquationNodeID(block, i);
                  eq_node->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
sebastien's avatar
sebastien committed
182
183
                }
            }
184
185
186
187
188
189
190
191
192
193
          for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
            {
              NodeID id=it->second.second;
              id->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
            }
          for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++)
            it->second->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
          for (t_derivative::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
            it->second->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
          v_temporary_terms_inuse[block] = temporary_terms_in_use;
sebastien's avatar
sebastien committed
194
        }
195
196
197
198
199
      // Add a mapping form node ID to temporary terms order
      int j=0;
      for (temporary_terms_type::const_iterator it = temporary_terms.begin();
           it != temporary_terms.end(); it++)
        map_idx[(*it)->idx]=j++;
sebastien's avatar
sebastien committed
200
201
202
203
    }
}

void
204
DynamicModel::writeModelEquationsOrdered_M(const string &dynamic_basename) const
ferhat's avatar
ferhat committed
205
206
207
208
209
210
211
  {
    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;
212
    temporary_terms_type local_temporary_terms;
ferhat's avatar
ferhat committed
213
214
215
    ofstream  output;
    int nze, nze_exo, nze_other_endo;
    vector<int> feedback_variables;
216
217
218
219
220
221
222
223
224
225
    ExprNodeOutputType local_output_type;

    if(global_temporary_terms)
      {
        local_output_type = oMatlabDynamicModelSparse;
        local_temporary_terms = temporary_terms;
      }
    else
      local_output_type = oMatlabDynamicModelSparseLocalTemporaryTerms;

ferhat's avatar
ferhat committed
226
227
    //----------------------------------------------------------------------
    //For each block
228
    for (unsigned int block = 0; block < getNbBlocks(); block++)
ferhat's avatar
ferhat committed
229
      {
230

231
        //recursive_variables.clear();
ferhat's avatar
ferhat committed
232
233
        feedback_variables.clear();
        //For a block composed of a single equation determines wether we have to evaluate or to solve the equation
234
235
236
237
238
239
240
241
242
243
244
245
        nze = derivative_endo[block].size();
        nze_other_endo = derivative_other_endo[block].size();
        nze_exo = derivative_exo[block].size();
        BlockSimulationType simulation_type = getBlockSimulationType(block);
        unsigned int block_size = getBlockSize(block);
        unsigned int block_mfs = getBlockMfs(block);
        unsigned int block_recursive = block_size - block_mfs;
        unsigned int block_exo_size = exo_block[block].size();
        unsigned int block_exo_det_size = exo_det_block[block].size();
        unsigned int block_other_endo_size = other_endo_block[block].size();
        int block_max_lag=max_leadlag_block[block].first;
        if(global_temporary_terms)
ferhat's avatar
ferhat committed
246
          {
247
248
            local_output_type = oMatlabDynamicModelSparse;
            local_temporary_terms = temporary_terms;
ferhat's avatar
ferhat committed
249
          }
250
251
252
        else
          local_output_type = oMatlabDynamicModelSparseLocalTemporaryTerms;

ferhat's avatar
ferhat committed
253
        tmp1_output.str("");
254
        tmp1_output << dynamic_basename << "_" << block+1 << ".m";
ferhat's avatar
ferhat committed
255
256
257
258
259
260
261
        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";
262
        if (simulation_type ==EVALUATE_BACKWARD || simulation_type ==EVALUATE_FORWARD)
ferhat's avatar
ferhat committed
263
          {
264
            output << "function [y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, jacobian_eval, y_kmin, periods)\n";
ferhat's avatar
ferhat committed
265
          }
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
        else if (simulation_type ==SOLVE_FORWARD_COMPLETE || simulation_type ==SOLVE_BACKWARD_COMPLETE)
          output << "function [residual, y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, it_, jacobian_eval)\n";
        else if (simulation_type ==SOLVE_BACKWARD_SIMPLE || simulation_type ==SOLVE_FORWARD_SIMPLE)
          output << "function [residual, y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, it_, jacobian_eval)\n";
        else
          output << "function [residual, y, g1, g2, g3, b, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, periods, jacobian_eval, y_kmin, y_size)\n";
        BlockType block_type;
        if(simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE ||simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
          block_type = SIMULTAN;
        else if(simulation_type == SOLVE_FORWARD_COMPLETE ||simulation_type == SOLVE_BACKWARD_COMPLETE)
          block_type = SIMULTANS;
        else if((simulation_type == SOLVE_FORWARD_SIMPLE ||simulation_type == SOLVE_BACKWARD_SIMPLE ||
                 simulation_type == EVALUATE_BACKWARD    || simulation_type == EVALUATE_FORWARD)
                && getBlockFirstEquation(block) < prologue)
          block_type = PROLOGUE;
        else if((simulation_type == SOLVE_FORWARD_SIMPLE ||simulation_type == SOLVE_BACKWARD_SIMPLE ||
                 simulation_type == EVALUATE_BACKWARD    || simulation_type == EVALUATE_FORWARD)
                && getBlockFirstEquation(block) >= equations.size() - epilogue)
          block_type = EPILOGUE;
ferhat's avatar
ferhat committed
285
        else
286
          block_type = SIMULTANS;
ferhat's avatar
ferhat committed
287
        output << "  % ////////////////////////////////////////////////////////////////////////" << endl
288
        << "  % //" << string("                     Block ").substr(int(log10(block + 1))) << block + 1 << " " << BlockType0(block_type)
ferhat's avatar
ferhat committed
289
290
        << "          //" << endl
        << "  % //                     Simulation type "
291
        << BlockSim(simulation_type) << "  //" << endl
ferhat's avatar
ferhat committed
292
        << "  % ////////////////////////////////////////////////////////////////////////" << endl;
293
        output << "  global options_;" << endl;
ferhat's avatar
ferhat committed
294
        //The Temporary terms
295
        if (simulation_type ==EVALUATE_BACKWARD || simulation_type ==EVALUATE_FORWARD)
ferhat's avatar
ferhat committed
296
297
          {
            output << "  if(jacobian_eval)\n";
298
299
300
301
302
303
304
            output << "    g1 = spalloc(" << block_mfs  << ", " << block_mfs*(1+getBlockMaxLag(block)+getBlockMaxLead(block)) << ", " << nze << ");\n";
            output << "    g1_x=spalloc(" << block_size << ", " << (block_exo_size + block_exo_det_size)*
                      (1+max(exo_det_max_leadlag_block[block].first, exo_max_leadlag_block[block].first)+max(exo_det_max_leadlag_block[block].second, exo_max_leadlag_block[block].second))
                   << ", " << nze_exo << ");\n";
            output << "    g1_o=spalloc(" << block_size << ", " << block_other_endo_size*
                      (1+other_endo_max_leadlag_block[block].first+other_endo_max_leadlag_block[block].second)
                   << ", " << nze_other_endo << ");\n";
ferhat's avatar
ferhat committed
305
306
307
308
309
            output << "  end;\n";
          }
        else
          {
            output << "  if(jacobian_eval)\n";
310
311
312
313
314
315
316
            output << "    g1 = spalloc(" << block_size << ", " << block_size*(1+getBlockMaxLag(block)+getBlockMaxLead(block)) << ", " << nze << ");\n";
            output << "    g1_x=spalloc(" << block_size << ", " << (block_exo_size + block_exo_det_size)*
                      (1+max(exo_det_max_leadlag_block[block].first, exo_max_leadlag_block[block].first)+max(exo_det_max_leadlag_block[block].second, exo_max_leadlag_block[block].second))
                   << ", " << nze_exo << ");\n";
            output << "    g1_o=spalloc(" << block_size << ", " << block_other_endo_size*
                      (1+other_endo_max_leadlag_block[block].first+other_endo_max_leadlag_block[block].second)
                   << ", " << nze_other_endo << ");\n";
ferhat's avatar
ferhat committed
317
            output << "  else\n";
318
            if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE)
ferhat's avatar
ferhat committed
319
              {
320
321
                output << "    g1 = spalloc(" << block_mfs << "*options_.periods, "
                << block_mfs << "*(options_.periods+" << max_leadlag_block[block].first+max_leadlag_block[block].second+1 << ")"
322
                << ", " << nze << "*options_.periods);\n";
ferhat's avatar
ferhat committed
323
324
325
              }
            else
              {
326
327
328
329
330
331
                output << "    g1 = spalloc(" << block_mfs
                << ", " << block_mfs << ", " << nze << ");\n";
                output << "    g1_tmp_r = spalloc(" << block_recursive
                << ", " << block_size << ", " << nze << ");\n";
                output << "    g1_tmp_b = spalloc(" << block_mfs
                << ", " << block_size << ", " << nze << ");\n";
ferhat's avatar
ferhat committed
332
333
334
              }
            output << "  end;\n";
          }
sebastien's avatar
sebastien committed
335

ferhat's avatar
ferhat committed
336
        output << "  g2=0;g3=0;\n";
337
        if (v_temporary_terms_inuse[block].size())
ferhat's avatar
ferhat committed
338
339
          {
            tmp_output.str("");
340
341
            for (temporary_terms_inuse_type::const_iterator it = v_temporary_terms_inuse[block].begin();
                 it != v_temporary_terms_inuse[block].end(); it++)
ferhat's avatar
ferhat committed
342
343
344
              tmp_output << " T" << *it;
            output << "  global" << tmp_output.str() << ";\n";
          }
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
        if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE)
          {
            temporary_terms_type tt2;
            tt2.clear();
            for(int i=0; i< (int) block_size; i++)
              {
                if (v_temporary_terms[block][i].size() && global_temporary_terms)
                  {
                    output << "  " << "% //Temporary variables initialization" << endl
                           << "  " << "T_zeros = zeros(y_kmin+periods, 1);" << endl;
                    for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin();
                         it != v_temporary_terms[block][i].end(); it++)
                      {
                        output << "  ";
                        (*it)->writeOutput(output, oMatlabDynamicModel, local_temporary_terms);
                        output << " = T_zeros;" << endl;
                      }
                  }
              }
          }
        if (simulation_type==SOLVE_BACKWARD_SIMPLE || simulation_type==SOLVE_FORWARD_SIMPLE || simulation_type==SOLVE_BACKWARD_COMPLETE || simulation_type==SOLVE_FORWARD_COMPLETE)
          output << "  residual=zeros(" << block_mfs << ",1);\n";
        else if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE)
          output << "  residual=zeros(" << block_mfs << ",y_kmin+periods);\n";
        if (simulation_type==EVALUATE_BACKWARD)
ferhat's avatar
ferhat committed
370
          output << "  for it_ = (y_kmin+periods):y_kmin+1\n";
371
        if (simulation_type==EVALUATE_FORWARD)
ferhat's avatar
ferhat committed
372
373
          output << "  for it_ = y_kmin+1:(y_kmin+periods)\n";

374
        if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE)
ferhat's avatar
ferhat committed
375
          {
376
377
378
379
380
            output << "  b = zeros(periods*y_size,1);" << endl
                   << "  for it_ = y_kmin+1:(periods+y_kmin)" << endl
                   << "    Per_y_=it_*y_size;" << endl
                   << "    Per_J_=(it_-y_kmin-1)*y_size;" << endl
                   << "    Per_K_=(it_-1)*y_size;" << endl;
ferhat's avatar
ferhat committed
381
382
            sps="  ";
          }
sebastien's avatar
sebastien committed
383
        else
384
          if (simulation_type==EVALUATE_BACKWARD || simulation_type==EVALUATE_FORWARD )
ferhat's avatar
ferhat committed
385
386
387
388
            sps = "  ";
          else
            sps="";
        // The equations
389
        for (unsigned int i = 0; i < block_size; i++)
ferhat's avatar
ferhat committed
390
391
392
          {
            temporary_terms_type tt2;
            tt2.clear();
393
            if (v_temporary_terms[block].size())
ferhat's avatar
ferhat committed
394
              {
395
396
397
398
399
400
401
402
403
404
405
406
                output << "  " << "% //Temporary variables" << endl;
                for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin();
                     it != v_temporary_terms[block][i].end(); it++)
                  {
                    output << "  " <<  sps;
                    (*it)->writeOutput(output, local_output_type, local_temporary_terms);
                    output << " = ";
                    (*it)->writeOutput(output, local_output_type, tt2);
                    // Insert current node into tt2
                    tt2.insert(*it);
                    output << ";" << endl;
                  }
ferhat's avatar
ferhat committed
407
              }
408
409
410
411
412
413

            int variable_ID = getBlockVariableID(block, i);
            int equation_ID = getBlockEquationID(block, i);
            EquationType equ_type = getBlockEquationType(block, i);
            string sModel = symbol_table.getName(symbol_table.getID(eEndogenous, variable_ID)) ;
            eq_node = (BinaryOpNode*)getBlockEquationNodeID(block,i);
ferhat's avatar
ferhat committed
414
415
416
            lhs = eq_node->get_arg1();
            rhs = eq_node->get_arg2();
            tmp_output.str("");
417
418
						lhs->writeOutput(tmp_output, local_output_type, local_temporary_terms);
            switch (simulation_type)
ferhat's avatar
ferhat committed
419
420
421
              {
              case EVALUATE_BACKWARD:
              case EVALUATE_FORWARD:
422
423
424
evaluation:     if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE)
                  output << "    % equation " << getBlockEquationID(block, i)+1 << " variable : " << sModel
                  << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl;
ferhat's avatar
ferhat committed
425
                output << "    ";
426
                if (equ_type == E_EVALUATE)
ferhat's avatar
ferhat committed
427
428
429
                  {
                    output << tmp_output.str();
                    output << " = ";
430
                    rhs->writeOutput(output, local_output_type, local_temporary_terms);
ferhat's avatar
ferhat committed
431
                  }
432
                else if (equ_type == E_EVALUATE_S)
ferhat's avatar
ferhat committed
433
434
435
                  {
                    output << "%" << tmp_output.str();
                    output << " = ";
436
                    if (isBlockEquationRenormalized(block, i))
ferhat's avatar
ferhat committed
437
                      {
438
                        rhs->writeOutput(output, local_output_type, local_temporary_terms);
ferhat's avatar
ferhat committed
439
                        output << "\n    ";
440
                        tmp_output.str("");
441
                        eq_node = (BinaryOpNode *)getBlockEquationRenormalizedNodeID(block, i);
442
443
                        lhs = eq_node->get_arg1();
                        rhs = eq_node->get_arg2();
444
                        lhs->writeOutput(output, local_output_type, local_temporary_terms);
445
                        output << " = ";
446
                        rhs->writeOutput(output, local_output_type, local_temporary_terms);
ferhat's avatar
ferhat committed
447
448
449
450
                      }
                  }
                else
                  {
451
                    cerr << "Type missmatch for equation " << equation_ID+1  << "\n";
ferhat's avatar
ferhat committed
452
453
454
455
456
457
458
459
                    exit(EXIT_FAILURE);
                  }
                output << ";\n";
                break;
              case SOLVE_BACKWARD_SIMPLE:
              case SOLVE_FORWARD_SIMPLE:
              case SOLVE_BACKWARD_COMPLETE:
              case SOLVE_FORWARD_COMPLETE:
460
461
462
463
464
465
                if (i<block_recursive)
                  goto evaluation;
                feedback_variables.push_back(variable_ID);
                output << "  % equation " << equation_ID+1 << " variable : " << sModel
                << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl;
                output << "  " << "residual(" << i+1-block_recursive << ") = (";
ferhat's avatar
ferhat committed
466
467
468
                goto end;
              case SOLVE_TWO_BOUNDARIES_COMPLETE:
              case SOLVE_TWO_BOUNDARIES_SIMPLE:
469
470
471
472
473
474
475
                if (i<block_recursive)
                  goto evaluation;
                feedback_variables.push_back(variable_ID);
                output << "    % equation " << equation_ID+1 << " variable : " << sModel
                << " (" << variable_ID+1 << ") " << c_Equation_Type(equ_type) << endl;
                Uf[equation_ID] << "    b(" << i+1-block_recursive << "+Per_J_) = -residual(" << i+1-block_recursive << ", it_)";
                output << "    residual(" << i+1-block_recursive << ", it_) = (";
ferhat's avatar
ferhat committed
476
477
478
479
480
                goto end;
              default:
end:
                output << tmp_output.str();
                output << ") - (";
481
                rhs->writeOutput(output, local_output_type, local_temporary_terms);
ferhat's avatar
ferhat committed
482
                output << ");\n";
sebastien's avatar
sebastien committed
483
#ifdef CONDITION
484
                if (simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE)
ferhat's avatar
ferhat committed
485
                  output << "  condition(" << i+1 << ")=0;\n";
sebastien's avatar
sebastien committed
486
#endif
ferhat's avatar
ferhat committed
487
488
489
              }
          }
        // The Jacobian if we have to solve the block
490
        if (simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE)
ferhat's avatar
ferhat committed
491
          output << "  " << sps << "% Jacobian  " << endl;
sebastien's avatar
sebastien committed
492
        else
493
494
          if (simulation_type==SOLVE_BACKWARD_SIMPLE   || simulation_type==SOLVE_FORWARD_SIMPLE ||
              simulation_type==SOLVE_BACKWARD_COMPLETE || simulation_type==SOLVE_FORWARD_COMPLETE)
ferhat's avatar
ferhat committed
495
496
497
            output << "  % Jacobian  " << endl << "  if jacobian_eval" << endl;
          else
            output << "    % Jacobian  " << endl << "    if jacobian_eval" << endl;
498
        switch (simulation_type)
ferhat's avatar
ferhat committed
499
500
501
          {
          case EVALUATE_BACKWARD:
          case EVALUATE_FORWARD:
502
            for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++)
ferhat's avatar
ferhat committed
503
              {
504
505
506
507
508
509
510
511
512
513
514
515
                int lag = it->first.first;
                int eq = it->first.second.first;
                int var = it->first.second.second;
                int eqr = getBlockInitialEquationID(block, eq);
                int varr = getBlockInitialVariableID(block, var);

                NodeID id = it->second;

                output << "      g1(" << eqr+1 << ", " << varr+1+(lag+block_max_lag)*block_size << ") = ";
                id->writeOutput(output, local_output_type, local_temporary_terms);
                output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                    << "(" << lag
ferhat's avatar
ferhat committed
516
517
518
                    << ") " << var+1
                    << ", equation=" << eq+1 << endl;
              }
519
            for (t_derivative::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
ferhat's avatar
ferhat committed
520
              {
521
522
523
524
525
526
527
528
529
530
531
532
                int lag = it->first.first;
                int eq = it->first.second.first;
                int var = it->first.second.second;
                int eqr = getBlockInitialEquationID(block, eq);
                NodeID id = it->second;

                output << "      g1_o(" << eqr+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
                id->writeOutput(output, local_output_type, local_temporary_terms);
                output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                    << "(" << lag
                    << ") " << var+1
                    << ", equation=" << eq+1 << endl;
ferhat's avatar
ferhat committed
533
534
535
536
537
538
539
540
541
542
              }
            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:
543
            for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++)
ferhat's avatar
ferhat committed
544
              {
545
546
547
548
549
550
551
552
553
554
555
                int lag = it->first.first;
                unsigned int eq = it->first.second.first;
                unsigned int var = it->first.second.second;
                NodeID id = it->second;

                output << "    g1(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
                id->writeOutput(output, local_output_type, local_temporary_terms);
                output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                    << "(" << lag
                    << ") " << var+1
                    << ", equation=" << eq+1 << endl;
ferhat's avatar
ferhat committed
556
              }
557
558

            for (t_derivative::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
ferhat's avatar
ferhat committed
559
              {
560
561
562
563
564
565
566
567
568
569
570
                int lag = it->first.first;
                unsigned int eq = it->first.second.first;
                unsigned int var = it->first.second.second;
                NodeID id = it->second;

                output << "    g1_o(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
                id->writeOutput(output, local_output_type, local_temporary_terms);
                output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                    << "(" << lag
                    << ") " << var+1
                    << ", equation=" << eq+1 << endl;
ferhat's avatar
ferhat committed
571
572
573
574
              }
            output << "    varargout{1}=g1_x;\n";
            output << "    varargout{2}=g1_o;\n";
            output << "  else" << endl;
575
            for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
ferhat's avatar
ferhat committed
576
              {
577
578
579
580
581
582
583
584
585
586
587
588
                unsigned int eq = it->first.first;
                unsigned int var = it->first.second;
                unsigned int eqr = getBlockEquationID(block, eq);
                unsigned int varr = getBlockVariableID(block, var);
                NodeID id = it->second.second;
                int lag = it->second.first;
                output << "    g1(" << eq+1 << ", " << var+1-block_recursive << ") = ";
                id->writeOutput(output, local_output_type, local_temporary_terms);
                output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr))
                    << "(" << lag
                    << ") " << varr+1
                    << ", equation=" << eqr+1 << endl;
589
              }
ferhat's avatar
ferhat committed
590
591
592
593
594
            output << "  end;\n";
            break;
          case SOLVE_TWO_BOUNDARIES_SIMPLE:
          case SOLVE_TWO_BOUNDARIES_COMPLETE:
            output << "    if ~jacobian_eval" << endl;
595
            for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
ferhat's avatar
ferhat committed
596
              {
597
598
599
600
                unsigned int eq = it->first.first;
                unsigned int var = it->first.second;
                unsigned int eqr = getBlockEquationID(block, eq);
                unsigned int varr = getBlockVariableID(block, var);
601
                ostringstream tmp_output;
602
603
604
                NodeID id = it->second.second;
                int lag = it->second.first;
                if(eq>=block_recursive and var>=block_recursive)
ferhat's avatar
ferhat committed
605
                  {
606
607
608
                    if (lag==0)
                      Uf[eqr] << "+g1(" << eq+1-block_recursive
                        << "+Per_J_, " << var+1-block_recursive
609
                        << "+Per_K_)*y(it_, " << varr+1 << ")";
610
611
612
                    else if (lag==1)
                      Uf[eqr] << "+g1(" << eq+1-block_recursive
                        << "+Per_J_, " << var+1-block_recursive
613
                        << "+Per_y_)*y(it_+1, " << varr+1 << ")";
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
                    else if (lag>0)
                      Uf[eqr] << "+g1(" << eq+1-block_recursive
                        << "+Per_J_, " << var+1-block_recursive
                        << "+y_size*(it_+" << lag-1 << "))*y(it_+" << lag << ", " << varr+1 << ")";
                    else if (lag<0)
                      Uf[eqr] << "+g1(" << eq+1-block_recursive
                        << "+Per_J_, " << var+1-block_recursive
                        << "+y_size*(it_" << lag-1 << "))*y(it_" << lag << ", " << varr+1 << ")";
                    if (lag==0)
                      tmp_output << "     g1(" << eq+1-block_recursive << "+Per_J_, "
                        << var+1-block_recursive << "+Per_K_) = ";
                    else if (lag==1)
                      tmp_output << "     g1(" << eq+1-block_recursive << "+Per_J_, "
                        << var+1-block_recursive << "+Per_y_) = ";
                    else if (lag>0)
                      tmp_output << "     g1(" << eq+1-block_recursive << "+Per_J_, "
                        << var+1-block_recursive << "+y_size*(it_+" << lag-1 << ")) = ";
                    else if (lag<0)
                      tmp_output << "     g1(" << eq+1-block_recursive << "+Per_J_, "
                        << var+1-block_recursive << "+y_size*(it_" << lag-1 << ")) = ";
634
                    output << " " << tmp_output.str();
635
                    id->writeOutput(output, local_output_type, local_temporary_terms);
636
637
                    output << ";";
                    output << " %2 variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, varr))
638
                      << "(" << lag << ") " << varr+1
639
640
                      << ", equation=" << eqr+1 << " (" << eq+1 << ")" << endl;
                  }
641

sebastien's avatar
sebastien committed
642
#ifdef CONDITION
643
644
                output << "  if (fabs(condition[" << eqr << "])<fabs(u[" << u << "+Per_u_]))\n";
                output << "    condition(" << eqr << ")=u(" << u << "+Per_u_);\n";
sebastien's avatar
sebastien committed
645
#endif
ferhat's avatar
ferhat committed
646
              }
647
            for (unsigned int i = 0; i < block_size; i++)
ferhat's avatar
ferhat committed
648
              {
649
650
                if (i>=block_recursive)
                  output << "  " << Uf[getBlockEquationID(block, i)].str() << ";\n";
sebastien's avatar
sebastien committed
651
#ifdef CONDITION
ferhat's avatar
ferhat committed
652
653
                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
654
#endif
ferhat's avatar
ferhat committed
655
              }
sebastien's avatar
sebastien committed
656
#ifdef CONDITION
657
            for (m=0;m<=ModelBlock->Block_List[block].Max_Lead+ModelBlock->Block_List[block].Max_Lag;m++)
ferhat's avatar
ferhat committed
658
              {
659
660
                k=m-ModelBlock->Block_List[block].Max_Lag;
                for (i=0;i<ModelBlock->Block_List[block].IM_lead_lag[m].size;i++)
ferhat's avatar
ferhat committed
661
                  {
662
663
664
665
                    unsigned int eq=ModelBlock->Block_List[block].IM_lead_lag[m].Equ_Index[i];
                    unsigned int var=ModelBlock->Block_List[block].IM_lead_lag[m].Var_Index[i];
                    unsigned int u=ModelBlock->Block_List[block].IM_lead_lag[m].u[i];
                    unsigned int eqr=ModelBlock->Block_List[block].IM_lead_lag[m].Equ[i];
ferhat's avatar
ferhat committed
666
667
668
                    output << "  u(" << u+1 << "+Per_u_) = u(" << u+1 << "+Per_u_) / condition(" << eqr+1 << ");\n";
                  }
              }
669
            for (i = 0;i < ModelBlock->Block_List[block].Size;i++)
ferhat's avatar
ferhat committed
670
              output << "  u(" << i+1 << "+Per_u_) = u(" << i+1 << "+Per_u_) / condition(" << i+1 << ");\n";
sebastien's avatar
sebastien committed
671
672
#endif

ferhat's avatar
ferhat committed
673
            output << "    else" << endl;
674
675

            for (t_derivative::const_iterator it = derivative_endo[block].begin(); it != derivative_endo[block].end(); it++)
ferhat's avatar
ferhat committed
676
              {
677
678
679
680
681
682
683
684
685
                int lag = it->first.first;
                unsigned int eq = it->first.second.first;
                unsigned int var = it->first.second.second;
                NodeID id = it->second;
                output << "      g1(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
                id->writeOutput(output, local_output_type, local_temporary_terms);
                output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                    << "(" << lag
                    << ") " << var+1
ferhat's avatar
ferhat committed
686
687
                    << ", equation=" << eq+1 << endl;
              }
688
            for (t_derivative::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
ferhat's avatar
ferhat committed
689
              {
690
691
692
693
694
695
696
697
698
699
700
                int lag = it->first.first;
                unsigned int eq = it->first.second.first;
                unsigned int var = it->first.second.second;
                NodeID id = it->second;

                output << "      g1_o(" << eq+1 << ", " << var+1+(lag+block_max_lag)*block_size << ") = ";
                id->writeOutput(output, local_output_type, local_temporary_terms);
                output << "; % variable=" << symbol_table.getName(symbol_table.getID(eEndogenous, var))
                    << "(" << lag
                    << ") " << var+1
                    << ", equation=" << eq+1 << endl;
ferhat's avatar
ferhat committed
701
702
703
704
705
706
707
708
709
710
711
712
              }
            output << "      varargout{1}=g1_x;\n";
            output << "      varargout{2}=g1_o;\n";
            output << "    end;\n";
            output << "  end;\n";
            break;
          default:
            break;
          }
        output.close();
      }
  }
sebastien's avatar
sebastien committed
713
714

void
715
DynamicModel::writeModelEquationsCodeOrdered(const string file_name, const string bin_basename, map_idx_type map_idx) const
sebastien's avatar
sebastien committed
716
  {
ferhat's avatar
ferhat committed
717
718
719
720
721
722
723
724
725
726
727
    struct Uff_l
      {
        int u, var, lag;
        Uff_l *pNext;
      };

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

728
    int i,v;
ferhat's avatar
ferhat committed
729
730
731
732
733
734
735
    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;
736
    vector<int> feedback_variables;
ferhat's avatar
ferhat committed
737
    bool file_open=false;
738

ferhat's avatar
ferhat committed
739
740
741
742
743
744
745
746
747
    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
748

749
750
    FDIMT_ fdimt(temporary_terms.size());
    fdimt.write(code_file);
751

752
    for (unsigned int block = 0; block < getNbBlocks(); block++)
ferhat's avatar
ferhat committed
753
      {
754
        feedback_variables.clear();
755
        if (block>0)
ferhat's avatar
ferhat committed
756
          {
757
758
            FENDBLOCK_ fendblock;
            fendblock.write(code_file);
ferhat's avatar
ferhat committed
759
          }
760
761
        int count_u;
        int u_count_int=0;
762
763
764
765
766
767
768
769
        BlockSimulationType simulation_type = getBlockSimulationType(block);
        unsigned int block_size = getBlockSize(block);
        unsigned int block_mfs = getBlockMfs(block);
        unsigned int block_recursive = block_size - block_mfs;
        int block_max_lag=max_leadlag_block[block].first;

        if (simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE ||
            simulation_type==SOLVE_BACKWARD_COMPLETE || simulation_type==SOLVE_FORWARD_COMPLETE)
ferhat's avatar
ferhat committed
770
          {
771
772
            Write_Inf_To_Bin_File(file_name, bin_basename, block, u_count_int,file_open,
                                  simulation_type==SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type==SOLVE_TWO_BOUNDARIES_SIMPLE);
ferhat's avatar
ferhat committed
773
774
            file_open=true;
          }
775
776
777
778
779
780
781
        FBEGINBLOCK_ fbeginblock(block_mfs,
                                 simulation_type,
                                 getBlockFirstEquation(block),
                                 block_size,
                                 variable_reordered,
                                 equation_reordered,
                                 blocks_linear[block],
782
                                 symbol_table.endo_nbr(),
783
784
                                 block_max_lag,
                                 block_max_lag,
785
786
787
788
                                 u_count_int
                                 );
        fbeginblock.write(code_file);

789
790
791
792
793
794
795
        // The equations
        for (i = 0;i < (int) block_size;i++)
          {
            //The Temporary terms
            temporary_terms_type tt2;
            tt2.clear();
            if (v_temporary_terms[block][i].size())
ferhat's avatar
ferhat committed
796
              {
797
798
                for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin();
                     it != v_temporary_terms[block][i].end(); it++)
ferhat's avatar
ferhat committed
799
                  {
800
                    (*it)->compile(code_file, false, tt2, map_idx, true, false);
801
802
                    FSTPT_ fstpt((int)(map_idx.find((*it)->idx)->second));
                    fstpt.write(code_file);
ferhat's avatar
ferhat committed
803
804
                    // Insert current node into tt2
                    tt2.insert(*it);
sebastien's avatar
sebastien committed
805
#ifdef DEBUGC
ferhat's avatar
ferhat committed
806
807
808
809
                    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
810
811
#endif

ferhat's avatar
ferhat committed
812
                  }
813
              }
sebastien's avatar
sebastien committed
814
#ifdef DEBUGC
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
            for (temporary_terms_type::const_iterator it = v_temporary_terms[block][i].begin();
                     it != v_temporary_terms[block][i].end(); it++)
              {
                map_idx_type::const_iterator ii=map_idx.find((*it)->idx);
                cout << "map_idx[" << (*it)->idx <<"]=" << ii->second << "\n";
              }
#endif

            int variable_ID, equation_ID;
            EquationType equ_type;


            switch (simulation_type)
              {
evaluation:
              case EVALUATE_BACKWARD:
              case EVALUATE_FORWARD:
                equ_type = getBlockEquationType(block, i);
                if (equ_type == E_EVALUATE)
ferhat's avatar
ferhat committed
834
                  {
835
836
837
838
839
                    eq_node = (BinaryOpNode*)getBlockEquationNodeID(block,i);
                    lhs = eq_node->get_arg1();
                    rhs = eq_node->get_arg2();
                    rhs->compile(code_file, false, temporary_terms, map_idx, true, false);
                    lhs->compile(code_file, true, temporary_terms, map_idx, true, false);
ferhat's avatar
ferhat committed
840
                  }
841
                else if (equ_type == E_EVALUATE_S)
ferhat's avatar
ferhat committed
842
                  {
843
                    eq_node = (BinaryOpNode*)getBlockEquationRenormalizedNodeID(block,i);
844
845
                    lhs = eq_node->get_arg1();
                    rhs = eq_node->get_arg2();
846
                    rhs->compile(code_file, false, temporary_terms, map_idx, true, false);
847
                    lhs->compile(code_file, true, temporary_terms, map_idx, true, false);
ferhat's avatar
ferhat committed
848
                  }
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
                break;
              case SOLVE_BACKWARD_COMPLETE:
              case SOLVE_FORWARD_COMPLETE:
              case SOLVE_TWO_BOUNDARIES_COMPLETE:
              case SOLVE_TWO_BOUNDARIES_SIMPLE:
                if (i< (int) block_recursive)
                  goto evaluation;
                variable_ID = getBlockVariableID(block, i);
                equation_ID = getBlockEquationID(block, i);
                feedback_variables.push_back(variable_ID);
                Uf[equation_ID].Ufl=NULL;
                goto end;
              default:
end:
                eq_node = (BinaryOpNode*)getBlockEquationNodeID(block, i);
                lhs = eq_node->get_arg1();
                rhs = eq_node->get_arg2();
                lhs->compile(code_file, false, temporary_terms, map_idx, true, false);
                rhs->compile(code_file, false, temporary_terms, map_idx, true, false);

                FBINARY_ fbinary(oMinus);
                fbinary.write(code_file);
                FSTPR_ fstpr(i - block_recursive);
                fstpr.write(code_file);
ferhat's avatar
ferhat committed
873
              }
874
875
876
877
878
879
880
881
          }
        FENDEQU_ fendequ;
        fendequ.write(code_file);
        // The Jacobian if we have to solve the block
        if    (simulation_type != EVALUATE_BACKWARD
            && simulation_type != EVALUATE_FORWARD)
          {
            switch (simulation_type)
ferhat's avatar
ferhat committed
882
              {
883
884
885
              case SOLVE_BACKWARD_SIMPLE:
              case SOLVE_FORWARD_SIMPLE:
                compileDerivative(code_file, getBlockEquationID(block, 0), getBlockVariableID(block, 0), 0, map_idx);
ferhat's avatar
ferhat committed
886
                  {
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
                    FSTPG_ fstpg(0);
                    fstpg.write(code_file);
                  }
                break;

              case SOLVE_BACKWARD_COMPLETE:
              case SOLVE_FORWARD_COMPLETE:
              case SOLVE_TWO_BOUNDARIES_COMPLETE:
              case SOLVE_TWO_BOUNDARIES_SIMPLE:
                count_u = feedback_variables.size();
                for (t_block_derivatives_equation_variable_laglead_nodeid::const_iterator it = blocks_derivatives[block].begin(); it != (blocks_derivatives[block]).end(); it++)
                  {
                    unsigned int eq = it->first.first;
                    unsigned int var = it->first.second;
                    unsigned int eqr = getBlockEquationID(block, eq);
                    unsigned int varr = getBlockVariableID(block, var);
                    int lag = it->second.first;
                    if(eq>=block_recursive and var>=block_recursive)
905
                      {
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
                        if (!Uf[eqr].Ufl)
                          {
                            Uf[eqr].Ufl=(Uff_l*)malloc(sizeof(Uff_l));
                            Uf[eqr].Ufl_First=Uf[eqr].Ufl;
                          }
                        else
                          {
                            Uf[eqr].Ufl->pNext=(Uff_l*)malloc(sizeof(Uff_l));
                            Uf[eqr].Ufl=Uf[eqr].Ufl->pNext;
                          }
                        Uf[eqr].Ufl->pNext=NULL;
                        Uf[eqr].Ufl->u=count_u;
                        Uf[eqr].Ufl->var=varr;
                        Uf[eqr].Ufl->lag=lag;
                        compileChainRuleDerivative(code_file, eqr, varr, lag, map_idx);
                        FSTPU_ fstpu(count_u);
                        fstpu.write(code_file);
                        count_u++;
924
                      }
925
926
927
928
                  }
                for (i = 0;i < (int) block_size;i++)
                  {
                    if(i>= (int) block_recursive)
929
                      {
930
931
932
933
934
935
936
937
                        FLDR_ fldr(i-block_recursive);
                        fldr.write(code_file);

                        FLDZ_ fldz;
                        fldz.write(code_file);

                        v=getBlockEquationID(block, i);
                        for (Uf[v].Ufl=Uf[v].Ufl_First; Uf[v].Ufl; Uf[v].Ufl=Uf[v].Ufl->pNext)
938
                          {
939
940
941
942
943
944
945
946
947
948
949
950
951
                            FLDU_ fldu(Uf[v].Ufl->u);
                            fldu.write(code_file);
                            FLDV_ fldv(eEndogenous, Uf[v].Ufl->var, Uf[v].Ufl->lag);
                            fldv.write(code_file);

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

                            FCUML_ fcuml;
                            fcuml.write(code_file);
                          }
                        Uf[v].Ufl=Uf[v].Ufl_First;
                        while (Uf[v].Ufl)
952
                          {
953
954
                            Uf[v].Ufl_First=Uf[v].Ufl->pNext;
                            free(Uf[v].Ufl);
ferhat's avatar
ferhat committed
955
956
                            Uf[v].Ufl=Uf[v].Ufl_First;
                          }
957
958
959
960
961
                        FBINARY_ fbinary(oMinus);
                        fbinary.write(code_file);

                        FSTPU_ fstpu(i - block_recursive);
                        fstpu.write(code_file);
ferhat's avatar
ferhat committed
962
963
                      }
                  }
964
965
966
                break;
              default:
                break;
ferhat's avatar
ferhat committed
967
              }
968
          }
ferhat's avatar
ferhat committed
969
      }
970
971
972
973
    FENDBLOCK_ fendblock;
    fendblock.write(code_file);
    FEND_ fend;
    fend.write(code_file);
ferhat's avatar
ferhat committed
974
975
    code_file.close();
  }
sebastien's avatar
sebastien committed
976
977
978

void
DynamicModel::writeDynamicMFile(const string &dynamic_basename) const
ferhat's avatar
ferhat committed
979
980
981
982
983
984
985
986
987
988
  {
    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);
      }
989
    mDynamicModelFile << "function [residual, g1, g2, g3] = " << dynamic_basename << "(y, x, params, it_)" << endl
ferhat's avatar
ferhat committed
990
991
992
993
994
    << "%" << endl
    << "% Status : Computes dynamic model for Dynare" << endl
    << "%" << endl
    << "% Warning : this file is generated automatically by Dynare" << endl
    << "%           from model file (.mod)" << endl << endl;
995

996
997
998
    if (containsSteadyStateOperator())
      mDynamicModelFile << "global oo_;" << endl << endl;

999
    writeDynamicModel(mDynamicModelFile, false);
ferhat's avatar
ferhat committed
1000
1001
1002

    mDynamicModelFile.close();
  }
sebastien's avatar
sebastien committed
1003
1004
1005

void
DynamicModel::writeDynamicCFile(const string &dynamic_basename) const
ferhat's avatar
ferhat committed
1006
1007
1008
  {
    string filename = dynamic_basename + ".c";
    ofstream mDynamicModelFile;
1009

ferhat's avatar
ferhat committed
1010
1011
1012
1013
1014
1015
1016
    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
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
                      << " * " << 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
                      << endl
                      << "#define max(a, b) (((a) > (b)) ? (a) : (b))" << endl
                      << "#define min(a, b) (((a) > (b)) ? (b) : (a))" << endl;
ferhat's avatar
ferhat committed
1028
1029

    // Writing the function body
1030
    writeDynamicModel(mDynamicModelFile, true);
ferhat's avatar
ferhat committed
1031
1032
1033
1034
1035
1036

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