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

20
#include <cstdlib>
sebastien's avatar
sebastien committed
21
22
#include <iostream>
#include <fstream>
23
#include <typeinfo>
24
#include <cassert>
25
26
27
28
#ifndef _WIN32
# include <unistd.h>
#endif

29
#include "ModFile.hh"
30
#include "ConfigFile.hh"
31
#include "ComputingTasks.hh"
32

33
34
35
36
37
38
39
40
ModFile::ModFile(WarningConsolidation &warnings_arg)
  : expressions_tree(symbol_table, num_constants, external_functions_table),
    dynamic_model(symbol_table, num_constants, external_functions_table),
    trend_dynamic_model(symbol_table, num_constants, external_functions_table),
    ramsey_FOC_equations_dynamic_model(symbol_table, num_constants, external_functions_table),
    static_model(symbol_table, num_constants, external_functions_table),
    steady_state_model(symbol_table, num_constants, external_functions_table, static_model),
    linear(false), block(false), byte_code(false), use_dll(false), no_static(false), 
41
    differentiate_forward_vars(false),
42
    nonstationary_variables(false), ramsey_policy_orig_eqn_nbr(0),
43
    warnings(warnings_arg)
44
45
{
}
sebastien's avatar
sebastien committed
46
47
48

ModFile::~ModFile()
{
49
50
  for (vector<Statement *>::iterator it = statements.begin();
       it != statements.end(); it++)
sebastien's avatar
sebastien committed
51
52
53
    delete (*it);
}

54
void
55
ModFile::evalAllExpressions(bool warn_uninit)
56
{
sebastien's avatar
sebastien committed
57
  cout << "Evaluating expressions...";
58

sebastien's avatar
sebastien committed
59
  // Loop over all statements, and fill global eval context if relevant
60
  for (vector<Statement *>::const_iterator it = statements.begin(); it != statements.end(); it++)
61
    {
sebastien's avatar
sebastien committed
62
63
64
65
66
67
68
69
70
71
72
      InitParamStatement *ips = dynamic_cast<InitParamStatement *>(*it);
      if (ips)
        ips->fillEvalContext(global_eval_context);

      InitOrEndValStatement *ies = dynamic_cast<InitOrEndValStatement *>(*it);
      if (ies)
        ies->fillEvalContext(global_eval_context);

      LoadParamsAndSteadyStateStatement *lpass = dynamic_cast<LoadParamsAndSteadyStateStatement *>(*it);
      if (lpass)
        lpass->fillEvalContext(global_eval_context);
73
    }
sebastien's avatar
sebastien committed
74
75

  // Evaluate model local variables
sebastien's avatar
sebastien committed
76
  dynamic_model.fillEvalContext(global_eval_context);
sebastien's avatar
sebastien committed
77
78
79
80

  cout << "done" << endl;

  // Check if some symbols are not initialized, and give them a zero value then
81
  for (int id = 0; id <= symbol_table.maxID(); id++)
82
    {
sebastien's avatar
sebastien committed
83
84
      SymbolType type = symbol_table.getType(id);
      if ((type == eEndogenous || type == eExogenous || type == eExogenousDet
85
           || type == eParameter || type == eModelLocalVariable)
sebastien's avatar
sebastien committed
86
          && global_eval_context.find(id) == global_eval_context.end())
87
        {
88
          if (warn_uninit)
89
90
            warnings << "WARNING: Can't find a numeric initial value for "
                     << symbol_table.getName(id) << ", using zero" << endl;
sebastien's avatar
sebastien committed
91
          global_eval_context[id] = 0;
92
93
94
95
        }
    }
}

sebastien's avatar
sebastien committed
96
97
98
99
100
101
void
ModFile::addStatement(Statement *st)
{
  statements.push_back(st);
}

102
103
104
105
106
107
void
ModFile::addStatementAtFront(Statement *st)
{
  statements.insert(statements.begin(), st);
}

