mex_ms_sbvar.cc 19.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
 * Copyright (C) 2011 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/>.
 */

#if defined(MATLAB_MEX_FILE) || defined(OCTAVE_MEX_FILE)
#include "dynmex.h"

#include "mex_ms_sbvar.h"

#include <iostream>
#include <fstream>

extern "C"  {
#include "modify_for_mex.h"
#include "switch.h"
#include "switchio.h"
#include "VARio.h"
#include "dw_rand.h"
}

using namespace std;

int
file_exist(char *filename)
{
  int ret = 0;
  char ch;

  ifstream fin;
  fin.open(filename, ios_base::in);
  if (fin.is_open() && fin.get(ch))
    ret = 1;

  fin.close();
  return ret;
}

char *
CreateFilenameFromTag(const char *fmt, const char *tag, const char *dir)
{
  char *filename;
  if (!tag)
    tag = "";
  if (!dir)
    dir = "";
  sprintf(filename = (char *) mxMalloc(strlen(dir) + strlen(fmt) + strlen(tag) - 3), fmt, dir, tag);
  return filename;
}

/*
 *  initialize_ms_model
 *  - initiliazes a TstateModel given the filename or tagname of initialization file
 */
TStateModel *
initialize_ms_model(char *name)
{
  TStateModel *model = (TStateModel *) NULL;

  char *filename = (char *) NULL, *est_filename = (char *) NULL, *init_filename = (char *) NULL;
  est_filename = CreateFilenameFromTag("%sest_final_%s.out", name, "");
  init_filename = CreateFilenameFromTag("%sinit_%s.dat", name, "");

  if (file_exist(name))
    filename = name;
  else if (file_exist(est_filename))
    filename = est_filename;
  else if (file_exist(init_filename))
    filename = init_filename;
  else
    {
      printf("Can not open initialization or estimation file!\n");
      return (TStateModel *) NULL;
    }

  try
    {
      if (!(model = Read_VAR_Specification((FILE *) NULL, filename)))
        {
          mxFree(filename);
          printf("Can not initialize model with given name!\n");
          return (TStateModel *) NULL;
        }

      if (est_filename != NULL)
        {
          if (!strstr(est_filename, filename))
            {
              printf("Initializing with empty parameters %s\n", filename);
              // If no estimation file is around then just initialize the sizes

              double *theta = (double *) mxMalloc(sizeof(double)*NumberFreeParametersTheta(model));
              double *q = (double *) mxMalloc(sizeof(double)*NumberFreeParametersQ(model));
              ConvertFreeParametersToQ(model, q);
              ConvertFreeParametersToTheta(model, theta);
            }
        }
    }
  catch (const char *s)
    {
      printf("Error Initializing TStateModel: %s\n", s);
      model = (TStateModel *) NULL;
    }

  mxFree(filename);
  return model;
}

int
get_var_dimensions(TStateModel *model, int *nstates, int *nvars, int *npre, int *nfree)
{

  if (model)
    {
      try
        {
          *nfree = NumberFreeParametersTheta(model)+NumberFreeParametersQ(model);

          T_VAR_Parameters *p = (T_VAR_Parameters *) (model->theta);

          *nstates = model->sv->nstates;
          *nvars =  p->nvars;
          *npre = p->npre;
          return 0;
        }
      catch (const char *s)
        {
          printf("Error Getting VAR Dimensions");
          return 1;
        }

    }
  else
    {
      printf("The model passed was null!\n");
      return 1;
    }
}

int
set_parameters_in_VAR(TStateModel *model, double *free_parameters)
{
  int nfree;
  try
    {
      nfree = NumberFreeParametersTheta(model)+NumberFreeParametersQ(model);
      ConvertFreeParametersToQ(model, free_parameters+NumberFreeParametersTheta(model));
      ConvertFreeParametersToTheta(model, free_parameters);
      ComputeTransitionMatrix(0, model);
    }
  catch (const char *s)
    {
      return 1;
    }
  return 0;
}

