bytecode.cc 35.1 KB
Newer Older
1
/*
Sébastien Villemot's avatar
Sébastien Villemot committed
2
 * Copyright (C) 2007-2013 Dynare Team
sebastien's avatar
sebastien committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 *
 * 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/>.
 */
19
#include <cstring>
20
#include "Interpreter.hh"
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
21
22
23
#include "ErrorHandling.hh"
#include <ctime>
#include <math.h>
24

ferhat's avatar
ferhat committed
25
#ifdef DEBUG_EX
26

ferhat's avatar
ferhat committed
27
using namespace std;
sebastien's avatar
sebastien committed
28
# include <sstream>
29

Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
30
31
32



33
34
35
36
37
38
39
string
Get_Argument(const char *argv)
{
  string f(argv);
  return f;
}

ferhat's avatar
ferhat committed
40
#else
41

Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
42
43
44
void (*prev_fn)(int);


45
46
47
48
string
Get_Argument(const mxArray *prhs)
{
  const mxArray *mxa = prhs;
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
49
  mwSize buflen = mwSize(mxGetM(mxa) * mxGetN(mxa) + 1);
50
  char *first_argument;
sebastien's avatar
sebastien committed
51
  first_argument = (char *) mxCalloc(buflen, sizeof(char));
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
52
  size_t status = mxGetString(mxa, first_argument, buflen);
53
54
55
56
57
58
  if (status != 0)
    mexWarnMsgTxt("Not enough space. The first argument is truncated.");
  string f(first_argument);
  mxFree(first_argument);
  return f;
}
59
#endif
60

Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226

//#include <windows.h> 
#include <stdio.h> 
 

#ifdef CUDA
int
GPU_Test_and_Info(cublasHandle_t *cublas_handle, cusparseHandle_t *cusparse_handle, cusparseMatDescr_t *descr)
{
  cudaDeviceProp deviceProp;
  int device_count, device, version, version_max = 0;
  cublasStatus_t cublas_status;
  cudaError_t cuda_error;
  *descr=0;

  /* ask cuda how many devices it can find */
  cudaGetDeviceCount(&device_count);
  if (device_count < 1)
    {
      /* if it couldn't find any fail out */
      ostringstream tmp;
      tmp << " Unable to find a CUDA device. Unable to implement CUDA solvers\n";
      throw FatalExceptionHandling(tmp.str());
    }
  else
    {
      mexPrintf("-----------------------------------------\n");
      for (int i = 0; i < device_count; i++)
        {
          cudaSetDevice(i);
          // Statistics about the GPU device
          cuda_error = cudaGetDeviceProperties(&deviceProp, i);
          if (cuda_error != cudaSuccess)
            {
               ostringstream tmp;
               tmp << "  bytecode cudaGetDeviceProperties failed\n";
               throw FatalExceptionHandling(tmp.str());
            }
          mexPrintf("> GPU device %d: \"%s\" has:\n   - %d Multi-Processors,\n   - %d threads per multiprocessor,\n", i, deviceProp.name, deviceProp.multiProcessorCount, deviceProp.maxThreadsPerMultiProcessor);
          mexEvalString("drawnow;");
          version = (deviceProp.major * 0x10 + deviceProp.minor);
          if (version >= version_max)
            {
              device = i;
              version_max = version;
            }
          mexPrintf("   - %4.2fMhz clock rate,\n   - %2.0fMb of memory,\n   - %d.%d compute capabilities.\n", double(deviceProp.clockRate) / (1024 * 1024), double(deviceProp.totalGlobalMem) / (1024 * 1024), deviceProp.major, deviceProp.minor);
          mexEvalString("drawnow;");
        }
    }
  mexPrintf("> Device %d selected\n", device);
  mexEvalString("drawnow;");

  cuda_error = cudaSetDevice(device);
  if (cuda_error != cudaSuccess)
    {
       ostringstream tmp;
       tmp << "  bytecode cudaSetDevice failed\n";
       throw FatalExceptionHandling(tmp.str());
    }

  if(version_max < 0x11)
    {
       ostringstream tmp;
       tmp << "  bytecode requires a minimum CUDA compute 1.1 capability\n";
       cudaDeviceReset();
       throw FatalExceptionHandling(tmp.str());
    }

  // Initialize CuBlas library
  cublas_status = cublasCreate(cublas_handle);
  if (cublas_status != CUBLAS_STATUS_SUCCESS)
    {
      ostringstream tmp;
      switch(cublas_status)
        {
          case CUBLAS_STATUS_NOT_INITIALIZED:
            tmp << " the CUBLAS initialization failed.\n";
            break;
          case CUBLAS_STATUS_ALLOC_FAILED:
            tmp << " the resources could not be allocated.\n";
            break;
          default:
            tmp << " unknown error during the initialization of cusparse library.\n";
        }
      throw FatalExceptionHandling(tmp.str());
    }

  // Initialize the CuSparse library
  cusparseStatus_t cusparse_status;
  cusparse_status = cusparseCreate(cusparse_handle);
  if (cusparse_status != CUSPARSE_STATUS_SUCCESS)
    {
      ostringstream tmp;
      switch(cusparse_status)
        {
          case CUSPARSE_STATUS_NOT_INITIALIZED:
            tmp << " the CUDA Runtime initialization failed.\n";
            break;
          case CUSPARSE_STATUS_ALLOC_FAILED:
            tmp <<  " the resources could not be allocated.\n";
            break;
          case CUSPARSE_STATUS_ARCH_MISMATCH:
            tmp <<  " the device compute capability (CC) is less than 1.1. The CC of at least 1.1 is required.\n";
            break;
          default:
            tmp << " unknown error during the initialization of cusparse library.\n";
        }
      throw FatalExceptionHandling(tmp.str());
    }

  // Create and setup matrix descriptor
  cusparse_status = cusparseCreateMatDescr(descr);
  if (cusparse_status != CUSPARSE_STATUS_SUCCESS)
    {
      ostringstream tmp;
      tmp << " Matrix descriptor initialization failed\n";
      throw FatalExceptionHandling(tmp.str());
    }
  cusparseSetMatType(*descr, CUSPARSE_MATRIX_TYPE_GENERAL);
  cusparseSetMatIndexBase(*descr, CUSPARSE_INDEX_BASE_ZERO);

  mexPrintf("> Driver version:\n");
  int cuda_version;
  cuda_error = cudaDriverGetVersion(&cuda_version);
  if (cuda_error  != cudaSuccess)
    {
      ostringstream tmp;
      tmp << " cudaGetVersion has failed\n";
      throw FatalExceptionHandling(tmp.str());
    }
  mexPrintf("   - CUDA version %5.3f\n", double(cuda_version) / 1000);
  int cublas_version;
  cublas_status = cublasGetVersion(*cublas_handle, &cublas_version);
  if (cublas_status != CUBLAS_STATUS_SUCCESS)
    {
      ostringstream tmp;
      tmp << " cublasGetVersion has failed\n";
      throw FatalExceptionHandling(tmp.str());
    }
  mexPrintf("   - CUBLAS version %5.3f\n", double(cublas_version) / 1000);
  int cusparse_version;
  cusparse_status = cusparseGetVersion(*cusparse_handle, &cusparse_version);
  if (cusparse_status != CUSPARSE_STATUS_SUCCESS)
    {
      ostringstream tmp;
      tmp << " cusparseGetVersion has failed\n";
      throw FatalExceptionHandling(tmp.str());
    }
  mexPrintf("   - CUSPARSE version %5.3f\n", double(cusparse_version) / 1000);
  mexPrintf("-----------------------------------------\n");
  return device;
}