sebastien's avatar
sebastien committed
108
109
110
void
ModFile::checkPass()
{
111
112
  for (vector<Statement *>::iterator it = statements.begin();
       it != statements.end(); it++)
113
    (*it)->checkPass(mod_file_struct, warnings);
sebastien's avatar
sebastien committed
114

115
116
117
  // Check the steady state block
  steady_state_model.checkPass(mod_file_struct.ramsey_policy_present);

118
119
120
121
  // If order option has not been set, default to 2
  if (!mod_file_struct.order_option)
    mod_file_struct.order_option = 2;

sebastien's avatar
sebastien committed
122
123
124
  bool stochastic_statement_present = mod_file_struct.stoch_simul_present
    || mod_file_struct.estimation_present
    || mod_file_struct.osr_present
125
    || mod_file_struct.ramsey_policy_present
126
127
    || mod_file_struct.discretionary_policy_present
    || mod_file_struct.calib_smoother_present;
sebastien's avatar
sebastien committed
128

129
  // Allow empty model only when doing a standalone BVAR estimation
sebastien's avatar
sebastien committed
130
  if (dynamic_model.equation_number() == 0
131
132
      && (mod_file_struct.check_present
          || mod_file_struct.simul_present
sebastien's avatar
sebastien committed
133
134
135
          || stochastic_statement_present))
    {
      cerr << "ERROR: At least one model equation must be declared!" << endl;
136
      exit(EXIT_FAILURE);
sebastien's avatar
sebastien committed
137
138
    }

139
140
141
142
  if (((mod_file_struct.ramsey_policy_present || mod_file_struct.discretionary_policy_present) 
       && !mod_file_struct.planner_objective_present)
      || (!(mod_file_struct.ramsey_policy_present || mod_file_struct.discretionary_policy_present)
	  && mod_file_struct.planner_objective_present))
143
    {
144
      cerr << "ERROR: A planner_objective statement must be used with a ramsey_policy or a discretionary_policy statement and vice versa." << endl;
145
146
147
      exit(EXIT_FAILURE);
    }

148
149
150
151
152
153
154
155
  if ((mod_file_struct.osr_present && (!mod_file_struct.osr_params_present || !mod_file_struct.optim_weights_present))
      || ((!mod_file_struct.osr_present || !mod_file_struct.osr_params_present) && mod_file_struct.optim_weights_present)
      || ((!mod_file_struct.osr_present || !mod_file_struct.optim_weights_present) && mod_file_struct.osr_params_present))
    {
      cerr << "ERROR: The osr statement must be used with osr_params and optim_weights." << endl;
      exit(EXIT_FAILURE);
    }

156
  if (mod_file_struct.simul_present && stochastic_statement_present)
157
    {
158
      cerr << "ERROR: A .mod file cannot contain both a simul command and one of {stoch_simul, estimation, osr, ramsey_policy, discretionary_policy}" << endl;
159
      exit(EXIT_FAILURE);
160
161
    }

162
  if (mod_file_struct.k_order_solver && byte_code)
sebastien's avatar
sebastien committed
163
    {
164
      cerr << "ERROR: 'k_order_solver' (which is implicit if order >= 3), is not yet compatible with 'bytecode'." << endl;
sebastien's avatar
sebastien committed
165
166
167
      exit(EXIT_FAILURE);
    }

168
169
170
171
172
173
  if (use_dll && (block || byte_code))
    {
      cerr << "ERROR: In 'model' block, 'use_dll' option is not compatible with 'block' or 'bytecode'" << endl;
      exit(EXIT_FAILURE);
    }

174
175
176
177
178
179
180
  if (block || byte_code)
    if (dynamic_model.isModelLocalVariableUsed())
      {
        cerr << "ERROR: In 'model' block, 'block' or 'bytecode' options are not yet compatible with pound expressions" << endl;
        exit(EXIT_FAILURE);
      }

181
  if ((stochastic_statement_present || mod_file_struct.check_present || mod_file_struct.steady_present) && no_static)
182
    {
183
      cerr << "ERROR: no_static option is incompatible with stoch_simul, estimation, osr, ramsey_policy, discretionary_policy, steady and check commands" << endl;
184
185
      exit(EXIT_FAILURE);
    }
186

187
188
189
190
191
192
193
194
  if (mod_file_struct.dsge_var_estimated)
    if (!mod_file_struct.dsge_prior_weight_in_estimated_params)
      {
        cerr << "ERROR: When estimating a DSGE-VAR model and estimating the weight of the prior, dsge_prior_weight must "
             << "be referenced in the estimated_params block." << endl;
        exit(EXIT_FAILURE);
      }

195
196
197
198
199
200
201
202
  if (symbol_table.exists("dsge_prior_weight"))
    {
      if (symbol_table.getType("dsge_prior_weight") != eParameter)
        {
          cerr << "ERROR: dsge_prior_weight may only be used as a parameter." << endl;
          exit(EXIT_FAILURE);
        }
      else
203
204
205
        warnings << "WARNING: When estimating a DSGE-Var, declaring dsge_prior_weight as a "
                 << "parameter is deprecated. The preferred method is to do this via "
                 << "the dsge_var option in the estimation statement." << endl;
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

      if (mod_file_struct.dsge_var_estimated || !mod_file_struct.dsge_var_calibrated.empty())
        {
          cerr << "ERROR: dsge_prior_weight can either be declared as a parameter (deprecated) or via the dsge_var option "
               << "to the estimation statement (preferred), but not both." << endl;
          exit(EXIT_FAILURE);
        }

      if (!mod_file_struct.dsge_prior_weight_initialized && !mod_file_struct.dsge_prior_weight_in_estimated_params)
        {
          cerr << "ERROR: If dsge_prior_weight is declared as a parameter, it must either be initialized or placed in the "
               << "estimated_params block." << endl;
          exit(EXIT_FAILURE);
        }

      if (mod_file_struct.dsge_prior_weight_initialized && mod_file_struct.dsge_prior_weight_in_estimated_params)
        {
          cerr << "ERROR: dsge_prior_weight cannot be both initalized and estimated." << endl;
          exit(EXIT_FAILURE);
        }
    }

228
  if (mod_file_struct.dsge_prior_weight_in_estimated_params)
229
    if (!mod_file_struct.dsge_var_estimated && !mod_file_struct.dsge_var_calibrated.empty())
230
      {
231
        cerr << "ERROR: If dsge_prior_weight is in the estimated_params block, the prior weight cannot be calibrated "
232
233
234
             << "via the dsge_var option in the estimation statement." << endl;
        exit(EXIT_FAILURE);
      }
235
236
237
238
239
240
    else if (!mod_file_struct.dsge_var_estimated && !symbol_table.exists("dsge_prior_weight"))
      {
        cerr << "ERROR: If dsge_prior_weight is in the estimated_params block, it must either be declared as a parameter "
             << "(deprecated) or the dsge_var option must be passed to the estimation statement (preferred)." << endl;
        exit(EXIT_FAILURE);
      }
241
242
243
244
245
246
247
248
249
250
251
252
253

  if (dynamic_model.staticOnlyEquationsNbr() != dynamic_model.dynamicOnlyEquationsNbr())
    {
      cerr << "ERROR: the number of equations marked [static] must be equal to the number of equations marked [dynamic]" << endl;
      exit(EXIT_FAILURE);
    }
  
  if (dynamic_model.staticOnlyEquationsNbr() > 0 &&
      (mod_file_struct.ramsey_policy_present || mod_file_struct.discretionary_policy_present))
    {
      cerr << "ERROR: marking equations as [static] or [dynamic] is not possible with ramsey_policy or discretionary_policy" << endl;
      exit(EXIT_FAILURE);
    }
254
255
256
257
258
259
260
261
262
263
264
265
266

  if (stochastic_statement_present &&
      (dynamic_model.isUnaryOpUsed(oSign)
       || dynamic_model.isUnaryOpUsed(oAbs)
       || dynamic_model.isBinaryOpUsed(oMax)
       || dynamic_model.isBinaryOpUsed(oMin)
       || dynamic_model.isBinaryOpUsed(oGreater)
       || dynamic_model.isBinaryOpUsed(oLess)
       || dynamic_model.isBinaryOpUsed(oGreaterEqual)
       || dynamic_model.isBinaryOpUsed(oLessEqual)
       || dynamic_model.isBinaryOpUsed(oEqualEqual)
       || dynamic_model.isBinaryOpUsed(oDifferent)))
    warnings << "WARNING: you are using a function (max, min, abs, sign) or an operator (<, >, <=, >=, ==, !=) which is unsuitable for a stochastic context; see the reference manual, section about \"Expressions\", for more details." << endl;
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288

  // Test if some estimated parameters are used within the values of shocks
  // statements (see issue #469)
  set<int> parameters_intersect;
  set_intersection(mod_file_struct.parameters_within_shocks_values.begin(),
                   mod_file_struct.parameters_within_shocks_values.end(),
                   mod_file_struct.estimated_parameters.begin(),
                   mod_file_struct.estimated_parameters.end(),
                   inserter(parameters_intersect, parameters_intersect.begin()));
  if (parameters_intersect.size() > 0)
    {
      cerr << "ERROR: some estimated parameters (";
      for (set<int>::const_iterator it = parameters_intersect.begin();
           it != parameters_intersect.end(); )
        {
          cerr << symbol_table.getName(*it);
          if (++it != parameters_intersect.end())
            cerr << ", ";
        }
      cerr << ") also appear in the expressions defining the variance/covariance matrix of shocks; this is not allowed." << endl;
      exit(EXIT_FAILURE);
    }
sebastien's avatar
sebastien committed
289
290
291
}

