Debian Codegraph @

contrib/ms-sbvar/switch_dw/state_space/sbvar/VARio.c

raw
1 /*
2 * Copyright (C) 1996-2011 Daniel Waggoner and Tao Zha
3 *
4 * This free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * It is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * If you did not received a copy of the GNU General Public License
15 * with this software, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include "VARio.h"
19 #include "switchio.h"
20 #include "dw_error.h"
21 #include "dw_ascii.h"
22 #include "dw_parse_cmd.h"
23 #include "dw_std.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <math.h>
28
29 static int strlen_int(int n)
30 {
31 int i, j;
32 for (i=1, j=10; n >= j; i++, j*=10);
33 return i;
34 }
35
36 static void ReadError_VARio(char *id)
37 {
38 char *errmsg, *fmt="Error after line identifier ""%s""";
39 sprintf(errmsg=(char*)dw_malloc(strlen(fmt) + strlen(id) - 1),fmt,id);
40 dw_UserError(errmsg);
41 dw_free(errmsg);
42 }
43
44 static int ReadInteger_VARio(FILE *f_in, char *id)
45 {
46 int i;
47 if (!dw_SetFilePosition(f_in,id) || (fscanf(f_in," %d ",&i) != 1)) ReadError_VARio(id);
48 return i;
49 }
50
51 static PRECISION ReadScalar_VARio(FILE *f_in, char *id)
52 {
53 double x;
54 if (!dw_SetFilePosition(f_in,id) || (fscanf(f_in," %lf ",&x) != 1)) ReadError_VARio(id);
55 return (PRECISION)x;
56 }
57
58 static void ReadMatrix_VARio(FILE *f_in, char *id, TMatrix X)
59 {
60 if (!dw_SetFilePosition(f_in,id) || !dw_ReadMatrix(f_in,X)) ReadError_VARio(id);
61 }
62
63 static void ReadVector_VARio(FILE *f_in, char *id, TVector X)
64 {
65 if (!dw_SetFilePosition(f_in,id) || !dw_ReadVector(f_in,X)) ReadError_VARio(id);
66 }
67
68 static void ReadArray_VARio(FILE *f_in, char *id, void *X)
69 {
70 if (!dw_SetFilePosition(f_in,id) || !dw_ReadArray(f_in,X)) ReadError_VARio(id);
71 }
72
73 static FILE* OpenFile_VARio(FILE *f, char *filename)
74 {
75 char *errmsg, *fmt="Unable to open %s";
76 if (!f)
77 {
78 if (!filename)
79 dw_UserError("Filename pointer is null.");
80 else
81 if (!(f=fopen(filename,"rt")))
82 {
83 sprintf(errmsg=(char*)dw_malloc(strlen(fmt) + strlen(filename) - 1),fmt,filename);
84 dw_UserError(errmsg);
85 dw_free(errmsg);
86 }
87 }
88 return f;
89 }
90
91 /*
92 Assumes
93 posterior_file : FILE pointer to open file
94 model : pointer to valid TStateModel structure
95 flag : F_FREE - posterior value, likelihood value, theta, q format
96 F_FLAT - flat posterior draw format
97
98 Results
99 Upon success, new parameters are pushed into model
100
101 Returns
102 One upon success and zero otherwise.
103
104 */
105 int GetPosteriorDraw(FILE *posterior_file, TStateModel *model, int flag)
106 {
107 int terminal=dw_SetTerminalErrors(0), verbose=dw_SetVerboseErrors(0), rtrn=0, nq, nt;
108 TVector draw;
109 switch (flag)
110 {
111 case F_FREE:
112 nt=NumberFreeParametersTheta(model);
113 nq=NumberFreeParametersQ(model);
114 if (dw_ReadVector(posterior_file,draw=CreateVector(2+nt+nq)))
115 {
116 ConvertFreeParametersToTheta(model,pElementV(draw)+2);
117 ConvertFreeParametersToQ(model,pElementV(draw)+2+nt);
118 rtrn=1;
119 }
120 FreeVector(draw);
121 break;
122 case F_FLAT:
123 if (ReadBaseTransitionMatricesFlat(posterior_file,(char*)NULL,model) && Read_VAR_ParametersFlat(posterior_file,model))
124 rtrn=1;
125 break;
126 default:
127 dw_SetTerminalErrors(terminal);
128 dw_SetVerboseErrors(verbose);
129 dw_UserError("Incorrect type passed to GetPosteriorDraw()");
130 return rtrn;
131 }
132 dw_SetTerminalErrors(terminal);
133 dw_SetVerboseErrors(verbose);
134 return rtrn;
135 }
136
137 /******************************************************************************/
138 /******************************************************************************/
139 /******************************************************************************/
140 /*
141 Allocates memory for filename. Assumes that fmt is of the form
142
143 %s*%s*
144
145 where the first %s will be filled with dir and the second will be
146 filled with tag. If either dir or tag is a null pointer, then the
147 the empty sring will be used. The calling routine must free the
148 returned pointer.
149 */
150 char* CreateFilenameFromTag(char *fmt, char *tag, char *dir)
151 {
152 char *filename;
153 if (!tag) tag="";
154 if (!dir) dir="";
155 sprintf(filename=(char*)dw_malloc(strlen(dir) + strlen(fmt) + strlen(tag) - 3),fmt,dir,tag);
156 return filename;
157 }
158
159 /*
160 Create a full path name by appending a "/" if necessary. The
161 returned pathname must be freed by he calling routine.
162 */
163 char* CreatePath(char *path)
164 {
165 #ifdef _WIN32
166 #define DIR_DELIMITER '\\'
167 #else
168 #define DIR_DELIMITER '/'
169 #endif
170 char *fullpath;
171 int n;
172 if (!path) path="";
173 n=(int)strlen(path);
174 if (path[0] && path[n-1] != DIR_DELIMITER)
175 {
176 memcpy(fullpath=(char*)dw_malloc(n+2),path,n);
177 fullpath[n]=DIR_DELIMITER;
178 fullpath[n+1]='\0';
179 }
180 else
181 fullpath=dw_DuplicateString(path);
182 return fullpath;
183 #undef DIR_DELIMITER
184 }
185
186 TVARCommandLine* Create_VARCommandLine(void)
187 {
188 TVARCommandLine *cmd=(TVARCommandLine*)dw_malloc(sizeof(TVARCommandLine));
189 if (cmd)
190 {
191 cmd->out_directory=(char*)NULL;
192 cmd->in_directory=(char*)NULL;
193 cmd->in_tag=(char*)NULL;
194 cmd->out_tag=(char*)NULL;
195 cmd->out_header=(char*)NULL;
196
197 cmd->specification_filename=(char*)NULL;
198 cmd->parameters_filename=(char*)NULL;
199 cmd->parameters_header=(char*)NULL;
200
201 cmd->specification_filename_actual=(char*)NULL;
202 cmd->parameters_filename_actual=(char*)NULL;
203 cmd->parameters_header_actual=(char*)NULL;
204
205 cmd->MLE=0;
206
207 cmd->model=(TStateModel*)NULL;
208 }
209
210 return cmd;
211 }
212
213 void Free_VARCommandLine(TVARCommandLine *cmd)
214 {
215 if (cmd)
216 {
217 if (cmd->out_directory) dw_free(cmd->out_directory);
218 if (cmd->in_directory) dw_free(cmd->in_directory);
219 if (cmd->in_tag) dw_free(cmd->in_tag);
220 if (cmd->out_tag) dw_free(cmd->out_tag);
221 if (cmd->out_header) dw_free(cmd->out_header);
222 if (cmd->specification_filename) dw_free(cmd->specification_filename);
223 if (cmd->parameters_filename) dw_free(cmd->parameters_filename);
224 if (cmd->parameters_header) dw_free(cmd->parameters_header);
225 if (cmd->specification_filename_actual) dw_free(cmd->specification_filename_actual);
226 if (cmd->parameters_filename_actual) dw_free(cmd->parameters_filename_actual);
227 if (cmd->parameters_header_actual) dw_free(cmd->parameters_header_actual);
228 if (cmd->model) FreeStateModel(cmd->model);
229
230 dw_free(cmd);
231 }
232 }
233
234 TVARCommandLine* Base_VARCommandLine(int nargs, char **args)
235 {
236 TVARCommandLine *cmd=Create_VARCommandLine();
237 if (cmd)
238 {
239 // input directory
240 cmd->in_directory=CreatePath(dw_ParseString_String(nargs,args,"di",""));
241
242 // output directory
243 cmd->out_directory=CreatePath(dw_ParseString_String(nargs,args,"do",""));
244
245 // specification file
246 cmd->specification_filename=dw_DuplicateString(dw_ParseString_String(nargs,args,"fs",(char*)NULL));
247
248 // Parameters file
249 cmd->parameters_filename=dw_DuplicateString(dw_ParseString_String(nargs,args,"fp",(char*)NULL));
250
251 // MLE
252 cmd->MLE=(dw_FindArgument_String(nargs,args,"MLE") == -1) ? 0 : 1;
253
254 // parameter header
255 cmd->parameters_header=dw_DuplicateString(dw_ParseString_String(nargs,args,"ph",(char*)NULL));
256
257 // output file name
258 cmd->out_filename=dw_DuplicateString(dw_ParseString_String(nargs,args,"fo",(char*)NULL));
259
260 // output parameters header
261 cmd->out_header=dw_DuplicateString(dw_ParseString_String(nargs,args,"pho",(char*)NULL));
262
263 // input file tag
264 cmd->in_tag=dw_DuplicateString(dw_ParseString_String(nargs,args,"ft",(char*)NULL));
265
266 // output file tag
267 cmd->out_tag=dw_DuplicateString(dw_ParseString_String(nargs,args,"fto",(char*)NULL));
268 }
269 return cmd;
270 }
271
272 /*
273 if cmd->out_tag is null, then sets cmd->out_tag to cmd->in_tag if cmd->in_tag
274 is not null and or "notag" if cmd->in_tag is null.
275 */
276 void OutTag_VARCommandLine(TVARCommandLine *cmd)
277 {
278 if (!cmd->out_tag) cmd->out_tag=dw_DuplicateString(cmd->in_tag ? cmd->in_tag : "notag");
279 }
280
281 /*
282 Attempts to get the parameters from the last iteration in the intermediate
283 file. Returns one and sets cmd->parameters_file_actual,
284 cmd->parameters_header_actual and loads parameters upon success. Returns
285 zero upon failure.
286 */
287 static int GetLastIteration(TVARCommandLine *cmd)
288 {
289 char *filename, *header, *fmt="Iteration %d: ";
290 int cont=1, terminal_errors, i, j, k=1, rtrn=0;
291 FILE *f_in;
292
293 filename=CreateFilenameFromTag("%sest_intermediate_%s.out",cmd->in_tag,cmd->in_directory);
294 if (!(f_in=fopen(filename,"rt")))
295 {
296 dw_free(filename);
297 return 0;
298 }
299
300 terminal_errors=dw_SetTerminalErrors(dw_GetTerminalErrors() & (~USER_ERR));
301
302 do
303 {
304 for (j=10, i=1; k >= j; j*=10, i++);
305 sprintf(header=(char*)dw_malloc(strlen(fmt) + i - 1),fmt,k);
306 if (ReadBaseTransitionMatrices(f_in,(char*)NULL,header,cmd->model) && Read_VAR_Parameters(f_in,(char*)NULL,header,cmd->model))
307 k++;
308 else
309 cont=0;
310 dw_free(header);
311 }
312 while (cont);
313
314 if (k > 1)
315 {
316 k--;
317 for (j=10, i=1; k >= j; j*=10, i++);
318 sprintf(header=(char*)dw_malloc(strlen(fmt) + i - 1),fmt,k);
319 if (ReadBaseTransitionMatrices(f_in,(char*)NULL,header,cmd->model) && Read_VAR_Parameters(f_in,(char*)NULL,header,cmd->model))
320 {
321 if (cmd->parameters_filename_actual) dw_free(cmd->parameters_filename_actual);
322 cmd->parameters_filename_actual=filename;
323 if (cmd->parameters_header_actual) dw_free(cmd->parameters_header_actual);
324 cmd->parameters_header_actual=header;
325 rtrn=1;
326 }
327 else
328 dw_free(header);
329 }
330 else
331 {
332 header="Initial: ";
333 if (ReadBaseTransitionMatrices(f_in,(char*)NULL,header,cmd->model) && Read_VAR_Parameters(f_in,(char*)NULL,header,cmd->model))
334 {
335 if (cmd->parameters_filename_actual) dw_free(cmd->parameters_filename_actual);
336 cmd->parameters_filename_actual=filename;
337 if (cmd->parameters_header_actual) dw_free(cmd->parameters_header_actual);
338 cmd->parameters_header_actual=dw_DuplicateString(header);
339 rtrn=1;
340 }
341 }
342
343 fclose(f_in);
344 if (!rtrn) dw_free(filename);
345 dw_SetTerminalErrors(terminal_errors);
346 return 0;
347 }
348
349 /*
350 Attempts to set up model from command line.
351
352 specification file
353 1) cmd->specification_filename if non-null
354 2) if cmd->in_tag is non-null
355 a) est_final_<tag>.out if this file exists
356 b) init_<tag>.out if this file exists
357
358 parameter file
359 1) cmd->parameters_filename if non-null
360 a) Tries to read in a full specification
361 b) Tries to read in a file with only free parameters
362 2) cmd->specification_filename if non-null
363 3) if cmd->in_tag is non-null
364 a) est_final_<tag>.out if this file exists
365 b) est_intermediate_<tag>.out if this file exists
366 c) init_<tag>.out if this file exists
367
368 parameter header
369 1) if parameter file is cmd->parameters_filename, cmd->specification_filename, or est_final_<tag>.out
370 a) cmd->parameters_header if non-null
371 b) "MLE: " if -MLE is present in the command line
372 c) "Posterior mode: " if -MLE is not present in the command line
373 2) if parameter file is est_intermediate_<tag>.out, then either "Iteration %d: " or "Initial: "
374 3) if parameter file is init_<tag>.out, then "Initial: "
375
376 Returns valid pointer to a TVARCommandLine upon success. A null return indicates a lack of
377 memory. The if cmd->model or cmd->specification_filename_actual is null, then there was not enough
378 information on the command line to create the model. If cmd->parameters_filename_actual
379 or cmd->parameters_header_actual is null, then the there was not enough information on the
380 command line to initialize the parameters.
381 */
382 TVARCommandLine* CreateTStateModel_VARCommandLine(int nargs, char **args, TVARCommandLine *cmd)
383 {
384 char *filename, *header;
385 int terminal_errors;
386
387 if (!cmd && !(cmd=Base_VARCommandLine(nargs,args))) return cmd;
388
389 terminal_errors=dw_SetTerminalErrors(dw_GetTerminalErrors() & (~USER_ERR));
390
391 if (cmd->specification_filename)
392 {
393 filename=CreateFilenameFromTag("%s%s",cmd->specification_filename,cmd->in_directory);
394 if (!(cmd->model=Read_VAR_Specification((FILE*)NULL,filename)))
395 {
396 dw_free(filename);
397 dw_SetTerminalErrors(terminal_errors);
398 return cmd;
399 }
400 }
401 else
402 if (cmd->in_tag)
403 {
404 filename=CreateFilenameFromTag("%sest_final_%s.out",cmd->in_tag,cmd->in_directory);
405 if (!(cmd->model=Read_VAR_Specification((FILE*)NULL,filename)))
406 {
407 dw_free(filename);
408 filename=CreateFilenameFromTag("%sinit_%s.dat",cmd->in_tag,cmd->in_directory);
409 if (!(cmd->model=Read_VAR_Specification((FILE*)NULL,filename)))
410 {
411 dw_free(filename);
412 dw_SetTerminalErrors(terminal_errors);
413 return cmd;
414 }
415 }
416 }
417 else
418 {
419 dw_SetTerminalErrors(terminal_errors);
420 return cmd;
421 }
422
423 if (cmd->specification_filename_actual) dw_free(cmd->specification_filename_actual);
424 cmd->specification_filename_actual=filename;
425
426 header=cmd->parameters_header ? cmd->parameters_header : (cmd->MLE ? "MLE: " : "Posterior mode: ");
427
428 if (cmd->parameters_filename)
429 {
430 filename=CreateFilenameFromTag("%s%s",cmd->parameters_filename,cmd->in_directory);
431 if (!ReadBaseTransitionMatrices((FILE*)NULL,filename,header,cmd->model) || !Read_VAR_Parameters((FILE*)NULL,filename,header,cmd->model))
432 {
433 /* now try to initialize the parameters from a free paramter form */
434 if (!ReadFreeParameters((FILE*)NULL,filename,cmd->model))
435 {
436 dw_free(filename);
437 dw_SetTerminalErrors(terminal_errors);
438 return cmd;
439 }
440 }
441 }
442 else
443 if (cmd->specification_filename)
444 {
445 filename=CreateFilenameFromTag("%s%s",cmd->specification_filename,cmd->in_directory);
446 if (!ReadBaseTransitionMatrices((FILE*)NULL,filename,header,cmd->model) || !Read_VAR_Parameters((FILE*)NULL,filename,header,cmd->model))
447 {
448 dw_free(filename);
449 dw_SetTerminalErrors(terminal_errors);
450 return cmd;
451 }
452 }
453 else
454 if (cmd->in_tag)
455 {
456 filename=CreateFilenameFromTag("%sest_final_%s.out",cmd->in_tag,cmd->in_directory);
457 if (!ReadBaseTransitionMatrices((FILE*)NULL,filename,header,cmd->model) || !Read_VAR_Parameters((FILE*)NULL,filename,header,cmd->model))
458 {
459 dw_free(filename);
460 if (GetLastIteration(cmd))
461 {
462 dw_SetTerminalErrors(terminal_errors);
463 return cmd;
464 }
465 else
466 {
467 header="Initial: ";
468 filename=CreateFilenameFromTag("%sinit_%s.dat",cmd->in_tag,cmd->in_directory);
469 if (!ReadBaseTransitionMatrices((FILE*)NULL,filename,header,cmd->model) || !Read_VAR_Parameters((FILE*)NULL,filename,header,cmd->model))
470 {
471 dw_free(filename);
472 dw_SetTerminalErrors(terminal_errors);
473 return cmd;
474 }
475 }
476 }
477 }
478
479 if (cmd->parameters_filename_actual) dw_free(cmd->parameters_filename_actual);
480 cmd->parameters_filename_actual=filename;
481 if (cmd->parameters_header_actual) dw_free(cmd->parameters_header_actual);
482 cmd->parameters_header_actual=dw_DuplicateString(header);
483
484 dw_SetTerminalErrors(terminal_errors);
485 return cmd;
486 }
487 /******************************************************************************/
488 /******************************************************************************/
489 /******************************************************************************/
490
491
492
493 /*
494 Assumes:
495 f: valid file pointer or null
496 filename: pointer to null terminated string or null
497
498 Returns:
499 A pointer to a valid TStateModel upon success and null pointer upon failure.
500 Upon failure, the routine prints an error message if USER_ERR is a verbose
501 error and terminates if USER_ERR is a terminal error. The terminal errors
502 and verbose errors can be set with dw_SetTerminalErrors() and
503 dw_SetVerboseErrors().
504
505 Results:
506 Upon success, a valid TStateModel is created and initialized.
507
508 Notes:
509 One of f and filename must not be null.
510 */
511 TStateModel* Read_VAR_Specification(FILE *f, char *filename)
512 {
513 TMarkovStateVariable *sv;
514 T_VAR_Parameters *p;
515 char *id, *fmt;
516 int *IV;
517 int j, spec, nvars, nlags, nexg, npre, nstates, nobs;
518 PRECISION lambda_prior=0.0;
519 TVector zeta_a_prior, zeta_b_prior;
520 TMatrix *U, *V, *W, *A0_prior, *Aplus_prior, Y, X;
521 int **coef_states, **var_states;
522 PRECISION** A0_Metropolis_Scale=(PRECISION**)NULL;
523
524 // Valid file
525 FILE *f_in=OpenFile_VARio(f,filename);
526 if (!f_in) return (TStateModel*)NULL;
527
528 // Read Markov specifications
529 if (!(sv=ReadMarkovSpecification(f_in,(char*)NULL)))
530 {
531 if (!f) fclose(f_in);
532 return (TStateModel*)NULL;
533 }
534
535 //=== Sizes ===//
536 nvars=ReadInteger_VARio(f_in,"//== Number Variables ==//");
537 nlags=ReadInteger_VARio(f_in,"//== Number Lags ==//");
538 nexg=ReadInteger_VARio(f_in,"//== Exogenous Variables ==//");
539 nstates=ReadInteger_VARio(f_in,"//== Number States ==//");
540 nobs=ReadInteger_VARio(f_in,"//== Number Observations ==//");
541 npre=nvars*nlags+nexg;
542 if (nstates != sv->nstates)
543 {
544 dw_UserError("Read_VAR_Specification(): different values for nstates.");
545 if (!f) fclose(f_in);
546 return (TStateModel*)NULL;
547 }
548
549 //=== Restrictions - U[j] ===//
550 ReadArray_VARio(f_in,"//== Number of free parameters in each column of A0 ==//",IV=dw_CreateArray_int(nvars));
551 U=dw_CreateArray_matrix(nvars);
552 for (j=0; j < nvars; j++)
553 {
554 fmt="//== U[%d] ==//";
555 sprintf(id=(char*)dw_malloc(strlen(fmt) + strlen_int(j+1) - 1),fmt,j+1);
556 ReadMatrix_VARio(f_in,id,U[j]=CreateMatrix(nvars,IV[j]));
557 dw_free(id);
558 }
559 dw_FreeArray(IV);
560
561 //=== Restrictions - V[j] ===//
562 ReadArray_VARio(f_in,"//== Number of free parameters in each column of Aplus ==//",IV=dw_CreateArray_int(nvars));
563 V=dw_CreateArray_matrix(nvars);
564 for (j=0; j < nvars; j++)
565 if (IV[j] > 0)
566 {
567 fmt="//== V[%d] ==//";
568 sprintf(id=(char*)dw_malloc(strlen(fmt) + strlen_int(j+1) - 1),fmt,j+1);
569 ReadMatrix_VARio(f_in,id,V[j]=CreateMatrix(npre,IV[j]));
570 dw_free(id);
571 }
572 dw_FreeArray(IV);
573
574 //=== Restrictions - W[j] ===//
575 ReadArray_VARio(f_in,"//== Non-zero W[j] ==//",IV=dw_CreateArray_int(nvars));
576 W=dw_CreateArray_matrix(nvars);
577 for (j=0; j < nvars; j++)
578 if (IV[j])
579 {
580 fmt="//== W[%d] ==//";
581 sprintf(id=(char*)dw_malloc(strlen(fmt) + strlen_int(j+1) - 1),fmt,j+1);
582 ReadMatrix_VARio(f_in,id,W[j]=CreateMatrix(npre,nvars));
583 dw_free(id);
584 }
585 dw_FreeArray(IV);
586
587 //====== Priors ======
588 ReadVector_VARio(f_in,"//== Gamma prior on zeta - a ==//",zeta_a_prior=CreateVector(nvars));
589 ReadVector_VARio(f_in,"//== Gamma prior on zeta - b ==//",zeta_b_prior=CreateVector(nvars));
590
591 A0_prior=dw_CreateArray_matrix(nvars);
592 for (j=0; j < nvars; j++)
593 {
594 fmt="//== Variance of Gaussian prior on column %d of A0 ==//";
595 sprintf(id=(char*)dw_malloc(strlen(fmt) + strlen_int(j+1) - 1),fmt,j+1);
596 ReadMatrix_VARio(f_in,id,A0_prior[j]=CreateMatrix(nvars,nvars));
597 dw_free(id);
598 }
599
600 Aplus_prior=dw_CreateArray_matrix(nvars);
601 for (j=0; j < nvars; j++)
602 {
603 fmt="//== Variance of Gaussian prior on column %d of Aplus ==//";
604 sprintf(id=(char*)dw_malloc(strlen(fmt) + strlen_int(j+1) - 1),fmt,j+1);
605 ReadMatrix_VARio(f_in,id,Aplus_prior[j]=CreateMatrix(npre,npre));
606 dw_free(id);
607 }
608
609 //=== Specification ===//
610 spec=ReadInteger_VARio(f_in,"//== Specification (0=default 1=Sims-Zha 2=Random Walk) ==//");
611 switch (spec)
612 {
613 case 0: spec=0; break;
614 case 1: spec=SPEC_SIMS_ZHA | SPEC_RANDOM_WALK; break;
615 case 2: spec=SPEC_RANDOM_WALK; break;
616 default: ReadError_VARio("//== Specification (0=default 1=Sims-Zha 2=Random Walk) ==//"); dw_exit(0);
617 }
618 if (spec & SPEC_SIMS_ZHA)
619 lambda_prior=ReadScalar_VARio(f_in,"//== Variance of Gaussian prior on lambda ==//");
620
621 //====== coefficient and variance state variables ======
622 ReadArray_VARio(f_in,"//== Translation table for coefficient states ==//",coef_states=dw_CreateRectangularArray_int(nvars,nstates));
623 ReadArray_VARio(f_in,"//== Translation table for variance states ==//",var_states=dw_CreateRectangularArray_int(nvars,nstates));
624
625 //====== Metropolis jumping kernel info for A0 ======
626 if (dw_SetFilePosition(f_in,id="//== Metropolis kernel scales for A0 ==//"))
627 {
628 A0_Metropolis_Scale=dw_CreateArray_array(nvars);
629 for (j=nvars-1; j >= 0; j--)
630 A0_Metropolis_Scale[j]=dw_CreateArray_scalar(GetNumberStatesFromTranslationMatrix(j,coef_states));
631 if (!dw_ReadArray(f_in,A0_Metropolis_Scale)) ReadError_VARio(id);
632 }
633
634 //=== Data ===
635 ReadMatrix_VARio(f_in,"//== Data Y (nobs x nvars) ==//",Y=CreateMatrix(nobs,nvars));
636 ReadMatrix_VARio(f_in,"//== Data X (nobs x npre) ==//",X=CreateMatrix(nobs,npre));
637
638 //=== Create T_VAR_Parameters structure ===
639 p=CreateTheta_VAR(spec,nvars,nlags,nexg,nstates,nobs,coef_states,var_states,U,V,W,Y,X);
640 if (spec & SPEC_SIMS_ZHA)
641 SetPriors_VAR_SimsZha(p,A0_prior,Aplus_prior,zeta_a_prior,zeta_b_prior,lambda_prior);
642 else
643 SetPriors_VAR(p,A0_prior,Aplus_prior,zeta_a_prior,zeta_b_prior);
644
645 if (A0_Metropolis_Scale) SetupMetropolisInformation(A0_Metropolis_Scale,p);
646
647 //=== Close output file ===
648 if (!f) fclose(f_in);
649
650 //=== Free memory ===
651 dw_FreeArray(U);
652 dw_FreeArray(V);
653 dw_FreeArray(W);
654 FreeVector(zeta_a_prior);
655 FreeVector(zeta_b_prior);
656 dw_FreeArray(A0_prior);
657 dw_FreeArray(Aplus_prior);
658 FreeMatrix(X);
659 FreeMatrix(Y);
660 dw_FreeArray(coef_states);
661 dw_FreeArray(var_states);
662 dw_FreeArray(A0_Metropolis_Scale);
663
664 //=== return TStateModel structure ===
665 return CreateStateModel(nobs,sv,CreateRoutines_VAR(),p);
666 }
667
668 /*
669 Writes the specification
670 */
671 void Write_VAR_Specification(FILE *f, char *filename, TStateModel *model)
672 {
673 int j, t;
674 FILE *f_out=f ? f : dw_CreateTextFile(filename);
675 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
676
677 // Write Markov specifications
678 WriteMarkovSpecification(f_out,(char*)NULL,model);
679
680 //=== Sizes ===//
681 fprintf(f_out,"//== Number Variables ==//\n%d\n\n",p->nvars);
682 fprintf(f_out,"//== Number Lags ==//\n%d\n\n",p->nlags);
683 fprintf(f_out,"//== Exogenous Variables ==//\n%d\n\n",p->npre - p->nvars * p->nlags);
684 fprintf(f_out,"//== Number States ==//\n%d\n\n",p->nstates);
685 fprintf(f_out,"//== Number Observations ==//\n%d\n\n",p->nobs);
686
687 //=== Restrictions - U[j] ===//
688 fprintf(f_out,"//== Number of free parameters in each column of A0 ==//\n");
689 for (j=0; j < p->nvars; j++)
690 fprintf(f_out,"%d ",ColM(p->U[j]));
691 fprintf(f_out,"\n\n");
692 for (j=0; j < p->nvars; j++)
693 {
694 fprintf(f_out,"//== U[%d] ==//\n",j+1);
695 dw_PrintMatrix(f_out,p->U[j],"%22.14le ");
696 fprintf(f_out,"\n");
697 }
698
699 //=== Restrictions - V[j] ===//
700 fprintf(f_out,"//== Number of free parameters in each column of Aplus ==//\n");
701 for (j=0; j < p->nvars; j++)
702 fprintf(f_out,"%d ",p->V[j] ? ColM(p->V[j]) : 0);
703 fprintf(f_out,"\n\n");
704 for (j=0; j < p->nvars; j++)
705 if (p->V[j])
706 {
707 fprintf(f_out,"//== V[%d] ==//\n",j+1);
708 dw_PrintMatrix(f_out,p->V[j],"%22.14le ");
709 fprintf(f_out,"\n");
710 }
711
712 //=== Restrictions - W[j] ===//
713 fprintf(f_out,"//== Non-zero W[j] ==//\n");
714 for (j=0; j < p->nvars; j++)
715 fprintf(f_out,"%d ",p->W[j] ? 1 : 0);
716 fprintf(f_out,"\n\n");
717 for (j=0; j < p->nvars; j++)
718 if (p->W[j])
719 {
720 fprintf(f_out,"//== W[%d] ==//\n",j+1);
721 dw_PrintMatrix(f_out,p->W[j],"%22.14le ");
722 fprintf(f_out,"\n");
723 }
724
725 //====== Priors ======
726 fprintf(f_out,"//== Gamma prior on zeta - a ==//\n");
727 dw_PrintVector(f_out,p->zeta_a_prior,"%22.14le ");
728 fprintf(f_out,"\n");
729 fprintf(f_out,"//== Gamma prior on zeta - b ==//\n");
730 dw_PrintVector(f_out,p->zeta_b_prior,"%22.14le ");
731 fprintf(f_out,"\n");
732
733 for (j=0; j < p->nvars; j++)
734 {
735 fprintf(f_out,"//== Variance of Gaussian prior on column %d of A0 ==//\n",j+1);
736 dw_PrintMatrix(f_out,p->A0_prior[j],"%22.14le ");
737 fprintf(f_out,"\n");
738 }
739
740 for (j=0; j < p->nvars; j++)
741 {
742 fprintf(f_out,"//== Variance of Gaussian prior on column %d of Aplus ==//\n",j+1);
743 dw_PrintMatrix(f_out,p->Aplus_prior[j],"%22.14le ");
744 fprintf(f_out,"\n");
745 }
746
747 //=== Model specification ===//
748 fprintf(f_out,"//== Specification (0=default 1=Sims-Zha 2=Random Walk) ==//\n");
749 if (p->Specification & SPEC_SIMS_ZHA)
750 fprintf(f_out,"1\n\n");
751 else
752 if (p->Specification & SPEC_RANDOM_WALK)
753 fprintf(f_out,"2\n\n");
754 else
755 fprintf(f_out,"0\n\n");
756 if ((p->Specification & SPEC_SIMS_ZHA) == SPEC_SIMS_ZHA)
757 fprintf(f_out,"//== Variance of Gaussian prior on lambda ==//\n%22.14le\n\n",p->lambda_prior);
758
759 //====== coefficient and variance state variables ======
760 fprintf(f_out,"//== Translation table for coefficient states ==//\n");
761 dw_PrintArray(f_out,p->coef_states,"%4d ");
762
763 fprintf(f_out,"//== Translation table for variance states ==//\n");
764 dw_PrintArray(f_out,p->var_states,"%4d ");
765
766 //====== Metropolis jumping kernel info for A0 ======
767 fprintf(f_out,"//== Metropolis kernel scales for A0 ==//\n");
768 dw_PrintArray(f_out,p->A0_Metropolis_Scale,"%22.14le ");
769
770 //=== Data ===
771 fprintf(f_out,"//== Data Y (nobs x nvars) ==//\n");
772 for (t=1; t <= p->nobs; t++)
773 dw_PrintVector(f_out,p->Y[t],"%22.14le ");
774 fprintf(f_out,"\n");
775
776 fprintf(f_out,"//== Data X (nobs x npre) ==//\n");
777 for (t=1; t <= p->nobs; t++)
778 dw_PrintVector(f_out,p->X[t],"%22.14le ");
779 fprintf(f_out,"\n");
780
781 //=== Close output file ===
782 if (!f) fclose(f_out);
783 }
784
785 /*
786 Assumes:
787 f: valid file pointer or null
788 filename: pointer to null terminated string or null
789 model: pointer to valid TStateModel structure
790
791 Returns:
792 One upon success. Upon failure, the routine prints an error message if
793 USER_ERR is a verbose error, terminates if USER_ERR is a terminal error and
794 returns zero if USER_ERR is not a terminal error. The terminal errors and
795 verbose errors can be set with dw_SetTerminalErrors() and
796 dw_SetVerboseErrors().
797
798 Results:
799 Upon success, the following fields of p will be filled:
800
801 A0, Aplus, Zeta, b0, bplus.
802
803 If the Sims-Zha specification is used, the following fields will also be
804 filled
805
806 lambda, psi.
807
808 The routine Thetahanged() will be called.
809
810 Notes:
811 One of f and filename must not be null.
812
813 The file must contain line identifiers of the form
814
815 //== A0[s] ==//
816 //== Aplus[s] ==//
817 //== Zeta[s] ==//
818 FreeParametersToVAR
819 for 1 <= s <= p->nstates.
820
821 Zeta is checked for non-negativity. No checks are made to ensure that A0[s],
822 Aplus[s], or Zeta[s] satisfy any restrictions.
823 */
824 int Read_VAR_Parameters(FILE *f, char *filename, char *header, TStateModel *model)
825 {
826 FILE *f_in;
827 char *idbuffer, *fmt;
828 TMatrix *A0, *Aplus, *Zeta;
829 int i, j, s;
830 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
831
832 // Valid file
833 f_in=OpenFile_VARio(f,filename);
834 if (!f_in) return 0;
835
836 if (!header) header="";
837
838 // Allocate memory
839 A0=dw_CreateArray_matrix(p->nstates);
840 Aplus=dw_CreateArray_matrix(p->nstates);
841 Zeta=dw_CreateArray_matrix(p->nstates);
842
843 // Read File
844 for (s=0; s < p->nstates; s++)
845 {
846 fmt="//== %sA0[%d] ==//";
847 sprintf(idbuffer=(char*)dw_malloc(strlen(fmt)+strlen(header)+strlen_int(s+1)-3),fmt,header,s+1);
848 if (!dw_SetFilePosition(f_in,idbuffer) || !dw_ReadMatrix(f_in,A0[s]=CreateMatrix(p->nvars,p->nvars)))
849 {
850 ReadError_VARio(idbuffer);
851 dw_free(idbuffer);
852 if (!f) fclose(f_in);
853 return 0;
854 }
855 dw_free(idbuffer);
856
857 fmt="//== %sAplus[%d] ==//";
858 sprintf(idbuffer=(char*)dw_malloc(strlen(fmt)+strlen(header)+strlen_int(s+1)-3),fmt,header,s+1);
859 if (!dw_SetFilePosition(f_in,idbuffer) || !dw_ReadMatrix(f_in,Aplus[s]=CreateMatrix(p->npre,p->nvars)))
860 {
861 ReadError_VARio(idbuffer);
862 dw_free(idbuffer);
863 if (!f) fclose(f_in);
864 return 0;
865 }
866 dw_free(idbuffer);
867
868 fmt="//== %sZeta[%d] ==//";
869 sprintf(idbuffer=(char*)dw_malloc(strlen(fmt)+strlen(header)+strlen_int(s+1)-3),fmt,header,s+1);
870 if (!dw_SetFilePosition(f_in,idbuffer) || !dw_ReadMatrix(f_in,Zeta[s]=CreateMatrix(p->nvars,p->nvars)))
871 {
872 ReadError_VARio(idbuffer);
873 dw_free(idbuffer);
874 if (!f) fclose(f_in);
875 return 0;
876 }
877 dw_free(idbuffer);
878 }
879 if (!f) fclose(f_in);
880
881 // Set A0, Aplus, and Zeta
882 for (j=0; j < p->nvars; j++)
883 for (s=0; s < p->nstates; s++)
884 {
885 for (i=0; i < p->nvars; i++)
886 ElementV(p->A0[j][p->coef_states[j][s]],i)=ElementM(A0[s],i,j);
887
888 for (i=0; i < p->npre; i++)
889 ElementV(p->Aplus[j][p->coef_states[j][s]],i)=ElementM(Aplus[s],i,j);
890
891 p->Zeta[j][p->var_states[j][s]]=ElementM(Zeta[s],j,j);
892 }
893
894 // Free memory
895 dw_FreeArray(A0);
896 dw_FreeArray(Aplus);
897 dw_FreeArray(Zeta);
898
899 // Check Zeta non-negative
900 for (j=p->nvars-1; j >= 0; j--)
901 for (s=p->n_var_states[j]-1; s >= 0; s--)
902 if (p->Zeta[j][s] < 0.0)
903 {
904 dw_UserError("Zeta has negative value.");
905 p->valid_parameters=0;
906 ThetaChanged(model);
907 return 0;
908 }
909
910 // Update b0, bplus, lambda, psi
911 Update_b0_bplus_from_A0_Aplus(p);
912 if ((p->Specification & SPEC_SIMS_ZHA) == SPEC_SIMS_ZHA) Update_lambda_psi_from_bplus(p);
913
914 // Flags and notification that the VAR parameters have changed
915 p->valid_parameters=1;
916 ThetaChanged(model);
917
918 return 1;
919 }
920
921 /*
922 Reads VAR parameters from f_in. For 0 <= s < nstates, reads A0[s], Aplus[s],
923 and Zeta[s]. Assumes A0[s] and Aplus[s] were written in column major format,
924 and only the diagonal of Zeta[s] was written.
925 */
926 int Read_VAR_ParametersFlat(FILE *f_in, TStateModel *model)
927 {
928 TMatrix *A0, *Aplus;
929 TVector *Zeta;
930 int i, j, s, rtrn=0;
931 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
932
933 // Allocate memory
934 A0=dw_CreateArray_matrix(p->nstates);
935 Aplus=dw_CreateArray_matrix(p->nstates);
936 Zeta=dw_CreateArray_vector(p->nstates);
937
938 // Read File
939 for (s=0; s < p->nstates; s++)
940 {
941 A0[s]=CreateMatrix(p->nvars,p->nvars);
942 for (j=0; j < p->nvars; j++)
943 for (i=0; i < p->nvars; i++)
944 if (fscanf(f_in," %lf ",&ElementM(A0[s],i,j)) != 1)
945 goto ERRORCOND;
946
947 Aplus[s]=CreateMatrix(p->npre,p->nvars);
948 for (j=0; j < p->nvars; j++)
949 for (i=0; i < p->npre; i++)
950 if (fscanf(f_in," %lf ",&ElementM(Aplus[s],i,j)) != 1)
951 goto ERRORCOND;
952
953 Zeta[s]=CreateVector(p->nvars);
954 for (j=0; j < p->nvars; j++)
955 if (fscanf(f_in," %lf ",&ElementV(Zeta[s],j)) != 1)
956 goto ERRORCOND;
957 else
958 if (ElementV(Zeta[s],j) < 0.0)
959 goto ERRORCOND;
960 }
961
962 // Set A0, Aplus, and Zeta
963 for (j=0; j < p->nvars; j++)
964 for (s=0; s < p->nstates; s++)
965 {
966 for (i=0; i < p->nvars; i++)
967 ElementV(p->A0[j][p->coef_states[j][s]],i)=ElementM(A0[s],i,j);
968
969 for (i=0; i < p->npre; i++)
970 ElementV(p->Aplus[j][p->coef_states[j][s]],i)=ElementM(Aplus[s],i,j);
971
972 p->Zeta[j][p->var_states[j][s]]=ElementV(Zeta[s],j);
973 }
974
975 // Update b0, bplus, lambda, psi
976 Update_b0_bplus_from_A0_Aplus(p);
977 if ((p->Specification & SPEC_SIMS_ZHA) == SPEC_SIMS_ZHA) Update_lambda_psi_from_bplus(p);
978
979 // Flags and notification that the VAR parameters have changed
980 p->valid_parameters=1;
981 ThetaChanged(model);
982 rtrn=1;
983
984 ERRORCOND:
985
986 // Free memory
987 dw_FreeArray(A0);
988 dw_FreeArray(Aplus);
989 dw_FreeArray(Zeta);
990
991 return rtrn;
992 }
993
994 /*
995 Writes the VAR parameters to a file. The identifiers are
996
997 //== <header>A0[s] ==//
998 //== <header>Aplus[s] ==//
999 //== <header>Zeta[s] ==//
1000
1001 for 1 <= s <= nstates
1002 */
1003 int Write_VAR_Parameters(FILE *f, char *filename, char *header, TStateModel *model)
1004 {
1005 TMatrix X;
1006 int s;
1007 FILE *f_out;
1008 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1009
1010 f_out=f ? f :dw_CreateTextFile(filename);
1011
1012 if (!header) header="";
1013
1014 for (s=0; s < p->nstates; s++)
1015 {
1016 X=MakeA0((TMatrix)NULL,s,p);
1017 fprintf(f_out,"//== %sA0[%d] ==//\n",header,s+1);
1018 dw_PrintMatrix(f_out,X,"%22.14le ");
1019 fprintf(f_out,"\n");
1020 FreeMatrix(X);
1021
1022 X=MakeAplus((TMatrix)NULL,s,p);
1023 fprintf(f_out,"//== %sAplus[%d] ==//\n",header,s+1);
1024 dw_PrintMatrix(f_out,X,"%22.14le ");
1025 fprintf(f_out,"\n");
1026 FreeMatrix(X);
1027
1028 X=MakeZeta((TMatrix)NULL,s,p);
1029 fprintf(f_out,"//== %sZeta[%d] ==//\n",header,s+1);
1030 dw_PrintMatrix(f_out,X,"%22.14le ");
1031 fprintf(f_out,"\n");
1032 FreeMatrix(X);
1033 }
1034
1035 if (!f) fclose(f_out);
1036
1037 return 1;
1038 }
1039
1040 /*
1041 Writes the headers for Write_VAR_ParametersFlat(). This routine can
1042 be used to give the ordering for Write_VAR_ParametersFlat().
1043 */
1044 int Write_VAR_ParametersFlat_Headers(FILE *f_out, TStateModel *model)
1045 {
1046 int i, j, s;
1047 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1048
1049 if (!f_out) return 0;
1050
1051 for (s=0; s < p->nstates; s++)
1052 {
1053 for (j=0; j < p->nvars; j++)
1054 for (i=0; i < p->nvars; i++)
1055 fprintf(f_out,"A0[%d](%d,%d) ",s+1,i+1,j+1);
1056
1057 for (j=0; j < p->nvars; j++)
1058 for (i=0; i < p->npre; i++)
1059 fprintf(f_out,"Aplus[%d](%d,%d) ",s+1,i+1,j+1);
1060
1061 for (j=0; j < p->nvars; j++)
1062 fprintf(f_out,"Zeta[%d](%d,%d) ",s+1,j+1,j+1);
1063 }
1064
1065 return 1;
1066 }
1067
1068 /*
1069 For each state the VAR parameters are printed as follows
1070 A0 (by columns)
1071 Aplus (by columns)
1072 Zeta (diagonal)
1073 */
1074 int Write_VAR_ParametersFlat(FILE *f, TStateModel *model, char *fmt)
1075 {
1076 TMatrix A0, Aplus;
1077 int s, i, j;
1078 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1079
1080 if (!f) return 0;
1081
1082 if (!fmt) fmt="%lf ";
1083
1084 A0=CreateMatrix(p->nvars,p->nvars);
1085 Aplus=CreateMatrix(p->npre,p->nvars);
1086
1087 for (s=0; s < p->nstates; s++)
1088 {
1089 MakeA0(A0,s,p);
1090 for (j=0; j < p->nvars; j++)
1091 for (i=0; i < p->nvars; i++)
1092 fprintf(f,fmt,ElementM(A0,i,j));
1093
1094
1095 MakeAplus(Aplus,s,p);
1096 for (j=0; j < p->nvars; j++)
1097 for (i=0; i < p->npre; i++)
1098 fprintf(f,fmt,ElementM(Aplus,i,j));
1099
1100 for (j=0; j < p->nvars; j++)
1101 fprintf(f,fmt,p->Zeta[j][p->var_states[j][s]]);
1102 }
1103
1104 FreeMatrix(Aplus);
1105 FreeMatrix(A0);
1106
1107 return 1;
1108 }
1109
1110 /*
1111 For each state the VAR parameters are printed as follows
1112 A0 (by columns)
1113 Aplus (by columns)
1114 Zeta (diagonal)
1115 The system is normalized so that the diagonal of A0 is one.
1116 */
1117 int Write_VAR_ParametersFlat_A0_Diagonal_One(FILE *f, TStateModel *model, char *fmt)
1118 {
1119 TMatrix A0, Aplus;
1120 TVector i_diagonal, s_diagonal;
1121 int s, i, j;
1122 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1123 PRECISION x;
1124
1125 if (!f) return 0;
1126
1127 if (!fmt) fmt="%lf ";
1128
1129 A0=CreateMatrix(p->nvars,p->nvars);
1130 Aplus=CreateMatrix(p->npre,p->nvars);
1131 s_diagonal=CreateVector(p->nvars);
1132 i_diagonal=CreateVector(p->nvars);
1133
1134 for (s=0; s < p->nstates; s++)
1135 {
1136 MakeA0(A0,s,p);
1137 for (i=p->nvars-1; i >= 0; i--)
1138 {
1139 ElementV(i_diagonal,i)=1.0/(x=ElementM(A0,i,i));
1140 ElementV(s_diagonal,i)=x*x;
1141 }
1142
1143 for (j=0; j < p->nvars; j++)
1144 for (i=0; i < p->nvars; i++)
1145 fprintf(f,fmt,ElementM(A0,i,j)*ElementV(i_diagonal,j));
1146
1147 MakeAplus(Aplus,s,p);
1148 for (j=0; j < p->nvars; j++)
1149 for (i=0; i < p->npre; i++)
1150 fprintf(f,fmt,ElementM(Aplus,i,j)*ElementV(i_diagonal,j));
1151
1152 for (j=0; j < p->nvars; j++)
1153 fprintf(f,fmt,p->Zeta[j][p->var_states[j][s]] * ElementV(s_diagonal,j));
1154 }
1155
1156 FreeVector(i_diagonal);
1157 FreeVector(s_diagonal);
1158 FreeMatrix(Aplus);
1159 FreeMatrix(A0);
1160
1161 return 1;
1162 }
1163
1164 /*
1165 Attempts to read all parameters. The identifiers are
1166
1167 //== <id>States ==//
1168 //== <id>Transition matrix[] ==//
1169 //== <id>A0[s] ==//
1170 //== <id>Aplus[s] ==//
1171 //== <id>Zeta[s] ==//
1172
1173 for 1 <= s <= nstates
1174 */
1175 void ReadAllParameters(FILE *f, char *filename, char *id, TStateModel *model)
1176 {
1177 char *buffer, *fmt="//== %sStates ==//";
1178 FILE *f_in=f ? f :dw_OpenTextFile(filename);
1179
1180 if (!id) id="";
1181
1182 sprintf(buffer=(char*)dw_malloc(strlen(fmt) + strlen(id) - 1),fmt,id);
1183 ReadArray_VARio(f_in,buffer,model->S);
1184 dw_free(buffer);
1185
1186 ReadBaseTransitionMatrices(f_in,(char*)NULL,id,model);
1187 Read_VAR_Parameters(f_in,(char*)NULL,id,model);
1188
1189 if (!f) fclose(f_in);
1190 }
1191
1192 /*
1193 Attempts to write all parameters using a format readable by the routine
1194 ReadAllParameters().
1195 */
1196 void WriteAllParameters(FILE *f, char *filename, char *id, TStateModel *model)
1197 {
1198 FILE *f_in=f ? f : dw_CreateTextFile(filename);
1199
1200 if (!id) id="";
1201
1202 fprintf(f_in,"//== %sStates ==//\n",id);
1203 dw_PrintArray(f_in,model->S,(char*)NULL);
1204 fprintf(f_in,"\n");
1205
1206 WriteBaseTransitionMatrices(f_in,(char*)NULL,id,model);
1207 Write_VAR_Parameters(f_in,(char*)NULL,id,model);
1208
1209 if (!f) fclose(f_in);
1210 }
1211
1212 /*******************************************************************************/
1213 /******************************** Input/Output *********************************/
1214 /*******************************************************************************/
1215 void Write_ReducedFormVAR_Parameters(FILE *f, char *filename, T_VAR_Parameters *p)
1216 {
1217 TMatrix A0, Aplus, Zeta, C, Sigma;
1218 int k;
1219 FILE *f_out;
1220
1221 f_out=f ? f :dw_CreateTextFile(filename);
1222
1223 A0=CreateMatrix(p->nvars,p->nvars);
1224 Aplus=CreateMatrix(p->npre,p->nvars);
1225 Zeta=CreateMatrix(p->nvars,p->nvars);
1226 C=CreateMatrix(p->npre,p->nvars);
1227 Sigma=CreateMatrix(p->nvars,p->nvars);
1228
1229 for (k=0; k < p->nstates; k++)
1230 {
1231 MakeA0(A0,k,p);
1232 MakeAplus(Aplus,k,p);
1233 MakeZeta(Zeta,k,p);
1234
1235 //ProductInverseMM(C,Aplus,A0);
1236 //ProductMM(A0,A0,Xi);
1237 //ProductTransposeMM(Sigma,A0,A0);
1238 //Inverse_LU(Sigma,Sigma);
1239
1240 fprintf(f_out,"//== Reduced Form[%d] ==//\n",k+1);
1241 dw_PrintMatrix(f_out,C,"%lf ");
1242 fprintf(f_out,"\n");
1243
1244 fprintf(f_out,"//== Variance[%d] ==//\n",k+1);
1245 dw_PrintMatrix(f_out,Sigma,"%lf ");
1246 fprintf(f_out,"\n");
1247 }
1248
1249 FreeMatrix(A0);
1250 FreeMatrix(Aplus);
1251 FreeMatrix(Zeta);
1252 FreeMatrix(C);
1253 FreeMatrix(Sigma);
1254
1255 if (!f) fclose(f_out);
1256 }
1257
1258 /*
1259 Create Model from data file. Assumes that the state variables have a flat
1260 structure.
1261 */
1262 void Write_VAR_Info(FILE *f, char *filename, T_VAR_Parameters *p)
1263 {
1264 FILE *f_out;
1265 int j;
1266
1267 if (!f)
1268 f_out=dw_CreateTextFile(filename);
1269 else
1270 f_out=f;
1271
1272 //=== Write sizes ===//
1273 fprintf(f_out,"//== Number Observations ==//\n%d\n\n",p->nobs);
1274 fprintf(f_out,"//== Number Variables ==//\n%d\n\n",p->nvars);
1275 fprintf(f_out,"//== Number Lags ==//\n%d\n\n",p->nlags);
1276 fprintf(f_out,"//== Exogenous Variables ==//\n%d\n\n",p->npre - p->nvars * p->nlags);
1277
1278 //=== Restrictions - U[j] ===//
1279 fprintf(f_out,"//== Number of free parameters in jth column of A0 ==//\n");
1280 for (j=0; j < p->nvars; j++)
1281 fprintf(f_out,"%d ",ColM(p->U[j]));
1282 fprintf(f_out,"\n\n");
1283 fprintf(f_out,"//== U[j] 0 <= j < nvars ==//\n");
1284 for (j=0; j < p->nvars; j++)
1285 {
1286 dw_PrintMatrix(f_out,p->U[j],"%lf ");
1287 fprintf(f_out,"\n");
1288 }
1289
1290 //=== Restrictions - V[j] ===//
1291 fprintf(f_out,"//== Number of free parameters in jth column of Aplus ==//\n");
1292 for (j=0; j < p->nvars; j++)
1293 fprintf(f_out,"%d ",p->V[j] ? ColM(p->V[j]) : 0);
1294 fprintf(f_out,"\n\n");
1295 fprintf(f_out,"//== V[j] 0 <= j < nvars ==//\n");
1296 for (j=0; j < p->nvars; j++)
1297 if (p->V[j])
1298 {
1299 dw_PrintMatrix(f_out,p->V[j],"%lf ");
1300 fprintf(f_out,"\n");
1301 }
1302
1303 //=== Restrictions - W[j] ===//
1304 fprintf(f_out,"//== Non-zero W[j] ==//\n");
1305 for (j=0; j < p->nvars; j++)
1306 fprintf(f_out,"%d ",p->W[j] ? 1 : 0);
1307 fprintf(f_out,"\n\n");
1308 fprintf(f_out,"//== W[j] 0 <= j < nvars ==//\n");
1309 for (j=0; j < p->nvars; j++)
1310 if (p->W[j])
1311 {
1312 dw_PrintMatrix(f_out,p->W[j],"%lf ");
1313 fprintf(f_out,"\n");
1314 }
1315
1316 //====== Priors ======
1317 fprintf(f_out,"//== Gamma prior on Xi ==//\n");
1318 for (j=0; j < p->nvars; j++)
1319 fprintf(f_out,"%lf %lf\n",ElementV(p->zeta_a_prior,j),ElementV(p->zeta_b_prior,j));
1320 fprintf(f_out,"\n");
1321
1322 fprintf(f_out,"//== Prior on jth column of A0 - Gaussian variance ==//\n");
1323 for (j=0; j < p->nvars; j++)
1324 {
1325 dw_PrintMatrix(f_out,p->A0_prior[j],"%lf ");
1326 fprintf(f_out,"\n");
1327 }
1328
1329 fprintf(f_out,"//== Prior on jth column of Aplus - Gaussian variance ==//\n");
1330 for (j=0; j < p->nvars; j++)
1331 {
1332 dw_PrintMatrix(f_out,p->Aplus_prior[j],"%lf ");
1333 fprintf(f_out,"\n");
1334 }
1335
1336 /* //====== coefficient/variance state variables ====== */
1337 /* CStates=dw_CreateRegularArrayList_int(2,p->nvars,sv->n_state_variables); */
1338 /* id="//== Controlling states variables for coefficients ==//"; */
1339 /* if (!dw_SetFilePosition(f_in,id) || !dw_ReadArray(f_in,CStates)) dw_Error(PARSE_ERR); */
1340
1341 /* VStates=dw_CreateRegularArrayList_int(2,p->nvars,sv->n_state_variables); */
1342 /* id="//== Controlling states variables for variance ==//"; */
1343 /* if (!dw_SetFilePosition(f_in,id) || !dw_ReadArray(f_in,VStates)) dw_Error(PARSE_ERR); */
1344
1345 /* //=== Read Data === */
1346 /* if (!dw_SetFilePosition(f_in,"//== Data Y (T x nvars) ==//") */
1347 /* || !dw_SetFilePosition(f_in,"//== Data X (T x npre) ==//")) */
1348 /* p->X=p->Y=(TVector*)NULL; */
1349 /* else */
1350 /* { */
1351 /* // Initialize Y */
1352 /* id="//== Data Y (T x nvars) ==//"; */
1353 /* if (!dw_SetFilePosition(f_in,id)) dw_Error(PARSE_ERR); */
1354 /* p->Y=dw_CreateArray_vector(p->nobs+1); */
1355 /* for (t=1; t <= p->nobs; t++) */
1356 /* if (!dw_ReadVector(f_in,p->Y[t]=CreateVector(p->nvars))) dw_Error(PARSE_ERR); */
1357
1358 /* // Initialize X */
1359 /* id="//== Data X (T x npre) ==//"; */
1360 /* if (!dw_SetFilePosition(f_in,id)) dw_Error(PARSE_ERR); */
1361 /* p->X=dw_CreateArray_vector(p->nobs+1); */
1362 /* for (t=1; t <= p->nobs; t++) */
1363 /* if (!dw_ReadVector(f_in,p->X[t]=CreateVector(p->npre))) */
1364 /* dw_Error(PARSE_ERR); */
1365 /* } */
1366
1367 //=== Close output file ===
1368 if (!f) fclose(f_out);
1369 }
1370 /*******************************************************************************/
1371 /*******************************************************************************/
1372 /*******************************************************************************/
1373 /*
1374 There was a bug in the original coded that could cause a perturbation in the
1375 initial values. If was found that this perturbation sometimes inproved the
1376 performance of the estimation procedure. We include this technique so the
1377 results of original code can reproduced. A more systematic approach to
1378 perturbation is now used.
1379 */
1380 static void Update_lambda_psi_from_bplus_original(T_VAR_Parameters *p)
1381 {
1382 int j, k, i, m, n, dim=p->nlags*p->nvars;
1383 PRECISION *p_bplus, *p_lambda, *p_psi;
1384 for (j=p->nvars-1; j >= 0; j--)
1385 {
1386 p_psi=pElementV(p->psi[j]);
1387 p_bplus=pElementV(p->bplus[j][0]);
1388 memcpy(p_psi,p_bplus,dim*sizeof(PRECISION));
1389 ElementV(p->constant[j],0)=p_bplus[dim];
1390 InitializeVector(p->lambda[j][0],1.0);
1391
1392 for (k=dw_DimA(p->bplus[j])-1; k > 0; k--)
1393 {
1394 p_bplus=pElementV(p->bplus[j][k]);
1395 p_lambda=pElementV(p->lambda[j][k]);
1396 ElementV(p->constant[j],k)=p_bplus[dim];
1397 for (m=p->nvars-1; m >= 0; m--)
1398 {
1399 for (n=dim+m, i=n-p->nvars; i >= 0; i-=p->nvars)
1400 if (fabs(p_psi[i]) > fabs(p_psi[n])) n=i;
1401 p_lambda[m]=(p_psi[n] != 0) ? p_bplus[n]/p_psi[n] : 0;
1402 }
1403 }
1404 }
1405 }
1406 int Read_VAR_Parameters_Original(FILE *f, char *filename, char *header, TStateModel *model)
1407 {
1408 FILE *f_in;
1409 char *idbuffer, *fmt;
1410 TMatrix *A0, *Aplus, *Zeta;
1411 int i, j, s;
1412 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1413
1414 // Valid file
1415 f_in=OpenFile_VARio(f,filename);
1416 if (!f_in) return 0;
1417
1418 if (!header) header="";
1419
1420 // Allocate memory
1421 A0=dw_CreateArray_matrix(p->nstates);
1422 Aplus=dw_CreateArray_matrix(p->nstates);
1423 Zeta=dw_CreateArray_matrix(p->nstates);
1424
1425 // Read File
1426 for (s=0; s < p->nstates; s++)
1427 {
1428 fmt="//== %sA0[%d] ==//";
1429 sprintf(idbuffer=(char*)dw_malloc(strlen(fmt)+strlen(header)+strlen_int(s+1)-3),fmt,header,s+1);
1430 if (!dw_SetFilePosition(f_in,idbuffer) || !dw_ReadMatrix(f_in,A0[s]=CreateMatrix(p->nvars,p->nvars)))
1431 {
1432 ReadError_VARio(idbuffer);
1433 dw_free(idbuffer);
1434 if (!f) fclose(f_in);
1435 return 0;
1436 }
1437 dw_free(idbuffer);
1438
1439 fmt="//== %sAplus[%d] ==//";
1440 sprintf(idbuffer=(char*)dw_malloc(strlen(fmt)+strlen(header)+strlen_int(s+1)-3),fmt,header,s+1);
1441 if (!dw_SetFilePosition(f_in,idbuffer) || !dw_ReadMatrix(f_in,Aplus[s]=CreateMatrix(p->npre,p->nvars)))
1442 {
1443 ReadError_VARio(idbuffer);
1444 dw_free(idbuffer);
1445 if (!f) fclose(f_in);
1446 return 0;
1447 }
1448 dw_free(idbuffer);
1449
1450 fmt="//== %sZeta[%d] ==//";
1451 sprintf(idbuffer=(char*)dw_malloc(strlen(fmt)+strlen(header)+strlen_int(s+1)-3),fmt,header,s+1);
1452 if (!dw_SetFilePosition(f_in,idbuffer) || !dw_ReadMatrix(f_in,Zeta[s]=CreateMatrix(p->nvars,p->nvars)))
1453 {
1454 ReadError_VARio(idbuffer);
1455 dw_free(idbuffer);
1456 if (!f) fclose(f_in);
1457 return 0;
1458 }
1459 dw_free(idbuffer);
1460 }
1461 if (!f) fclose(f_in);
1462
1463 // Set A0, Aplus, and Zeta
1464 for (j=0; j < p->nvars; j++)
1465 for (s=0; s < p->nstates; s++)
1466 {
1467 for (i=0; i < p->nvars; i++)
1468 ElementV(p->A0[j][p->coef_states[j][s]],i)=ElementM(A0[s],i,j);
1469
1470 for (i=0; i < p->npre; i++)
1471 ElementV(p->Aplus[j][p->coef_states[j][s]],i)=ElementM(Aplus[s],i,j);
1472
1473 p->Zeta[j][p->var_states[j][s]]=ElementM(Zeta[s],j,j);
1474 }
1475
1476 // Free memory
1477 dw_FreeArray(A0);
1478 dw_FreeArray(Aplus);
1479 dw_FreeArray(Zeta);
1480
1481 // Check Zeta non-negative
1482 for (j=p->nvars-1; j >= 0; j--)
1483 for (s=p->n_var_states[j]-1; s >= 0; s--)
1484 if (p->Zeta[j][s] < 0.0)
1485 {
1486 dw_UserError("Zeta has negative value.");
1487 p->valid_parameters=0;
1488 ThetaChanged(model);
1489 return 0;
1490 }
1491
1492 // Update b0, bplus, lambda, psi
1493 Update_b0_bplus_from_A0_Aplus(p);
1494 if ((p->Specification & SPEC_SIMS_ZHA) == SPEC_SIMS_ZHA) Update_lambda_psi_from_bplus_original(p);
1495
1496 // Flags and notification that the VAR parameters have changed
1497 p->valid_parameters=1;
1498 ThetaChanged(model);
1499
1500 return 1;
1501 }
1502 /*******************************************************************************/
1503 /*******************************************************************************/
1504 /*******************************************************************************/
1505
1506
1507 /*
1508 Create Model from data file. Assumes that the state variables have a flat
1509 structure.
1510 */
1511 /**
1512 TStateModel* CreateStateModel_VAR_File(FILE *f, char *filename)
1513 {
1514 TMarkovStateVariable *sv;
1515 T_VAR_Parameters *p;
1516
1517 //=== Create Markov State Variable ===
1518 sv=CreateMarkovStateVariable_File(f,filename,0);
1519
1520 //=== Create VAR Parameters
1521 p=Create_VAR_Parameters_File(f,filename,sv);
1522
1523 //=== Create TStateModel ===
1524 return CreateStateModel_new(sv,CreateRoutines_VAR(),p);
1525 }
1526 **/