Debian Codegraph @

contrib/ms-sbvar/switch_dw/state_space/sbvar/VARbase.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 "VARbase.h"
19 #include "VARio.h"
20 #include "dw_switchio.h"
21 #include "dw_error.h"
22 #include "dw_array.h"
23 #include "dw_matrix_array.h"
24 #include "dw_rand.h"
25 #include "dw_matrix_rand.h"
26 #include "dw_ascii.h"
27 #include "dw_std.h"
28 #include "bmatrix.h"
29
30 #include <math.h>
31 #include <time.h>
32 #include <stdlib.h>
33 #include <string.h>
34
35 static int IncrementIndex(int idx, int i, TMarkovStateVariable *top, TMarkovStateVariable *sv);
36 static int* CreateStateIndex(TMarkovStateVariable* sv, TMarkovStateVariable** list, int n);
37 static void CreateFlipped(T_VAR_Parameters *p);
38 static void SetFlipped_VAR(T_VAR_Parameters *p);
39
40 //=== Private counter for improper normal distribution ===
41 static int _VAR_IMPROPER_DISTRIBUTION_COUNTER = 0;
42 int Reset_VAR_Improper_Distribution_Counter(void)
43 {
44 int rtrn=_VAR_IMPROPER_DISTRIBUTION_COUNTER;
45 _VAR_IMPROPER_DISTRIBUTION_COUNTER=0;
46 return rtrn;
47 }
48
49 int Get_VAR_Improper_Distribution_Counter(void)
50 {
51 return _VAR_IMPROPER_DISTRIBUTION_COUNTER;
52 }
53
54 #define BPLUS_ERR 1
55 #define PSI_ERR 2
56 #define LAMBDA_ERR 3
57
58 static int _SINGULAR_ERROR = 0;
59
60 static int _VERBOSE_COUNT = 0;
61 FILE *V_FILE = (FILE*)NULL;
62
63 void Increment_Verbose(void)
64 {
65 _VERBOSE_COUNT++;
66 }
67
68 void SetVerboseFile(FILE *f)
69 {
70 V_FILE=f;
71 }
72
73 int Get_VAR_Sigular_Error(void)
74 {
75 return _SINGULAR_ERROR;
76 }
77
78 TVector DrawNormal_InverseVariance_SVD(TVector x, TVector b, TMatrix S);
79 TVector SingularInverseVariance_RecoveryAttempt(TVector x, TVector b, TMatrix S, TMatrix InversePrior, TStateModel *model, int code);
80 //=========================================================
81
82
83 /*******************************************************************************/
84 /************************** Constructors/Destructors ***************************/
85 /*******************************************************************************/
86 void FreeTheta_VAR(T_VAR_Parameters *p)
87 {
88 int j;
89 if (p)
90 {
91 // Free parameters
92 dw_FreeArray(p->A0);
93 dw_FreeArray(p->Aplus);
94 dw_FreeArray(p->Zeta);
95
96 // Free state variable translation
97 dw_FreeArray(p->n_var_states);
98 dw_FreeArray(p->var_states);
99 dw_FreeArray(p->n_coef_states);
100 dw_FreeArray(p->coef_states);
101 dw_FreeArray(p->A0_states);
102 dw_FreeArray(p->A0_column_states);
103
104 // Free free parameters
105 dw_FreeArray(p->dim_b0);
106 dw_FreeArray(p->b0);
107 dw_FreeArray(p->dim_bplus);
108 dw_FreeArray(p->bplus);
109
110 // Free Sims-Zha specification parameters and workspace
111 dw_FreeArray(p->lambda);
112
113 //--- Non-standard memory management ---
114 if (p->constant)
115 for (j=dw_DimA(p->constant)-1; j >= 0; j--)
116 if (p->constant[j])
117 pElementV(p->constant[j])=(PRECISION*)NULL;
118 dw_FreeArray(p->constant);
119 //--------------------------------------
120
121 dw_FreeArray(p->psi);
122 dw_FreeArray(p->inverse_psi_prior);
123
124 // Free Priors
125 FreeVector(p->zeta_a_prior);
126 FreeVector(p->zeta_b_prior);
127 dw_FreeArray(p->A0_prior);
128 dw_FreeArray(p->Aplus_prior);
129
130 // Free identifiying restrictions
131 dw_FreeArray(p->U);
132 dw_FreeArray(p->V);
133 dw_FreeArray(p->W);
134 dw_FreeArray(p->IsIdentity_V);
135
136 // Free normalization
137 dw_FreeArray(p->flipped);
138 dw_FreeArray(p->Target);
139
140 // Free workspace
141 FreeVector(p->inverse_zeta_b_prior);
142 dw_FreeArray(p->inverse_b0_prior);
143 dw_FreeArray(p->inverse_bplus_prior);
144 FreeVector(p->log_abs_det_A0);
145 dw_FreeArray(p->A0_dot_products);
146 dw_FreeArray(p->Aplus_dot_products);
147
148 // Free state dependent fields
149 dw_FreeArray(p->YY);
150 dw_FreeArray(p->XY);
151 dw_FreeArray(p->XX);
152 dw_FreeArray(p->yy);
153 dw_FreeArray(p->xy);
154 dw_FreeArray(p->xx);
155 dw_FreeArray(p->S);
156 dw_FreeArray(p->T);
157
158 // A0 Metropolis Info
159 dw_FreeArray(p->A0_Metropolis_Scale);
160 dw_FreeArray(p->A0_Metropolis_Jumps);
161
162 // Free Data
163 dw_FreeArray(p->Y);
164 dw_FreeArray(p->X);
165
166 // Free pointer
167 dw_free(p);
168 }
169 }
170
171 ThetaRoutines* CreateRoutines_VAR(void)
172 {
173 ThetaRoutines *rtns=CreateThetaRoutines_empty();
174
175 rtns->pLogConditionalLikelihood=LogConditionalProbability_VAR;
176 rtns->pExpectationSingleStep=ExpectationSingleStep_VAR;
177 rtns->pDestructor=(void (*)(void*))FreeTheta_VAR;
178 rtns->pLogPrior=LogPrior_VAR;
179 rtns->pNumberFreeParametersTheta=NumberFreeParametersVAR;
180 rtns->pConvertFreeParametersToTheta=FreeParametersToVAR;
181 rtns->pConvertThetaToFreeParameters=VARToFreeParameters;
182 rtns->pDrawParameters=DrawParameters_VAR;
183 rtns->pStatesChanged=StatesChanged_VAR;
184 rtns->pThetaChanged=ThetaChanged_VAR;
185 rtns->pInitializeForwardRecursion=InitializeForwardRecursion_VAR;
186 rtns->pIsDegenerate=IsDegenerate_VAR;
187 rtns->pNormalizeRegimes=NormalizeRegimes_VAR;
188
189 return rtns;
190 }
191
192 T_VAR_Parameters* CreateTheta_VAR(int flag, int nvars, int nlags, int nexg, int nstates, int nobs, // Specification and Sizes
193 int **coef_states, int **var_states, // Translation Tables
194 TMatrix *U, TMatrix *V, TMatrix *W, // Restrictions
195 TMatrix Y, TMatrix X) // Data
196 {
197 T_VAR_Parameters *p;
198 int i, j, k, t, npre;
199 TMatrix S;
200
201 if ((nvars <= 0) || (nlags < 0) || (nexg < 0))
202 {
203 printf("CreateTheta_VAR(): Invalid arguments passed.\n");
204 dw_exit(0);
205 }
206
207 //=== Allocate memory for T_VAR_Parameters ===
208 if (!(p=(T_VAR_Parameters*)dw_malloc(sizeof(T_VAR_Parameters))))
209 {
210 printf("Out of memory\n");
211 dw_exit(0);
212 }
213
214 //=== Model Specification ===
215 if (flag & SPEC_SIMS_ZHA) flag|=SPEC_RANDOM_WALK;
216 p->Specification=flag;
217
218 //====== Flags ======
219 p->valid_state_dependent_fields=0;
220 p->valid_state_dependent_fields_previous=0;
221 p->valid_log_abs_det_A0=0;
222 p->valid_dot_products=0;
223 p->valid_parameters=0;
224 p->valid_normalization=-1;
225
226 //=== Sizes ===//
227 p->nobs=nobs;
228 p->nstates=nstates;
229 p->nvars=nvars;
230 p->nlags=nlags;
231 p->npre=npre=nvars*nlags+nexg;
232
233 //====== Create n_coef_states, n_var_states ======
234 p->n_coef_states=(int*)dw_CreateArray_int(nvars);
235 p->n_var_states=(int*)dw_CreateArray_int(nvars);
236 for (j=nvars-1; j >= 0; j--)
237 {
238 for (p->n_coef_states[j]=0, i=p->nstates-1; i >= 0; i--)
239 if (coef_states[j][i] > p->n_coef_states[j])
240 p->n_coef_states[j]=coef_states[j][i];
241 p->n_coef_states[j]++;
242
243 for (p->n_var_states[j]=0, i=nstates-1; i >= 0; i--)
244 if (var_states[j][i] > p->n_var_states[j])
245 p->n_var_states[j]=var_states[j][i];
246 p->n_var_states[j]++;
247 }
248
249 //====== Create coef_states, var_states ======
250 p->coef_states=(int**)dw_CopyArray((void*)NULL,coef_states);
251 p->var_states=(int**)dw_CopyArray((void*)NULL,var_states);
252
253 //====== Create A0, Aplus, Zeta ======
254 p->A0=(TVector**)dw_CreateArray_array(nvars);
255 p->Aplus=(TVector**)dw_CreateArray_array(nvars);
256 p->Zeta=(PRECISION**)dw_CreateArray_array(nvars);
257 for (j=nvars-1; j >= 0; j--)
258 {
259 p->A0[j]=dw_CreateArray_vector(p->n_coef_states[j]);
260 for (k=p->n_coef_states[j]-1; k >= 0; k--)
261 p->A0[j][k]=CreateVector(nvars);
262
263 p->Aplus[j]=(TVector*)dw_CreateArray_vector(p->n_coef_states[j]);
264 for (k=p->n_coef_states[j]-1; k >= 0; k--)
265 p->Aplus[j][k]=CreateVector(npre);
266
267 p->Zeta[j]=(PRECISION*)dw_CreateArray_scalar(p->n_var_states[j]);
268 }
269
270 //====== A0 Metropolis Info ======
271 p->A0_Metropolis_Scale=dw_CreateArray_array(nvars);
272 for (j=nvars-1; j >= 0; j--)
273 p->A0_Metropolis_Scale[j]=dw_CreateArray_scalar(p->n_coef_states[j]);
274 dw_InitializeArray_scalar(p->A0_Metropolis_Scale,1.0);
275
276 p->A0_Metropolis_Jumps=dw_CreateArray_array(nvars);
277 for (j=nvars-1; j >= 0; j--)
278 p->A0_Metropolis_Jumps[j]=dw_CreateArray_int(p->n_coef_states[j]);
279 dw_InitializeArray_int(p->A0_Metropolis_Jumps,0);
280
281 //====== Create A0_states, A0_column_states, and log_det_abs_A0 ======
282 p->A0_states=dw_CreateArray_int(nstates);
283 for (p->n_A0_states=0, i=0; i < nstates; i++)
284 {
285 for (k=i-1; k >= 0; k--)
286 {
287 for (j=nvars-1; j >= 0; j--)
288 if (coef_states[j][i] != coef_states[j][k]) break;
289 if (j < 0) break;
290 }
291 p->A0_states[i]=(k < 0) ? p->n_A0_states++ : p->A0_states[k];
292 }
293
294 p->A0_column_states=dw_CreateRectangularArray_int(nvars,p->n_A0_states);
295 for (i=0; i < p->n_A0_states; i++)
296 for (k=0; k < nstates; k++)
297 if (p->A0_states[k] == i)
298 {
299 for (j=nvars-1; j >= 0; j--)
300 p->A0_column_states[j][i]=coef_states[j][k];
301 break;
302 }
303
304 InitializeVector(p->log_abs_det_A0=CreateVector(p->n_A0_states),-1.0);
305
306 //=== Set Restrictions ===
307 p->U=dw_CopyArray(NULL,U);
308 p->b0=(TVector**)dw_CreateArray_array(nvars);
309 p->dim_b0=dw_CreateArray_int(nvars);
310 for (j=nvars-1; j >= 0; j--)
311 {
312 p->b0[j]=(TVector*)dw_CreateArray_vector(p->n_coef_states[j]);
313 for (k=p->n_coef_states[j]-1; k >= 0; k--)
314 p->b0[j][k]=CreateVector(p->dim_b0[j]=ColM(U[j]));
315 }
316
317 //=== Normalization ===
318 p->Target=(TVector**)NULL;
319 p->flipped=(int**)NULL;
320 Setup_No_Normalization_VAR(p);
321
322 //=== Specification ===
323 if (flag & SPEC_RANDOM_WALK)
324 {
325 p->W=dw_CreateArray_matrix(nvars);
326 InitializeMatrix(S=CreateMatrix(npre,nvars),0.0);
327 for (j=nvars-1; j >= 0; j--) ElementM(S,j,j)=-1.0;
328 for (j=nvars-1; j >= 0; j--) p->W[j]=EquateMatrix((TMatrix)NULL,S);
329 FreeMatrix(S);
330 }
331 else
332 p->W=dw_CopyArray((void*)NULL,W);
333
334 if (flag & SPEC_SIMS_ZHA)
335 {
336 dw_InitializeArray_int(p->IsIdentity_V=dw_CreateArray_int(nvars),1);
337 p->V=dw_CreateArray_matrix(nvars);
338 for (j=p->nvars-1; j >= 0; j--) p->V[j]=IdentityMatrix((TMatrix)NULL,npre);
339
340 // Setup psi and lambda parameters
341 p->lambda=(TVector**)dw_CreateArray_array(nvars);
342 p->psi=dw_CreateArray_vector(nvars);
343 for (j=nvars-1; j >= 0; j--)
344 {
345 p->lambda[j]=dw_CreateArray_vector(p->n_coef_states[j]);
346 for (k=dw_DimA(p->lambda[j])-1; k >= 0; k--)
347 p->lambda[j][k]=CreateVector(nvars);
348
349 p->psi[j]=CreateVector(npre - 1 + p->n_coef_states[j]);
350 }
351
352 //--- non-standard memory management ---
353 p->constant=(TVector*)dw_CreateArray_vector(nvars);
354 for (j=nvars-1; j >= 0; j--)
355 {
356 p->constant[j]=CreateVector(p->n_coef_states[j]);
357 dw_free(pElementV(p->constant[j]));
358 pElementV(p->constant[j])=pElementV(p->psi[j]) + npre - 1;
359 }
360 //--------------------------------------
361 }
362 else
363 {
364 //====== Sims-Zha Specification ======
365 p->lambda=(TVector**)NULL;
366 p->psi=(TVector*)NULL;
367 p->constant=(TVector*)NULL;
368
369 //====== If the number of columns in V[j] == npre then we may assume that V[j] is the identity. ======
370 dw_InitializeArray_int(p->IsIdentity_V=dw_CreateArray_int(nvars),0);
371 p->V=dw_CreateArray_matrix(nvars);
372 for (j=nvars-1; j >= 0; j--)
373 if (V[j])
374 {
375 if (ColM(V[j]) < npre)
376 p->V[j]=EquateMatrix((TMatrix)NULL,V[j]);
377 else
378 {
379 p->V[j]=IdentityMatrix((TMatrix)NULL,npre);
380 p->IsIdentity_V[j]=1;
381 }
382 }
383 }
384 p->bplus=(TVector**)dw_CreateArray_array(nvars);
385 p->dim_bplus=dw_CreateArray_int(nvars);
386 for (j=nvars-1; j >= 0; j--)
387 if (V[j])
388 {
389 p->bplus[j]=(TVector*)dw_CreateArray_vector(p->n_coef_states[j]);
390 for (k=p->n_coef_states[j]-1; k >= 0; k--)
391 p->bplus[j][k]=CreateVector(p->dim_bplus[j]=ColM(V[j]));
392 }
393
394 //====== Data ======
395 p->Y=dw_CreateArray_vector(nobs+1);
396 p->X=dw_CreateArray_vector(nobs+1);
397 for (t=nobs; t > 0; t--)
398 {
399 p->Y[t]=CreateVector(nvars);
400 for (i=nvars-1; i >= 0; i--) ElementV(p->Y[t],i)=ElementM(Y,t-1,i);
401
402 p->X[t]=CreateVector(p->npre);
403 for (i=p->npre-1; i >= 0; i--) ElementV(p->X[t],i)=ElementM(X,t-1,i);
404 }
405
406 //====== Workspace ======
407 p->minus_half_nvars_times_log2pi=-0.5*(double)nvars*log(2.0*3.141592653589793);
408
409 // Dot products
410 p->A0_dot_products=(PRECISION***)dw_CreateArray_array(nobs+1);
411 for (t=0; t <= nobs; t++)
412 {
413 p->A0_dot_products[t]=(PRECISION**)dw_CreateArray_array(nvars);
414 for (j=0; j < nvars; j++)
415 p->A0_dot_products[t][j]=dw_CreateArray_scalar(p->n_coef_states[j]);
416 }
417
418 p->Aplus_dot_products=(PRECISION***)dw_CreateArray_array(nobs+1);
419 for (t=0; t <= nobs; t++)
420 {
421 p->Aplus_dot_products[t]=(PRECISION**)dw_CreateArray_array(nvars);
422 for (j=0; j < nvars; j++)
423 p->Aplus_dot_products[t][j]=dw_CreateArray_scalar(p->n_coef_states[j]);
424 }
425
426 // State dependent data
427 p->T=dw_CreateArray_int(nstates);
428 p->YY=dw_CreateArray_matrix(nstates);
429 p->XY=dw_CreateArray_matrix(nstates);
430 p->XX=dw_CreateArray_matrix(nstates);
431 for (k=nstates-1; k >= 0; k--)
432 {
433 p->YY[k]=CreateMatrix(nvars,nvars);
434 p->XY[k]=CreateMatrix(p->npre,nvars);
435 p->XX[k]=CreateMatrix(p->npre,p->npre);
436 }
437 p->yy=dw_CreateArray_matrix(nobs+1);
438 p->xy=dw_CreateArray_matrix(nobs+1);
439 p->xx=dw_CreateArray_matrix(nobs+1);
440 p->S=dw_CreateArray_int(nobs+1);
441 for (t=nobs; t > 0; t--)
442 {
443 p->yy[t]=OuterProduct((TMatrix)NULL,p->Y[t],p->Y[t]);
444 p->xy[t]=OuterProduct((TMatrix)NULL,p->X[t],p->Y[t]);
445 p->xx[t]=OuterProduct((TMatrix)NULL,p->X[t],p->X[t]);
446 }
447
448 //====== Set priors to null ======
449 p->A0_prior=(TMatrix*)NULL;
450 p->Aplus_prior=(TMatrix*)NULL;
451 p->zeta_a_prior=(TVector)NULL;
452 p->zeta_b_prior=(TVector)NULL;
453 p->lambda_prior=0.0;
454
455 p->inverse_b0_prior=(TMatrix*)NULL;
456 p->inverse_bplus_prior=(TMatrix*)NULL;
457 p->inverse_zeta_b_prior=(TVector)NULL;
458 p->inverse_lambda_prior=0.0;
459 p->inverse_psi_prior=(TMatrix*)NULL;
460
461 //====== Set number of free parameters ======
462 SetNumberFreeParametersVAR(p);
463
464 //====== Return ======
465 return p;
466 }
467
468 void SetPriors_VAR(T_VAR_Parameters *theta, TMatrix* A0_prior, TMatrix* Aplus_prior, TVector zeta_a_prior, TVector zeta_b_prior)
469 {
470 int j;
471 TMatrix S;
472
473 //====== Priors ======
474 theta->A0_prior=dw_CopyArray(NULL,A0_prior);
475 theta->Aplus_prior=dw_CopyArray(NULL,Aplus_prior);
476 theta->zeta_a_prior=EquateVector((TVector)NULL,zeta_a_prior);
477 theta->zeta_b_prior=EquateVector((TVector)NULL,zeta_b_prior);
478
479 //====== Prior workspace ======
480 theta->inverse_zeta_b_prior=CreateVector(theta->nvars);
481 for (j=theta->nvars-1; j >= 0; j--)
482 ElementV(theta->inverse_zeta_b_prior,j)=1.0/ElementV(zeta_b_prior,j);
483
484 theta->inverse_b0_prior=dw_CreateArray_matrix(theta->nvars);
485 for (j=theta->nvars-1; j >= 0; j--)
486 {
487 S=Inverse_LU((TMatrix)NULL,A0_prior[j]);
488 theta->inverse_b0_prior[j]=MatrixInnerProductSymmetric((TMatrix)NULL,theta->U[j],S);
489 ProductMS(theta->inverse_b0_prior[j],theta->inverse_b0_prior[j],theta->n_A0_states/theta->n_coef_states[j]);
490 FreeMatrix(S);
491 }
492
493 theta->inverse_bplus_prior=dw_CreateArray_matrix(theta->nvars);
494 for (j=theta->nvars-1; j >= 0; j--)
495 if (theta->V[j])
496 {
497 S=Inverse_LU((TMatrix)NULL,Aplus_prior[j]);
498 theta->inverse_bplus_prior[j]=MatrixInnerProductSymmetric((TMatrix)NULL,theta->V[j],S);
499 ProductMS(theta->inverse_bplus_prior[j],theta->inverse_bplus_prior[j],theta->n_A0_states/theta->n_coef_states[j]);
500 FreeMatrix(S);
501 }
502
503 //====== Set prior constant ======
504 SetLogPriorConstant_VAR(theta);
505 }
506
507 void SetPriors_VAR_SimsZha(T_VAR_Parameters *theta, TMatrix* A0_prior, TMatrix* Aplus_prior, TVector zeta_a_prior,
508 TVector zeta_b_prior, PRECISION lambda_prior)
509 {
510 int j, k, n, m;
511 TMatrix V, S, I, inverse_Aplus_prior;
512
513 if (theta->Specification & SPEC_SIMS_ZHA)
514 {
515 theta->lambda_prior=lambda_prior;
516 theta->inverse_lambda_prior=1.0/lambda_prior;
517
518 theta->inverse_psi_prior=dw_CreateArray_matrix(theta->nvars);
519 for (j=theta->nvars-1; j >= 0; j--)
520 {
521 inverse_Aplus_prior=Inverse_LU((TMatrix)NULL,Aplus_prior[j]);
522 I=IdentityMatrix((TMatrix)NULL,theta->n_A0_states);
523 S=KroneckerProduct((TMatrix)NULL,I,inverse_Aplus_prior);
524 InitializeMatrix(V=CreateMatrix(theta->npre * theta->n_A0_states,theta->npre-1 + theta->n_coef_states[j]),0.0);
525 for (k=theta->n_A0_states-1; k >= 0; k--)
526 {
527 for (n=theta->npre-2; n >= 0; n--)
528 for (m=theta->npre-1; m >= 0; m--)
529 ElementM(V,k*theta->npre + m,n)=ElementM(theta->V[j],m,n);
530
531 n=theta->npre - 1 + theta->A0_column_states[j][k];
532 for (m=theta->npre-1; m >= 0; m--)
533 ElementM(V,k * theta->npre + m,n)=ElementM(theta->V[j],m,theta->npre - 1);
534 }
535 theta->inverse_psi_prior[j]=MatrixInnerProductSymmetric((TMatrix)NULL,V,S);
536 FreeMatrix(V);
537 FreeMatrix(S);
538 FreeMatrix(I);
539 FreeMatrix(inverse_Aplus_prior);
540 }
541
542 SetPriors_VAR(theta,A0_prior,Aplus_prior,zeta_a_prior,zeta_b_prior);
543 }
544 else
545 {
546 printf("Error SetPriors_VAR_SimsZha(): specification flag not set to SPEC_SIM_ZHA\n");
547 dw_exit(0);
548 }
549 }
550
551 /*
552 Assumes
553 model: a properly initialized TStateModel structure.
554
555 Returns
556 A properly initialized TStateModel structure with the same number of first
557 level state variables, but only one overall state.
558 */
559 TStateModel* CreateConstantModeCreateConstantModel(TStateModel *model)
560 {
561 TMarkovStateVariable *sv, **sv_array;
562 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta), *theta;
563 ThetaRoutines *routines;
564 TMatrix X, Y;
565 int **translation_table, i, j, t;
566
567 if (model->sv->n_state_variables == 1)
568 sv=CreateMarkovStateVariable_ConstantState(model->nobs);
569 else
570 {
571 sv_array=dw_CreateArray_pointer(model->sv->n_state_variables,(void (*)(void*))FreeMarkovStateVariable);
572 for (i=model->sv->n_state_variables-1; i >= 0; i--)
573 sv_array[i]=CreateMarkovStateVariable_ConstantState(model->nobs);
574 sv=CreateMarkovStateVariable_Multiple(model->nobs,sv_array);
575 }
576
577 routines=CreateRoutines_VAR();
578
579 Y=CreateMatrix(p->nobs,p->nvars);
580 X=CreateMatrix(p->nobs,p->npre);
581 for (t=p->nobs; t > 0; t--)
582 {
583 for (i=p->nvars-1; i >= 0; i--) ElementM(Y,t-1,i)=ElementV(p->Y[t],i);
584 for (i=p->npre-1; i >= 0; i--) ElementM(X,t-1,i)=ElementV(p->X[t],i);
585 }
586
587 dw_InitializeArray_int(translation_table=dw_CreateRectangularArray_int(p->nvars,1),0);
588 theta=CreateTheta_VAR(p->Specification,p->nvars,p->nlags,p->npre - p->nlags*p->nvars,1,p->nobs,translation_table,translation_table,p->U,p->V,p->W,Y,X);
589 if (p->Specification & SPEC_SIMS_ZHA)
590 SetPriors_VAR_SimsZha(theta,p->A0_prior,p->Aplus_prior,p->zeta_a_prior,p->zeta_b_prior,p->lambda_prior);
591 else
592 SetPriors_VAR(theta,p->A0_prior,p->Aplus_prior,p->zeta_a_prior,p->zeta_b_prior);
593
594 FreeMatrix(X);
595 FreeMatrix(Y);
596 dw_FreeArray(translation_table);
597
598 // Initialize parameters
599 for (j=0; j < p->nvars; j++)
600 {
601 theta->Zeta[j][0]=p->Zeta[j][0];
602 EquateVector(theta->A0[j][0],p->A0[j][0]);
603 EquateVector(theta->Aplus[j][0],p->Aplus[j][0]);
604 }
605 Update_b0_bplus_from_A0_Aplus(theta);
606 if ((theta->Specification & SPEC_SIMS_ZHA) == SPEC_SIMS_ZHA)
607 Update_lambda_psi_from_bplus(theta);
608 theta->valid_parameters=1;
609
610 //InitializeParameters_VAR(theta);
611
612 return CreateStateModel(model->nobs,sv,routines,theta);
613 }
614
615 /*
616 Attempts to find the Markov state variable sv in the chain of Markov variables
617 given by top. If found, multiples the existing index by the number of states
618 in sv and adds the appropriate index number.
619 */
620 static int IncrementIndex(int idx, int i, TMarkovStateVariable *top, TMarkovStateVariable *sv)
621 {
622 int j, k;
623 if (top == sv) return i + idx * sv->nstates;
624 if (top->n_state_variables > 1)
625 for (j=0; j < top->n_state_variables; j++)
626 if ((k=IncrementIndex(idx,top->index[i][j],top->state_variable[j],sv)) >= 0)
627 return k;
628 return -1;
629 }
630
631 /*
632 Assumes:
633 sv - Valid pointer to TMarkovStateVariable structure.
634 list - Array of valid pointers of TMarkovStateVariable structures. Each
635 structure in the array must be in the tree whose root is sv.
636
637 Returns:
638 Integer array of length sv->nstates.
639 */
640 static int* CreateStateIndex(TMarkovStateVariable* sv, TMarkovStateVariable** list, int n)
641 {
642 int i, j, k;
643 int* index;
644 if (!(index=dw_CreateArray_int(sv->nstates)))
645 {
646 printf("CreateStateIndex(): Out of memory.\n");
647 dw_exit(0);
648 }
649 for (i=sv->nstates-1; i >= 0; i--)
650 {
651 for (k=j=0; j < n; j++)
652 if ((k=IncrementIndex(k,i,sv,list[j])) == -1)
653 {
654 printf("CreateStateIndex(): Unable to find required state variable.\n");
655 dw_exit(0);
656 }
657 index[i]=k;
658 }
659 return index;
660 }
661
662 /*
663 Assumes:
664 list :
665 */
666 int **CreateTranslationMatrix(TMarkovStateVariable ***list, TMarkovStateVariable *sv)
667 {
668 int j, **states=(int**)dw_CreateArray_array(dw_DimA(list));
669 for (j=dw_DimA(list)-1; j >= 0; j--)
670 states[j]=CreateStateIndex(sv,list[j],list[j] ? dw_DimA(list[j]) : 0);
671 return states;
672 }
673
674
675 /*
676 Assumes
677 table: Properly initialized translation table.
678 restricted table: Properly initialize translation table.
679 */
680 int **ExpandTranslationTable(int **table, TMarkovStateVariable *sv, TMarkovStateVariable *rsv, int s)
681 {
682 int i, j, k, nstates;
683 int **rtable, *idx, *master;
684
685 // Compute size of new table.
686 for (nstates=1, k=sv->n_state_variables-1; k >= 0; k--)
687 nstates*=(k == s) ? rsv->state_variable[k]->nstates + 1 : rsv->state_variable[k]->nstates;
688
689 // Create new table
690 dw_InitializeArray_int(rtable=dw_CreateRectangularArray_int(dw_DimA(table),nstates),0);
691
692 // Fill table
693 idx=(int*)dw_malloc(sv->nstates*sizeof(int));
694 master=(int*)dw_malloc(nstates*sizeof(int));
695 for (k=i=0; k < sv->nstates; k++)
696 {
697 for (j=sv->n_state_variables-1; j >= 0; j--)
698 if (sv->index[k][j] > rsv->state_variable[j]->nstates)
699 break;
700 else
701 if ((j != s) && (sv->index[k][j] == rsv->state_variable[j]->nstates))
702 break;
703 if (j == -1) master[i++]=k;
704 }
705 for (j=dw_DimA(table)-1; j >= 0; j--)
706 {
707 for (k=sv->nstates-1; k >= 0; k--) idx[k]=0;
708 for (k=nstates-1; k >= 0; k--)
709 idx[table[j][master[k]]]=1;
710 for (k=i=0; k < sv->nstates; k++) idx[k]=idx[k] ? i++ : -1;
711 for (k=nstates-1; k >= 0; k--)
712 rtable[j][k]=idx[table[j][master[k]]];
713 }
714 dw_free(master);
715 dw_free(idx);
716
717 // verbose
718 //dw_PrintArray(stdout,rtable,(char*)NULL); printf("\n"); dw_PrintArray(stdout,table,(char*)NULL); getchar();
719 //dw_PrintArray(stdout,sv->Index,(char*)NULL); getchar();
720
721 return rtable;
722 }
723
724 /*
725 Assumes
726 model:
727 Properly intialized TStateModel structure. The Markov state variable
728 structure must be flat with the same number state variables as
729 restricted_model. Each state variable must have as least as many states
730 as the corresponding state variable in restricted_model.
731
732 restricted_model:
733 Properly intialized TStateModel structure. The Markov state variable
734 structure must be flat with the same number state variables as model. Each
735 state variable must have no more states as the corresponding state
736 variable in model.
737
738 s:
739 The state variable to expand. It must be the case that s is between 0 and
740 model->n_state_variables - 1, inclusive, and that the number of states in
741 the sth state variable of model is strictly larger than the number of
742 states in the sth state variable of restricted_model.
743
744 Returns
745 Properly initialized TStateModel structure with in which the sth state
746 variable has one more state.
747
748 Notes
749 A Markov state variable structure is flat if state_variable[i] is a single
750 Markov state variable for 0 <= i < n_state_variables.
751 */
752 /* TStateModel* ExpandModel_VAR(TStateModel *model, TStateModel *restricted_model, int s) */
753 /* { */
754 /* int i, j, k, m, q, t; */
755 /* TStateModel *expanded_model; */
756 /* T_VAR_Parameters *p=model->theta, *restricted_p=restricted_model->theta, *expanded_p; */
757 /* TMarkovStateVariable *sv=model->sv, *restricted_sv=restricted_model->sv, *expanded_sv, **sv_array; */
758 /* TMatrix X, Y; */
759 /* int **coef_table, **var_table; */
760
761 /* // Check sizes */
762 /* if ((p->nvars != restricted_p->nvars) || (p->nlags != restricted_p->nlags) */
763 /* || (p->npre != restricted_p->npre) || (p->nobs != restricted_p->nobs) */
764 /* || (sv->n_state_variables != restricted_sv->n_state_variables) */
765 /* || (s < 0) || (s > sv->n_state_variables)) */
766 /* return (TStateModel*)NULL; */
767
768 /* for (k=sv->n_state_variables-1; k >= 0; k--) */
769 /* if (sv->state_variable[k]->nstates < restricted_sv->state_variable[k]->nstates) return (TStateModel*)NULL; */
770
771 /* if (sv->state_variable[s]->nstates == restricted_sv->state_variable[s]->nstates) return (TStateModel*)NULL; */
772
773 /* // Check VAR Restrictions */
774
775 /* // Check VAR Priors */
776
777 /* // Setup new Markov state variable */
778 /* sv_array=dw_CreateArray_pointer(sv->n_state_variables,(void (*)(void*))FreeMarkovStateVariable); */
779 /* for (k=model->sv->n_state_variables-1; k >= 0; k--) */
780 /* if (k != s) */
781 /* sv_array[k]=DuplicateMarkovStateVariable(restricted_sv->state_variable[k]); */
782 /* else */
783 /* sv_array[s]=RestrictMarkovStateVariable(sv->state_variable[k],restricted_sv->state_variable[k]->nstates+1); */
784
785 /* // Create multiple Markov state variable */
786 /* if (sv->n_state_variables == 1) */
787 /* { */
788 /* expanded_sv=sv_array[0]; */
789 /* sv_array[0]=(TMarkovStateVariable*)NULL; */
790 /* dw_FreeArray(sv_array); */
791 /* } */
792 /* else */
793 /* expanded_sv=CreateMarkovStateVariable_Multiple(model->nobs,sv_array); */
794
795 /* // Data */
796 /* Y=CreateMatrix(p->nobs,p->nvars); */
797 /* X=CreateMatrix(p->nobs,p->npre); */
798 /* for (t=p->nobs; t > 0; t--) */
799 /* { */
800 /* for (i=p->nvars-1; i >= 0; i--) ElementM(Y,t-1,i)=ElementV(p->Y[t],i); */
801 /* for (i=p->npre-1; i >= 0; i--) ElementM(X,t-1,i)=ElementV(p->X[t],i); */
802 /* } */
803
804 /* // Setup new translation tables */
805 /* coef_table=ExpandTranslationTable(p->coef_states,model->sv,restricted_model->sv,s); */
806 /* var_table=ExpandTranslationTable(p->var_states,model->sv,restricted_model->sv,s); */
807
808 /* // Setup new VAR */
809 /* expanded_p=CreateTheta_VAR(p->Specification,p->nvars,p->nlags,p->npre - p->nlags*p->nvars,expanded_sv->nstates,p->nobs,coef_table,var_table,p->U,p->V,p->W,Y,X); */
810 /* if (p->Specification & SPEC_SIMS_ZHA) */
811 /* SetPriors_VAR_SimsZha(expanded_p,p->A0_prior,p->Aplus_prior,p->zeta_a_prior,p->zeta_b_prior,p->lambda_prior); */
812 /* else */
813 /* SetPriors_VAR(expanded_p,p->A0_prior,p->Aplus_prior,p->zeta_a_prior,p->zeta_b_prior); */
814
815 /* // Create expanded model */
816 /* expanded_model=CreateStateModel(expanded_sv,CreateRoutines_VAR(),expanded_p); */
817
818 /* // Clean up */
819 /* FreeMatrix(X); */
820 /* FreeMatrix(Y); */
821 /* dw_FreeArray(coef_table); */
822 /* dw_FreeArray(var_table); */
823
824 /* // Set VAR parameters */
825 /* for (j=0; j < p->nvars; j++) */
826 /* { */
827 /* for (k=expanded_p->n_var_states[j]-1; k >= 0; k--) */
828 /* { */
829 /* for (i=expanded_p->nstates-1; i >= 0; i--) */
830 /* if (expanded_p->var_states[j][i] == k) break; */
831
832 /* for (q=m=0; q <= s; q++) m=m*expanded_sv->state_variable[q]->nstates + expanded_sv->index[i][q]; */
833 /* if (expanded_sv->index[i][s] == expanded_sv->state_variable[s]->nstates - 1) m--; */
834 /* for ( ; q < expanded_sv->n_state_variables; q++) m=m*expanded_sv->state_variable[q]->nstates + expanded_sv->index[i][q]; */
835
836 /* expanded_p->Zeta[j][k]=restricted_p->Zeta[j][restricted_p->var_states[j][m]]; */
837 /* } */
838
839 /* for (k=expanded_p->n_coef_states[j]-1; k >= 0; k--) */
840 /* { */
841 /* for (i=expanded_p->nstates-1; i >= 0; i--) */
842 /* if (expanded_p->coef_states[j][i] == k) break; */
843
844 /* for (q=m=0; q <= s; q++) m=m*expanded_sv->state_variable[q]->nstates + expanded_sv->index[i][q]; */
845 /* if (expanded_sv->index[i][s] == expanded_sv->state_variable[s]->nstates - 1) m--; */
846 /* for ( ; q < expanded_sv->n_state_variables; q++) m=m*expanded_sv->state_variable[q]->nstates + expanded_sv->index[i][q]; */
847
848 /* EquateVector(expanded_p->A0[j][k],restricted_p->A0[j][restricted_p->coef_states[j][m]]); */
849 /* EquateVector(expanded_p->Aplus[j][k],restricted_p->Aplus[j][restricted_p->coef_states[j][m]]); */
850 /* } */
851 /* } */
852 /* Update_b0_bplus_from_A0_Aplus(expanded_p); */
853 /* if ((expanded_p->Specification & SPEC_SIMS_ZHA) == SPEC_SIMS_ZHA) */
854 /* Update_lambda_psi_from_bplus(expanded_p); */
855 /* expanded_p->valid_parameters=1; */
856
857 /* // Set transition matrices */
858 /* if (!restricted_model->sv->valid_transition_matrix) */
859 /* { */
860 /* FreeStateModel(expanded_model); */
861 /* return (TStateModel*)NULL; */
862 /* } */
863 /* for (k=expanded_sv->n_state_variables-1; k >= 0; k--) */
864 /* { */
865 /* if (k != s) */
866 /* { */
867 /* //EquateMatrix(expanded_sv->state_variable[k]->Q,restricted_sv->state_variable[k]->Q); */
868 /* //Update_B_from_Q_SV(expanded_sv->state_variable[k]); */
869
870 /* EquateMatrix(expanded_sv->state_variable[k]->Q,restricted_sv->state_variable[k]->Q); */
871 /* EquateVector(expanded_sv->state_variable[k]->B,restricted_sv->state_variable[k]->B); */
872 /* } */
873 /* else */
874 /* { */
875 /* /\* j=restricted_sv->state_variable[k]->nstates; *\/ */
876 /* /\* for (i=0; i <= restricted_sv->state_variable[k]->nstates; i++) *\/ */
877 /* /\* for (j=0; j <= restricted_sv->state_variable[k]->nstates; j++) *\/ */
878 /* /\* ElementM(expanded_sv->state_variable[k]->Q,i,j)=0.5; *\/ */
879 /* //===================================================================================================================== */
880 /* /\* j=restricted_sv->state_variable[k]->nstates; *\/ */
881 /* /\* InsertSubMatrix(expanded_sv->state_variable[k]->Q,restricted_sv->state_variable[k]->Q,0,0,0,0,j,j); *\/ */
882 /* /\* for (i=j; i >= 0; i--) *\/ */
883 /* /\* { *\/ */
884 /* /\* ElementM(expanded_sv->state_variable[k]->Q,i,j)=0.0; *\/ */
885 /* /\* ElementM(expanded_sv->state_variable[k]->Q,j,i)=0.0; *\/ */
886 /* /\* } *\/ */
887 /* /\* ElementM(expanded_sv->state_variable[k]->Q,j,j)= 0.5*ElementM(expanded_sv->state_variable[k]->Q,j-1,j-1); *\/ */
888 /* /\* ElementM(expanded_sv->state_variable[k]->Q,j-1,j)=0.5*ElementM(expanded_sv->state_variable[k]->Q,j-1,j-1); *\/ */
889 /* /\* for (i=0; i < j-1; i++) *\/ */
890 /* /\* ElementM(expanded_sv->state_variable[k]->Q,i,j)= ElementM(expanded_sv->state_variable[k]->Q,i,j-1); *\/ */
891 /* /\* Update_B_from_Q_SV(expanded_sv->state_variable[k]); *\/ */
892 /* //===================================================================================================================== */
893 /* // Draw states for restricted model */
894 /* DrawStates(restricted_model); */
895
896 /* // Copy states for kth state variable */
897 /* dw_CopyArray(expanded_sv->state_variable[k]->S,restricted_sv->state_variable[k]->S); */
898
899 /* //dw_PrintArray(stdout,expanded_sv->state_variable[k]->S,(char*)NULL); getchar(); */
900
901 /* // Draw transition matrix for kth state variable */
902 /* DrawTransitionMatrix_SV(expanded_sv->state_variable[k]); */
903 /* //===================================================================================================================== */
904 /* // Then new state for the sth state variable is made to be reflecting */
905 /* /\* j=restricted_sv->state_variable[k]->nstates; *\/ */
906 /* /\* InsertSubMatrix(expanded_sv->state_variable[k]->Q,restricted_sv->state_variable[k]->Q,0,0,0,0,j,j); *\/ */
907 /* /\* for (i=j; i >= 0; i--) *\/ */
908 /* /\* { *\/ */
909 /* /\* ElementM(expanded_sv->state_variable[k]->Q,i,j)=0.0; *\/ */
910 /* /\* ElementM(expanded_sv->state_variable[k]->Q,j,i)=0.0; *\/ */
911 /* /\* } *\/ */
912 /* /\* ElementM(expanded_sv->state_variable[k]->Q,j-1,j)=1.0; *\/ */
913 /* /\* Update_B_from_Q_SV(expanded_sv->state_variable[k]); *\/ */
914 /* } */
915 /* } */
916 /* PropagateTransitionMatrices_SV(expanded_sv); */
917 /* // expanded_model->ValidTransitionMatrix=1; */
918 /* ValidateTransitionMatrices_SV(expanded_sv); */
919 /* // return */
920 /* return expanded_model; */
921 /* } */
922
923
924
925
926 /*
927 The free transition matrix parameters are chosen to be equal.
928 */
929 /* void FlatTransitionMatrix(TMarkovStateVariable *sv) */
930 /* { */
931 /* int i, j; */
932 /* PRECISION p; */
933 /* if (sv->n_state_variables == 1) */
934 /* { */
935 /* for (i=dw_DimA(sv->b)-1; i >= 0; i--) */
936 /* for (p=1.0/(PRECISION)DimV(sv->b[i]), j=DimV(sv->b[i])-1; j >= 0; j--) */
937 /* ElementV(sv->b[i],j)=p; */
938 /* Update_Q_from_B_SV(sv); */
939 /* } */
940 /* else */
941 /* { */
942 /* for (i=sv->n_state_variables-1; i >= 0; i--) */
943 /* FlatTransitionMatrix(sv->state_variable[i]); */
944 /* MatrixTensor(sv->Q,sv->QA); */
945 /* } */
946 /* } */
947
948 /*
949
950 */
951 /* int NestTransitionMatrices_SV(TMarkovStateVariable *sv, TMarkovStateVariable *restricted_sv) */
952 /* { */
953 /* int i, j; */
954 /* PRECISION tmp; */
955 /* if (sv->n_state_variables < restricted_sv->n_state_variables) return 0; */
956 /* if (sv->n_state_variables == 1) */
957 /* if (sv->nstates < restricted_sv->nstates) */
958 /* return 0; */
959 /* else */
960 /* { */
961 /* for (i=0; i < restricted_sv->nstates-1; i++) */
962 /* { */
963 /* for (j=0; j < restricted_sv->nstates; j++) */
964 /* ElementM(sv->Q,i,j)=ElementM(restricted_sv->Q,i,j); */
965 /* for (tmp=ElementM(restricted_sv->Q,i,j-1); j < sv->nstates; j++) */
966 /* ElementM(sv->Q,i,j)=tmp; */
967 /* } */
968
969 /* for (j=0; j < restricted_sv->nstates; j++) */
970 /* { */
971 /* tmp=ElementM(restricted_sv->Q,restricted_sv->nstates-1,j)/(double)(sv->nstates - restricted_sv->nstates + 1); */
972 /* // tmp=0.0; */
973 /* for (i=restricted_sv->nstates-1; i < sv->nstates; i++) */
974 /* ElementM(sv->Q,i,j)=tmp; */
975 /* } */
976 /* for ( ; j < sv->nstates; j++) */
977 /* for (i=restricted_sv->nstates-1; i < sv->nstates; i++) */
978 /* ElementM(sv->Q,i,j)=tmp; */
979
980 /* return Update_B_from_Q_SV(sv); */
981 /* } */
982 /* else */
983 /* { */
984 /* for (i=sv->n_state_variables-1; i >= restricted_sv->n_state_variables; i--) */
985 /* FlatTransitionMatrix(sv->state_variable[i]); */
986 /* for ( ; i >= 0; i--) */
987 /* if (!NestTransitionMatrices_SV(sv->state_variable[i],restricted_sv->state_variable[i])) */
988 /* return 0; */
989 /* MatrixTensor(sv->Q,sv->QA); */
990 /* } */
991 /* return 1; */
992 /* } */
993
994 /*
995 Sets the parameters of model so that it is equivalent to the parameters of
996 restricted_model. Currently, the routine only checks that the sizes of the
997 two models are the same. It should be the case that the restrictions are
998 also identical.
999 *
1000 int NestModel_VAR(TStateModel *model, TStateModel *restricted_model)
1001 {
1002 int j, k;
1003 T_VAR_Parameters *p=model->theta, *restricted_p=restricted_model->theta;
1004
1005 // Set transition matrices
1006 if (!restricted_model->ValidTransitionMatrix || !NestTransitionMatrices_SV(model->sv,restricted_model->sv))
1007 return 0;
1008 else
1009 model->ValidTransitionMatrix=1;
1010
1011 // Check VAR sizes
1012 if ((p->nvars != restricted_p->nvars) || (p->nlags != restricted_p->nlags)
1013 || (p->npre != restricted_p->npre) || (p->nobs != restricted_p->nobs))
1014 return 0;
1015
1016 // Set VAR parameters
1017 for (j=0; j < p->nvars; j++)
1018 {
1019 if (p->n_var_states[j] < restricted_p->n_var_states[j]) return 0;
1020 for (k=0; k < restricted_p->n_var_states[j]; k++)
1021 p->Zeta[j][k]=restricted_p->Zeta[j][k];
1022 for ( ; k < p->n_var_states[j]; k++)
1023 p->Zeta[j][k]=restricted_p->Zeta[j][restricted_p->n_var_states[j]-1];
1024
1025 if (p->n_coef_states[j] < restricted_p->n_coef_states[j]) return 0;
1026 for (k=0; k < restricted_p->n_coef_states[j]; k++)
1027 {
1028 EquateVector(p->A0[j][k],restricted_p->A0[j][k]);
1029 EquateVector(p->Aplus[j][k],restricted_p->Aplus[j][k]);
1030 }
1031 for ( ; k < p->n_coef_states[j]; k++)
1032 {
1033 EquateVector(p->A0[j][k],restricted_p->A0[j][restricted_p->n_coef_states[j]-1]);
1034 EquateVector(p->Aplus[j][k],restricted_p->Aplus[j][restricted_p->n_coef_states[j]-1]);
1035 }
1036 }
1037 Update_b0_bplus_from_A0_Aplus(model->theta);
1038 return 1;
1039 }
1040 *******************************************************************************/
1041 /*******************************************************************************/
1042 /*******************************************************************************/
1043
1044
1045 /*******************************************************************************/
1046 /*************************** Workspace computations ****************************/
1047 /*******************************************************************************/
1048 void ComputeDotProducts_All(T_VAR_Parameters *p)
1049 {
1050 TVector *Y=p->Y, *X=p->X;
1051 int t, j, k;
1052
1053 for (t=p->nobs; t > 0; t--)
1054 for (j=p->nvars-1; j >= 0; j--)
1055 for (k=p->n_coef_states[j]-1; k >= 0; k--)
1056 {
1057 p->A0_dot_products[t][j][k]=DotProduct(Y[t],p->A0[j][k]);
1058 p->Aplus_dot_products[t][j][k]=DotProduct(X[t],p->Aplus[j][k]);
1059 }
1060
1061 p->valid_dot_products=1;
1062
1063 }
1064
1065 /*
1066 Assumes:
1067 p: A valid T_VAR_Parameters structure and p->A0 has been initialized.
1068
1069 Results:
1070 Fill the vector p->log_abs_det_A0 with the natural logarithm of the the
1071 abso
1072 */
1073 void ComputeLogAbsDetA0_All(T_VAR_Parameters *p)
1074 {
1075 TMatrix A0;
1076 int j, k=DimV(p->log_abs_det_A0)-1;
1077
1078 A0=CreateMatrix(p->nvars,p->nvars);
1079
1080 //=== Set initial A0 ===
1081 for (j=p->nvars-1; j >= 0; j--)
1082 memcpy(&ElementM(A0,0,j),pElementV(p->A0[j][p->A0_column_states[j][k]]),p->nvars*sizeof(PRECISION));
1083
1084 ElementV(p->log_abs_det_A0,k)=LogAbsDeterminant_LU(A0);
1085
1086 while (--k >= 0)
1087 {
1088 //=== Reset A0 ===
1089 for (j=p->nvars-1; j >= 0; j--)
1090 if (p->A0_column_states[j][k] != p->A0_column_states[j][k+1])
1091 memcpy(&ElementM(A0,0,j),pElementV(p->A0[j][p->A0_column_states[j][k]]),p->nvars*sizeof(PRECISION));
1092
1093 ElementV(p->log_abs_det_A0,k)=LogAbsDeterminant_LU(A0);
1094 }
1095
1096 FreeMatrix(A0);
1097
1098 p->valid_log_abs_det_A0=1;
1099 }
1100
1101 /*
1102 Computes the log of the absolute value of the determinant of A0(s) if
1103 A0_column_states[j][s] == k.
1104 */
1105 void ComputeLogAbsDetA0(int j, int k, T_VAR_Parameters *p)
1106 {
1107 TMatrix A0;
1108 int i, s;
1109
1110 A0=CreateMatrix(p->nvars,p->nvars);
1111
1112 for (s=DimV(p->log_abs_det_A0)-1; s >= 0; s--)
1113 if (p->A0_column_states[j][s] == k)
1114 {
1115 for (i=p->nvars-1; i >= 0; i--)
1116 memcpy(&ElementM(A0,0,i),pElementV(p->A0[i][p->A0_column_states[i][s]]),p->nvars*sizeof(PRECISION));
1117
1118 ElementV(p->log_abs_det_A0,s)=LogAbsDeterminant_LU(A0);
1119 }
1120
1121 FreeMatrix(A0);
1122 }
1123
1124 /*
1125 If p->A_state_variable is non-negative, then it controls A0 and Aplus. If
1126 p->A_state_variable is negative, then A0 and Aplus are constant across states.
1127
1128 If Xi is not null and p->Xi_state_variable LogConditionalProbability_VARis non-negative, then it controls
1129 Xi. If Xi is not null and p->Xi_state_variable is negative, then Xi is
1130 constant across states. If Xi is null, then this parameter does not appear.
1131
1132 -n*log(2*pi)/2 + log|A0[i]| + log|diag(Xi[j])|
1133 - (Y[t]'*A0[i] - X[t]'*Aplus[i])*diag(Xi[j])*diag(Xi[j])*(Y[t]'*A0[i] - X[t]'*Aplus[i])/2
1134 */
1135 PRECISION LogConditionalProbability_VAR(int s, int t, TStateModel *model)
1136 {
1137 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1138 PRECISION x, y, sum=0.0, logdet=0.0;
1139 int j;
1140
1141 if (!(p->valid_parameters)) return MINUS_INFINITY;
1142
1143 //====== Computes log(abs(det(A0[i]))) and log(abs(det(Xi))) ======
1144 if (!p->valid_log_abs_det_A0) ComputeLogAbsDetA0_All(p);
1145
1146 //====== Compute quadratic form ======
1147 if (p->valid_dot_products)
1148 for (j=p->nvars-1; j >= 0; j--)
1149 {
1150 y=p->Zeta[j][p->var_states[j][s]];
1151 x=p->A0_dot_products[t][j][p->coef_states[j][s]]
1152 - p->Aplus_dot_products[t][j][p->coef_states[j][s]];
1153 if (y <= 0)
1154 return MINUS_INFINITY;
1155 else
1156 logdet+=log(y);
1157 sum+=y*x*x;
1158 }
1159 else
1160 for (j=p->nvars-1; j >= 0; j--)
1161 {
1162 y=p->Zeta[j][p->var_states[j][s]];
1163 x=DotProduct(p->Y[t],p->A0[j][p->coef_states[j][s]])
1164 - DotProduct(p->X[t],p->Aplus[j][p->coef_states[j][s]]);
1165 if (y <= 0)
1166 return MINUS_INFINITY;
1167 else
1168 logdet+=log(y);
1169 sum+=y*x*x;
1170 }
1171
1172 //====== Get log(det(A0)) ======
1173 logdet=0.5*logdet + ElementV(p->log_abs_det_A0,p->A0_states[s]);
1174
1175 return p->minus_half_nvars_times_log2pi + logdet - 0.5*sum;
1176 }
1177
1178 /*
1179 Since
1180
1181 y(t)' * A0(s(t)) = x(t)' * Aplus(s(t)) + epsilon(t)' * Inverse(Xi(s(t)))
1182
1183 The expectation is
1184
1185 y(t)' = x(t)' * Aplus(s(t)) * Inverse(A0(s(t))
1186 */
1187 TVector ExpectationSingleStep_VAR(TVector y, int s, int t, TStateModel *model)
1188 {
1189 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1190 TMatrix A0, Aplus;
1191
1192 if ((t < 1) || (p->nobs < t))
1193 {
1194 dw_Error(SIZE_ERR);
1195 return (TVector)NULL;
1196 }
1197
1198 A0=MakeA0((TMatrix)NULL,s,p);
1199 Aplus=MakeAplus((TMatrix)NULL,s,p);
1200
1201 if (!y && !(y=CreateVector(p->nvars)))
1202 return (TVector)y;
1203
1204 ProductVM(y,p->X[t],Aplus);
1205 ProductInverseVM(y,y,A0);
1206
1207 FreeMatrix(Aplus);
1208 FreeMatrix(A0);
1209
1210 return y;
1211 }
1212 /*******************************************************************************/
1213 /*******************************************************************************/
1214 /*******************************************************************************/
1215
1216 /******************************** Notification *********************************/
1217 void StatesChanged_VAR(TStateModel *model)
1218 {
1219 ((T_VAR_Parameters*)(model->theta))->valid_state_dependent_fields=0;
1220 }
1221
1222 void ThetaChanged_VAR(TStateModel *model)
1223 {
1224 ((T_VAR_Parameters*)(model->theta))->valid_log_abs_det_A0
1225 =((T_VAR_Parameters*)(model->theta))->valid_dot_products=0;
1226 if (((T_VAR_Parameters*)(model->theta))->normalization_type != VAR_NORMALIZATION_NONE)
1227 ((T_VAR_Parameters*)(model->theta))->valid_normalization=-1;
1228 }
1229
1230 int InitializeForwardRecursion_VAR(TStateModel *model)
1231 {
1232 if (!((T_VAR_Parameters*)(model->theta))->valid_dot_products)
1233 ComputeDotProducts_All((T_VAR_Parameters*)(model->theta));
1234 return 1;
1235 }
1236
1237 /*******************************************************************************/
1238 /********************************* Simulations *********************************/
1239 /*******************************************************************************/
1240 void DrawParameters_VAR(TStateModel *model)
1241 {
1242 // Draw unnormalized theta
1243 DrawZeta_DotProducts(model);
1244 DrawA0_Metropolis(model);
1245 DrawAplus(model);
1246
1247 // Normalize
1248 //Normalize_VAR((T_VAR_Parameters*)(model->theta));
1249
1250 // Flags and notification that the VAR parameters have changed
1251 ((T_VAR_Parameters*)(model->theta))->valid_parameters=1;
1252 ThetaChanged(model);
1253 }
1254
1255 /*
1256 Choose a random initial value for the VAR parameters. The function
1257 ThetaChanged() cannot be called.
1258 */
1259 void InitializeParameters_VAR(T_VAR_Parameters *p)
1260 {
1261 int j, s;
1262 TMatrix X;
1263
1264 // Initialize Zeta to one
1265 for (j=p->nvars-1; j >= 0; j--)
1266 for (s=p->n_var_states[j]-1; s >= 0; s--)
1267 p->Zeta[j][s]=1;
1268
1269 // Draw b0 from prior - identical across states A0[j][s] = U[j]*b0[j][s].
1270 for (j=p->nvars-1; j >= 0; j--)
1271 {
1272 X=CholeskyUT((TMatrix)NULL,p->inverse_b0_prior[j]);
1273 Inverse_UT(X,X);
1274 dw_NormalVector(p->b0[j][0]);
1275 ProductMV(p->b0[j][0],X,p->b0[j][0]);
1276 ProductMV(p->A0[j][0],p->U[j],p->b0[j][0]);
1277 for (s=p->n_coef_states[j]-1; s > 0; s--)
1278 EquateVector(p->A0[j][s],p->A0[j][0]);
1279 FreeMatrix(X);
1280 }
1281
1282 // Set Aplus[j][s] = W[j]*A0[j][s].
1283 for (j=p->nvars-1; j >= 0; j--)
1284 {
1285 if (!p->W[j])
1286 InitializeVector(p->Aplus[j][0],0.0);
1287 else
1288 ProductMV(p->Aplus[j][0],p->W[j],p->A0[j][0]);
1289 for (s=p->n_coef_states[j]-1; s > 0; s--)
1290 EquateVector(p->Aplus[j][s],p->Aplus[j][0]);
1291 }
1292
1293 // Update b0, bplus, lambda, psi
1294 Update_b0_bplus_from_A0_Aplus(p);
1295 if ((p->Specification & SPEC_SIMS_ZHA) == SPEC_SIMS_ZHA) Update_lambda_psi_from_bplus(p);
1296
1297 // Flags and notification that the VAR parameters have changed
1298 p->valid_parameters=1;
1299 }
1300
1301 int IsDegenerate_VAR(int *regime_counts, TStateModel *model)
1302 {
1303 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1304 int *d=(int*)dw_malloc(model->sv->nstates*sizeof(int)), i, j;
1305
1306 // variance states
1307 for (j=p->nvars-1; j >= 0; j--)
1308 {
1309 for (i=p->n_var_states[j]-1; i >= 0; i--) d[i]=0;
1310 for (i=model->sv->nstates-1; i >= 0; i--) d[p->var_states[j][i]]+=regime_counts[i];
1311 for (i=p->n_var_states[j]-1; i >= 0; i--)
1312 if (d[i] < model->degenerate_draws_cutoff)
1313 {
1314 dw_free(d);
1315 return 1;
1316 }
1317 }
1318
1319 // coefficients states
1320 for (j=p->nvars-1; j >= 0; j--)
1321 {
1322 for (i=p->n_coef_states[j]-1; i >= 0; i--) d[i]=0;
1323 for (i=model->sv->nstates-1; i >= 0; i--) d[p->coef_states[j][i]]+=regime_counts[i];
1324 for (i=p->n_coef_states[j]-1; i >= 0; i--)
1325 if (d[i] <= model->degenerate_draws_cutoff)
1326 {
1327 dw_free(d);
1328 return 1;
1329 }
1330 }
1331
1332 dw_free(d);
1333 return 0;
1334 }
1335
1336 //-----------------------------------------------------------------------------//
1337 //--------------------------------- Draw Zeta ---------------------------------//
1338 //-----------------------------------------------------------------------------//
1339 void DrawZeta_Aplus(TStateModel *model)
1340 {
1341 int j, k, s, T;
1342 PRECISION v;
1343 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1344
1345 if (!p->valid_state_dependent_fields) UpdateStateDependentFields(p,model->S);
1346
1347 for (j=p->nvars-1; j >= 0; j--)
1348 {
1349 for (s=p->n_var_states[j]-1; s > 0; s--)
1350 {
1351 v=0.0;
1352 T=0;
1353 for (k=p->nstates-1; k >= 0; k--)
1354 {
1355 if (p->var_states[j][k] == s)
1356 {
1357 v+=InnerProductSymmetric(p->A0[j][p->coef_states[j][k]],p->YY[k])
1358 - 2.0 * InnerProductNonSymmetric(p->Aplus[j][p->coef_states[j][k]],p->A0[j][p->coef_states[j][k]],p->XY[k])
1359 + InnerProductSymmetric(p->Aplus[j][p->coef_states[j][k]],p->XX[k]);
1360 T+=p->T[k];
1361 }
1362 }
1363 p->Zeta[j][s]=dw_gamma_rnd(0.5*(PRECISION)T + ElementV(p->zeta_a_prior,j))/(0.5*v + ElementV(p->inverse_zeta_b_prior,j));
1364 }
1365
1366 //=== State 0 is normalized to one
1367 p->Zeta[j][0]=1.0;
1368 }
1369 }
1370
1371 void DrawZeta_DotProducts(TStateModel *model)
1372 {
1373 int j, s, t;
1374 PRECISION x;
1375 TVector v, T;
1376 int *S=model->S;
1377 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1378
1379 if (!p->valid_dot_products) ComputeDotProducts_All(p);
1380
1381 for (j=p->nvars-1; j >= 0; j--)
1382 {
1383 v=InitializeVector(CreateVector(p->n_var_states[j]),0.0);
1384 T=InitializeVector(CreateVector(p->n_var_states[j]),0.0);
1385 for (t=p->nobs; t > 0; t--)
1386 {
1387 s=p->coef_states[j][S[t]];
1388 x=p->A0_dot_products[t][j][s] - p->Aplus_dot_products[t][j][s];
1389 s=p->var_states[j][S[t]];
1390 ElementV(v,s)+=x*x;
1391 ElementV(T,s)+=1.0;
1392 }
1393 for (s=p->n_var_states[j]-1; s > 0; s--)
1394 p->Zeta[j][s]=dw_gamma_rnd(0.5*ElementV(T,s) + ElementV(p->zeta_a_prior,j))/(0.5*ElementV(v,s) + ElementV(p->inverse_zeta_b_prior,j));
1395 FreeVector(v);
1396 FreeVector(T);
1397
1398 //=== State 0 is normalized to one
1399 p->Zeta[j][0]=1.0;
1400 }
1401 }
1402
1403 //-----------------------------------------------------------------------------//
1404 //-------------------------- Metropolis Draws of A0 ---------------------------//
1405 //-----------------------------------------------------------------------------//
1406 #define MID 0.35
1407 #define LOG_MID -1.0498221244987
1408 #define LOWER_BOUND 0.0052521875
1409 #define UPPER_BOUND 0.81061308309895
1410 void AdaptiveMetropolisScale(TStateModel *model, int iterations, int period, int verbose, FILE *f_posterior)
1411 {
1412 struct TAdaptive
1413 {
1414 int begin_jump_ratio;
1415 int iterations;
1416 int end_iteration_count;
1417 PRECISION best_scale;
1418 PRECISION low_scale;
1419 PRECISION low_jump_ratio;
1420 PRECISION high_scale;
1421 PRECISION high_jump_ratio;
1422 } ***Adaptive;
1423
1424 PRECISION new_scale, new_jump_ratio;
1425 int j, k, begin_time=0, count, check=period;
1426 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1427
1428 Adaptive=(struct TAdaptive***)dw_CreateArray_array(p->nvars);
1429 for (j=p->nvars-1; j >= 0; j--)
1430 {
1431 Adaptive[j]=(struct TAdaptive**)dw_CreateArray_pointer(p->n_coef_states[j],dw_free);
1432 for (k=p->n_coef_states[j]-1; k >= 0; k--)
1433 {
1434 Adaptive[j][k]=((struct TAdaptive*)dw_malloc(sizeof(struct TAdaptive)));
1435 Adaptive[j][k]->begin_jump_ratio=p->A0_Metropolis_Jumps[j][k];
1436 Adaptive[j][k]->iterations=period;
1437 Adaptive[j][k]->end_iteration_count=period;
1438 Adaptive[j][k]->low_scale=Adaptive[j][k]->low_jump_ratio=Adaptive[j][k]->high_scale=Adaptive[j][k]->high_jump_ratio=-1.0;
1439 Adaptive[j][k]->best_scale=p->A0_Metropolis_Scale[j][k];
1440 }
1441 }
1442
1443 ResetMetropolisInformation(p);
1444
1445 if (verbose)
1446 {
1447 printf("Beginning adaptive burn in -- %d iterations.\n",iterations);
1448 begin_time=(int)time((time_t*)NULL);
1449 }
1450
1451 for (count=1; count <= iterations; count++)
1452 {
1453 DrawAll(model);
1454 if (count == check)
1455 {
1456 #ifdef OCTAVE_MEX_FILE
1457 OCTAVE_QUIT;
1458 #elif defined(MATLAB_MEX_FILE)
1459 if (utIsInterruptPending())
1460 {
1461 mexPrintf("\n\n** Ctrl-C detected, quitting...\n");
1462 dw_exit(0);
1463 }
1464 #endif
1465 if (f_posterior) fprintf(f_posterior,"%le\n",LogPosterior_StatesIntegratedOut(model));
1466
1467 if (verbose)
1468 printf("%d iterations completed out of %d - elapsed time: %d seconds\n",count,iterations,(int)time((time_t*)NULL) - begin_time);
1469
1470 for (j=p->nvars-1; j >= 0; j--)
1471 {
1472 for (k=p->n_coef_states[j]-1; k >= 0; k--)
1473 if (Adaptive[j][k]->end_iteration_count == count)
1474 {
1475 // Compute new jump ratio and get scale
1476 new_jump_ratio=(PRECISION)(p->A0_Metropolis_Jumps[j][k] - Adaptive[j][k]->begin_jump_ratio)
1477 /(PRECISION)(Adaptive[j][k]->iterations);
1478
1479 // Set new low or high bounds
1480 if (new_jump_ratio < MID)
1481 {
1482 Adaptive[j][k]->low_scale=p->A0_Metropolis_Scale[j][k];
1483 Adaptive[j][k]->low_jump_ratio=new_jump_ratio;
1484 }
1485 else
1486 {
1487 Adaptive[j][k]->high_scale=p->A0_Metropolis_Scale[j][k];
1488 Adaptive[j][k]->high_jump_ratio=new_jump_ratio;
1489 }
1490
1491 // Compute new scale and best scale
1492 if (Adaptive[j][k]->low_jump_ratio < 0.0)
1493 {
1494 Adaptive[j][k]->best_scale=Adaptive[j][k]->high_scale;
1495 if (Adaptive[j][k]->low_scale < 0.0)
1496 new_scale=((new_jump_ratio > UPPER_BOUND) ? 5.0 : LOG_MID/log(new_jump_ratio))*Adaptive[j][k]->high_scale;
1497 else
1498 {
1499 new_scale=Adaptive[j][k]->low_scale;
1500 Adaptive[j][k]->low_scale=-1;
1501 }
1502 }
1503 else
1504 if (Adaptive[j][k]->high_jump_ratio < 0.0)
1505 {
1506 Adaptive[j][k]->best_scale=Adaptive[j][k]->low_scale;
1507 if (Adaptive[j][k]->high_scale < 0.0)
1508 new_scale=((new_jump_ratio < LOWER_BOUND) ? 0.2 : LOG_MID/log(new_jump_ratio))*Adaptive[j][k]->low_scale;
1509 else
1510 {
1511 new_scale=Adaptive[j][k]->high_scale;
1512 Adaptive[j][k]->high_scale=-1.0;
1513 }
1514 }
1515 else
1516 {
1517 new_scale=Adaptive[j][k]->best_scale=0.5*(Adaptive[j][k]->low_scale + Adaptive[j][k]->high_scale);
1518 //Adaptive[j][k]->iterations+=period;
1519 Adaptive[j][k]->iterations*=2;
1520 Adaptive[j][k]->low_jump_ratio=Adaptive[j][k]->high_jump_ratio=-1.0;
1521 }
1522
1523 // Print data
1524 if (verbose)
1525 printf("col: %d state: %d (%d %lf %lf %lf)\n",j+1,k+1,p->A0_Metropolis_Jumps[j][k],
1526 new_jump_ratio,p->A0_Metropolis_Scale[j][k],new_scale);
1527
1528 // Reset adaptive counts and A0_Metropolis_Scale
1529 Adaptive[j][k]->begin_jump_ratio=p->A0_Metropolis_Jumps[j][k];
1530 Adaptive[j][k]->end_iteration_count+=Adaptive[j][k]->iterations;
1531 p->A0_Metropolis_Scale[j][k]=new_scale;
1532 }
1533 else
1534 if (verbose)
1535 {
1536 new_jump_ratio=(PRECISION)(p->A0_Metropolis_Jumps[j][k] - Adaptive[j][k]->begin_jump_ratio)
1537 /(PRECISION)(Adaptive[j][k]->iterations - (Adaptive[j][k]->end_iteration_count - count));
1538
1539 printf("col: %d state: %d (%d %lf %lf -)\n",j+1,k+1,p->A0_Metropolis_Jumps[j][k],
1540 new_jump_ratio,p->A0_Metropolis_Scale[j][k]);
1541 }
1542 }
1543
1544 if (verbose) printf("\n");
1545
1546 check+=period;
1547 }
1548 }
1549
1550 for (j=p->nvars-1; j >= 0; j--)
1551 for (k=p->n_coef_states[j]-1; k >= 0; k--)
1552 p->A0_Metropolis_Scale[j][k]=Adaptive[j][k]->best_scale;
1553
1554 ResetMetropolisInformation(p);
1555
1556 dw_FreeArray(Adaptive);
1557 }
1558 #undef MID
1559 #undef UPPER
1560 #undef LOWER
1561
1562 void SetupMetropolisInformation(PRECISION **Scale, T_VAR_Parameters *p)
1563 {
1564 dw_CopyArray(p->A0_Metropolis_Scale,Scale);
1565 ResetMetropolisInformation(p);
1566 }
1567
1568 void ResetMetropolisInformation(T_VAR_Parameters *p)
1569 {
1570 p->Total_A0_Metropolis_Draws=0;
1571 dw_InitializeArray_int(p->A0_Metropolis_Jumps,0);
1572 }
1573
1574 static void GetProposedJump_A0(TVector b, int j, int k, T_VAR_Parameters *p)
1575 {
1576 TMatrix YY, XX, XY, S, M0, M1;
1577 int s;
1578 PRECISION x;
1579 int terminal_errors;
1580
1581 // Accumulate XX, XY, and YY
1582 InitializeMatrix(XX=CreateMatrix(p->npre,p->npre),0.0);
1583 InitializeMatrix(XY=CreateMatrix(p->npre,p->nvars),0.0);
1584 InitializeMatrix(YY=CreateMatrix(p->nvars,p->nvars),0.0);
1585 for (s=p->nstates-1; s >= 0; s--)
1586 if (p->coef_states[j][s] == k)
1587 {
1588 x=p->Zeta[j][p->var_states[j][s]];
1589 UpdateM(1.0,XX,x,p->XX[s]);
1590 UpdateM(1.0,XY,x,p->XY[s]);
1591 UpdateM(1.0,YY,x,p->YY[s]);
1592 }
1593
1594 // S = inverse_b0_prior + U[j]'*(YY + W[j]'*XY + XY'*W[j] + W[j]'*XX*W[j])*U[j]
1595 if (p->W[j])
1596 {
1597 // M0 = W[j]'*(XX*W[j] + XY) + (XY'*W[j])
1598 M0=ProductMM((TMatrix)NULL,XX,p->W[j]);
1599 AddMM(M0,M0,XY);
1600 M1=TransposeProductMM((TMatrix)NULL,p->W[j],M0);
1601 AddMM(YY,YY,M1);
1602 TransposeProductMM(M1,XY,p->W[j]);
1603 AddMM(YY,YY,M1);
1604 FreeMatrix(M1);
1605 FreeMatrix(M0);
1606 }
1607 S=MatrixInnerProductSymmetric((TMatrix)NULL,p->U[j],YY);
1608 //dw_PrintMatrix(stdout,S,"%.17le "); printf("\n");
1609 AddMM(S,S,p->inverse_b0_prior[j]);
1610
1611 //dw_PrintMatrix(stdout,S,"%.17le "); fgetc(stdin);
1612
1613 // Simulate draw
1614 terminal_errors=dw_SetTerminalErrors(NO_ERR);
1615 dw_NormalVector(b);
1616 if (!InverseProductUV(b,CholeskyUT(S,S),b))
1617 {
1618 printf("Error in GetProposedJump_A0()\n");
1619 printf("j = %d, k = %d\n,Prior =\n",j,k);
1620 dw_PrintMatrix(stdout,p->inverse_b0_prior[j],"%lg ");
1621 printf("S =\n");
1622 dw_PrintMatrix(stdout,S,"%lg ");
1623 dw_exit(1);
1624 }
1625 dw_SetTerminalErrors(terminal_errors);
1626 /* else */
1627 /* { */
1628 /* printf("GetProposedJump_A0()\n"); */
1629 /* printf("j = %d, k = %d\n,Prior =\n",j,k); */
1630 /* dw_PrintMatrix(stdout,p->inverse_b0_prior[j],"%lg "); */
1631 /* printf("S =\n"); */
1632 /* dw_PrintMatrix(stdout,S,"%lg "); */
1633 /* getchar(); */
1634 /* } */
1635
1636 // Scale factor
1637 ProductVS(b,b,p->A0_Metropolis_Scale[j][k]);
1638
1639 // Free memory
1640 FreeMatrix(S);
1641 FreeMatrix(YY);
1642 FreeMatrix(XY);
1643 FreeMatrix(XX);
1644 }
1645
1646 /*
1647 Assumes
1648 j column
1649 k state A0[j], 0 <= k < dw_DimA(A[j])
1650 p pointer to valid T_VAR_Parameters structure
1651
1652 Returns
1653 The log of the density of a[j][k] conditional on all other parameters.
1654
1655 Notes
1656 Uses the following information in model->parametes = p and model->data = d.
1657
1658 p->XX[], p->XY[], p->YY, p->nobs_by_state[], p->log_det_abs_A0[]
1659
1660 p->A0[j][k], p->b0[j][k], p->Aplus[j][k], p->Xi[j][]
1661
1662 p->coef_states[j][], p->var_states[j][], p->A0_states[],
1663 p->inverse_b0_prior[j]
1664 */
1665 PRECISION LogKernel_A0(int j, int k, TStateModel *model)
1666 {
1667 int s;
1668 PRECISION rtrn;
1669 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1670
1671 //====== Prior ======
1672 rtrn=-0.5*InnerProductSymmetric(p->b0[j][k],p->inverse_b0_prior[j]);
1673
1674 for (s=p->nstates-1; s >= 0; s--)
1675 if (p->coef_states[j][s] == k)
1676 rtrn+=ElementV(p->log_abs_det_A0,p->A0_states[s]) * p->T[s]
1677 - 0.5 * p->Zeta[j][p->var_states[j][s]] * (InnerProductSymmetric(p->A0[j][k],p->YY[s])
1678 - 2.0*InnerProductNonSymmetric(p->Aplus[j][k],p->A0[j][k],p->XY[s])
1679 + InnerProductSymmetric(p->Aplus[j][k],p->XX[s]));
1680 return rtrn;
1681 }
1682
1683 PRECISION LogKernel_A0_DotProduct(int j, int k, TStateModel *model)
1684 {
1685 int s, t;
1686 int* S=model->S;
1687 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1688 PRECISION x, rtrn;
1689
1690 //====== Prior ======
1691 rtrn=-0.5*InnerProductSymmetric(p->b0[j][k],p->inverse_b0_prior[j]);
1692
1693 for (t=model->nobs; t > 0; t--)
1694 if (p->coef_states[j][s=S[t]] == k)
1695 {
1696 x=DotProduct(p->Y[t],p->A0[j][k]) - DotProduct(p->X[t],p->Aplus[j][k]);
1697 rtrn+=ElementV(p->log_abs_det_A0,p->A0_states[s]) - 0.5*p->Zeta[j][p->var_states[j][s]]*x*x;
1698 }
1699
1700 return rtrn;
1701 }
1702
1703 /*
1704 Assumes:
1705 p - pointer to a valid T_VAR_Parameter structure
1706 Jumps - null pointer or pointer to a 2-dimensional integer array with the
1707 first dimensional at lease p->nvars and the second dimension at
1708 least the dimension of p->A0[j].
1709
1710 Results:
1711 New values for p->b0 and p->A0 are obtained using the Metropolis algorithm.
1712 If Jumps is not null, then Jump[j][k] is updated for all the Metropolis
1713 jumps that were accepted.
1714
1715 Notes:
1716 Calls GetA0MetropolisJumpSize() to get the variance for the normal jumping
1717 kernel used in this algorithm. Calls LogConditionalDensity_A0() to compute
1718 the appropriate posterior density.
1719 */
1720 void DrawA0_Metropolis(TStateModel *model)
1721 {
1722 int j, k;
1723 PRECISION old_log_kernel, log_difference;
1724 TVector old_b0, old_a0, old_aplus, old_log_abs_det_A0;
1725 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1726
1727 if (!p->valid_state_dependent_fields) UpdateStateDependentFields(p,model->S);
1728
1729 old_a0=CreateVector(p->nvars);
1730 old_aplus=CreateVector(p->npre);
1731 old_log_abs_det_A0=CreateVector(DimV(p->log_abs_det_A0));
1732
1733 for (j=p->nvars-1; j >= 0; j--)
1734 {
1735 old_b0=CreateVector(DimV(p->b0[j][0]));
1736
1737 for (k=dw_DimA(p->A0[j])-1; k >= 0; k--)
1738 {
1739 //=== Save old values ===
1740 EquateVector(old_b0,p->b0[j][k]);
1741 EquateVector(old_a0,p->A0[j][k]);
1742 EquateVector(old_aplus,p->Aplus[j][k]);
1743 EquateVector(old_log_abs_det_A0,p->log_abs_det_A0);
1744 old_log_kernel=LogKernel_A0(j,k,model);
1745 //old_log_kernel=LogKernel_A0_DotProduct(j,k,model);
1746
1747 //=== Jump ===
1748 GetProposedJump_A0(p->b0[j][k],j,k,p);
1749 AddVV(p->b0[j][k],p->b0[j][k],old_b0);
1750 ProductMV(p->A0[j][k],p->U[j],p->b0[j][k]);
1751 Update_aplus_from_bplus_a0(j,k,p);
1752 ComputeLogAbsDetA0(j,k,p);
1753
1754 //=== Accept Jump ===
1755 log_difference=LogKernel_A0(j,k,model) - old_log_kernel;
1756 //log_difference=LogKernel_A0_DotProduct(j,k,model) - old_log_kernel;
1757 if ((log_difference >= 0.0) || (dw_uniform_rnd() < exp(log_difference)))
1758 {
1759 p->A0_Metropolis_Jumps[j][k]++;
1760 p->valid_dot_products=0;
1761 }
1762 else
1763 {
1764 EquateVector(p->b0[j][k],old_b0);
1765 EquateVector(p->A0[j][k],old_a0);
1766 EquateVector(p->Aplus[j][k],old_aplus);
1767 EquateVector(p->log_abs_det_A0,old_log_abs_det_A0);
1768 }
1769 }
1770
1771 FreeVector(old_b0);
1772 }
1773
1774 FreeVector(old_log_abs_det_A0);
1775 FreeVector(old_aplus);
1776 FreeVector(old_a0);
1777
1778 p->Total_A0_Metropolis_Draws++;
1779 }
1780
1781 //-----------------------------------------------------------------------------//
1782 //-------------------------------- Draw Aplus ---------------------------------//
1783 //-----------------------------------------------------------------------------//
1784 /*
1785 The following matrices must be updated before calling this routine:
1786
1787 p->A0 p->Xi p->XX p->XY
1788
1789 The following matrices are used in this routine
1790
1791 p->V p->W p->coef_states p->var_states p->inverse_bplus_prior
1792
1793 The following matrices are modified in this routine
1794
1795 p->bplus p->Aplus
1796 */
1797 void DrawAplus(TStateModel *model)
1798 {
1799 int j, k, s;
1800 TMatrix S, XX, XY, M;
1801 TVector v;
1802 PRECISION x;
1803 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1804
1805 if (!p->valid_state_dependent_fields)
1806 UpdateStateDependentFields(p,model->S);
1807
1808 if (p->Specification & SPEC_SIMS_ZHA)
1809 {
1810 Draw_psi(model);
1811 Draw_lambda(model);
1812 Update_bplus_from_lambda_psi(p);
1813 }
1814 else
1815 {
1816 XX=CreateMatrix(p->npre,p->npre);
1817 XY=CreateMatrix(p->npre,p->nvars);
1818 v=CreateVector(p->npre);
1819
1820 for (j=p->nvars-1; j >= 0; j--)
1821 if (p->bplus[j])
1822 {
1823 S=CreateMatrix(p->dim_bplus[j],p->dim_bplus[j]);
1824
1825 for (k=p->n_coef_states[j]-1; k >= 0; k--)
1826 {
1827 InitializeMatrix(XX,0.0);
1828 InitializeMatrix(XY,0.0);
1829 for (s=p->nstates-1; s >= 0; s--)
1830 if (p->coef_states[j][s] == k)
1831 {
1832 x=p->Zeta[j][p->var_states[j][s]];
1833 UpdateM(1.0,XX,x,p->XX[s]);
1834 UpdateM(1.0,XY,x,p->XY[s]);
1835 }
1836
1837 //=== Compute inverse variance ===
1838 if (!p->IsIdentity_V[j])
1839 MatrixInnerProductSymmetric(S,p->V[j],XX);
1840 else
1841 EquateMatrix(S,XX);
1842 AddMM(S,S,p->inverse_bplus_prior[j]);
1843
1844 //=== Compute b ===
1845 if (p->W[j])
1846 {
1847 if (p->Specification & SPEC_RANDOM_WALK)
1848 if (MajorForm(XY) && MajorForm(XX))
1849 bSubtractV(pElementM(XY),pElementM(XY),pElementM(XX),RowM(XX)*p->nvars);
1850 //SubtractMM(XY,XY,XX);
1851 else
1852 {
1853 M=SubMatrix((TMatrix)NULL,XX,0,0,RowM(XX),p->nvars);
1854 SubtractMM(XY,XY,M);
1855 FreeMatrix(M);
1856 }
1857 else
1858 {
1859 M=ProductMM((TMatrix)NULL,XX,p->W[j]);
1860 AddMM(XY,XY,M);
1861 FreeMatrix(M);
1862 }
1863 }
1864 if (!p->IsIdentity_V[j])
1865 {
1866 ProductMV(v,XY,p->A0[j][k]);
1867 TransposeProductMV(p->bplus[j][k],p->V[j],v);
1868 }
1869 else
1870 ProductMV(p->bplus[j][k],XY,p->A0[j][k]);
1871
1872 //=== Draw bplus ===
1873 if (!DrawNormal_InverseVariance(p->bplus[j][k],p->bplus[j][k],S))
1874 SingularInverseVariance_RecoveryAttempt(p->bplus[j][k],p->bplus[j][k],S,p->inverse_bplus_prior[j],model,BPLUS_ERR);
1875 }
1876
1877 FreeMatrix(S);
1878 }
1879
1880 FreeMatrix(XX);
1881 FreeMatrix(XY);
1882 FreeVector(v);
1883 }
1884
1885 Update_Aplus_from_bplus_A0(p);
1886 ThetaChanged(model);
1887 }
1888
1889 //-----------------------------------------------------------------------------//
1890 //--------------------------------- Draw psi ----------------------------------//
1891 //-----------------------------------------------------------------------------//
1892 /*
1893 Assumes:
1894 S: (n*b + j) x (n*b + j) matrix with j > k. S must be column major.
1895 XX: (n*b + 1) x (n*b + 1) matrix. XX must be column major.
1896 lambda: n dimensional vector.
1897
1898 Results:
1899 Adds
1900
1901 PSI[k]'*diag(LAMBDA*lambda + e)*XX*diag(LAMBDA*lambda + e)*PSI[k]
1902
1903 to S. The matrices LAMBDA and PSI[k] are given by
1904
1905 - -
1906 | I(n) |
1907 | . | - -
1908 | . | | I(n*b) 0(n*b,j) |
1909 LAMBDA = | . | PSI[k] = | |
1910 | | | 0(1,n*b) e(j,k+1)'|
1911 | I(n) | - -
1912 | 0(1,n) |
1913 - -
1914
1915 where I(r) is the r x r identity matrix, 0(r,s) is the r x s zero matrix,
1916 and e(r,s) is the sth column of I(r). e is the vector e(n*b+1,n*b+1).
1917
1918 Notes:
1919 k is a zero based index.
1920 */
1921 void update_psi_quadratic_form(TMatrix S, int n, int m, int k, TVector lambda, TMatrix XX)
1922 {
1923 int i, j, p, u=n*m-1, v;
1924 PRECISION *x, *s, *z=pElementV(lambda), w;
1925
1926 s=pElementM(S)+(n*m+k)*RowM(S)+u;
1927 x=pElementM(XX)+n*m*RowM(XX)+u;
1928 s[k+1]=x[1];
1929 for (v=m-1; v >= 0; v--)
1930 for (i=n-1; i >= 0; s--, x--, i--)
1931 (*s)+=z[i]*(*x);
1932 for (p=n-1, j=u; j >= 0; p--, j--)
1933 {
1934 if (p < 0) p=n-1;
1935 w=z[p];
1936 s=pElementM(S)+j*RowM(S)+u;
1937 x=pElementM(XX)+j*RowM(XX)+u;
1938 s[k+1]=x[1]*w;
1939 for (v=m-1; v >= 0; v--)
1940 for (i=n-1; i >= 0; s--, x--, i--)
1941 (*s)+=z[i]*(*x)*w;
1942 }
1943 }
1944
1945 /*
1946 Assmes:
1947 model: point to a valid TStateModel structure
1948
1949 Results:
1950 A draw of psi conditional on A0,
1951
1952 Notes:
1953 The matrices MUST be in column major format. Basic matrix routines from
1954 bmatrix.c are called in this routine.
1955 */
1956 void Draw_psi(TStateModel *model)
1957 {
1958 int j, k, s, i, m;
1959 TVector b, v;
1960 TMatrix S, XX, XY;
1961 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
1962
1963 // Update state dependent matrices if necessary
1964 if (!p->valid_state_dependent_fields)
1965 UpdateStateDependentFields(p,model->S);
1966
1967 // Allocate memory
1968 XX=CreateMatrix(p->npre,p->npre);
1969 XY=CreateMatrix(p->npre,p->nvars);
1970 v=CreateVector(p->npre);
1971
1972 if (_VERBOSE_COUNT)
1973 fprintf(V_FILE,"//=== Draw_psi() (count = %d) =====================================//\n",_VERBOSE_COUNT);
1974
1975 for (j=p->nvars-1; j >= 0; j--)
1976 {
1977 InitializeVector(b=CreateVector(DimV(p->psi[j])),0.0);
1978 InitializeMatrix(S=CreateMatrix(DimV(p->psi[j]),DimV(p->psi[j])),0.0);
1979
1980 for (k=p->n_coef_states[j]-1; k >= 0; k--)
1981 {
1982 // Accumulate XX and YY
1983 InitializeMatrix(XX,0.0);
1984 InitializeMatrix(XY,0.0);
1985 for (s=p->nstates-1; s >= 0; s--)
1986 if (p->coef_states[j][s] == k)
1987 {
1988 UpdateM(1.0,XX,p->Zeta[j][p->var_states[j][s]],p->XX[s]);
1989 UpdateM(1.0,XY,p->Zeta[j][p->var_states[j][s]],p->XY[s]);
1990 }
1991
1992 // XY + XX*W[j] - bSubtractV requires column major format.
1993 bSubtractV(pElementM(XY),pElementM(XY),pElementM(XX),p->npre*p->nvars);
1994 //SubtractMM(XY,XY,XX);
1995
1996 // (XY + XX*W[j])*a0[j][k]
1997 ProductMV(v,XY,p->A0[j][k]);
1998
1999 // b += PSI[k]'*diag(LAMBDA*lambda[j][k]+e)*(XY + XX*W[j])*a0[j][k]
2000 ElementV(b,p->npre-1+k)+=ElementV(v,i=p->npre-1);
2001 for (i--; i >= 0; )
2002 for (m=p->nvars-1; m >= 0; i--, m--)
2003 ElementV(b,i)+=ElementV(p->lambda[j][k],m)*ElementV(v,i);
2004
2005 // S += PSI[k]'*diag(LAMBDA*lambda[j][k]+e)*XX*diag(LAMBDA*lambda[j][k]+e)*PSI[k]
2006 update_psi_quadratic_form(S,p->nvars,p->nlags,k,p->lambda[j][k],XX);
2007
2008 if (_VERBOSE_COUNT)
2009 {
2010 fprintf(V_FILE,"//=== (j = %d k = %d) ===//\n",j,k);
2011 fprintf(V_FILE,"XX =\n");
2012 dw_PrintMatrix(V_FILE,XX,"%lg ");
2013
2014 fprintf(V_FILE,"lambda[%d][%d] =\n",j,k);
2015 dw_PrintVector(V_FILE,p->lambda[j][k],"%lg ");
2016
2017 fprintf(V_FILE,"S =\n");
2018 dw_PrintMatrix(V_FILE,S,"%lg ");
2019 }
2020 }
2021
2022 // Add inverse prior
2023 AddMM(S,S,p->inverse_psi_prior[j]);
2024
2025 /* TMatrix U,V; */
2026 /* TVector d; */
2027 /* int size=RowM(p->inverse_psi_prior[j]); */
2028 /* printf("inverse psi prior (%d)\n",j); */
2029 /* SVD(U=CreateMatrix(size,size),d=CreateVector(size),V=CreateMatrix(size,size),p->inverse_psi_prior[j]); */
2030 /* dw_PrintVector(stdout,d,"%lg "); */
2031 /* FreeMatrix(U); FreeMatrix(V); FreeVector(d); */
2032 /* getchar(); */
2033 if (_VERBOSE_COUNT)
2034 {
2035 fprintf(V_FILE,"inverse prior=\n");
2036 dw_PrintMatrix(V_FILE,p->inverse_psi_prior[j],"%lg ");
2037
2038 fprintf(V_FILE,"S =\n");
2039 dw_PrintMatrix(V_FILE,S,"%lg ");
2040 fprintf(V_FILE,"//=====================================================================//\n");
2041 }
2042
2043 // Draw psi[j]
2044 if (!DrawNormal_InverseVariance(p->psi[j],b,S))
2045 SingularInverseVariance_RecoveryAttempt(p->psi[j],b,S,p->inverse_psi_prior[j],model,PSI_ERR);
2046
2047 FreeMatrix(S);
2048 FreeVector(b);
2049 }
2050
2051 FreeVector(v);
2052 FreeMatrix(XY);
2053 FreeMatrix(XX);
2054 }
2055
2056 //-----------------------------------------------------------------------------//
2057 //-------------------------------- Draw lambda --------------------------------//
2058 //-----------------------------------------------------------------------------//
2059 /*
2060 Assumes:
2061 S: n x n matrix.
2062 XX: (n*b + 1) x (n*b + 1) symmetric matrix. XX must be column major.
2063 psi: (n*b+j) dimensional vector with j > 0.
2064
2065 Results:
2066 Set S to
2067
2068 LAMBDA'*diag(PSI[k]*psi)*XX*diag(PSI[k]*psi)*LAMBDA
2069
2070 to S. The matrices LAMBDA and PSI[k] are given by
2071
2072 - -
2073 | I(n) |
2074 | . | - -
2075 | . | | I(n*b) 0(n*b,j) |
2076 LAMBDA = | . | PSI[k] = | |
2077 | | | 0(1,n*b) e(j,k)' |
2078 | I(n) | - -
2079 | 0(1,n) |
2080 - -
2081
2082 where I(r) is the r x r identity matrix, 0(r,s) is the r x s zero matrix,
2083 and e(r,s) is the sth column of I(r).
2084
2085 Notes:
2086 Even though PSI[k] depends on k, the term diag(PSI[k]*psi)*LAMBDA does not.
2087 For this reason, k is not passed.
2088 */
2089 void lambda_quadratic_form(TMatrix S, int b, TVector psi, TMatrix XX)
2090 {
2091 int bj, j, i, r, n=RowM(S);
2092 PRECISION *x=pElementM(XX)+(b*n-1)*RowM(XX), *y, *z=pElementV(psi), w;
2093 InitializeMatrix(S,0.0);
2094 for (bj=b-1; bj >= 0; bj--)
2095 for (y=pElementM(S)+(n-1)*n, j=n-1; j >= 0; x-=RowM(XX), y-=n, j--)
2096 {
2097 w=z[bj*n+j];
2098 for (r=b*n-1; r >= 0; )
2099 for (i=n-1; i >= 0; r--, i--)
2100 y[i]+=z[r]*x[r]*w;
2101 }
2102 }
2103
2104 /*
2105
2106 Notes:
2107 The matrices MUST be in column major format. Basic matrix routines from
2108 bmatrix.c are called in this routine.
2109 */
2110 void Draw_lambda(TStateModel *model)
2111 {
2112 int j, k, s, i, m;
2113 TVector b, v;
2114 TMatrix S, XX, XY;
2115 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
2116
2117 // Update state dependent matrices if necessary
2118 if (!p->valid_state_dependent_fields)
2119 UpdateStateDependentFields(p,model->S);
2120
2121 // Allocate memory
2122 XX=CreateMatrix(p->npre,p->npre);
2123 XY=CreateMatrix(p->npre,p->nvars);
2124 v=CreateVector(p->npre);
2125 b=CreateVector(p->nvars);
2126 S=CreateMatrix(p->nvars,p->nvars);
2127
2128 if (_VERBOSE_COUNT)
2129 fprintf(V_FILE,"//=== Draw_psi() (count = %d) =====================================//\n",_VERBOSE_COUNT);
2130
2131 for (j=p->nvars-1; j >= 0; j--)
2132 {
2133 for (k=p->n_coef_states[j]-1; k > 0; k--)
2134 {
2135 // Accumulate XX and XY
2136 InitializeMatrix(XX,0.0);
2137 InitializeMatrix(XY,0.0);
2138 for (s=p->nstates-1; s >= 0; s--)
2139 if (p->coef_states[j][s] == k)
2140 {
2141 UpdateM(1.0,XX,p->Zeta[j][p->var_states[j][s]],p->XX[s]);
2142 UpdateM(1.0,XY,p->Zeta[j][p->var_states[j][s]],p->XY[s]);
2143 }
2144
2145 // Compute mean
2146 // XY + XX*W[j] - bSubtractV requires column major format
2147 bSubtractV(pElementM(XY),pElementM(XY),pElementM(XX),p->npre*p->nvars);
2148 //SubtractMM(XY,XY,XX);
2149
2150 // (XY + XX*W[j])*a0[j][k]
2151 ProductMV(v,XY,p->A0[j][k]);
2152
2153 // (XY + XX*W[j])*a0[j][k] - XX*diag(PSI[k]*psi[j])*e
2154 //bLinearUpdateScalar(pElementV(v),pElementM(XX)+p->npre*(p->npre-1),-ElementV(p->constant[j],k),p->npre);
2155 bLinearCombinationV(pElementV(v),1.0,pElementV(v),-ElementV(p->constant[j],k),pElementM(XX)+p->npre*(p->npre-1),p->npre);
2156
2157 // b = LAMBDA'*diag(PSI[j][k]*psi[j])*((XY + XX*W[j])*a0[j][k] - XX*diag(PSI[k]*psi[j])*lambda_hat)
2158 InitializeVector(b,0.0);
2159 for (i=p->npre-2; i >= 0; )
2160 for (m=p->nvars-1; m >= 0; i--, m--)
2161 ElementV(b,m)+=ElementV(p->psi[j],i)*ElementV(v,i);
2162
2163 // Compute inverse variance matrix
2164 // S = LAMBDA'*diag(PSI[j][k]*psi[j])*XX*diag(PSI[j][k]*psi[j])*LAMBDA
2165 lambda_quadratic_form(S,p->nlags,p->psi[j],XX);
2166
2167 for (i=p->nvars-1; i >= 0; i--) ElementM(S,i,i)+=p->inverse_lambda_prior;
2168
2169 if (_VERBOSE_COUNT)
2170 {
2171 fprintf(V_FILE,"//=== (j = %d k = %d) ===//\n",j,k);
2172 fprintf(V_FILE,"XX =\n");
2173 dw_PrintMatrix(V_FILE,XX,"%lg ");
2174
2175 fprintf(V_FILE,"psi[%d][%d] =\n",j,k);
2176 dw_PrintVector(V_FILE,p->psi[j],"%lg ");
2177
2178 fprintf(V_FILE,"S =\n");
2179 dw_PrintMatrix(V_FILE,S,"%lg ");
2180
2181 fprintf(V_FILE,"inverse prior = %lg\n",p->inverse_lambda_prior);
2182 }
2183
2184 // Draw lambda[j][k]
2185 if (!DrawNormal_InverseVariance(p->lambda[j][k],b,S))
2186 {
2187 TMatrix InversePrior=IdentityMatrix((TMatrix)NULL,p->nvars);
2188 ProductMS(InversePrior,InversePrior,p->inverse_lambda_prior);
2189 SingularInverseVariance_RecoveryAttempt(p->lambda[j][k],b,S,InversePrior,model,LAMBDA_ERR);
2190 FreeMatrix(InversePrior);
2191 }
2192 }
2193
2194 // State 0 normalized to one
2195 InitializeVector(p->lambda[j][k],1.0);
2196 }
2197
2198 if (_VERBOSE_COUNT)
2199 fprintf(V_FILE,"//====================================================//\n");
2200
2201 // Free memory
2202 FreeMatrix(S);
2203 FreeVector(b);
2204 FreeVector(v);
2205 FreeMatrix(XY);
2206 FreeMatrix(XX);
2207 }
2208 /******************************************************************************/
2209 /******************************************************************************/
2210 /******************************************************************************/
2211
2212 /******************************************************************************/
2213 /********************** Updating T_VAR_Parameter Fields ***********************/
2214 /******************************************************************************/
2215 void UpdateStateDependentFields(T_VAR_Parameters *p, int *S)
2216 {
2217 int i, s_prev, s_curr, t;
2218
2219 dw_InitializeArray_int(p->T,0);
2220
2221 if (!p->valid_state_dependent_fields_previous)
2222 {
2223 //=== Update Y'Y, X'Y, and X'X ===
2224 for (i=dw_DimA(p->YY)-1; i >= 0; i--)
2225 {
2226 InitializeMatrix(p->YY[i],0.0);
2227 InitializeMatrix(p->XY[i],0.0);
2228 InitializeMatrix(p->XX[i],0.0);
2229 }
2230 for (t=p->nobs; t > 0; t--)
2231 {
2232 s_curr=S[t];
2233 AddMM(p->YY[s_curr],p->YY[s_curr],p->yy[t]);
2234 AddMM(p->XY[s_curr],p->XY[s_curr],p->xy[t]);
2235 AddMM(p->XX[s_curr],p->XX[s_curr],p->xx[t]);
2236 p->T[s_curr]++;
2237 }
2238 //p->valid_state_dependent_fields_previous=1;
2239 }
2240 else
2241 {
2242 for (t=p->nobs; t > 0; t--)
2243 {
2244 if ((s_curr=S[t]) != (s_prev=p->S[t]))
2245 {
2246 SubtractMM(p->YY[s_prev],p->YY[s_prev],p->yy[t]);
2247 SubtractMM(p->XY[s_prev],p->XY[s_prev],p->xy[t]);
2248 SubtractMM(p->XX[s_prev],p->XX[s_prev],p->xx[t]);
2249 AddMM(p->YY[s_curr],p->YY[s_curr],p->yy[t]);
2250 AddMM(p->XY[s_curr],p->XY[s_curr],p->xy[t]);
2251 AddMM(p->XX[s_curr],p->XX[s_curr],p->xx[t]);
2252 }
2253 p->T[s_curr]++;
2254 }
2255 }
2256
2257 //memcpy(p->S,S,(p->nobs+1)*sizeof(int));
2258
2259 p->valid_state_dependent_fields=1;
2260 }
2261
2262 /*
2263 Assumes:
2264 p: Pointer to valid T_VAR_Parameters structure with b0 updated.
2265
2266 Results:
2267 Updates A0
2268
2269 Notes:
2270 Uses the relation
2271
2272 A0[j][k] = U[j]*b0[j][k]
2273
2274 */
2275 void Update_A0_from_b0(T_VAR_Parameters *p)
2276 {
2277 int j, k;
2278
2279 for (j=p->nvars-1; j >= 0; j--)
2280 for (k=dw_DimA(p->A0[j])-1; k >= 0; k--)
2281 ProductMV(p->A0[j][k],p->U[j],p->b0[j][k]);
2282 }
2283
2284 /*
2285 Sets
2286
2287 Aplus[j][k] = V[j]*b0[j][k] - W[j]*A0[j][k]
2288
2289 where 0 <= j < p->nvars and 0 <= k < p->n_coef_states[j].
2290
2291 If (p->Specification & SPEC_RANDOMWALK) is set, uses the fact that
2292 W'[j] = [-I 0]. In this case a call to the base matrix function bAdd() is
2293 made.
2294
2295 If p->IsIdentity_V[j] is set, uses the fact that V[j] = I.
2296 */
2297 void Update_aplus_from_bplus_a0(int j, int k, T_VAR_Parameters *p)
2298 {
2299 TVector v;
2300
2301 if (p->IsIdentity_V[j])
2302 if (p->W[j])
2303 if (p->Specification & SPEC_RANDOM_WALK)
2304 {
2305 bAddV(pElementV(p->Aplus[j][k]),pElementV(p->bplus[j][k]),pElementV(p->A0[j][k]),p->nvars);
2306 memcpy(pElementV(p->Aplus[j][k]) + p->nvars,pElementV(p->bplus[j][k]) + p->nvars,(p->npre - p->nvars)*sizeof(PRECISION));
2307 }
2308 else
2309 {
2310 ProductMV(p->Aplus[j][k],p->W[j],p->A0[j][k]);
2311 SubtractVV(p->Aplus[j][k],p->bplus[j][k],p->Aplus[j][k]);
2312 }
2313 else
2314 EquateVector(p->Aplus[j][k],p->bplus[j][k]);
2315 else
2316 if (p->V[j])
2317 {
2318 ProductMV(p->Aplus[j][k],p->V[j],p->bplus[j][k]);
2319 if (p->W[j])
2320 {
2321 if (p->Specification & SPEC_RANDOM_WALK)
2322 bAddV(pElementV(p->Aplus[j][k]),pElementV(p->Aplus[j][k]),pElementV(p->A0[j][k]),p->nvars);
2323 else
2324 {
2325 v=ProductMV((TVector)NULL,p->W[j],p->A0[j][k]);
2326 SubtractVV(p->Aplus[j][k],p->Aplus[j][k],v);
2327 FreeVector(v);
2328 }
2329 }
2330 }
2331 else
2332 if (p->W[j])
2333 if (p->Specification & SPEC_RANDOM_WALK)
2334 {
2335 InitializeVector(p->Aplus[j][k],0.0);
2336 memcpy(pElementV(p->Aplus[j][k]),pElementV(p->A0[j][k]),p->nvars*sizeof(PRECISION));
2337 }
2338 else
2339 {
2340 ProductMV(p->Aplus[j][k],p->W[j],p->A0[j][k]);
2341 MinusV(p->Aplus[j][k],p->Aplus[j][k]);
2342 }
2343 else
2344 InitializeVector(p->Aplus[j][k],0.0);
2345 }
2346
2347 /*
2348 Assumes:
2349 p: Pointer to valid T_VAR_Parameters structure with A0 and bplus updated.
2350
2351 Results:
2352 Updates Aplus
2353
2354 Notes:
2355 Uses the relation
2356
2357 Aplus[j][k] = V[j]*bplus[j][k] - W[j]*A0[j][k]
2358
2359 If the Sims-Zha specification is used, special code is used to take advantage
2360 of the fact that V[j] is the identity and W[j] is diagonal with minus ones
2361 along the diagonal.
2362
2363 */
2364 void Update_Aplus_from_bplus_A0(T_VAR_Parameters *p)
2365 {
2366 int j, k;
2367 for (j=p->nvars-1; j >= 0; j--)
2368 for (k=p->n_coef_states[j]-1; k >= 0; k--)
2369 Update_aplus_from_bplus_a0(j,k,p);
2370 }
2371
2372 /*
2373 Assumes:
2374 p: Pointer to valid TStateModel structure with psi and lambda updated.
2375
2376 Results:
2377 Updates bplus
2378
2379 Notes:
2380 | lambda[j][k][i % nvars]*psi[j][i] for 0 <= i < nvars*nlags
2381 bplus[j][k][i] = |
2382 | psi[j][i] for nvar*nlags <= i
2383
2384 The normalization lambda[j][0][i] = 1 is used. This is the Sims-Zha
2385 specification.
2386
2387 */
2388 void Update_bplus_from_lambda_psi(T_VAR_Parameters *p)
2389 {
2390 int j, k, i, m;
2391 PRECISION *p_bplus, *p_lambda, *p_psi;
2392 if (!(p->Specification & SPEC_SIMS_ZHA))
2393 {
2394 printf("Update_bplus_from_lambda_psi() called without Sims-Zha specification\n");
2395 dw_exit(0);
2396 }
2397 for (j=p->nvars-1; j >= 0; j--)
2398 {
2399 p_psi=pElementV(p->psi[j]);
2400 for (k=dw_DimA(p->bplus[j])-1; k >= 0; k--)
2401 {
2402 p_bplus=pElementV(p->bplus[j][k]);
2403 p_lambda=pElementV(p->lambda[j][k]);
2404 p_bplus[i=p->nlags * p->nvars]=ElementV(p->constant[j],k);
2405 for (i--; i >= 0; )
2406 for (m=p->nvars-1; m >= 0; i--, m--)
2407 p_bplus[i]=p_lambda[m]*p_psi[i];
2408 }
2409 }
2410 }
2411
2412 /*
2413 Assumes:
2414 p: Pointer to valid T_VAR_Parameters structure with A0 and Aplus udated.
2415
2416 Results:
2417 Updates b0 and bplus
2418
2419 Notes:
2420 Uses the relations
2421
2422 A0[j][k] = U[j]*b0[j][k]
2423
2424 Aplus[j][k] = V[j]*bplus[j][k] - W[j]*A0[j][k]
2425
2426 U'[j]*U[j] = identity
2427
2428 V'[j]*V[j] = identity
2429 */
2430 void Update_b0_bplus_from_A0_Aplus(T_VAR_Parameters *p)
2431 {
2432 int i, j, k;
2433 TVector v;
2434 PRECISION *p_Aplus, *p_bplus, *p_A0;
2435
2436 // A0
2437 for (j=p->nvars-1; j >= 0; j--)
2438 for (k=dw_DimA(p->A0[j])-1; k >= 0; k--)
2439 TransposeProductMV(p->b0[j][k],p->U[j],p->A0[j][k]);
2440
2441 // Aplus
2442 if (p->Specification & SPEC_SIMS_ZHA)
2443 {
2444 for (j=p->nvars-1; j >= 0; j--)
2445 for (k=dw_DimA(p->Aplus[j])-1; k >= 0; k--)
2446 {
2447 p_A0=pElementV(p->A0[j][k]);
2448 p_Aplus=pElementV(p->Aplus[j][k]);
2449 p_bplus=pElementV(p->bplus[j][k]);
2450 i=p->nvars;
2451 memcpy(p_bplus+i,p_Aplus+i,(p->npre - p->nvars)*sizeof(PRECISION));
2452 for (i--; i >= 0; i--) p_bplus[i]=p_Aplus[i]-p_A0[i];
2453 }
2454 }
2455 else
2456 {
2457 v=CreateVector(p->npre);
2458 for (j=p->nvars-1; j >= 0; j--)
2459 if (p->V[j])
2460 {
2461 for (k=dw_DimA(p->A0[j])-1; k >= 0; k--)
2462 if (p->W[j])
2463 {
2464 ProductMV(v,p->W[j],p->A0[j][k]);
2465 AddVV(v,v,p->Aplus[j][k]);
2466 TransposeProductMV(p->bplus[j][k],p->V[j],v);
2467 }
2468 else
2469 TransposeProductMV(p->bplus[j][k],p->V[j],p->Aplus[j][k]);
2470 }
2471 FreeVector(v);
2472 }
2473 }
2474
2475 /*
2476 Assumes:
2477 model: pointer to valid TStateModel structure with bplus updated.
2478
2479 Results:
2480 Updates lambda and psi.
2481
2482 Notes:
2483 | lambda[j][k][i % nvars]*psi[j][i] for 0 <= i < nvars*nlags
2484 bplus[j][k][i] = |
2485 | psi[j][i] for nvar*nlags <= i
2486
2487 The normalization lambda[j][0][i] = 1 is used. This is the Sims-Zha
2488 specification.
2489 */
2490 void Update_lambda_psi_from_bplus(T_VAR_Parameters *p)
2491 {
2492 int j, k, i, m, n, dim=p->nlags*p->nvars;
2493 PRECISION *p_bplus, *p_lambda, *p_psi;
2494 for (j=p->nvars-1; j >= 0; j--)
2495 {
2496 p_psi=pElementV(p->psi[j]);
2497 p_bplus=pElementV(p->bplus[j][0]);
2498 memcpy(p_psi,p_bplus,dim*sizeof(PRECISION));
2499 ElementV(p->constant[j],0)=p_bplus[dim];
2500 InitializeVector(p->lambda[j][0],1.0);
2501
2502 for (k=dw_DimA(p->bplus[j])-1; k > 0; k--)
2503 {
2504 p_bplus=pElementV(p->bplus[j][k]);
2505 p_lambda=pElementV(p->lambda[j][k]);
2506 ElementV(p->constant[j],k)=p_bplus[dim];
2507 for (m=p->nvars-1; m >= 0; m--)
2508 {
2509 for (n=dim-p->nvars+m, i=n-p->nvars; i >= 0; i-=p->nvars)
2510 if (fabs(p_psi[i]) > fabs(p_psi[n])) n=i;
2511 p_lambda[m]=(p_psi[n] != 0) ? p_bplus[n]/p_psi[n] : 0;
2512 }
2513 }
2514 }
2515 }
2516
2517
2518 /******************************************************************************/
2519 /******************************************************************************/
2520 /******************************************************************************/
2521
2522 /******************************************************************************/
2523 /********************************* Forecasts **********************************/
2524 /******************************************************************************/
2525 /*
2526 Assumes:
2527 forecast : horizon x nvars matrix or null pointer
2528 horizon : positive integer - forecast horizon
2529 initial : initial value of predetermined variables.
2530 shocks : array of length horizon of shocks or null pointer. If null
2531 pointer, then the shocks are all zero. Each vector is of length
2532 nvar.
2533 S : array of length horizon. S[t] is the state at time T+1+t.
2534 model : pointer to valid TStateModel structure.
2535
2536 Results:
2537 Computes forecast
2538
2539 Returns:
2540 The matrix forecast upon success and null upon failure. If forecast is
2541 null, then it created.
2542 */
2543 TMatrix forecast_base(TMatrix forecast, int horizon, TVector initial, TVector *shocks, int *S, TStateModel *model)
2544 {
2545 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
2546 TMatrix *A0, *Aplus;
2547 TVector x, y;
2548 int i, t;
2549
2550 // allocate forecast if necessary
2551 if (!forecast && !(forecast=CreateMatrix(horizon,p->nvars)))
2552 return (TMatrix)NULL;
2553
2554 // allocate memory
2555 y=CreateVector(p->nvars);
2556 x=EquateVector((TVector)NULL,initial);
2557 A0=MakeA0_All((TMatrix*)NULL,p);
2558 Aplus=MakeAplus_All((TMatrix*)NULL,p);
2559
2560 // forecast
2561 for (t=0; t < horizon; t++)
2562 {
2563 ProductVM(y,x,Aplus[S[t]]);
2564 if (shocks)
2565 {
2566 for (i=p->nvars-1; i >= 0; i--)
2567 ElementV(y,i)+=ElementV(shocks[t],i)/sqrt(p->Zeta[i][p->var_states[i][S[t]]]);
2568 }
2569 ProductInverseVM(y,y,A0[S[t]]);
2570 for (i=p->nvars-1; i >= 0; i--)
2571 ElementM(forecast,t,i)=ElementV(y,i);
2572
2573 memmove(pElementV(x)+p->nvars,pElementV(x),(p->nlags-1)*p->nvars*sizeof(PRECISION));
2574 memcpy(pElementV(x),pElementV(y),p->nvars*sizeof(PRECISION));
2575 }
2576
2577 // free memory
2578 dw_FreeArray(Aplus);
2579 dw_FreeArray(A0);
2580 FreeVector(x);
2581 FreeVector(y);
2582
2583 return forecast;
2584 }
2585
2586
2587 /******************************************************************************/
2588 /** Impulse Response Routines **/
2589 /******************************************************************************/
2590 /*
2591 Consider the model
2592
2593 y'(t) = [y'(t-1) ... y'(t-p) z'(t)]*B + epsilon'(t) * Inverse(A0*Xi)
2594
2595
2596 The impulse response of variable j to shock i
2597 at horizon h is the element in row i and colum j of
2598
2599 Inverse(A0*Xi) * J * S^(h-1) * J'
2600
2601 where
2602
2603 B(1) I ... 0
2604 . . . .
2605 S = . . . .
2606 . . . .
2607 B(p-1) 0 ... I
2608 B(p) 0 ... 0
2609
2610 J = [I 0 ... 0]
2611
2612 B'= [B'(1) ... B'(p) C']
2613 */
2614 TMatrix ComputeImpulseResponseReducedForm(TMatrix R, int h, TMatrix A0_Xi_inv, TMatrix B, int nlags)
2615 {
2616 TMatrix X=R, S, T, W;
2617 int n, t, i, j, m;
2618
2619 dw_ClearError();
2620
2621 if (!A0_Xi_inv || ((h > 1) && !B))
2622 {
2623 dw_Error(NULL_ERR);
2624 return (TMatrix)NULL;
2625 }
2626 n=RowM(A0_Xi_inv);
2627 if (!X)
2628 {
2629 if (!(X=CreateMatrix(h,n*n))) return (TMatrix)NULL;
2630 }
2631 else
2632 if ((RowM(X) != h) || (ColM(X) != n*n))
2633 {
2634 dw_Error(SIZE_ERR);
2635 return (TMatrix)NULL;
2636 }
2637
2638 for (m=n*n-1, i=n-1; i >= 0; i--)
2639 for (j=n-1; j >= 0; m--, j--)
2640 ElementM(X,0,m)=ElementM(A0_Xi_inv,i,j);
2641
2642 if (h > 1)
2643 {
2644 InitializeMatrix(S=CreateMatrix(n*nlags,n*nlags),0.0);
2645 for (i=n*(nlags - 1) - 1; i >= 0; i--) ElementM(S,i,i+n)=1.0;
2646 InsertSubMatrix(S,B,0,0,0,0,n*nlags,n);
2647
2648
2649 W=SubMatrix((TMatrix)NULL,S,0,0,n,n);
2650 ProductMM(W,A0_Xi_inv,W);
2651 for (m=n*n-1, i=n-1; i >= 0; i--)
2652 for (j=n-1; j >= 0; m--, j--)
2653 ElementM(X,1,m)=ElementM(W,i,j);
2654
2655 if (h > 2)
2656 {
2657 T=EquateMatrix((TMatrix)NULL,S);
2658
2659 for (t=2; t < h; t++)
2660 {
2661 ProductMM(T,T,S);
2662 SubMatrix(W,T,0,0,n,n);
2663 ProductMM(W,A0_Xi_inv,W);
2664 for (m=n*n-1, i=n-1; i >= 0; i--)
2665 for (j=n-1; j >= 0; m--, j--)
2666 ElementM(X,t,m)=ElementM(W,i,j);
2667 }
2668
2669 FreeMatrix(T);
2670 }
2671
2672 FreeMatrix(W);
2673 FreeMatrix(S);
2674 }
2675
2676 if (dw_GetError() != NO_ERR)
2677 {
2678 if (X != R) FreeMatrix(X);
2679 return (TMatrix)NULL;
2680 }
2681
2682 return X;
2683 }
2684
2685 /*
2686 Consider the model
2687
2688 y'(t)*A(0) = [y'(t-1) ... y'(t-p) z'(t)]*Aplus + epsilon'(t)*Inverse(Xi)
2689
2690
2691 The impulse response of variable j to shock i
2692 at horizon h is the element in row i and colum j of
2693
2694 Inverse(A0*Xi) * J * S^(h-1) * J'
2695
2696 where
2697
2698 B(1) I ... 0
2699 . . . .
2700 S = . . . .
2701 . . . .
2702 B(p-1) 0 ... I
2703 B(p) 0 ... 0
2704
2705 J = [I 0 ... 0]
2706
2707 B = Aplus * Inverse(A0)
2708
2709 B'= [B'(1) ... B'(p) C']
2710
2711 Note that if Y'(t)=[y'(t) ... y'(t-p+1)], then
2712
2713 Y'(t) = Y'(t-1)*S + J*z'(t)*C + J*epsilon'(t)*Inverse(A0*Xi)
2714 */
2715 TMatrix ComputeImpulseResponseStructural(TMatrix R, int h, TMatrix A0, TMatrix Aplus, TVector Xi, int nlags)
2716 {
2717 TMatrix X, B;
2718 int n=RowM(A0), i, j;
2719 PRECISION xi_inv;
2720
2721 X=Inverse_LU((TMatrix)NULL,A0);
2722
2723 B=(h > 1) ? ProductMM((TMatrix)NULL,Aplus,X) : (TMatrix)NULL;
2724
2725 for (i=n-1; i >= 0; i--)
2726 for (xi_inv=1.0/ElementV(Xi,i), j=n-1; j >= 0; j--)
2727 ElementM(X,i,j)*=xi_inv;
2728
2729 R=ComputeImpulseResponseReducedForm(R,h,X,B,nlags);
2730
2731 FreeMatrix(X);
2732 FreeMatrix(B);
2733
2734 return R;
2735 }
2736
2737 /*
2738 Consider the model
2739
2740 y(t)' * A(0)(s(t)) = Sum[y(t-i)' * A(i)(s(t)),i=1,...,p] +
2741 + z(t)' * C + epsilon(t)' * Inverse(Xi(s(t)))
2742
2743
2744 Condition on state k occuring, the impulse response of variable j to shock i
2745 at horizon h is the element in row i and colum j of
2746
2747 Inverse(Xi(k)) * Inverse(A(0)(k)) * J * S^(h-1) * J'
2748
2749 where
2750
2751 S = A(1)(k)*Inverse(A(0)(k)) I ... 0
2752 . . . .
2753 . . . .
2754 . . . .
2755 A(p-1)(k)*Inverse(A(0)(k)) 0 ... I
2756 A(p)(k)*Inverse(A(0)(k)) 0 ... 0
2757 and
2758
2759 J = [I 0 ... 0].
2760 */
2761 TMatrix ComputeImpulseResponse(TMatrix R, int h, int k, TStateModel *model)
2762 {
2763 TMatrix X, Aplus, B;
2764 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
2765 PRECISION xi_inv;
2766 int n=p->nvars, i, j;
2767
2768 if ((k < 0) || (k >= p->nstates))
2769 {
2770 dw_Error(SIZE_ERR);
2771 return (TMatrix)NULL;
2772 }
2773
2774 X=MakeA0((TMatrix)NULL,k,p);
2775 Inverse_LU(X,X);
2776
2777 if (h > 1)
2778 {
2779 Aplus=MakeAplus((TMatrix)NULL,k,p);
2780 B=ProductMM((TMatrix)NULL,Aplus,X);
2781 }
2782 else
2783 Aplus=B=(TMatrix)NULL;
2784
2785 for (i=n-1; i >= 0; i--)
2786 for (xi_inv=1.0/sqrt(p->Zeta[i][p->var_states[i][k]]), j=n-1; j >= 0; j--)
2787 ElementM(X,i,j)*=xi_inv;
2788
2789 R=ComputeImpulseResponseReducedForm(R,h,X,B,p->nlags);
2790
2791 FreeMatrix(B);
2792 FreeMatrix(Aplus);
2793 FreeMatrix(X);
2794
2795 return R;
2796 }
2797
2798 /*
2799 Computes the cummulative variance decomposition of the impulse responses (IR).
2800 */
2801 TMatrix ComputeVarianceDecomposition(TMatrix X, TMatrix IR, int nvars)
2802 {
2803 TMatrix Y=X;
2804 int t, i, j;
2805 PRECISION sum, tmp;
2806
2807 dw_ClearError();
2808
2809 if (!IR)
2810 {
2811 dw_Error(NULL_ERR);
2812 return (TMatrix)NULL;
2813 }
2814 else
2815 if (ColM(IR) != nvars*nvars)
2816 {
2817 dw_Error(SIZE_ERR);
2818 return (TMatrix)NULL;
2819 }
2820 else
2821 if (!Y)
2822 {
2823 if (!(Y=CreateMatrix(RowM(IR),ColM(IR)))) return (TMatrix)NULL;
2824 }
2825 else
2826 if ((RowM(Y) != RowM(IR)) || (ColM(Y) != ColM(IR)))
2827 {
2828 dw_Error(SIZE_ERR);
2829 return (TMatrix)NULL;
2830 }
2831
2832 // Compute cummulative variation
2833 for (j=nvars*nvars-1; j >= 0; j--)
2834 {
2835 tmp=ElementM(IR,0,j);
2836 ElementM(Y,0,j)=tmp*tmp;
2837 }
2838 for (t=1; t < RowM(IR); t++)
2839 for (j=nvars*nvars-1; j >= 0; j--)
2840 {
2841 tmp=ElementM(IR,t,j);
2842 ElementM(Y,t,j)=tmp*tmp + ElementM(Y,t-1,j);
2843 }
2844
2845 // Compute cummulative variance decomposition
2846 for (t=0; t < RowM(IR); t++)
2847 for (j=nvars-1; j >= 0; j--)
2848 {
2849 for (sum=0.0, i=nvars*(nvars-1)+j; i >= 0; i-=nvars) sum+=ElementM(Y,t,i);
2850 if (sum > 0)
2851 for (sum=1.0/sum, i=nvars*(nvars-1)+j; i >= 0; i-=nvars) ElementM(Y,t,i)*=sum;
2852 }
2853
2854 return Y;
2855 }
2856 /******************************************************************************/
2857 /******************************************************************************/
2858 /******************************************************************************/
2859
2860
2861
2862 /*******************************************************************************/
2863 /******************************** Optimization *********************************/
2864 /*******************************************************************************/
2865 /* PRECISION ComputeConstantSimsZha(TStateModel *model) */
2866 /* { */
2867 /* int j; */
2868 /* PRECISION constant=0.0; */
2869 /* T_VAR_Parameters *p=(T_VAR_Parameters*)(model->p->p); */
2870 /* for (j=p->nvars-1; j >= 0; j--) */
2871 /* { */
2872 /* // b0 */
2873 /* constant+=0.5*p->n_coef_states[j]*DimV(p->b0[j][0])*log(p->n_A0_states/p->n_coef_states[j]); */
2874
2875 /* // bplus or psi and constant */
2876 /* if (p->bplus[j]) */
2877 /* if (p->Specification & SPEC_SIMS_ZHA) */
2878 /* constant+=0.5*((p->npre-1)*log(p->n_A0_states) + p->n_coef_states[j]*log(p->n_A0_states/p->n_coef_states[j])); */
2879 /* else */
2880 /* constant+=0.5*p->n_coef_states[j]*DimV(p->bplus[j][0])*log(p->n_A0_states/p->n_coef_states[j]); */
2881 /* } */
2882 /* return constant; */
2883 /* } */
2884
2885 #define LN_TWO_PI 1.837877066409345
2886 void SetLogPriorConstant_VAR(T_VAR_Parameters *p)
2887 {
2888 int j;
2889
2890 p->log_prior_constant=0.0;
2891
2892 for (j=p->nvars-1; j >= 0; j--)
2893 {
2894 // Gamma prior on Zeta
2895 if (p->n_var_states[j] > 1)
2896 p->log_prior_constant+=(p->n_var_states[j] - 1)*(ElementV(p->zeta_a_prior,j)*log(ElementV(p->zeta_b_prior,j))
2897 - dw_log_gamma(ElementV(p->zeta_a_prior,j)));
2898
2899 // Normal prior on b0 (A0)
2900 p->log_prior_constant+=0.5*p->n_coef_states[j]*(-DimV(p->b0[j][0])*LN_TWO_PI + LogAbsDeterminant_LU(p->inverse_b0_prior[j]));
2901
2902 if (p->Specification & SPEC_SIMS_ZHA)
2903 {
2904 // Independent normal prior each element of delta with variance equal to delta_prior
2905 p->log_prior_constant-=0.5 * (dw_DimA(p->lambda[j])-1) * p->nvars * (LN_TWO_PI + log(p->lambda_prior));
2906
2907 // Normal prior on psi and constant
2908 p->log_prior_constant+=0.5*(-(p->npre-1+p->n_coef_states[j])*LN_TWO_PI + LogAbsDeterminant_LU(p->inverse_psi_prior[j]));
2909 }
2910 else
2911 {
2912 // Normal prior on bplus (Aplus)
2913 if (p->bplus[j])
2914 p->log_prior_constant+=0.5*p->n_coef_states[j]*(-DimV(p->bplus[j][0])*LN_TWO_PI + LogAbsDeterminant_LU(p->inverse_bplus_prior[j]));
2915 }
2916 }
2917
2918 }
2919 #undef LN_TWO_PI
2920 PRECISION LogPrior_VAR(TStateModel *model)
2921 {
2922 int j, k;
2923 PRECISION x, y, log_prior=0.0;
2924 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
2925
2926 if (!(p->valid_parameters) || !IsNormalized_VAR(p)) return MINUS_INFINITY;
2927
2928 for (j=p->nvars-1; j >= 0; j--)
2929 {
2930 // Gamma prior on Zeta
2931 if (p->n_var_states[j] > 1)
2932 {
2933 x=ElementV(p->zeta_b_prior,j);
2934 y=2*(ElementV(p->zeta_a_prior,j)-1);
2935 for (k=p->n_var_states[j]-1; k > 0; k--)
2936 log_prior+=y*sqrt(p->Zeta[j][k]) - x*p->Zeta[j][k];
2937 }
2938
2939 // Normal prior on b0 (A0)
2940 for (k=p->n_coef_states[j]-1; k >= 0; k--)
2941 log_prior-=0.5*InnerProductSymmetric(p->b0[j][k],p->inverse_b0_prior[j]);
2942
2943 if (p->Specification & SPEC_SIMS_ZHA)
2944 {
2945 // Independent normal prior each element of lambda with variance equal to lambda_prior
2946 if (dw_DimA(p->lambda[j]) > 1)
2947 {
2948 for (x=0.0, k=p->n_coef_states[j]-1; k > 0; k--)
2949 x+=DotProduct(p->lambda[j][k],p->lambda[j][k]);
2950 log_prior-=0.5 * x * p->inverse_lambda_prior;
2951 }
2952
2953 // Normal prior on psi and constant
2954 log_prior-=0.5*InnerProductSymmetric(p->psi[j],p->inverse_psi_prior[j]);
2955 }
2956 else
2957 {
2958 // Normal prior on bplus (Aplus)
2959 for (k=p->n_coef_states[j]-1; k >= 0; k--)
2960 log_prior-=0.5*InnerProductSymmetric(p->bplus[j][k],p->inverse_bplus_prior[j]);
2961 }
2962 }
2963
2964 return log_prior + p->log_prior_constant + p->log_normalization_constant;
2965 }
2966
2967 void SetNumberFreeParametersVAR(T_VAR_Parameters *p)
2968 {
2969 int j, k;
2970 p->n_free_parameters=0;
2971
2972 // b0
2973 for (j=0; j < p->nvars; j++)
2974 for (k=0; k < dw_DimA(p->b0[j]); k++)
2975 p->n_free_parameters+=DimV(p->b0[j][k]);
2976
2977 if (p->Specification & SPEC_SIMS_ZHA)
2978 {
2979 // lambda
2980 for (j=0; j < p->nvars; j++)
2981 for (k=1; k < dw_DimA(p->lambda[j]); k++)
2982 p->n_free_parameters+=DimV(p->lambda[j][k]);
2983
2984 // psi
2985 for (j=0; j < p->nvars; j++)
2986 p->n_free_parameters+=DimV(p->psi[j]);
2987 }
2988 else
2989 {
2990 // bplus
2991 for (j=0; j < p->nvars; j++)
2992 if (p->bplus[j])
2993 for (k=0; k < dw_DimA(p->bplus[j]); k++)
2994 p->n_free_parameters+=DimV(p->bplus[j][k]);
2995 }
2996
2997 // Zeta
2998 for (j=0; j < p->nvars; j++)
2999 p->n_free_parameters+=dw_DimA(p->Zeta[j])-1;
3000 }
3001
3002 int NumberFreeParametersVAR(TStateModel *model)
3003 {
3004 return ((T_VAR_Parameters*)(model->theta))->n_free_parameters;
3005 }
3006
3007 void FreeParametersToVAR(TStateModel *model, PRECISION *f)
3008 {
3009 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
3010 int k, j;
3011
3012 // b0
3013 for (j=0; j < p->nvars; j++)
3014 for (k=0; k < dw_DimA(p->b0[j]); k++)
3015 {
3016 memcpy(pElementV(p->b0[j][k]),f,DimV(p->b0[j][k])*sizeof(PRECISION));
3017 f+=DimV(p->b0[j][k]);
3018 }
3019
3020 if (p->Specification & SPEC_SIMS_ZHA)
3021 {
3022 // lambda
3023 for (j=0; j < p->nvars; j++)
3024 {
3025 InitializeVector(p->lambda[j][0],1.0);
3026 for (k=1; k < dw_DimA(p->lambda[j]); k++)
3027 {
3028 memcpy(pElementV(p->lambda[j][k]),f,DimV(p->lambda[j][k])*sizeof(PRECISION));
3029 f+=DimV(p->lambda[j][k]);
3030 }
3031 }
3032
3033 // psi
3034 for (j=0; j < p->nvars; j++)
3035 {
3036 memcpy(pElementV(p->psi[j]),f,DimV(p->psi[j])*sizeof(PRECISION));
3037 f+=DimV(p->psi[j]);
3038 }
3039 }
3040 else
3041 {
3042 // bplus
3043 for (j=0; j < p->nvars; j++)
3044 if (p->bplus[j])
3045 for (k=0; k < dw_DimA(p->bplus[j]); k++)
3046 {
3047 memcpy(pElementV(p->bplus[j][k]),f,DimV(p->bplus[j][k])*sizeof(PRECISION));
3048 f+=DimV(p->bplus[j][k]);
3049 }
3050 }
3051
3052 // Zeta
3053 for (j=0; j < p->nvars; j++)
3054 {
3055 // Zeta non-negative
3056 for (k=dw_DimA(p->Zeta[j])-2; k >= 0; k--)
3057 if (f[k] < 0.0)
3058 {
3059 p->valid_parameters=0;
3060 return;
3061 }
3062
3063 p->Zeta[j][0]=1.0;
3064 memcpy(p->Zeta[j]+1,f,(dw_DimA(p->Zeta[j])-1)*sizeof(PRECISION));
3065 f+=dw_DimA(p->Zeta[j])-1;
3066 }
3067
3068 // Update A0 and Aplus
3069 if (p->Specification & SPEC_SIMS_ZHA) Update_bplus_from_lambda_psi(p);
3070 Update_A0_from_b0(p);
3071 Update_Aplus_from_bplus_A0(p);
3072
3073 // Set flags
3074 p->valid_parameters=1;
3075 ThetaChanged(model);
3076 }
3077
3078 void VARToFreeParameters(TStateModel *model, PRECISION *f)
3079 {
3080 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
3081 int k, j;
3082
3083 // b0
3084 for (j=0; j < p->nvars; j++)
3085 for (k=0; k < dw_DimA(p->b0[j]); k++)
3086 {
3087 memcpy(f,pElementV(p->b0[j][k]),DimV(p->b0[j][k])*sizeof(PRECISION));
3088 f+=DimV(p->b0[j][k]);
3089 }
3090
3091 if (p->Specification & SPEC_SIMS_ZHA)
3092 {
3093 // lambda
3094 for (j=0; j < p->nvars; j++)
3095 for (k=1; k < dw_DimA(p->lambda[j]); k++)
3096 {
3097 memcpy(f,pElementV(p->lambda[j][k]),DimV(p->lambda[j][k])*sizeof(PRECISION));
3098 f+=DimV(p->lambda[j][k]);
3099 }
3100
3101 // psi
3102 for (j=0; j < p->nvars; j++)
3103 {
3104 memcpy(f,pElementV(p->psi[j]),DimV(p->psi[j])*sizeof(PRECISION));
3105 f+=DimV(p->psi[j]);
3106 }
3107 }
3108 else
3109 {
3110 //bplus
3111 for (j=0; j < p->nvars; j++)
3112 if (p->bplus[j])
3113 for (k=0; k < dw_DimA(p->bplus[j]); k++)
3114 {
3115 memcpy(f,pElementV(p->bplus[j][k]),DimV(p->bplus[j][k])*sizeof(PRECISION));
3116 f+=DimV(p->bplus[j][k]);
3117 }
3118 }
3119
3120 // Zeta
3121 for (j=0; j < p->nvars; j++)
3122 {
3123 memcpy(f,p->Zeta[j]+1,(dw_DimA(p->Zeta[j])-1)*sizeof(PRECISION));
3124 f+=dw_DimA(p->Zeta[j])-1;
3125 }
3126 }
3127
3128 /*
3129 Assumes:
3130 p: pointer to valid T_VAR_Parameters structure
3131
3132 Returns:
3133 The starting position of the Zeta parameters in the array of free
3134 parameters.
3135 */
3136 int ZetaIndex(T_VAR_Parameters *p)
3137 {
3138 int j, k, index=0;
3139
3140 // b0
3141 for (j=0; j < p->nvars; j++)
3142 for (k=0; k < dw_DimA(p->b0[j]); k++)
3143 index+=DimV(p->b0[j][k]);
3144
3145 if (p->Specification & SPEC_SIMS_ZHA)
3146 {
3147 // lambda
3148 for (j=0; j < p->nvars; j++)
3149 for (k=1; k < dw_DimA(p->lambda[j]); k++)
3150 index+=DimV(p->lambda[j][k]);
3151
3152 // psi
3153 for (j=0; j < p->nvars; j++)
3154 index+=DimV(p->psi[j]);
3155 }
3156 else
3157 {
3158 // bplus
3159 for (j=0; j < p->nvars; j++)
3160 if (p->bplus[j])
3161 for (k=0; k < dw_DimA(p->bplus[j]); k++)
3162 index+=DimV(p->bplus[j][k]);
3163 }
3164
3165 return index;
3166 }
3167
3168 /*
3169 Assumes:
3170 p: pointer to valid T_VAR_Parameters structure
3171
3172 Returns:
3173 The the number of Zeta parameters in the array of free parameters.
3174 */
3175 int ZetaLength(T_VAR_Parameters *p)
3176 {
3177 int j, length=0;
3178 for (j=0; j < p->nvars; j++) length+=dw_DimA(p->Zeta[j])-1;
3179 return length;
3180 }
3181 /*******************************************************************************/
3182 /*******************************************************************************/
3183 /*******************************************************************************/
3184
3185
3186 /*******************************************************************************/
3187 /******************************** Normalization ********************************/
3188 /*******************************************************************************/
3189 #define LN_TWO 0.6931471805599453
3190 /*
3191 Sets up no normalization.
3192 */
3193 void Setup_No_Normalization_VAR(T_VAR_Parameters *p)
3194 {
3195 p->normalization_type=VAR_NORMALIZATION_NONE;
3196 p->inconclusive_normalizations=0;
3197 p->log_normalization_constant=0.0;
3198 p->valid_normalization=1;
3199 if (!p->Target) dw_FreeArray(p->Target);
3200 p->Target=(TVector**)NULL;
3201 }
3202
3203 /*
3204 Sets up the diagonal normalization.
3205 */
3206 void Setup_Diagonal_Normalization_VAR(T_VAR_Parameters *p)
3207 {
3208 int j, k;
3209 p->normalization_type=VAR_NORMALIZATION_RECURSIVE;
3210 p->inconclusive_normalizations=0;
3211 p->log_normalization_constant=p->nvars*LN_TWO;
3212 p->valid_normalization=-1;
3213 if (!p->Target) dw_FreeArray(p->Target);
3214 p->Target=(TVector**)dw_CreateArray_array(p->nvars);
3215 for (j=p->nvars-1; j >= 0; j--)
3216 {
3217 p->Target[j]=dw_CreateArray_vector(p->n_coef_states[j]);
3218 for (k=p->n_coef_states[j]-1; k >= 0; k--)
3219 {
3220 InitializeVector(p->Target[j][k]=CreateVector(p->nvars),0.0);
3221 ElementV(p->Target[j][k],j)=1.0;
3222 }
3223 }
3224 }
3225
3226 /*
3227 Sets up the default recursive normalization.
3228 */
3229 void Setup_Default_Recursive_Normalization_VAR(T_VAR_Parameters *p)
3230 {
3231 int i, j, k, m;
3232 p->normalization_type=VAR_NORMALIZATION_RECURSIVE;
3233 p->inconclusive_normalizations=0;
3234 p->log_normalization_constant=p->nvars*LN_TWO;
3235 p->valid_normalization=-1;
3236 if (!p->Target) dw_FreeArray(p->Target);
3237 p->Target=(TVector**)dw_CreateArray_array(p->nvars);
3238 for (j=p->nvars-1; j >= 0; j--)
3239 {
3240 for (m=j; m < p->nvars; m++)
3241 {
3242 for (i=p->nvars-1; i >= 0; i--)
3243 if (fabs(ElementM(p->U[j],j,i)) > SQRT_MACHINE_EPSILON) break;
3244 if (i >= 0) break;
3245 }
3246 if (m == p->nvars)
3247 for (m=0; m < j; m++)
3248 {
3249 for (i=p->nvars-1; i >= 0; i--)
3250 if (fabs(ElementM(p->U[j],j,i)) > SQRT_MACHINE_EPSILON) break;
3251 if (i >= 0) break;
3252 }
3253
3254 p->Target[j]=dw_CreateArray_vector(p->n_coef_states[j]);
3255 for (k=p->n_coef_states[j]-1; k >= 0; k--)
3256 {
3257 InitializeVector(p->Target[j][k]=CreateVector(p->nvars),0.0);
3258 ElementV(p->Target[j][k],m)=1.0;
3259 }
3260 }
3261 }
3262
3263 /*
3264 Sets up the recursive normalization.
3265 */
3266 void Setup_Recursive_Normalization_VAR(TVector **Target, T_VAR_Parameters *p)
3267 {
3268 p->normalization_type=VAR_NORMALIZATION_RECURSIVE;
3269 p->inconclusive_normalizations=0;
3270 p->log_normalization_constant=p->nvars*LN_TWO;
3271 p->valid_normalization=-1;
3272 if (!p->Target) dw_FreeArray(p->Target);
3273 p->Target=dw_CopyArray((void*)NULL,Target);
3274 }
3275
3276 /*
3277 Sets up the Waggoner-Zha normalization.
3278 */
3279 void Setup_WZ_Normalization_VAR(TVector **Target, T_VAR_Parameters *p)
3280 {
3281 p->normalization_type=VAR_NORMALIZATION_WZ;
3282 p->inconclusive_normalizations=0;
3283 p->log_normalization_constant=p->nvars*LN_TWO;
3284 p->valid_normalization=-1;
3285 if (!p->Target) dw_FreeArray(p->Target);
3286 p->Target=dw_CopyArray((void*)NULL,Target);
3287 CreateFlipped(p);
3288 }
3289 #undef LN_TWO
3290
3291 /*
3292 Returns one if the parameters are normalized and zero otherwise. Does not
3293 perform normalization.
3294 */
3295 int IsNormalized_VAR(T_VAR_Parameters *p)
3296 {
3297 int j, k;
3298 if (p->valid_normalization == -1)
3299 {
3300 switch (p->normalization_type)
3301 {
3302 case VAR_NORMALIZATION_WZ:
3303 // Waggoner-Zha normalization
3304 SetFlipped_VAR(p);
3305 for (j=p->nvars-1; j >= 0; j--)
3306 for (k=p->n_coef_states[j]-1; k >= 0; k--)
3307 if ((p->flipped[j][k] < 0) || ((p->flipped[j][k] == 0) && (DotProduct(p->Target[j][k],p->A0[j][k]) < 0)))
3308 {
3309 p->valid_normalization=0;
3310 return 0;
3311 }
3312 break;
3313 case VAR_NORMALIZATION_RECURSIVE:
3314 // Recursive normalization
3315 for (j=p->nvars-1; j >= 0; j--)
3316 for (k=p->n_coef_states[j]-1; k >= 0; k--)
3317 if (DotProduct(p->Target[j][k],p->A0[j][k]) < 0)
3318 {
3319 p->valid_normalization=0;
3320 return 0;
3321 }
3322 break;
3323 case VAR_NORMALIZATION_NONE:
3324 // No normalization
3325 break;
3326 }
3327 p->valid_normalization=1;
3328 }
3329 return p->valid_normalization;
3330 }
3331
3332 /*
3333 Assumes
3334 p : pointer to properly initialized T_VAR_Parameters structure.
3335
3336 Returns
3337 1 : successful normalization/at least one column changed
3338 0 : successful normalization/no column changed
3339 */
3340 int Normalize_VAR(TStateModel *model, PRECISION *buffer)
3341 {
3342 PRECISION dot;
3343 int j, k, changed=0, inconclusive=0;
3344 T_VAR_Parameters *p=(T_VAR_Parameters*)(model->theta);
3345 PRECISION *f=(PRECISION*)NULL;
3346 if (p->valid_normalization == 1) return 0;
3347 switch (p->normalization_type)
3348 {
3349 case VAR_NORMALIZATION_WZ:
3350 // Waggoner-Zha normalization. Inconclusive if abs(p->flipped[j][k]) != p->n_A0_states/p->n_coef_states[j].
3351 if (buffer)
3352 {
3353 f=(PRECISION*)dw_malloc(NumberFreeParametersVAR(model)*sizeof(PRECISION));
3354 VARToFreeParameters(model,f);
3355 }
3356 SetFlipped_VAR(p);
3357 for (j=p->nvars-1; j >= 0; j--)
3358 for (k=p->n_coef_states[j]-1; k >= 0; k--)
3359 {
3360 if ((p->flipped[j][k] < 0) || ((p->flipped[j][k] == 0) && (DotProduct(p->Target[j][k],p->A0[j][k]) < 0)))
3361 {
3362 MinusV(p->A0[j][k],p->A0[j][k]);
3363 MinusV(p->Aplus[j][k],p->Aplus[j][k]);
3364 changed=1;
3365 }
3366 if (abs(p->flipped[j][k])*p->n_coef_states[j] != p->n_A0_states) inconclusive=1;
3367 }
3368 break;
3369 case VAR_NORMALIZATION_RECURSIVE:
3370 // Recursive normalization
3371 if (buffer)
3372 {
3373 f=(PRECISION*)dw_malloc(NumberFreeParametersVAR(model)*sizeof(PRECISION));
3374 VARToFreeParameters(model,f);
3375 }
3376 for (j=p->nvars-1; j >= 0; j--)
3377 for (k=p->n_coef_states[j]-1; k >= 0; k--)
3378 if ((dot=DotProduct(p->Target[j][k],p->A0[j][k]) < 0))
3379 {
3380 MinusV(p->A0[j][k],p->A0[j][k]);
3381 MinusV(p->Aplus[j][k],p->Aplus[j][k]);
3382 changed=1;
3383 }
3384 else if (dot == 0.0) inconclusive=1;
3385 break;
3386 case VAR_NORMALIZATION_NONE:
3387 // No normalization
3388 p->valid_normalization=1;
3389 return 0;
3390 }
3391 if (changed)
3392 {
3393 Update_b0_bplus_from_A0_Aplus(p);
3394 if ((p->Specification & SPEC_SIMS_ZHA) == SPEC_SIMS_ZHA) Update_lambda_psi_from_bplus(p);
3395 if (buffer)
3396 {
3397 VARToFreeParameters(model,buffer);
3398 FreeParametersToVAR(model,f);
3399 }
3400 else
3401 ThetaChanged(model);
3402 }
3403 if (f) dw_free(f);
3404 if (inconclusive) p->inconclusive_normalizations++;
3405 p->valid_normalization=1;
3406 return changed;
3407 }
3408
3409 /*
3410 Creates flipped array
3411 */
3412 static void CreateFlipped(T_VAR_Parameters *p)
3413 {
3414 int j;
3415 if (!p->flipped)
3416 {
3417 p->flipped=(int**)dw_CreateArray_array(p->nvars);
3418 for (j=p->nvars-1; j >= 0; j--)
3419 p->flipped[j]=dw_CreateArray_int(p->n_coef_states[j]);
3420 }
3421 }
3422
3423 /*
3424 Sets flipped array - must only be used with Waggoner-Zha normalization. This
3425 condition is not checked.
3426 */
3427 static void SetFlipped_VAR(T_VAR_Parameters *p)
3428 {
3429 int j, k, m, n=p->nvars;
3430 TMatrix A0;
3431 PRECISION x, *y, *z;
3432
3433 // zero flipped
3434 for (j=n-1; j >= 0; j--)
3435 for (k=p->n_coef_states[j]-1; k >= 0; k--)
3436 p->flipped[j][k]=0;
3437
3438 // Waggoner-Zha normalization
3439 A0=CreateMatrix(n,n);
3440 for (k=p->n_A0_states-1; k >= 0; k--)
3441 {
3442 for (j=n-1; j >= 0; j--)
3443 memcpy(pElementM(A0)+j*n,pElementV(p->A0[j][p->A0_column_states[j][k]]),n*sizeof(PRECISION));
3444 if (!MajorForm(A0)) Transpose(A0,A0);
3445 Inverse_LU(A0,A0);
3446 if (MajorForm(A0)) Transpose(A0,A0);
3447 for (j=n-1; j >= 0; j--)
3448 {
3449 y=pElementV(p->Target[j][p->A0_column_states[j][k]]);
3450 z=pElementM(A0)+j*n;
3451 x=(*z)*(*y);
3452 for (m=p->nvars-1; m > 0; m--) x+=z[m]*y[m];
3453 if (x < 0.0)
3454 p->flipped[j][p->A0_column_states[j][k]]--;
3455 else if (x > 0.0)
3456 p->flipped[j][p->A0_column_states[j][k]]++;
3457 }
3458 }
3459
3460 // cleanup
3461 FreeMatrix(A0);
3462 }
3463
3464 /*
3465 p : model->sv->nstates permutation
3466
3467 */
3468 /* int NormalizeRegimes_VAR(int *p, TStateModel *model, PRECISION *buffer) */
3469 /* { */
3470 /* PRECISION *f=(PRECISION*)NULL, *z, *x; */
3471 /* TPermutation P; */
3472 /* int j, k, *q, m, n; */
3473 /* T_VAR_Parameters *var=(T_VAR_Parameters*)(model->theta); */
3474 /* if (!p) */
3475 /* dw_Error(NULL_ERR); */
3476 /* else */
3477 /* { */
3478 /* for (j=var->nstates-1; j >= 0; j--) */
3479 /* if (j != p[j]) break; */
3480 /* if (j >= 0) */
3481 /* { */
3482 /* if (buffer) */
3483 /* { */
3484 /* f=(PRECISION*)dw_malloc(NumberFreeParametersVAR(model)*sizeof(PRECISION)); */
3485 /* VARToFreeParameters(model,f); */
3486 /* } */
3487 /* z=dw_malloc(var->nstates*sizeof(PRECISION)); */
3488 /* q=dw_malloc(var->nstates*sizeof(int)); */
3489 /* m=var->nvars*sizeof(PRECISION); */
3490 /* n=var->npre*sizeof(PRECISION); */
3491 /* x=dw_malloc((n > m) ? n : m); */
3492
3493 /* for (j=var->nvars-1; j >= 0; j--) */
3494 /* { */
3495 /* // form permutation */
3496 /* for (k=var->nstates-1; k >= 0; k--) */
3497 /* q[var->coef_states[j][k]]=var->coef_states[j][p[k]]; */
3498 /* P=InitializePermutation((TPermutation)NULL,q,var->n_coef_states[j]); */
3499
3500 /* // permute A0 */
3501 /* for (k=UseP(P)-1; k >= 0; k--) */
3502 /* if (k != P[k]) */
3503 /* { */
3504 /* memcpy(x,pElementV(var->A0[j][k]),m); */
3505 /* memcpy(pElementV(var->A0[j][k]),pElementV(var->A0[j][P[k]]),m); */
3506 /* memcpy(pElementV(var->A0[j][P[k]]),x,m); */
3507 /* } */
3508
3509 /* // permute Aplus */
3510 /* for (k=UseP(P)-1; k >= 0; k--) */
3511 /* if (k != P[k]) */
3512 /* { */
3513 /* memcpy(x,pElementV(var->Aplus[j][k]),n); */
3514 /* memcpy(pElementV(var->Aplus[j][k]),pElementV(var->Aplus[j][P[k]]),n); */
3515 /* memcpy(pElementV(var->Aplus[j][P[k]]),x,n); */
3516 /* } */
3517
3518 /* // permute Zeta */
3519 /* for (k=var->nstates-1; k >= 0; k--) */
3520 /* z[var->var_states[j][k]]=var->Zeta[j][var->var_states[j][p[k]]]; */
3521 /* for (k=var->n_var_states[j]-1; k >= 0; k--) */
3522 /* var->Zeta[j][k]=z[k]; */
3523 /* } */
3524 /* dw_free(x); */
3525 /* dw_free(q); */
3526 /* dw_free(z); */
3527 /* Update_b0_bplus_from_A0_Aplus(var); */
3528 /* if ((var->Specification & SPEC_SIMS_ZHA) == SPEC_SIMS_ZHA) Update_lambda_psi_from_bplus(var); */
3529 /* if (f) */
3530 /* { */
3531 /* VARToFreeParameters(model,buffer); */
3532 /* FreeParametersToVAR(model,f); */
3533 /* dw_free(f); */
3534 /* } */
3535 /* else */
3536 /* ThetaChanged(model); */
3537 /* return 1; */
3538 /* } */
3539 /* } */
3540 /* return 0; */
3541 /* } */
3542 int NormalizeRegimes_VAR(int *p, TStateModel *model, PRECISION *buffer)
3543 {
3544 PRECISION *f=(PRECISION*)NULL, *z, scale;
3545 TVector *b;
3546 int j, k;
3547 T_VAR_Parameters *var=(T_VAR_Parameters*)(model->theta);
3548 if (!p)
3549 dw_Error(NULL_ERR);
3550 else
3551 {
3552 for (j=var->nstates-1; j >= 0; j--)
3553 if (j != p[j]) break;
3554 if (j >= 0)
3555 {
3556 if (buffer)
3557 {
3558 f=(PRECISION*)dw_malloc(NumberFreeParametersVAR(model)*sizeof(PRECISION));
3559 VARToFreeParameters(model,f);
3560 }
3561 b=dw_malloc(var->nstates*sizeof(TVector));
3562 z=dw_malloc(var->nstates*sizeof(PRECISION));
3563
3564 for (j=var->nvars-1; j >= 0; j--)
3565 {
3566 // permute b0
3567 for (k=var->nstates-1; k >= 0; k--)
3568 b[var->coef_states[j][k]]=var->b0[j][var->coef_states[j][p[k]]];
3569 for (k=var->n_coef_states[j]-1; k >= 0; k--)
3570 var->b0[j][k]=b[k];
3571
3572 // permute bplus
3573 for (k=var->nstates-1; k >= 0; k--)
3574 b[var->coef_states[j][k]]=var->bplus[j][var->coef_states[j][p[k]]];
3575 for (k=var->n_coef_states[j]-1; k >= 0; k--)
3576 var->bplus[j][k]=b[k];
3577
3578 // permute Zeta
3579 for (k=var->nstates-1; k >= 0; k--)
3580 z[var->var_states[j][k]]=var->Zeta[j][var->var_states[j][p[k]]];
3581 for (k=var->n_var_states[j]-1; k >= 0; k--)
3582 var->Zeta[j][k]=z[k];
3583 }
3584 dw_free(z);
3585 dw_free(b);
3586
3587 // Normalize first variance regime to one if necessary
3588 for (j=var->nvars-1; j >= 0; j--)
3589 if (var->Zeta[j][0] != 1)
3590 {
3591 scale=sqrt(var->Zeta[j][0]);
3592 for (k=var->n_coef_states[j]-1; k >= 0; k--)
3593 {
3594 ProductVS(var->b0[j][k],var->b0[j][k],scale);
3595 ProductVS(var->bplus[j][k],var->bplus[j][k],scale);
3596 }
3597 scale=1.0/var->Zeta[j][0];
3598 for (k=var->n_var_states[j]-1; k > 0; k--)
3599 var->Zeta[j][k]*=scale;
3600 var->Zeta[j][0]=1.0;
3601 }
3602
3603 Update_A0_from_b0(var);
3604 Update_Aplus_from_bplus_A0(var);
3605 if ((var->Specification & SPEC_SIMS_ZHA) == SPEC_SIMS_ZHA) Update_lambda_psi_from_bplus(var);
3606
3607 if (f)
3608 {
3609 VARToFreeParameters(model,buffer);
3610 FreeParametersToVAR(model,f);
3611 dw_free(f);
3612 }
3613 else
3614 ThetaChanged(model);
3615 return 1;
3616 }
3617 }
3618 return 0;
3619 }
3620 /*******************************************************************************/
3621 /*******************************************************************************/
3622 /*******************************************************************************/
3623
3624
3625 /*******************************************************************************/
3626 /********************************** Utilities **********************************/
3627 /*******************************************************************************/
3628 /*
3629 Assumes:
3630 X : A m x n matrix or null pointer.
3631 Y : A array of pointers to vectors of length n. For each i, Y[i] is an
3632 array of vectors of positive length. For each i and j, Y[i][j] is
3633 a vector of length m. Y must have be created via calls to the function
3634 CreateVectorMultidimensionArray() so that the macros DimA(Y) and
3635 DimA(Y[i]) are valid.
3636
3637 Results:
3638 Creates X if X is null. Sets X[i][j] to Y[j][k][i] if k is less than
3639 DimA(Y[j]) and to Y[j][0][i] otherwise.
3640
3641 Returns:
3642 Returns the matrix X.
3643
3644 Notes:
3645 The routine does not check to ensure that every Y[i] is non-null (and hence
3646 of positive length) nor does it check that all the vectors Y[i][j] are of
3647 the same length.
3648 */
3649 TMatrix ConstructMatrixFromColumns(TMatrix X, TVector **Y, int k)
3650 {
3651 int i, j, s;
3652 if (!Y)
3653 {
3654 dw_Error(NULL_ERR);
3655 return (TMatrix)NULL;
3656 }
3657 if (!X)
3658 {
3659 if (!(X=CreateMatrix(DimV(Y[0][0]),dw_DimA(Y))))
3660 return (TMatrix)NULL;
3661 }
3662 else
3663 if ((RowM(X) != DimV(Y[0][0])) || (ColM(X) != dw_DimA(Y)))
3664 {
3665 dw_Error(SIZE_ERR);
3666 return (TMatrix)NULL;
3667 }
3668 if (MajorForm(X))
3669 for (i=RowM(X)*sizeof(PRECISION), j=ColM(X)-1; j >= 0; j--)
3670 memcpy(&ElementM(X,0,j),pElementV(Y[j][(k < dw_DimA(Y[j])) ? k : 0]),i);
3671 else
3672 for (j=ColM(X)-1; j >= 0; j--)
3673 {
3674 s=(k < dw_DimA(Y[j])) ? k : 0;
3675 for (i=RowM(X)-1; i >= 0; i--) ElementM(X,i,j)=ElementV(Y[j][s],i);
3676 }
3677 return X;
3678 }
3679
3680 /*
3681 Assumes:
3682 A0 : p->nvars x p->nvars matrix or null pointer
3683 s : 0 <= k < p->nstates
3684 */
3685 TMatrix MakeA0(TMatrix A0, int s, T_VAR_Parameters *p)
3686 {
3687 int j;
3688 if (!A0)
3689 {
3690 if (!(A0=CreateMatrix(p->nvars,p->nvars)))
3691 return (TMatrix)NULL;
3692 }
3693 else
3694 if ((RowM(A0) != p->nvars) || (ColM(A0) != p->nvars))
3695 {
3696 dw_Error(SIZE_ERR);
3697 return (TMatrix)NULL;
3698 }
3699 for (j=p->nvars-1; j >= 0; j--)
3700 memcpy(&ElementM(A0,0,j),pElementV(p->A0[j][p->coef_states[j][s]]),p->nvars*sizeof(PRECISION));
3701 if (!MajorForm(A0)) Transpose(A0,A0);
3702 return A0;
3703 }
3704
3705 /*
3706 Assumes:
3707 A0 : Matrix array of length n_states or null pointer. A0[s] is either
3708 p->nvars x p->nvars matrix or null pointer
3709 */
3710 TMatrix* MakeA0_All(TMatrix *A0, T_VAR_Parameters *p)
3711 {
3712 int s;
3713 TMatrix X, *A0_in=A0;
3714 if (!A0)
3715 {
3716 if (!(A0=dw_CreateArray_matrix(p->nstates)))
3717 return (TMatrix*)NULL;
3718 }
3719 else
3720 if ((dw_DimA(A0) != p->nstates))
3721 {
3722 dw_Error(SIZE_ERR);
3723 return (TMatrix*)NULL;
3724 }
3725 for (s=p->nstates-1; s >= 0; s--)
3726 if (!(X=MakeA0(A0[s],s,p)))
3727 {
3728 if (A0_in != A0) dw_FreeArray(A0);
3729 return (TMatrix*)NULL;
3730 }
3731 else
3732 A0[s]=X;
3733 return A0;
3734 }
3735
3736 /*
3737 Assumes:
3738 Aplus : p->npre x p->nvars matrix or null pointer
3739 k : 0 <= k < p->nstates
3740
3741 Notes:
3742 Optimized for column major format
3743 */
3744 TMatrix MakeAplus(TMatrix Aplus, int k, T_VAR_Parameters *p)
3745 {
3746 int i, j;
3747 if (!Aplus)
3748 {
3749 if (!(Aplus=CreateMatrix(p->npre,p->nvars)))
3750 return (TMatrix)NULL;
3751 }
3752 else
3753 if ((RowM(Aplus) != p->npre) || (ColM(Aplus) != p->nvars))
3754 {
3755 dw_Error(SIZE_ERR);
3756 return (TMatrix)NULL;
3757 }
3758 if (MajorForm(Aplus))
3759 for (j=p->nvars-1; j >= 0; j--)
3760 memcpy(&ElementM(Aplus,0,j),pElementV(p->Aplus[j][p->coef_states[j][k]]),p->npre*sizeof(PRECISION));
3761 else
3762 for (j=p->nvars-1; j >= 0; j--)
3763 for (i=p->npre-1; i >= 0; i--)
3764 ElementM(Aplus,i,j)=ElementV(p->Aplus[j][p->coef_states[j][k]],i);
3765 return Aplus;
3766 }
3767
3768 /*
3769 Assumes:
3770 Aplus : Matrix array of length n_states or null pointer. Aplus[s] is either
3771 p->npre x p->nvars matrix or null pointer
3772 */
3773 TMatrix* MakeAplus_All(TMatrix *Aplus, T_VAR_Parameters *p)
3774 {
3775 int s;
3776 TMatrix X, *Aplus_in=Aplus;
3777 if (!Aplus)
3778 {
3779 if (!(Aplus=dw_CreateArray_matrix(p->nstates)))
3780 return (TMatrix*)NULL;
3781 }
3782 else
3783 if ((dw_DimA(Aplus) != p->nstates))
3784 {
3785 dw_Error(SIZE_ERR);
3786 return (TMatrix*)NULL;
3787 }
3788 for (s=p->nstates-1; s >= 0; s--)
3789 if (!(X=MakeAplus(Aplus[s],s,p)))
3790 {
3791 if (Aplus_in != Aplus) dw_FreeArray(Aplus);
3792 return (TMatrix*)NULL;
3793 }
3794 else
3795 Aplus[s]=X;
3796 return Aplus;
3797 }
3798
3799 TMatrix MakeZeta(TMatrix Zeta, int k, T_VAR_Parameters *p)
3800 {
3801 int j;
3802 if (!Zeta)
3803 {
3804 if (!(Zeta=CreateMatrix(p->nvars,p->nvars)))
3805 return (TMatrix)NULL;
3806 }
3807 else
3808 if ((RowM(Zeta) != p->nvars) || (ColM(Zeta) != p->nvars))
3809 {
3810 dw_Error(SIZE_ERR);
3811 return (TMatrix)NULL;
3812 }
3813 InitializeMatrix(Zeta,0.0);
3814 for (j=0; j < p->nvars; j++)
3815 ElementM(Zeta,j,j)=p->Zeta[j][p->var_states[j][k]];
3816 return Zeta;
3817 }
3818
3819 /*
3820 Assumes:
3821 Zeta : Matrix array of length n_states or null pointer. Zeta[s] is either
3822 p->vars x p->nvars matrix or null pointer
3823 */
3824 TMatrix* MakeZeta_All(TMatrix *Zeta, T_VAR_Parameters *p)
3825 {
3826 int s;
3827 TMatrix X, *Zeta_in=Zeta;
3828 if (!Zeta)
3829 {
3830 if (!(Zeta=dw_CreateArray_matrix(p->nstates)))
3831 return (TMatrix*)NULL;
3832 }
3833 else
3834 if ((dw_DimA(Zeta) != p->nstates))
3835 {
3836 dw_Error(SIZE_ERR);
3837 return (TMatrix*)NULL;
3838 }
3839 for (s=p->nstates-1; s >= 0; s--)
3840 if (!(X=MakeZeta(Zeta[s],s,p)))
3841 {
3842 if (Zeta_in != Zeta) dw_FreeArray(Zeta);
3843 return (TMatrix*)NULL;
3844 }
3845 else
3846 Zeta[s]=X;
3847 return Zeta;
3848 }
3849
3850 /*
3851 Assumes:
3852 B : p->nvars x p->nvars matrix or null pointer
3853 k : 0 <= k < p->nstates
3854
3855 Results:
3856 B=Aplus*Inverse(A0)
3857 */
3858 TMatrix MakeB(TMatrix B, int s, T_VAR_Parameters *p)
3859 {
3860 TMatrix A0;
3861 if ((B=MakeAplus(B,s,p)))
3862 if ((A0=MakeA0((TMatrix)NULL,s,p)))
3863 {
3864 ProductInverseMM(B,B,A0);
3865 FreeMatrix(A0);
3866 }
3867 return B;
3868 }
3869
3870 /*
3871 Assumes:
3872 B : Matrix array of length n_states or null pointer. B[s] is either
3873 p->nvars x p->nvars matrix or null pointer
3874 */
3875 TMatrix* MakeB_All(TMatrix *B, T_VAR_Parameters *p)
3876 {
3877 int s;
3878 TMatrix X, *B_in=B;
3879 if (!B)
3880 {
3881 if (!(B=dw_CreateArray_matrix(p->nstates)))
3882 return (TMatrix*)NULL;
3883 }
3884 else
3885 if ((dw_DimA(B) != p->nstates))
3886 {
3887 dw_Error(SIZE_ERR);
3888 return (TMatrix*)NULL;
3889 }
3890 for (s=p->nstates-1; s >= 0; s--)
3891 if (!(X=MakeB(B[s],s,p)))
3892 {
3893 if (B_in != B) dw_FreeArray(B);
3894 return (TMatrix*)NULL;
3895 }
3896 else
3897 B[s]=X;
3898 return B;
3899 }
3900
3901 /*
3902 Assumes
3903 X: n x n matrix or null pointer in column major format
3904 Y: m x n matrix in column major format
3905 S: m x m symmetric matrix in column major format
3906
3907 Returns
3908 X = Y'*S*Y. If X is null, it is created.
3909
3910 Notes:
3911 The matrix X must be distinct from either Y or S.
3912 */
3913 TMatrix MatrixInnerProductSymmetric(TMatrix X, TMatrix Y, TMatrix S)
3914 {
3915 PRECISION *x, *y, *z, *s, w;
3916 int m, n, i, j, sj, k;
3917 if (!Y || !S)
3918 {
3919 dw_Error(NULL_ERR);
3920 return (TMatrix)NULL;
3921 }
3922 if (!X)
3923 {
3924 if (!(X=CreateMatrix(ColM(Y),ColM(Y)))) return (TMatrix)NULL;
3925 }
3926 else
3927 if ((RowM(S) != RowM(Y)) || (ColM(S) != RowM(Y)) || (RowM(X) != ColM(Y)) || (ColM(X) != ColM(Y)))
3928 {
3929 dw_Error(SIZE_ERR);
3930 return (TMatrix)NULL;
3931 }
3932
3933 InitializeMatrix(X,0.0);
3934 m=RowM(Y); n=ColM(Y);
3935 for (i=n-1, x=pElementM(X)+i, y=pElementM(Y)+i*m; i >= 0; x--, y-=m, i--)
3936 {
3937 for (s=pElementM(S)+(sj=m-1)*m; sj >= 0; z--, s-=m, sj--)
3938 {
3939 for (w=0.0, k=m-1; k >= 0; k--)
3940 w+=y[k]*s[k];
3941 z=pElementM(Y)+(n-1)*m+sj;
3942 for (j=n*(n-1); j >= 0; z-=m, j-=n)
3943 x[j]+=w*(*z);
3944 }
3945 }
3946 return X;
3947 }
3948
3949 /*
3950 Assumes
3951 x : m-vector
3952 S : m x m symmetric matrix in column major format
3953
3954 Results
3955 returns x'*S*x
3956 */
3957 PRECISION InnerProductSymmetric(TVector x, TMatrix S)
3958 {
3959 PRECISION *s, result=0.0, tmp;
3960 int i, j;
3961 if ((DimV(x) != RowM(S)) || (DimV(x) != ColM(S)))
3962 {
3963 dw_Error(SIZE_ERR);
3964 return 0.0;
3965 }
3966 for (s=pElementM(S), j=0; j < DimV(x); j++)
3967 {
3968 for (tmp=0.0, i=0; i < j; s++, i++) tmp+=ElementV(x,i)*(*s);
3969 result+=(2.0*tmp + ElementV(x,j)*(*s))*ElementV(x,j);
3970 s+=(DimV(x) - j);
3971 }
3972 return result;
3973 }
3974
3975 /*
3976 Assumes
3977 x : m-vector
3978 y : n-vector
3979 S : m x n matrix in column major format
3980
3981 Results
3982 returns x'*S*y
3983 */
3984 PRECISION InnerProductNonSymmetric(TVector x, TVector y, TMatrix S)
3985 {
3986 PRECISION *s, result=0.0, tmp;
3987 int i, j;
3988 if ((DimV(x) != RowM(S)) || (DimV(y) != ColM(S)))
3989 {
3990 dw_Error(SIZE_ERR);
3991 return 0.0;
3992 }
3993 for (s=pElementM(S)+DimV(x)*DimV(y)-1, j=DimV(y)-1; j >= 0; j--)
3994 {
3995 for (tmp=0.0, i=DimV(x)-1; i >= 0; s--, i--) tmp+=ElementV(x,i)*(*s);
3996 result+=tmp*ElementV(y,j);
3997 }
3998 return result;
3999 }
4000
4001
4002 /*
4003 Assumes
4004 x : n-vector or null pointer
4005 b : n-vector
4006 S : n x n symmetric and positive definite matrix
4007
4008 Results
4009 The vector x is drawn from a multivariate normal distribution with
4010
4011 variance = Inverse(S)
4012 and
4013 mean = Inverse(S)*b
4014
4015 If x is null, it is created. The matrix S is modified.
4016
4017 Returns
4018 The vector x upon success and null upon failure.
4019
4020 Notes
4021 Uses the Cholesky decomposition of S and the function
4022 DrawNormal_UpperTriangular().
4023 */
4024 TVector DrawNormal_InverseVariance(TVector x, TVector b, TMatrix S)
4025 {
4026 int terminal_error=dw_SetTerminalErrors(0);
4027 TMatrix U=CholeskyUT((TMatrix)NULL,S);
4028 dw_SetTerminalErrors(terminal_error);
4029 if (U)
4030 {
4031 x=DrawNormal_InverseUpperTriangular(x,b,U);
4032 FreeMatrix(U);
4033 return x;
4034 }
4035 else
4036 return (TVector)NULL;
4037 //return DrawNormal_InverseVariance_SVD(x,b,S);
4038 }
4039
4040 /*
4041 Assumes
4042 x : n-vector or null pointer
4043 b : n-vector
4044 S : n x n symmetric and positive definite matrix
4045
4046 Results
4047 The vector x is drawn from a multivariate normal distribution with
4048
4049 variance = Inverse(S)
4050 and
4051 mean = Inverse(S)*b
4052
4053 If x is null, it is created. The matrix S is modified.
4054
4055 Returns
4056 The vector x upon success and null upon failure.
4057
4058 Notes
4059 Uses the Singular value decomposition of S to compute the square root of the
4060 inverse of S. If S = A'*A, and c is drawn from a standard normal
4061 distribution, then
4062
4063 Inverse(A)*(c + Inverse(A')*b)
4064
4065 is drawn from the required distribution.
4066 */
4067 TVector DrawNormal_InverseVariance_SVD(TVector x, TVector b, TMatrix S)
4068 {
4069 PRECISION tol, scale;
4070 TMatrix U, V;
4071 TVector d, rtrn;
4072 int i, j, n=DimV(b);
4073
4074 _VAR_IMPROPER_DISTRIBUTION_COUNTER++;
4075
4076 SVD(U=CreateMatrix(n,n),d=CreateVector(n),V=CreateMatrix(n,n),S);
4077 for (tol=ElementV(d,0), i=n-1; i > 0; i--)
4078 if (tol < ElementV(d,i)) tol=ElementV(d,i);
4079 //tol*=n*MACHINE_EPSILON;
4080 tol*=SQRT_MACHINE_EPSILON;
4081 for (j=n-1; j >= 0; j--)
4082 {
4083 scale=(ElementV(d,j) < tol) ? 1.0/sqrt(tol) : 1.0/sqrt(ElementV(d,j));
4084 for (i=n-1; i >= 0; i--)
4085 ElementM(V,i,j)*=scale;
4086 }
4087 rtrn=ProductTransposeVM(x,b,V);
4088 for (i=n-1; i >= 0; i--) ElementV(rtrn,i)+=dw_gaussian_rnd();
4089 ProductMV(rtrn,V,rtrn);
4090 FreeMatrix(U);
4091 FreeMatrix(V);
4092 FreeVector(d);
4093 return rtrn;
4094 }
4095
4096 /*
4097 Assumes
4098 x : n-vector or null pointer
4099 b : n-vector
4100 U : n x n upper triangular matrix with non-zero diagonal
4101
4102 Results
4103 The vector x is drawn from a multivariate normal distribution with
4104
4105 variance = Inverse(U'*U)
4106 and
4107 mean = Inverse(U'*U)*b
4108
4109 If x is null, it is created.
4110
4111 Returns
4112 The vector x upon success and null upon failure.
4113
4114 Notes
4115 If c is drawn from a standard normal distribution, then
4116
4117 Inverse(U)*(c + Inverse(U')*b)
4118
4119 is drawn from the required distribution. If S=U'U, then x is drawn from the
4120 multivariate normal distribution with mean Inverse(S)*b and variance
4121 Inverse(S). The matrix U can be obtained from S by calling CholeskyUT(U,S).
4122 */
4123 TVector DrawNormal_InverseUpperTriangular(TVector x, TVector b, TMatrix U)
4124 {
4125 int i;
4126 TVector rtrn=ProductInverseVU(x,b,U);
4127 if (rtrn)
4128 {
4129 for (i=DimV(rtrn)-1; i >= 0; i--) ElementV(rtrn,i)+=dw_gaussian_rnd();
4130 if (!InverseProductUV(rtrn,U,rtrn))
4131 {
4132 if (!x) FreeVector(rtrn);
4133 return (TVector)NULL;
4134 }
4135 }
4136 return rtrn;
4137 }
4138
4139
4140 /*
4141 Attempts recovery from a singular inverse variance matrix.
4142 */
4143 TVector SingularInverseVariance_RecoveryAttempt(TVector x, TVector b, TMatrix S, TMatrix InversePrior, TStateModel *model, int code)
4144 {
4145 FILE *f_out;
4146 char *header;
4147 char filename[256];
4148
4149 // print warning
4150 printf("Singular error\n");
4151
4152 // Construct file name and open file
4153 if (!V_FILE)
4154 {
4155 sprintf(filename,"singular_error_%03d_test.dat",_VAR_IMPROPER_DISTRIBUTION_COUNTER);
4156 f_out=dw_CreateTextFile(filename);
4157 }
4158 else
4159 f_out=V_FILE;
4160
4161 fprintf(f_out,"//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\n");
4162
4163 // Print error message, inverse variance matrix, and inverse prior
4164 switch (code)
4165 {
4166 case BPLUS_ERR:
4167 fprintf(f_out,"Error in DrawAplus(): Inverse of variance is singular\n");
4168 break;
4169 case PSI_ERR:
4170 fprintf(f_out,"Error in Draw_psi(): Inverse of variance is singular\n");
4171 break;
4172 case LAMBDA_ERR:
4173 fprintf(f_out,"Error in Draw_Lambda(): Inverse of variance is singular\n");
4174 break;
4175 default:
4176 fprintf(f_out,"Unknown routine code: Inverse of variance is singular\n");
4177 break;
4178 }
4179 fprintf(f_out,"Inverse variance =\n");
4180 dw_PrintMatrix(f_out,S,"%lg ");
4181 fprintf(f_out,"Inverse prior =\n");
4182 dw_PrintMatrix(f_out,InversePrior,"%lg ");
4183 fprintf(f_out,"\n");
4184
4185 // Print generator state
4186 fprintf(f_out,"\\== Generator State ==\\\n");
4187 dw_print_generator_state(f_out);
4188 fprintf(f_out,"\n");
4189
4190 // Attempt recovery
4191 x=DrawNormal_InverseVariance_SVD(x,b,S);
4192
4193 // Print parameters
4194 header="Error draw: ";
4195 WriteStates(f_out,(char*)NULL,header,model);
4196 WriteBaseTransitionMatrices(f_out,(char*)NULL,header,model);
4197 Write_VAR_Parameters(f_out,(char*)NULL,header,model);
4198
4199 fprintf(f_out,"//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//\n");
4200
4201 // Close file
4202 if (f_out != V_FILE) fclose(f_out);
4203
4204 _SINGULAR_ERROR=1;
4205
4206 return x;
4207 }
4208
4209 /*******************************************************************************/
4210 /*******************************************************************************/
4211 /*******************************************************************************/