void
292
ModFile::transformPass(bool nostrict)
sebastien's avatar
sebastien committed
293
{
294
295
296
297
298
299
300
301
302
303
304
305
  if (nostrict)
    {
      set<int> unusedEndogs = symbol_table.getEndogenous();
      dynamic_model.findUnusedEndogenous(unusedEndogs);
      for (set<int>::iterator it = unusedEndogs.begin(); it != unusedEndogs.end(); it++)
        {
          symbol_table.changeType(*it, eUnusedEndogenous);
          warnings << "WARNING: '" << symbol_table.getName(*it)
                   << "' not used in model block, removed by nostrict command-line option" << endl;
        }
    }

sebastien's avatar
sebastien committed
306
307
  if (symbol_table.predeterminedNbr() > 0)
    dynamic_model.transformPredeterminedVariables();
308

309
310
311
  // Create auxiliary vars for Expectation operator
  dynamic_model.substituteExpectation(mod_file_struct.partial_information);

312
313
314
315
316
317
318
  if (nonstationary_variables)
    {
      dynamic_model.detrendEquations();
      dynamic_model.cloneDynamic(trend_dynamic_model);
      dynamic_model.removeTrendVariableFromEquations();
    }

319
320
321
322
323
324
325
326
327
  if (mod_file_struct.ramsey_policy_present)
    {
      StaticModel *planner_objective = NULL;
      for (vector<Statement *>::iterator it = statements.begin(); it != statements.end(); it++)
        {
          PlannerObjectiveStatement *pos = dynamic_cast<PlannerObjectiveStatement *>(*it);
          if (pos != NULL)
            planner_objective = pos->getPlannerObjective();
        }
328
      assert(planner_objective != NULL);
329
330
331
332
333
334
335
      ramsey_policy_orig_eqn_nbr = dynamic_model.equation_number();

      /*
        clone the model then clone the new equations back to the original because
        we have to call computeDerivIDs (in computeRamseyPolicyFOCs and computingPass)
       */
      dynamic_model.cloneDynamic(ramsey_FOC_equations_dynamic_model);
336
      ramsey_FOC_equations_dynamic_model.computeRamseyPolicyFOCs(*planner_objective);
337
338
339
      ramsey_FOC_equations_dynamic_model.replaceMyEquations(dynamic_model);
    }

sebastien's avatar
sebastien committed
340
341
342
  if (mod_file_struct.stoch_simul_present
      || mod_file_struct.estimation_present
      || mod_file_struct.osr_present
343
      || mod_file_struct.ramsey_policy_present
344
345
      || mod_file_struct.discretionary_policy_present
      || mod_file_struct.calib_smoother_present)
sebastien's avatar
sebastien committed
346
    {
347
348
349
350
351
352
353
354
355
356
357
      // In stochastic models, create auxiliary vars for leads and lags greater than 2, on both endos and exos
      dynamic_model.substituteEndoLeadGreaterThanTwo(false);
      dynamic_model.substituteExoLead(false);
      dynamic_model.substituteEndoLagGreaterThanTwo(false);
      dynamic_model.substituteExoLag(false);
    }
  else
    {
      // In deterministic models, create auxiliary vars for leads and lags endogenous greater than 2, only on endos (useless on exos)
      dynamic_model.substituteEndoLeadGreaterThanTwo(true);
      dynamic_model.substituteEndoLagGreaterThanTwo(true);
sebastien's avatar
sebastien committed
358
    }
359

360
  if (differentiate_forward_vars)
361
    dynamic_model.differentiateForwardVars(differentiate_forward_vars_subset);
362

363
  if (mod_file_struct.dsge_var_estimated || !mod_file_struct.dsge_var_calibrated.empty())
364
365
    try
      {
366
367
        int sid = symbol_table.addSymbol("dsge_prior_weight", eParameter);
        if (!mod_file_struct.dsge_var_calibrated.empty())
368
          addStatementAtFront(new InitParamStatement(sid,
369
                                                     expressions_tree.AddNonNegativeConstant(mod_file_struct.dsge_var_calibrated),
370
                                                     symbol_table));
371
372
373
374
375
376
377
378
      }
    catch (SymbolTable::AlreadyDeclaredException &e)
      {
        cerr << "ERROR: dsge_prior_weight should not be declared as a model variable / parameter "
             << "when the dsge_var option is passed to the estimation statement." << endl;
        exit(EXIT_FAILURE);
      }

sebastien's avatar
sebastien committed
379
380
381
  // Freeze the symbol table
  symbol_table.freeze();

382
  /*
383
    Enforce the same number of equations and endogenous, except in three cases:
384
385
    - ramsey_policy is used
    - a BVAR command is used and there is no equation (standalone BVAR estimation)
386
    - nostrict option is passed and there are more endogs than equations (dealt with before freeze)
387
  */
388
  if (!(mod_file_struct.ramsey_policy_present || mod_file_struct.discretionary_policy_present)
389
      && !(mod_file_struct.bvar_present && dynamic_model.equation_number() == 0)
sebastien's avatar
sebastien committed
390
      && (dynamic_model.equation_number() != symbol_table.endo_nbr()))
sebastien's avatar
sebastien committed
391
    {
sebastien's avatar
sebastien committed
392
      cerr << "ERROR: There are " << dynamic_model.equation_number() << " equations but " << symbol_table.endo_nbr() << " endogenous variables!" << endl;
393
      exit(EXIT_FAILURE);
sebastien's avatar
sebastien committed
394
    }
395

396
397
398
399
400
  if (symbol_table.exo_det_nbr() > 0 && mod_file_struct.simul_present)
    {
      cerr << "ERROR: A .mod file cannot contain both a simul command and varexo_det declaration (all exogenous variables are deterministic in this case)" << endl;
      exit(EXIT_FAILURE);
    }
401

402
403
404
405
406
407
  if (mod_file_struct.ramsey_policy_present && symbol_table.exo_det_nbr() > 0)
    {
      cerr << "ERROR: ramsey_policy is incompatible with deterministic exogenous variables" << endl;
      exit(EXIT_FAILURE);
    }

408
409
410
411
412
413
414
  if (!mod_file_struct.ramsey_policy_present)
    cout << "Found " << dynamic_model.equation_number() << " equation(s)." << endl;
  else
    {
      cout << "Found " << ramsey_policy_orig_eqn_nbr  << " equation(s)." << endl;
      cout << "Found " << dynamic_model.equation_number() << " FOC equation(s) for Ramsey Problem." << endl;
    }
415

416
  if (symbol_table.exists("dsge_prior_weight"))
417
418
419
420
    if (mod_file_struct.bayesian_irf_present)
      {
        if (symbol_table.exo_nbr() != symbol_table.observedVariablesNbr())
          {
421
422
            cerr << "ERROR: When estimating a DSGE-Var and the bayesian_irf option is passed to the estimation "
                 << "statement, the number of shocks must equal the number of observed variables." << endl;
423
424
425
426
427
428
            exit(EXIT_FAILURE);
          }
      }
    else
      if (symbol_table.exo_nbr() < symbol_table.observedVariablesNbr())
        {
429
430
          cerr << "ERROR: When estimating a DSGE-Var, the number of shocks must be "
               << "greater than or equal to the number of observed variables." << endl;
431
432
          exit(EXIT_FAILURE);
        }
sebastien's avatar
sebastien committed
433
}
sebastien's avatar
sebastien committed
434