int
convert_free_parameters_to_VAR(TStateModel *model, double *free_parameters, double *A0, double *Aplus, double *Zeta, double *Q)
{
  int nstates = 0, nvars = 0, npre = 0;
  int i = 0, j = 0, s = 0;

  if (model == NULL)
    {
      printf("The model passed was null in Convert Free Parameters!\n");
      return 1;
    }

  if (set_parameters_in_VAR(model, free_parameters) > 0)
    {
      printf("Could not set Parameters in model when converting parameters to var\n");
      return 2;
    }

  try
    {
      T_VAR_Parameters *p = (T_VAR_Parameters *) (model->theta);
      nstates = model->sv->nstates;
      nvars = p->nvars;
      npre = p->npre;

      TMatrix a = NULL, aplus = NULL;
      a = CreateMatrix(p->nvars, p->nvars);
      aplus = CreateMatrix(p->npre, p->nvars);

      // Is this is a good idea in matlab?
      if (A0 == NULL)
        A0 = new double [nstates*nvars*nvars];
      //A0 = malloc(sizeof(double)*(nstates*nvars*nvars));
      if (Aplus == NULL)
        Aplus = new double [nstates*npre*nvars];
      //Aplus = malloc(sizeof(double)*(nstates*npre*nvars));
      if (Zeta == NULL)
        Zeta = new double [nstates*nvars*nvars];
      //Zeta = malloc(sizeof(double)*(nstates*nvars*nvars));
      if (Q == NULL)
        Q = new double [nstates*nstates];
      //Q = malloc(sizeof(double)*(nstates*nstates));

      for (s = 0; s < nstates; s++)
        {
          MakeA0(a, s, p);
          for (i = 0; i < nvars; i++)
            {
              for (j = 0; j < nvars; j++)
                A0[(s)+((i+j*nvars)*nstates)] = ElementM(a, i, j);
            }
          MakeAplus(aplus, s, p);
          for (i = 0; i < npre; i++)
            {
              for (j = 0; j < nvars; j++)
                Aplus[(s)+((i+j*npre)*nstates)] = ElementM(aplus, i, j);
            }
          MakeZeta(a, s, p);
          for (i = 0; i < nvars; i++)
            {
              for (j = 0; j < nvars; j++)
                Zeta[(s)+((i+j*nvars)*nstates)] = ElementM(a, i, j);
            }
        }

      // Grand Transition Matrix
      for (i = 0; i < nstates; i++)
        for (j = 0; j < nstates; j++)
          Q[i + j*nstates] = ElementM(model->sv->Q, i, j);

      FreeMatrix(a);
      FreeMatrix(aplus);
    }
  catch (const char *s)
    {
      printf("Exception: convert_free_parameters\n");
      return 3;
    }
  return 0;
}

/*
   Additional command line parameters

   'horizon', <integer>
      If this argument exists, then the forecast horizon is given by the passed
      integer.  The default value is 12.

   'filtered'
      Uses filtered probabilities at the end of the sample as initial conditions
      for regime probabilities.  The default behavior is to us the erogdic
      distribution for the initial conditions.  This flag only applies if neither
      -regimes nor -regime is specified.

   'error_bands'
      Output error bands.  (default = off - only median is computed)

   'percentiles' n p_1 p_2 ... p_n
      Percentiles to compute. The first parameter after percentiles must be the
      number of percentiles and the following values are the actual percentiles.
      default = 3  0.16  0.50  0.84   if error_bands flag is set
              = 1  0.50               otherwise

   'parameter_uncertainty'
      Apply parameter uncertainty when computing error bands or median. When set,
      will default shocks = 1

   'shocks' or 'shocks_per_parameter', <integer>
      Number of regime paths to draw for each parameter draw.  The default value
      is 1 if parameter_uncertainty is set and 10,000 otherwise.

   'thin'
      Thinning factor.  Only 1/thin of the draws in posterior draws file are
      used. The default value is 1.

   'regimes'
      Produces forecasts as if each regime were permanent. (default = off)

   'regime' <integer>
      Produces forecasts as if regime were permanent.  Regime numbers are zero
      based.  (default = off)

   'simulation_file', <string>
      name of the file containing the model's simulated free values

   'number_observations', <integer>
         If this argument exists, then the number of data points included in the
         output is given by the passed integer int the forecast output.  The default value is 0.

   'free_parameters' <vector>:
        Vector of free paramters to initialize the model with.

   'median':
      Shortcut for setting 'percentiles',[0.5]

   'mean':
      Compute the mean, instead of percentiles

   'seed':
      Set the Seed for random number generation, default=0 (random)
 */

SbvarOption *
initialize_sbvar_options(char *file_tag)
{
  SbvarOption *options = new SbvarOption;
  options->shocks = 10000;
  options->thin = 1;
  options->horizon = 20;
  options->number_observations = 0;
  options->regime = -1;
  options->regimes = false;
  options->parameter_uncertainty = false;
  options->num_percentiles = 3;
  options->percentiles = new double[3];
  options->percentiles[0] = 0.16;
  options->percentiles[1] = 0.5;
  options->percentiles[2] = 0.84;
  options->filtered_probabilities = false;
  options->num_parameters = -1;
  options->free_parameters = (double *) NULL;
  options->mean = false;
  options->seed = 0;

  if (file_tag != NULL)
    {
      options->simulation_filename = (char *) CreateFilenameFromTag("%ssimulation_%s.out", file_tag, "");
      if (file_exist(options->simulation_filename))
        options->simulation_file = fopen(options->simulation_filename, "r");
    }
  else
    {
      options->simulation_filename = (char *) NULL;
      options->simulation_file = (FILE *) NULL;
    }
  return options;
}