void
GPU_close(cublasHandle_t cublas_handle, cusparseHandle_t cusparse_handle, cusparseMatDescr_t descr)
{
  cublasChk(cublasDestroy(cublas_handle),"in bytecode cublasDestroy failed\n");
  cusparseChk(cusparseDestroyMatDescr(descr), "in bytecode cusparseDestroyMatDescr failed\n");
  cusparseChk(cusparseDestroy(cusparse_handle),"in bytecode cusparseDestroy failed\n");
}

#endif
string
deblank(string x)
{
227
  for(int i = 0; i < (int) x.length(); i++)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
228
229
230
231
232
    if (x[i] == ' ')
      x.erase(i--, 1);
  return x;
}

sebastien's avatar
sebastien committed
233
void
234
Get_Arguments_and_global_variables(int nrhs,
235
#ifndef DEBUG_EX
236
                                   const mxArray *prhs[],
237
#else
238
                                   const char *prhs[],
239
#endif
240
                                   int &count_array_argument,
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
241
242
243
244
                                   double *yd[], size_t &row_y, size_t &col_y,
                                   double *xd[], size_t &row_x, size_t &col_x,
                                   double *params[],
                                   double *steady_yd[], size_t &steady_row_y, size_t &steady_col_y,
245
                                   unsigned int &periods,
246
247
248
249
#ifndef DEBUG_EX
                                   mxArray *block_structur[],
#endif
                                   bool &steady_state, bool &evaluate, int &block,
250
                                   mxArray *M_[], mxArray *oo_[], mxArray *options_[], bool &global_temporary_terms,
251
                                   bool &print,
252
                                   bool &print_error,
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
253
254
                                   mxArray *GlobalTemporaryTerms[],
                                   string *plan_struct_name, string *pfplan_struct_name)