sebastien's avatar
sebastien committed
435
void
436
ModFile::computingPass(bool no_tmp_terms)
sebastien's avatar
sebastien committed
437
{
438
  // Mod file may have no equation (for example in a standalone BVAR estimation)
sebastien's avatar
sebastien committed
439
  if (dynamic_model.equation_number() > 0)
sebastien's avatar
sebastien committed
440
    {
441
442
      if (nonstationary_variables)
        trend_dynamic_model.runTrendTest(global_eval_context);
443

sebastien's avatar
sebastien committed
444
      // Compute static model and its derivatives
445
      dynamic_model.toStatic(static_model);
446
      if (!no_static)
447
        {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
448
449
          if (mod_file_struct.stoch_simul_present
              || mod_file_struct.estimation_present || mod_file_struct.osr_present
450
451
              || mod_file_struct.ramsey_policy_present || mod_file_struct.identification_present
              || mod_file_struct.calib_smoother_present)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
452
            static_model.set_cutoff_to_zero();
453
454
455

          const bool static_hessian = mod_file_struct.identification_present
            || mod_file_struct.estimation_analytic_derivation;
456
457
          const bool paramsDerivatives = mod_file_struct.identification_present
            || mod_file_struct.estimation_analytic_derivation;
458
          static_model.computingPass(global_eval_context, no_tmp_terms, static_hessian,
459
                                     paramsDerivatives, block, byte_code);
460
        }
sebastien's avatar
sebastien committed
461
      // Set things to compute for dynamic model
462
463
464
      if (mod_file_struct.simul_present || mod_file_struct.check_present
          || mod_file_struct.stoch_simul_present
          || mod_file_struct.estimation_present || mod_file_struct.osr_present
465
466
          || mod_file_struct.ramsey_policy_present || mod_file_struct.identification_present
          || mod_file_struct.calib_smoother_present)
sebastien's avatar
sebastien committed
467
        {
468
          if (mod_file_struct.simul_present)
469
            dynamic_model.computingPass(true, false, false, false, global_eval_context, no_tmp_terms, block, use_dll, byte_code);
470
          else
471
            {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
472
473
              if (mod_file_struct.stoch_simul_present
                  || mod_file_struct.estimation_present || mod_file_struct.osr_present
474
475
                  || mod_file_struct.ramsey_policy_present || mod_file_struct.identification_present
                  || mod_file_struct.calib_smoother_present)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
476
                dynamic_model.set_cutoff_to_zero();
477
478
479
480
481
              if (mod_file_struct.order_option < 1 || mod_file_struct.order_option > 3)
                {
                  cerr << "ERROR: Incorrect order option..." << endl;
                  exit(EXIT_FAILURE);
                }
482
              bool hessian = mod_file_struct.order_option >= 2 || mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation;
483
              bool thirdDerivatives = mod_file_struct.order_option == 3 || mod_file_struct.estimation_analytic_derivation;
484
              bool paramsDerivatives = mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation;
485
              dynamic_model.computingPass(true, hessian, thirdDerivatives, paramsDerivatives, global_eval_context, no_tmp_terms, block, use_dll, byte_code);
486
            }
sebastien's avatar
sebastien committed
487
        }
488
489
      else // No computing task requested, compute derivatives up to 2nd order by default
        dynamic_model.computingPass(true, true, false, false, global_eval_context, no_tmp_terms, block, use_dll, byte_code);
490
    }
491

492
493
  for (vector<Statement *>::iterator it = statements.begin();
       it != statements.end(); it++)
sebastien's avatar
sebastien committed
494
    (*it)->computingPass();
sebastien's avatar
sebastien committed
495
496
}