int
351
set_options(SbvarOption *options, const mxArray *prhs[])
352
353
354
355
356
357
{
  if (options == NULL)
    options = initialize_sbvar_options((char *) NULL);

  double *temp_buf;
  bool shocks_passed = false;
358
359
  int num_options = mxGetN(prhs[0]);
  for (int i = 1; i < num_options; i++)
360
    {
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
      mxArray *this_option = mxGetCell(prhs[0],i);
      char *option_name_c = mxArrayToString(mxGetCell(this_option,0));
      string option_name (option_name_c);
      mxArray *this_option_value = NULL;
      if (mxGetN(this_option) > 1)
        this_option_value = mxGetCell(this_option,1);

      if (option_name == "horizon")
        if (this_option_value && mxIsNumeric(this_option_value))
          {
            temp_buf = (double *) mxGetData(this_option_value);
            options->horizon = (int) temp_buf[0];
          }
        else
          {
            cout << "You must pass an integer after specifying the 'horizon' option" << endl;
            return 1;
          }
      else if (option_name == "filtered")
        options->filtered_probabilities = true;
      else if (option_name == "error_bands")
382
        {
383
384
385
386
387
388
389
390
391
          free(options->percentiles);
          options->num_percentiles = 3;
          options->percentiles = new double[3];
          options->percentiles[0] = 0.16;
          options->percentiles[1] = 0.5;
          options->percentiles[2] = 0.84;

          // Check if the user specified to turn off error bands
          if (this_option_value && mxIsNumeric(this_option_value))
392
            {
393
394
              temp_buf = (double *) mxGetData(this_option_value);
              if (temp_buf[0] == 0)
395
                {
396
397
398
                  options->num_percentiles = 1;
                  options->percentiles = new double[1];
                  options->percentiles[0] = 0.50;
399
400
                }
            }
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
        }
      else if (option_name == "median")
        {
          free(options->percentiles);
          options->num_percentiles = 1;
          options->percentiles = new double[1];
          options->percentiles[0] = 0.5;
        }
      else if (option_name == "percentiles")
        if (this_option_value)
          {
            options->num_percentiles = mxGetN(this_option_value)
              > mxGetM(this_option_value) ? mxGetN(this_option_value)
              : mxGetM(this_option_value);
            options->percentiles = mxGetPr(this_option_value);
          }
        else
          {
            cout << "You must pass a vector after the 'percentiles' argument with the "
                 << "percentiles that you want to have computed, ex "
                 << "'percentiles',[.16 .5 .84]" << endl;
            return 1;
          }
      else if (option_name == "parameter_uncertainty")
        {
          options->parameter_uncertainty = true;
          if (shocks_passed == false)
            options->shocks = 1;
        }
430
      else if (option_name == "shocks_per_parameter")
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
        if (this_option_value && mxIsNumeric(this_option_value))
          {
            temp_buf = (double *) mxGetData(this_option_value);
            options->shocks = (int) temp_buf[0];
            shocks_passed = true;
          }
        else
          {
            cout << "You must pass an integer after specifying the 'shocks' option" << endl;
            return 1;
          }
      else if (option_name == "thin")
        if (this_option_value && mxIsNumeric(this_option_value))
          {
            temp_buf = (double *) mxGetData(this_option_value);
            options->thin = (int) temp_buf[0];
          }
        else
          {
            cout << "You must pass an integer after specifying the 'thin' option" << endl;
            return 1;
          }
      else if (option_name == "simulation_file")
        {
          char *posterior_filename = mxArrayToString(this_option_value);
          strcpy(options->simulation_filename, posterior_filename);
          if (!(options->simulation_file = fopen(posterior_filename, "rt")))
458
            {
459
460
461
              cout << "Can not open posterior file " << options->simulation_file
                   << " for reading. " << endl;
              return 1;
462
            }
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
          mxFree(posterior_filename);
        }
      else if (option_name == "regimes")
        options->regimes = true;
      else if (option_name == "regime")
        if (this_option_value && mxIsNumeric(this_option_value))
          {
            temp_buf = (double *) mxGetData(this_option_value);
            options->regime = (int) temp_buf[0];
          }
        else
          {
            cout << "You must pass an integer after specifying the 'regime' "
                 << "option, or alternatively you can specify 'regimes'" << endl;
            return 1;
          }
      else if (option_name == "number_observations")
        if (this_option_value && mxIsNumeric(this_option_value))
          {
            temp_buf = (double *) mxGetData(this_option_value);
            options->number_observations = (int) temp_buf[0];
          }
        else
          {
            cout << "You must pass an integer after specifying the "
                 << "'number_observations' option" << endl;
            return 1;
          }
      else if (option_name == "free_parameters")
        if (this_option_value && mxIsNumeric(this_option_value))
          {
            options->num_parameters = mxGetM(this_option_value);
            options->free_parameters = mxGetPr(this_option_value);
          }
        else
          {
            cout << "You must pass a vector of free parameters after "
                 << "specifying 'free_parameters'" << endl;
            return 1;
          }
      else if (option_name == "mean")
        {
          options->mean = true;
          options->num_percentiles = 0;
          options->percentiles = (double *) NULL;
508
509

        }
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
      else if (option_name == "seed")
        if (this_option_value && mxIsNumeric(this_option_value))
          {
            temp_buf = (double *) mxGetData(this_option_value);
            options->seed = (long) temp_buf[0];
          }
        else
          {
            cout << "You must pass an integer after specifying the 'seed' option" << endl;
            return 1;
          }
      else
          {
            cout << "set_options error: option '" << option_name << "' not matched" << endl;
            return 1;
          }
      mxFree(option_name_c);
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
554
555
556
557
558
559
560
561
562
    } // End Optional Arguments
  return 0;
}