255
{
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
256
  size_t pos;
257
#ifdef DEBUG_EX
258
  for (int i = 2; i < nrhs; i++)
259
#else
260
    for (int i = 0; i < nrhs; i++)
261
#endif
262
      {
263
#ifndef DEBUG_EX
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
        if (!mxIsChar(prhs[i]))
          {
            switch (count_array_argument)
              {
              case 0:
                *yd = mxGetPr(prhs[i]);
                row_y = mxGetM(prhs[i]);
                col_y = mxGetN(prhs[i]);
                break;
              case 1:
                *xd =  mxGetPr(prhs[i]);
                row_x = mxGetM(prhs[i]);
                col_x = mxGetN(prhs[i]);
                break;
              case 2:
                *params = mxGetPr(prhs[i]);
                break;
              case 3:
282
283
284
                *steady_yd = mxGetPr(prhs[i]);
                steady_row_y = mxGetM(prhs[i]);
                steady_col_y = mxGetN(prhs[i]);
285
286
                break;
              case 4:
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
287
                periods = int(mxGetScalar(prhs[i]));
288
289
                break;
              case 5:
290
291
292
                *block_structur = mxDuplicateArray(prhs[i]);
                break;
              case 6:
293
294
295
296
                global_temporary_terms = true;
                *GlobalTemporaryTerms = mxDuplicateArray(prhs[i]);
                break;
              default:
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
297
                mexPrintf("Unknown argument count_array_argument=%d\n",count_array_argument);
298
299
300
301
302
                break;
              }
            count_array_argument++;
          }
        else
303
#endif
304
305
306
307
308
309
310
311
312
313
          if (Get_Argument(prhs[i]) == "static")
            steady_state = true;
          else if (Get_Argument(prhs[i]) == "dynamic")
            steady_state = false;
          else if (Get_Argument(prhs[i]) == "evaluate")
            evaluate = true;
          else if (Get_Argument(prhs[i]) == "global_temporary_terms")
            global_temporary_terms = true;
          else if (Get_Argument(prhs[i]) == "print")
            print = true;
314
315
          else if (Get_Argument(prhs[i]) == "no_print_error")
            print_error = false;
316
317
          else
            {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
318
              ;
319
              if ((pos = Get_Argument(prhs[i]).find("block")) != string::npos)
320
                {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
321
                  size_t pos1 = Get_Argument(prhs[i]).find("=", pos+5);
322
                  if (pos1 != string::npos)
323
324
325
326
327
                    pos = pos1 + 1;
                  else
                    pos += 5;
                  block =  atoi(Get_Argument(prhs[i]).substr(pos, string::npos).c_str())-1;
                }
328
              else if ((pos = Get_Argument(prhs[i]).find("pfplan")) != string::npos)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
329
330
                {
                  size_t pos1 = Get_Argument(prhs[i]).find("=", pos+6);
331
                  if (pos1 != string::npos)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
332
333
334
335
336
                    pos = pos1 + 1;
                  else
                    pos += 6;
                  *pfplan_struct_name =  deblank(Get_Argument(prhs[i]).substr(pos, string::npos));
                }
337
              else if ((pos = Get_Argument(prhs[i]).find("plan")) != string::npos)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
338
339
                {
                  size_t pos1 = Get_Argument(prhs[i]).find("=", pos+4);
340
                  if (pos1 != string::npos)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
341
342
343
344
345
                    pos = pos1 + 1;
                  else
                    pos += 4;
                  *plan_struct_name =  deblank(Get_Argument(prhs[i]).substr(pos, string::npos));
                }
346
347
348
349
350
351
              else
                {
                  ostringstream tmp;
                  tmp << " in main, unknown argument : " << Get_Argument(prhs[i]) << "\n";
                  throw FatalExceptionHandling(tmp.str());
                }
352
            }
353
      }
354
  if (count_array_argument > 0 && count_array_argument < 5)
355
    {
356
357
358
359
360
      if (count_array_argument == 3 && steady_state)
        periods = 1;
      else
        {
          ostringstream tmp;
361
          tmp << " in main, missing arguments. All the following arguments have to be indicated y, x, params, it_, ys\n";
362
363
          throw FatalExceptionHandling(tmp.str());
        }
364
    }
365
  *M_ = mexGetVariable("global", "M_");
sebastien's avatar
sebastien committed
366
  if (M_ == NULL)
367
    {
368
369
370
      ostringstream tmp;
      tmp << " in main, global variable not found: M_\n";
      throw FatalExceptionHandling(tmp.str());
371
372
    }
  /* Gets variables and parameters from global workspace of Matlab */
373
  *oo_ = mexGetVariable("global", "oo_");
sebastien's avatar
sebastien committed
374
  if (oo_ == NULL)
375
    {
376
377
378
      ostringstream tmp;
      tmp << " in main, global variable not found: oo_\n";
      throw FatalExceptionHandling(tmp.str());
379
    }
380
  *options_ = mexGetVariable("global", "options_");
sebastien's avatar
sebastien committed
381
  if (options_ == NULL)
382
    {
383
384
385
      ostringstream tmp;
      tmp << " in main, global variable not found: options_\n";
      throw FatalExceptionHandling(tmp.str());
386
    }
387
388
}

Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
389

390
391
392
393
394
#ifdef DEBUG_EX
int
main(int nrhs, const char *prhs[])
#else
/* The gateway routine */
395
396
  void
  mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