sebastien's avatar
sebastien committed
497
void
498
ModFile::writeOutputFiles(const string &basename, bool clear_all, bool no_log, bool no_warn, bool console, bool nograph, bool nointeractive, const ConfigFile &config_file
499
#if defined(_WIN32) || defined(__CYGWIN32__)
500
                          , bool cygwin, bool msvc
501
#endif
502
                          ) const
sebastien's avatar
sebastien committed
503
504
{
  ofstream mOutputFile;
505

sebastien's avatar
sebastien committed
506
507
508
  if (basename.size())
    {
      string fname(basename);
sebastien's avatar
sebastien committed
509
      fname += ".m";
sebastien's avatar
sebastien committed
510
511
512
      mOutputFile.open(fname.c_str(), ios::out | ios::binary);
      if (!mOutputFile.is_open())
        {
sebastien's avatar
sebastien committed
513
          cerr << "ERROR: Can't open file " << fname
sebastien's avatar
sebastien committed
514
               << " for writing" << endl;
515
          exit(EXIT_FAILURE);
sebastien's avatar
sebastien committed
516
517
518
519
        }
    }
  else
    {
sebastien's avatar
sebastien committed
520
      cerr << "ERROR: Missing file name" << endl;
521
      exit(EXIT_FAILURE);
sebastien's avatar
sebastien committed
522
523
    }

sebastien's avatar
sebastien committed
524
525
526
527
528
  mOutputFile << "%" << endl
              << "% Status : main Dynare file " << endl
              << "%" << endl
              << "% Warning : this file is generated automatically by Dynare" << endl
              << "%           from model file (.mod)" << endl << endl;
sebastien's avatar
sebastien committed
529

530
531
532
  if (no_warn)
    mOutputFile << "warning off" << endl; // This will be executed *after* function warning_config()

sebastien's avatar
sebastien committed
533
  if (clear_all)
534
    mOutputFile << "clear all" << endl;
535
536

  mOutputFile << "tic;" << endl
537
              << "global M_ oo_ options_ ys0_ ex0_ estimation_info" << endl
538
539
540
541
              << "options_ = [];" << endl
              << "M_.fname = '" << basename << "';" << endl
              << "%" << endl
              << "% Some global variables initialization" << endl
542
543
544
              << "%" << endl;
  config_file.writeHooks(mOutputFile);
  mOutputFile << "global_initialization;" << endl
545
546
              << "diary off;" << endl;
  if (!no_log)
547
    mOutputFile << "diary('" << basename << ".log');" << endl;
548

549
  if (console)
550
551
    mOutputFile << "options_.console_mode = 1;" << endl
                << "options_.nodisplay = 1;" << endl;
552
553
  if (nograph)
    mOutputFile << "options_.nograph = 1;" << endl;
554
555
556

  if (nointeractive)
    mOutputFile << "options_.nointeractive = 1;" << endl;
557
    
558
  cout << "Processing outputs ...";
559

sebastien's avatar
sebastien committed
560
561
  symbol_table.writeOutput(mOutputFile);

562
  // Initialize M_.Sigma_e, M_.Correlation_matrix, M_.H, and M_.Correlation_matrix_ME
Sébastien Villemot's avatar
Sébastien Villemot committed
563
  mOutputFile << "M_.Sigma_e = zeros(" << symbol_table.exo_nbr() << ", "
564
565
              << symbol_table.exo_nbr() << ");" << endl
              << "M_.Correlation_matrix = eye(" << symbol_table.exo_nbr() << ", "
Sébastien Villemot's avatar
Sébastien Villemot committed
566
567
568
569
              << symbol_table.exo_nbr() << ");" << endl;

  if (mod_file_struct.calibrated_measurement_errors)
    mOutputFile << "M_.H = zeros(" << symbol_table.observedVariablesNbr() << ", "
570
571
                << symbol_table.observedVariablesNbr() << ");" << endl
                << "M_.Correlation_matrix_ME = eye(" << symbol_table.observedVariablesNbr() << ", "
Sébastien Villemot's avatar
Sébastien Villemot committed
572
573
                << symbol_table.observedVariablesNbr() << ");" << endl;
  else
574
575
    mOutputFile << "M_.H = 0;" << endl
                << "M_.Correlation_matrix_ME = 1;" << endl;
Sébastien Villemot's avatar
Sébastien Villemot committed
576

sebastien's avatar
sebastien committed
577
578
579
  if (linear == 1)
    mOutputFile << "options_.linear = 1;" << endl;

580
  mOutputFile << "options_.block=" << block << ";" << endl
581
582
              << "options_.bytecode=" << byte_code << ";" << endl
              << "options_.use_dll=" << use_dll << ";" << endl;
583

584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
  if (parallel_local_files.size() > 0)
    {
      mOutputFile << "options_.parallel_info.local_files = {" << endl;
      for (size_t i = 0; i < parallel_local_files.size(); i++)
        {
          size_t j = parallel_local_files[i].find_last_of("/\\");
          if (j == string::npos)
            mOutputFile << "'', '" << parallel_local_files[i] << "';" << endl;
          else
            mOutputFile << "'" << parallel_local_files[i].substr(0, j+1) << "', '"
                        << parallel_local_files[i].substr(j+1, string::npos) << "';" << endl;
        }
      mOutputFile << "};" << endl;
    }

599
600
  config_file.writeCluster(mOutputFile);

601
602
603
604
605
  if (byte_code)
    mOutputFile << "if exist('bytecode') ~= 3" << endl
                << "  error('DYNARE: Can''t find bytecode DLL. Please compile it or remove the ''bytecode'' option.')" << endl
                << "end" << endl;

606
  // Erase possible remnants of previous runs
607
608
  string dynfile = basename + "_dynamic.m";
  unlink(dynfile.c_str());
609

610
611
  string statfile = basename + "_static.m";
  unlink(statfile.c_str());
612

613
614
615
  string steadystatefile = basename + "_steadystate2.m";
  unlink(steadystatefile.c_str());

616
  if (!use_dll)
617
618
619
620
    {
      mOutputFile << "erase_compiled_function('" + basename + "_static');" << endl;
      mOutputFile << "erase_compiled_function('" + basename + "_dynamic');" << endl;
    }
621

622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
#if defined(_WIN32) || defined(__CYGWIN32__)
  // If using USE_DLL with MSVC, check that the user didn't use a function not supported by MSVC (because MSVC doesn't comply with C99 standard)
  if (use_dll && msvc)
    {
      if (dynamic_model.isUnaryOpUsed(oAcosh))
        {
          cerr << "ERROR: acosh() function is not supported with USE_DLL option and MSVC compiler; use Cygwin compiler instead." << endl;
          exit(EXIT_FAILURE);
        }
      if (dynamic_model.isUnaryOpUsed(oAsinh))
        {
          cerr << "ERROR: asinh() function is not supported with USE_DLL option and MSVC compiler; use Cygwin compiler instead." << endl;
          exit(EXIT_FAILURE);
        }
      if (dynamic_model.isUnaryOpUsed(oAtanh))
        {
          cerr << "ERROR: atanh() function is not supported with USE_DLL option and MSVC compiler; use Cygwin compiler instead." << endl;
          exit(EXIT_FAILURE);
        }
      if (dynamic_model.isTrinaryOpUsed(oNormcdf))
        {
          cerr << "ERROR: normcdf() function is not supported with USE_DLL option and MSVC compiler; use Cygwin compiler instead." << endl;
          exit(EXIT_FAILURE);
        }
    }
#endif

649
650
  // Compile the dynamic MEX file for use_dll option
  if (use_dll)
651
652
653
654
655
    {
      mOutputFile << "if ~exist('OCTAVE_VERSION')" << endl;
      // Some mex commands are enclosed in an eval(), because otherwise it will make Octave fail
#if defined(_WIN32) || defined(__CYGWIN32__)
      if (msvc)
656
        // MATLAB/Windows + Microsoft Visual C++
657
        mOutputFile << "    eval('mex -O LINKFLAGS=\"$LINKFLAGS /export:Dynamic\" " << basename << "_dynamic.c " << basename << "_dynamic_mex.c')" << endl
658
                    << "    eval('mex -O LINKFLAGS=\"$LINKFLAGS /export:Static\" " << basename << "_static.c "<< basename << "_static_mex.c')" << endl;
659
      else if (cygwin)
660
        // MATLAB/Windows + Cygwin g++
661
        mOutputFile << "    eval('mex -O PRELINK_CMDS1=\"echo EXPORTS > mex.def & echo mexFunction >> mex.def & echo Dynamic >> mex.def\" " << basename << "_dynamic.c " << basename << "_dynamic_mex.c')" << endl
662
                    << "    eval('mex -O PRELINK_CMDS1=\"echo EXPORTS > mex.def & echo mexFunction >> mex.def & echo Static >> mex.def\" " << basename << "_static.c "<< basename << "_static_mex.c')" << endl;
663
      else
664
        mOutputFile << "    error('When using the USE_DLL option, you must give either ''cygwin'' or ''msvc'' option to the ''dynare'' command')" << endl;
665
#else
666
# ifdef __linux__
667
      // MATLAB/Linux
668
669
      mOutputFile << "    eval('mex -O LDFLAGS=''-pthread -shared -Wl,--no-undefined'' " << basename << "_dynamic.c " << basename << "_dynamic_mex.c')" << endl
                  << "    eval('mex -O LDFLAGS=''-pthread -shared -Wl,--no-undefined'' " << basename << "_static.c "<< basename << "_static_mex.c')" << endl;
670
# else // MacOS
671
      // MATLAB/MacOS
672
673
674
675
      mOutputFile << "    eval('mex -O LDFLAGS=''-Wl,-twolevel_namespace -undefined error -arch \\$ARCHS -Wl,-syslibroot,\\$SDKROOT -mmacosx-version-min=\\$MACOSX_DEPLOYMENT_TARGET -bundle'' "
                  << basename << "_dynamic.c " << basename << "_dynamic_mex.c')" << endl
                  << "    eval('mex -O LDFLAGS=''-Wl,-twolevel_namespace -undefined error -arch \\$ARCHS -Wl,-syslibroot,\\$SDKROOT -mmacosx-version-min=\\$MACOSX_DEPLOYMENT_TARGET -bundle'' "
                  << basename << "_static.c " << basename << "_static_mex.c')" << endl;
676
# endif
677
#endif
678
      mOutputFile << "else" << endl // Octave
679
680
                  << "    mex " << basename << "_dynamic.c " << basename << "_dynamic_mex.c" << endl
                  << "    mex " << basename << "_static.c " << basename << "_static_mex.c" << endl
681
                  << "end" << endl;
682
    }
683
684
685
686
687

  // Add path for block option with M-files
  if (block && !byte_code)
    mOutputFile << "addpath " << basename << ";" << endl;

688
689
690
  if (mod_file_struct.ramsey_policy_present)
    mOutputFile << "M_.orig_eq_nbr = " << ramsey_policy_orig_eqn_nbr << ";" << endl;

sebastien's avatar
sebastien committed
691
  if (dynamic_model.equation_number() > 0)
692
    {
693
      dynamic_model.writeOutput(mOutputFile, basename, block, byte_code, use_dll, mod_file_struct.order_option, mod_file_struct.estimation_present);
694
      if (!no_static)
Houtan Bastani's avatar
Houtan Bastani committed
695
        static_model.writeOutput(mOutputFile, block);
696
    }
sebastien's avatar
sebastien committed
697
698

  // Print statements
699
700
  for (vector<Statement *>::const_iterator it = statements.begin();
       it != statements.end(); it++)
sebastien's avatar
sebastien committed
701
702
703
    {
      (*it)->writeOutput(mOutputFile, basename);

704
705
      /* Special treatment for initval block: insert initial values for the
         auxiliary variables and initialize exo det */
sebastien's avatar
sebastien committed
706
707
708
      InitValStatement *ivs = dynamic_cast<InitValStatement *>(*it);
      if (ivs != NULL)
        {
709
          static_model.writeAuxVarInitval(mOutputFile, oMatlabOutsideModel);
sebastien's avatar
sebastien committed
710
711
712
          ivs->writeOutputPostInit(mOutputFile);
        }

713
714
715
716
717
      // Special treatment for endval block: insert initial values for the auxiliary variables
      EndValStatement *evs = dynamic_cast<EndValStatement *>(*it);
      if (evs != NULL)
        static_model.writeAuxVarInitval(mOutputFile, oMatlabOutsideModel);

sebastien's avatar
sebastien committed
718
719
      // Special treatment for load params and steady state statement: insert initial values for the auxiliary variables
      LoadParamsAndSteadyStateStatement *lpass = dynamic_cast<LoadParamsAndSteadyStateStatement *>(*it);
720
      if (lpass && !no_static)
721
        static_model.writeAuxVarInitval(mOutputFile, oMatlabOutsideModel);
sebastien's avatar
sebastien committed
722
    }
sebastien's avatar
sebastien committed
723

724
725
726
  // Remove path for block option with M-files
  if (block && !byte_code)
    mOutputFile << "rmpath " << basename << ";" << endl;
727

728
729
730
731
732
733
734
735
736
  mOutputFile << "save('" << basename << "_results.mat', 'oo_', 'M_', 'options_');" << endl
              << "if exist('estim_params_', 'var') == 1" << endl
              << "  save('" << basename << "_results.mat', 'estim_params_', '-append');" << endl << "end" << endl
              << "if exist('bayestopt_', 'var') == 1" << endl
              << "  save('" << basename << "_results.mat', 'bayestopt_', '-append');" << endl << "end" << endl
              << "if exist('dataset_', 'var') == 1" << endl
              << "  save('" << basename << "_results.mat', 'dataset_', '-append');" << endl << "end" << endl
              << "if exist('estimation_info', 'var') == 1" << endl
              << "  save('" << basename << "_results.mat', 'estimation_info', '-append');" << endl << "end" << endl;
737
738
739

  config_file.writeEndParallel(mOutputFile);

740
741
742
  mOutputFile << endl << endl
	      << "disp(['Total computing time : ' dynsec2hms(toc) ]);" << endl;

743
744
  if (!no_warn)
    {
745
746
747
748
      if (warnings.countWarnings() > 0)
        mOutputFile << "disp('Note: " << warnings.countWarnings() << " warning(s) encountered in the preprocessor')" << endl;

      mOutputFile << "if ~isempty(lastwarn)" << endl
749
750
751
752
                  << "  disp('Note: warning(s) encountered in MATLAB/Octave code')" << endl
                  << "end" << endl;
    }
  
753

754
755
  if (!no_log)
    mOutputFile << "diary off" << endl;
sebastien's avatar
sebastien committed
756
757

  mOutputFile.close();
758

759
760
761
  // Create static and dynamic files
  if (dynamic_model.equation_number() > 0)
    {
762
      if (!no_static)
763
764
765
766
        {
          static_model.writeStaticFile(basename, block, byte_code, use_dll);
          static_model.writeParamsDerivativesFile(basename);
        }
767

768
769
      dynamic_model.writeDynamicFile(basename, block, byte_code, use_dll, mod_file_struct.order_option);
      dynamic_model.writeParamsDerivativesFile(basename);
770
771
    }

772
  // Create steady state file
773
  steady_state_model.writeSteadyStateFile(basename, mod_file_struct.ramsey_policy_present);
774

775
  cout << "done" << endl;
sebastien's avatar
sebastien committed
776
}