int
print_sbvar_options(SbvarOption *options)
{
  using namespace std;
  int i;

  if (options == NULL)
    return 1;

  cout << "SBVAR OPTIONS" << endl;
  cout << "Number of Shocks: " << options->shocks << endl;
  cout << "Thinning Factor: " << options->thin << endl;
  cout << "Horizon: " << options->horizon << endl;
  cout << "Number of Observations to Show: " << options->number_observations << endl;
  cout << "Regime: " << options->regime << endl;
  cout << "Regimes: " << options->regimes << endl;
  cout << "Number Free parameters: " << options->num_parameters << endl;
  cout << "Parameter Uncertainty: " << options->parameter_uncertainty << endl;
  cout << "Mean: " << options->mean << endl;
  cout << "Number Percentiles: " << options->num_percentiles << endl;
  cout << "Percentiles: ";
  for (i = 0; i < options->num_percentiles; i++)
    cout << options->percentiles[i] << " ";
  cout << endl;
  cout << "Filtered Probabilities: " << options->filtered_probabilities << endl;
  cout << "Simulation Filename: " << options->simulation_filename << endl;
  cout << "Random Number Seed: " << options->seed << endl;

  return 0;
}

TStateModel *
563
initialize_model_and_options(SbvarOption **options, const mxArray *prhs[], int *nstates, int *nvars, int *npre, int *nfree)
564
{
565
  char *name;
566
567
568
569
  TStateModel *model = (TStateModel *) NULL;
  SbvarOption *opt;

  // Initialize the StateSpace Model with the initialization file
570
  name = mxArrayToString(mxGetCell(mxGetCell(prhs[0],0),1));
571
572
573
574
575
576
577
578
579
580
581
582
583
584
  model = initialize_ms_model(name);
  if (model == NULL)
    {
      cout << "Could not initialize State Space Switching model with the given tag." << endl;
      return (TStateModel *) NULL;
    }
  if (get_var_dimensions(model, nstates, nvars, npre, nfree) > 0)
    {
      cout << "Problems Determining the size of the Initialized model." << endl;
      return (TStateModel *) NULL;
    }

  // Process the rest of the options
  opt = initialize_sbvar_options(name);
585
586
  mxFree(name);
  if (set_options(opt, prhs) > 0)
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
    {
      cout << "There was a problem with the options passed." << endl;
      return (TStateModel *) NULL;
    }

  // Set seed value
  try
    {
      dw_initialize_generator(opt->seed);
    }
  catch (const char *s)
    {
      cout << "Exception: " << s << endl;
      cout << "Exception thrown initializing Random Seed." << endl;
      return (TStateModel *) NULL;
    }

  // If free parameters have been passed, then set them in the model
  if (opt->num_parameters > 0)
    {
      if (opt->num_parameters == *nfree + 2)
        {
          opt->free_parameters = opt->free_parameters+2;
          opt->num_parameters = opt->num_parameters - 2;
        }
      if (opt->num_parameters != *nfree)
        {
          cout << "The Free Parameter vector passed is the wrong size for the given model" << endl;
          return (TStateModel *) NULL;
        }

      // Set the paramters as the current 'theta'
      if (set_parameters_in_VAR(model, opt->free_parameters) > 0)
        {
          cout << "Problem with the free parameters that were passed being set in MS-SBVAR Model." << endl;
          return (TStateModel *) NULL;
        }
    }

  *options = opt;

  return model;
}

#endif