397
398
399
#endif
{
  mxArray *M_, *oo_, *options_;
400
  mxArray *GlobalTemporaryTerms;
401
402
403
404
405
#ifndef DEBUG_EX
  mxArray *block_structur = NULL;
#else
  int nlhs = 0;
  char *plhs[1];
406
  load_global((char *) prhs[1]);
407
#endif
408
  mxArray *pfplan_struct = NULL;
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
409
410
  size_t i, row_y = 0, col_y = 0, row_x = 0, col_x = 0, nb_row_xd = 0;
  size_t steady_row_y, steady_col_y;
411
412
413
414
415
416
417
418
419
  int y_kmin = 0, y_kmax = 0, y_decal = 0;
  unsigned int periods = 1;
  double *direction;
  bool steady_state = false;
  bool evaluate = false;
  int block = -1;
  double *params = NULL;
  double *yd = NULL, *xd = NULL;
  int count_array_argument = 0;
420
  bool global_temporary_terms = false;
421
  bool print = false, print_error = true, print_it = false;
422
  double *steady_yd = NULL, *steady_xd = NULL;
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
423
424
425
426
427
428
429
430
431
432
  string plan, pfplan;

  vector<s_plan> splan, spfplan;

#ifdef CUDA
  int CUDA_device = -1;
  cublasHandle_t cublas_handle;
  cusparseHandle_t cusparse_handle;
  cusparseMatDescr_t descr;
#endif
433
434
435
  try
    {
      Get_Arguments_and_global_variables(nrhs, prhs, count_array_argument,
436
437
                                         &yd, row_y, col_y,
                                         &xd, row_x, col_x,
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
438
                                         &params,
439
440
                                         &steady_yd, steady_row_y, steady_col_y,
                                         periods,
441
#ifndef DEBUG_EX
442
                                         &block_structur,
443
#endif
444
445
                                         steady_state, evaluate, block,
                                         &M_, &oo_, &options_, global_temporary_terms,
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
446
447
                                         print, print_error, &GlobalTemporaryTerms,
                                         &plan, &pfplan);
448
449
450
451
452
    }
  catch (GeneralExceptionHandling &feh)
    {
      DYN_MEX_FUNC_ERR_MSG_TXT(feh.GetErrorMsg().c_str());
    }
453
  if (!count_array_argument)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
454
455
456
457
458
459
    {
      int field = mxGetFieldNumber(M_, "params");
      if (field < 0)
        DYN_MEX_FUNC_ERR_MSG_TXT("params is not a field of M_");
      params = mxGetPr(mxGetFieldByNumber(M_, 0, field));
    }
460

Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
461
  ErrorMsg emsg;
462
  
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
463
464
465
466
467
468
469
470
471
472
473
474
475


  if (plan.length()>0)
    {
      mxArray* plan_struct = mexGetVariable("base", plan.c_str());
      if (plan_struct == NULL)
        {
          string tmp = plan;
          tmp.insert(0,"Can't find the plan: ");
          DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
        }
      size_t n_plan = mxGetN(plan_struct);
      splan.resize(n_plan);
476
      for (int i = 0; i < (int) n_plan; i++)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
        {
          splan[i].var = "";
          splan[i].exo = "";
          mxArray* tmp = mxGetField(plan_struct, i, "exo");
          if (tmp)
            {
              char name [100];
              mxGetString(tmp, name, 100);
              splan[i].var = name;
              SymbolType variable_type;
              int exo_num = emsg.get_ID(name, &variable_type);
              if (variable_type == eExogenous || variable_type == eExogenousDet)
                splan[i].var_num = exo_num;
              else
                {
                  string tmp = name;
                  tmp.insert(0,"the variable '");
                  tmp.append("'  defined as var in plan is not an exogenous or a deterministic exogenous\n");
                  DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
                }
            }
          tmp = mxGetField(plan_struct, i, "var");
          if (tmp)
            {
              char name [100];
              mxGetString(tmp, name, 100);
              splan[i].exo = name;
              SymbolType variable_type;
              int exo_num = emsg.get_ID(name, &variable_type);
              if (variable_type == eEndogenous)
                splan[i].exo_num = exo_num;
              else
                {
                  string tmp = name;
                  tmp.insert(0,"the variable '");
                  tmp.append("'  defined as exo in plan is not an endogenous variable\n");
                  DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
                }
            }
          tmp = mxGetField(plan_struct, i, "per_value");
          if (tmp)
            {
              size_t num_shocks = mxGetM(tmp);
              (splan[i]).per_value.resize(num_shocks);
              double * per_value = mxGetPr(tmp);
522
              for (int j = 0; j < (int) num_shocks; j++)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
523
524
525
                (splan[i]).per_value[j] = make_pair(ceil(per_value[j]), per_value[j + num_shocks]);
            }
        }
526
      int i = 0;
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
      for (vector<s_plan>::iterator it = splan.begin(); it != splan.end(); it++)
        {
          mexPrintf("----------------------------------------------------------------------------------------------------\n");
          mexPrintf("suprise n%d\n", i+1);
          if (it->exo.length())
            mexPrintf(" plan fliping var=%s (%d) exo=%s (%d) for the following periods and with the following values:\n", it->var.c_str(), it->var_num, it->exo.c_str(), it->exo_num);
          else
            mexPrintf(" plan shocks on var=%s for the following periods and with the following values:\n", it->var.c_str());
          for (vector<pair<int, double> >::iterator it1 = it->per_value.begin(); it1 != it->per_value.end(); it1++)
            {
              mexPrintf("  %3d %10.5f\n",it1->first, it1->second);
            }
          i++;
        }
    }

  if (pfplan.length()>0)
    {
      pfplan_struct = mexGetVariable("base", pfplan.c_str());
      if (!pfplan_struct)
        {
          string tmp = pfplan;
          tmp.insert(0,"Can't find the pfplan: ");
          DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
        }
      size_t n_plan = mxGetN(pfplan_struct);
      spfplan.resize(n_plan);
554
      for (int i = 0; i < (int) n_plan; i++)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
        {
          spfplan[i].var = "";
          spfplan[i].exo = "";
          mxArray* tmp = mxGetField(pfplan_struct, i, "var");
          if (tmp)
            {
              char name [100];
              mxGetString(tmp, name, 100);
              spfplan[i].var = name;
              SymbolType variable_type;
              int exo_num = emsg.get_ID(name, &variable_type);
              if (variable_type == eExogenous || variable_type == eExogenousDet)
                splan[i].var_num = exo_num;
              else
                {
                  string tmp = name;
                  tmp.insert(0,"the variable '");
                  tmp.append("' defined as var in pfplan is not an exogenous or a deterministic exogenous\n");
                  DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
                }
            }
          tmp = mxGetField(pfplan_struct, i, "exo");
          if (tmp)
            {
              char name [100];
              mxGetString(tmp, name, 100);
              spfplan[i].exo = name;
              SymbolType variable_type;
              int exo_num = emsg.get_ID(name, &variable_type);
              if (variable_type == eEndogenous)
                spfplan[i].exo_num = exo_num;
              else
                {
                  string tmp = name;
                  tmp.insert(0,"the variable '");
                  tmp.append("' defined as exo in pfplan  is not an endogenous variable\n");
                  DYN_MEX_FUNC_ERR_MSG_TXT(tmp.c_str());
                }
            }
          tmp = mxGetField(pfplan_struct, i, "per_value");
          if (tmp)
            {
              size_t num_shocks = mxGetM(tmp);
              double * per_value = mxGetPr(tmp);
              (spfplan[i]).per_value.resize(num_shocks);
600
              for (int j = 0; j < (int) num_shocks; j++)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
601
602
603
                spfplan[i].per_value[j] = make_pair(ceil(per_value[j]), per_value[j+ num_shocks]);
            }
        }
604
      int i = 0;
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
      for (vector<s_plan>::iterator it = spfplan.begin(); it != spfplan.end(); it++)
        {
          mexPrintf("----------------------------------------------------------------------------------------------------\n");
          mexPrintf("perfect foresight n%d\n", i+1);
          if (it->exo.length())
            mexPrintf(" plan flipping var=%s (%d) exo=%s (%d) for the following periods and with the following values:\n", it->var.c_str(), it->var_num, it->exo.c_str(), it->exo_num);
          else
            mexPrintf(" plan shocks on var=%s (%d) for the following periods and with the following values:\n", it->var.c_str(), it->var_num);
          for (vector<pair<int, double> >::iterator it1 = it->per_value.begin(); it1 != it->per_value.end(); it1++)
            {
              mexPrintf("  %3d %10.5f\n",it1->first, it1->second);
            }
          i++;
        }
    }



  int field_steady_state = mxGetFieldNumber(oo_, "steady_state");
  if (field_steady_state < 0)
    DYN_MEX_FUNC_ERR_MSG_TXT("steady_state is not a field of oo_");
  int field_exo_steady_state = mxGetFieldNumber(oo_, "exo_steady_state");
  if (field_exo_steady_state < 0)
    DYN_MEX_FUNC_ERR_MSG_TXT("exo_steady_state is not a field of oo_");

sebastien's avatar
sebastien committed
630
  if (!steady_state)
631
    {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
632
633
634
635
636
637
638
639
      int field_endo_simul = mxGetFieldNumber(oo_, "endo_simul");
      if (field_endo_simul < 0)
        DYN_MEX_FUNC_ERR_MSG_TXT("endo_simul is not a field of oo_");

      int field_exo_simul = mxGetFieldNumber(oo_, "exo_simul");
      if (field_exo_simul < 0)
        DYN_MEX_FUNC_ERR_MSG_TXT("exo_simul is not a field of oo_");

640
641
      if (!count_array_argument)
        {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
642
643
644
645
646
647
648
649
          mxArray* endo_sim_arr = mxGetFieldByNumber(oo_, 0, field_endo_simul);
          yd = mxGetPr(endo_sim_arr);
          row_y = mxGetM(endo_sim_arr);
          col_y = mxGetN(endo_sim_arr);
          mxArray* exo_sim_arr = mxGetFieldByNumber(oo_, 0, field_exo_simul);
          xd = mxGetPr(exo_sim_arr);
          row_x = mxGetM(exo_sim_arr);
          col_x = mxGetN(exo_sim_arr);
650
          nb_row_xd = row_x;
651
        }
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
      int field = mxGetFieldNumber(M_, "maximum_lag");
      if (field >= 0)
        y_kmin = int (floor(*(mxGetPr(mxGetFieldByNumber(M_, 0, field)))));
      else
        DYN_MEX_FUNC_ERR_MSG_TXT("maximum_lag is not a field of M_");
      field = mxGetFieldNumber(M_, "maximum_lead");
      if (field >= 0)
        y_kmax = int (floor(*(mxGetPr(mxGetFieldByNumber(M_, 0, field)))));
      else
        DYN_MEX_FUNC_ERR_MSG_TXT("maximum_lead is not a field of M_");
      field = mxGetFieldNumber(M_, "maximum_endo_lag");
      if (field >= 0)
        y_decal = max(0, y_kmin-int (floor(*(mxGetPr(mxGetFieldByNumber(M_, 0, field))))));
      else
        DYN_MEX_FUNC_ERR_MSG_TXT("maximum_endo_lag is not a field of M_");
667

668
      if (!count_array_argument)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
669
670
671
672
673
674
675
676
        {
          int field = mxGetFieldNumber(options_, "periods");
          if (field >= 0)
            periods = int (floor(*(mxGetPr(mxGetFieldByNumber(options_, 0, field)))));
          else
            DYN_MEX_FUNC_ERR_MSG_TXT("options_ is not a field of options_");
        }

677
678
      if (!steady_yd )
        {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
679
680
681
682
          mxArray* steady_state_arr = mxGetFieldByNumber(oo_, 0, field_steady_state);
          steady_yd = mxGetPr(steady_state_arr);
          steady_row_y = mxGetM(steady_state_arr);
          steady_col_y = mxGetN(steady_state_arr);
683
        }
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
684
      steady_xd = mxGetPr(mxGetFieldByNumber(oo_, 0, field_exo_steady_state));
sebastien's avatar
sebastien committed
685
686
687
    }
  else
    {
688
689
      if (!count_array_argument)
        {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
690
691
692
693
          mxArray* steady_state_arr = mxGetFieldByNumber(oo_, 0, field_steady_state);
          yd = mxGetPr(steady_state_arr);
          row_y = mxGetM(steady_state_arr);
          col_y = mxGetN(steady_state_arr);
694

Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
695
696
697
698
          mxArray* exo_steady_state_arr = mxGetFieldByNumber(oo_, 0, field_exo_steady_state);
          xd = mxGetPr(exo_steady_state_arr);
          row_x = mxGetM(exo_steady_state_arr);
          col_x = mxGetN(exo_steady_state_arr);
699
          nb_row_xd = row_x;
700
        }
701
    }
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
702
703
704
705
706
707
  int field = mxGetFieldNumber(options_, "verbosity");
  int verbose = 0;
  if (field >= 0)
    verbose = int(*mxGetPr((mxGetFieldByNumber(options_, 0, field))));
  else
    DYN_MEX_FUNC_ERR_MSG_TXT("verbosity is not a field of options_");
708
709
  if (verbose)
    print_it = true;
710
  field = mxGetFieldNumber(options_, "simul.maxit");// Not sure of that...
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
711
  if (field < 0)
712
    DYN_MEX_FUNC_ERR_MSG_TXT("simul.maxit is not a field of options_");
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
  int maxit_ = int (floor(*(mxGetPr(mxGetFieldByNumber(options_, 0, field)))));
  field = mxGetFieldNumber(options_, "slowc");
  if (field < 0)
    DYN_MEX_FUNC_ERR_MSG_TXT("slows is not a field of options_");
  double slowc = double (*(mxGetPr(mxGetFieldByNumber(options_, 0, field))));
  field = mxGetFieldNumber(options_, "markowitz");
  if (field < 0)
    DYN_MEX_FUNC_ERR_MSG_TXT("markowitz is not a field of options_");
  double markowitz_c = double (*(mxGetPr(mxGetFieldByNumber(options_, 0, field))));
  field = mxGetFieldNumber(options_, "minimal_solving_periods");
  if (field < 0)
    DYN_MEX_FUNC_ERR_MSG_TXT("minimal_solving_periods is not a field of options_");
  int minimal_solving_periods = int (*(mxGetPr(mxGetFieldByNumber(options_, 0, field))));
  field = mxGetFieldNumber(options_, "stack_solve_algo");
  if (field < 0)
    DYN_MEX_FUNC_ERR_MSG_TXT("stack_solve_algo is not a field of options_");
  int stack_solve_algo = int (*(mxGetPr(mxGetFieldByNumber(options_, 0, field))));
730
  int solve_algo;
731
  double solve_tolf;
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
732

sebastien's avatar
sebastien committed
733
  if (steady_state)
734
    {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
735
736
737
738
739
740
741
742
743
744
      int field = mxGetFieldNumber(options_, "solve_algo");
      if (field >= 0)
        solve_algo = int (*(mxGetPr(mxGetFieldByNumber(options_, 0, field))));
      else
        DYN_MEX_FUNC_ERR_MSG_TXT("solve_algo is not a field of options_");
      field = mxGetFieldNumber(options_, "solve_tolf");
      if (field >= 0)
        solve_tolf = *(mxGetPr(mxGetFieldByNumber(options_, 0, field)));
      else
        DYN_MEX_FUNC_ERR_MSG_TXT("solve_tolf is not a field of options_");
745
    }
sebastien's avatar
sebastien committed
746
  else
747
748
    {
      solve_algo = stack_solve_algo;
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
749
750
751
752
753
754
755
756
757
758
759
      int field = mxGetFieldNumber(options_, "dynatol");
      mxArray *dynatol;
      if (field >= 0)
        dynatol = mxGetFieldByNumber(options_, 0, field);
      else
        DYN_MEX_FUNC_ERR_MSG_TXT("dynatol is not a field of options_");
      field = mxGetFieldNumber(dynatol, "f");
      if (field >= 0)
        solve_tolf= *mxGetPr((mxGetFieldByNumber(dynatol, 0, field)));
      else
        DYN_MEX_FUNC_ERR_MSG_TXT("f is not a field of options_.dynatol");
760
    }
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
761
762
763
764
765
766
767
  field = mxGetFieldNumber(M_, "fname");
  mxArray *mxa;
  if (field >= 0)
    mxa = mxGetFieldByNumber(M_, 0, field);
  else
    DYN_MEX_FUNC_ERR_MSG_TXT("fname is not a field of M_");
  size_t buflen = mxGetM(mxa) * mxGetN(mxa) + 1;
768
  char *fname;
769
  fname = (char *) mxCalloc(buflen+1, sizeof(char));
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
770
  size_t status = mxGetString(mxa, fname, int(buflen));
771
  fname[buflen] = ' ';
772
773
  if (status != 0)
    mexWarnMsgTxt("Not enough space. Filename is truncated.");
774
  string file_name = fname;
775

Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
#ifdef CUDA
  try
    {
      if (stack_solve_algo == 7 && !steady_state)
        CUDA_device = GPU_Test_and_Info(&cublas_handle, &cusparse_handle, &descr);
    }
  catch (GeneralExceptionHandling &feh)
    {
      DYN_MEX_FUNC_ERR_MSG_TXT(feh.GetErrorMsg().c_str());
    }
#else
  if (stack_solve_algo == 7 && !steady_state)
    DYN_MEX_FUNC_ERR_MSG_TXT("bytecode has not been compiled with CUDA option. Bytecode Can't use options_.stack_solve_algo=7\n");
#endif

  size_t size_of_direction = col_y*row_y*sizeof(double);
sebastien's avatar
sebastien committed
792
793
794
795
796
797
  double *y = (double *) mxMalloc(size_of_direction);
  double *ya = (double *) mxMalloc(size_of_direction);
  direction = (double *) mxMalloc(size_of_direction);
  memset(direction, 0, size_of_direction);
  double *x = (double *) mxMalloc(col_x*row_x*sizeof(double));
  for (i = 0; i < row_x*col_x; i++)
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
798
799
800
    {
      x[i] = double (xd[i]);
    }
sebastien's avatar
sebastien committed
801
  for (i = 0; i < row_y*col_y; i++)
802
    {
sebastien's avatar
sebastien committed
803
804
      y[i]  = double (yd[i]);
      ya[i] = double (yd[i]);
805
    }
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
806
807
  size_t y_size = row_y;
  size_t nb_row_x = row_x;
sebastien's avatar
sebastien committed
808
  clock_t t0 = clock();
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
809
810
811
812
813
814
815
  Interpreter interprete(params, y, ya, x, steady_yd, steady_xd, direction, y_size, nb_row_x, nb_row_xd, periods, y_kmin, y_kmax, maxit_, solve_tolf, size_of_direction, slowc, y_decal,
                         markowitz_c, file_name, minimal_solving_periods, stack_solve_algo, solve_algo, global_temporary_terms, print, print_error, GlobalTemporaryTerms, steady_state,
                         print_it
#ifdef CUDA
                         , CUDA_device, cublas_handle, cusparse_handle, descr
#endif
                         );
816
  string f(fname);
817
  mxFree(fname);
818
  int nb_blocks = 0;
819
  double *pind;
820
  bool no_error = true;
821
822
  try
    {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
823
      interprete.compute_blocks(f, f, evaluate, block, nb_blocks);
824
825
826
827
828
829
    }
  catch (GeneralExceptionHandling &feh)
    {
      DYN_MEX_FUNC_ERR_MSG_TXT(feh.GetErrorMsg().c_str());
    }

Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
830
831
832
833
834
#ifdef CUDA
  if (stack_solve_algo == 7 && !steady_state)
    GPU_close(cublas_handle, cusparse_handle, descr);
#endif

sebastien's avatar
sebastien committed
835
  clock_t t1 = clock();
836
  if (!steady_state && !evaluate && no_error && print)
sebastien's avatar
sebastien committed
837
    mexPrintf("Simulation Time=%f milliseconds\n", 1000.0*(double (t1)-double (t0))/double (CLOCKS_PER_SEC));
838
#ifndef DEBUG_EX
839
  bool dont_store_a_structure = false;
sebastien's avatar
sebastien committed
840
  if (nlhs > 0)
841
    {
842
      plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
843
      pind = mxGetPr(plhs[0]);
844
845
      if (no_error)
        pind[0] = 0;
846
      else
847
        pind[0] = 1;
sebastien's avatar
sebastien committed
848
849
      if (nlhs > 1)
        {
850
851
852
853
854
          if (block >= 0)
            {
              if (evaluate)
                {
                  vector<double> residual = interprete.get_residual();
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
855
                  plhs[1] = mxCreateDoubleMatrix(int(residual.size()/double(col_y)), int(col_y), mxREAL);
856
857
858
859
860
861
                  pind = mxGetPr(plhs[1]);
                  for (i = 0; i < residual.size(); i++)
                    pind[i] = residual[i];
                }
              else
                {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
862
                  plhs[1] = mxCreateDoubleMatrix(int(row_y), int(col_y), mxREAL);
863
864
865
866
867
                  pind = mxGetPr(plhs[1]);
                  for (i = 0; i < row_y*col_y; i++)
                    pind[i] = y[i];
                }
            }
sebastien's avatar
sebastien committed
868
          else
869
            {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
870
              plhs[1] = mxCreateDoubleMatrix(int(row_y), int(col_y), mxREAL);
871
872
              pind = mxGetPr(plhs[1]);
              if (evaluate)
873
874
875
876
877
                {
                  vector<double> residual = interprete.get_residual();
                  for (i = 0; i < residual.size(); i++)
                    pind[i] = residual[i];
                }
878
879
              else
                for (i = 0; i < row_y*col_y; i++)
880
                  pind[i] = y[i];
881
            }
882
883
          if (nlhs > 2)
            {
884
              if (evaluate)
885
                {
886
887
888
                  int jacob_field_number = 0, jacob_exo_field_number = 0, jacob_exo_det_field_number = 0, jacob_other_endo_field_number = 0;
                  if (!block_structur)
                    {
889
890
891
892
                      const char *field_names[] = {"g1", "g1_x", "g1_xd", "g1_o"};
                      jacob_field_number = 0;
                      jacob_exo_field_number = 1;
                      jacob_exo_det_field_number = 2;
893
                      jacob_other_endo_field_number = 3;
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
894
                      mwSize dims[1] = {(mwSize)nb_blocks };
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
                      plhs[2] = mxCreateStructArray(1, dims, 4, field_names);
                    }
                  else if (!mxIsStruct(block_structur))
                    {
                      plhs[2] = interprete.get_jacob(0);
                      //mexCallMATLAB(0,NULL, 1, &plhs[2], "disp");
                      dont_store_a_structure = true;
                    }
                  else
                    {
                      plhs[2] = block_structur;
                      jacob_field_number = mxAddField(plhs[2], "g1");
                      if (jacob_field_number == -1)
                        DYN_MEX_FUNC_ERR_MSG_TXT("Fatal error in bytecode: in main, cannot add extra field jacob to the structArray\n");
                      jacob_exo_field_number = mxAddField(plhs[2], "g1_x");
                      if (jacob_exo_field_number == -1)
                        DYN_MEX_FUNC_ERR_MSG_TXT("Fatal error in bytecode: in main, cannot add extra field jacob_exo to the structArray\n");
                      jacob_exo_det_field_number = mxAddField(plhs[2], "g1_xd");
                      if (jacob_exo_det_field_number == -1)
                        DYN_MEX_FUNC_ERR_MSG_TXT("Fatal error in bytecode: in main, cannot add extra field jacob_exo_det to the structArray\n");
                      jacob_other_endo_field_number = mxAddField(plhs[2], "g1_o");
                      if (jacob_other_endo_field_number == -1)
                        DYN_MEX_FUNC_ERR_MSG_TXT("Fatal error in bytecode: in main, cannot add extra field jacob_other_endo to the structArray\n");
                    }
                  if (!dont_store_a_structure)
                    {
                      for (int i = 0; i < nb_blocks; i++)
922
923
                        {
                          mxSetFieldByNumber(plhs[2], i, jacob_field_number, interprete.get_jacob(i));
924
925
926
927
928
929
                          if (!steady_state)
                            {
                              mxSetFieldByNumber(plhs[2], i, jacob_exo_field_number, interprete.get_jacob_exo(i));
                              mxSetFieldByNumber(plhs[2], i, jacob_exo_det_field_number, interprete.get_jacob_exo_det(i));
                              mxSetFieldByNumber(plhs[2], i, jacob_other_endo_field_number, interprete.get_jacob_other_endo(i));
                            }
930
931
                        }
                    }
932
                }
933
              else
934
                {
935
936
937
                  plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL);
                  pind = mxGetPr(plhs[0]);
                  pind[0] = NAN;
938
939
                }
              if (nlhs > 3)
940
                {
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
941
                  plhs[3] = mxCreateDoubleMatrix(int(row_y), int(col_y), mxREAL);
942
943
944
                  pind = mxGetPr(plhs[3]);
                  for (i = 0; i < row_y*col_y; i++)
                    pind[i] = y[i];
945
946
                  if (nlhs > 4)
                    {
947
                      mxArray *GlobalTemporaryTerms = interprete.get_Temporary_Terms();
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
948
949
                      size_t nb_temp_terms = mxGetM(GlobalTemporaryTerms);
                      plhs[4] = mxCreateDoubleMatrix(int(nb_temp_terms), 1, mxREAL);
950
951
952
953
954
                      pind = mxGetPr(plhs[4]);
                      double *tt = mxGetPr(GlobalTemporaryTerms);
                      for (i = 0; i < nb_temp_terms; i++)
                        pind[i] = tt[i];
                    }
955
                }
956

957
            }
sebastien's avatar
sebastien committed
958
        }
959
    }
960
961
962
#else
  Free_global();
#endif
sebastien's avatar
sebastien committed
963
  if (x)
ferhat's avatar
ferhat committed
964
    mxFree(x);
sebastien's avatar
sebastien committed
965
  if (y)
ferhat's avatar
ferhat committed
966
    mxFree(y);
sebastien's avatar
sebastien committed
967
  if (ya)
ferhat's avatar
ferhat committed
968
    mxFree(ya);
sebastien's avatar
sebastien committed
969
  if (direction)
ferhat's avatar
ferhat committed
970
    mxFree(direction);
Ferhat Mihoubi's avatar
Ferhat Mihoubi committed
971
972
973
974
#ifdef _MSC_VER_
  /*fFreeResult =*/ FreeLibrary(hinstLib);
#endif
  return;
975
}