Debian Codegraph @

contrib/ms-sbvar/switch_dw/switching/dw_switch.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 "dw_switch.h"
19 #include "dw_metropolis_theta.h"
20 #include "dw_array.h"
21 #include "dw_matrix_array.h"
22 #include "dw_error.h"
23 #include "dw_rand.h"
24 #include "dw_math.h"
25 #include "dw_std.h"
26
27 #include <math.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <limits.h>
31
32
33 /*******************************************************************************/
34 /********************************** QRoutines **********************************/
35 /*******************************************************************************/
36 QRoutines* CreateQRoutines_empty(void)
37 {
38 QRoutines* pRoutines=(QRoutines*)dw_malloc(sizeof(QRoutines));
39
40 if (pRoutines)
41 {
42 pRoutines->ComputeTransitionMatrix=NULL;
43 pRoutines->pLogPrior=NULL;
44 pRoutines->Probability_s0=NULL;
45
46 pRoutines->DrawProposalTransitionMatrixParameters=NULL;
47 pRoutines->DrawTransitionMatrixParameters=NULL;
48 pRoutines->pDrawTransitionMatrixParametersFromPrior=NULL;
49
50 pRoutines->FreeInfo=NULL;
51 pRoutines->DuplicateInfo=NULL;
52
53 pRoutines->WriteSpecification=NULL;
54
55 pRoutines->Update_q_from_BaseTransitionMatrix=NULL;
56 pRoutines->DefaultTransitionMatrixParameters=NULL;
57 }
58
59 return pRoutines;
60 }
61
62 QRoutines* DuplicateQRoutines(QRoutines *routines)
63 {
64 QRoutines* pRoutines=(QRoutines*)NULL;
65 if (routines && (pRoutines=(QRoutines*)dw_malloc(sizeof(QRoutines))))
66 memcpy(pRoutines,routines,sizeof(QRoutines));
67 return pRoutines;
68 }
69 /*******************************************************************************/
70 /*******************************************************************************/
71 /*******************************************************************************/
72
73
74 /*******************************************************************************/
75 /******************************** ThetaRoutines ********************************/
76 /*******************************************************************************/
77 ThetaRoutines* CreateThetaRoutines_empty(void)
78 {
79 ThetaRoutines* pRoutines=(ThetaRoutines*)dw_malloc(sizeof(ThetaRoutines));
80
81 if (pRoutines)
82 {
83 pRoutines->pLogConditionalLikelihood=NULL;
84 pRoutines->pLogPrior=NULL;
85 pRoutines->pExpectationSingleStep=NULL;
86 pRoutines->pExpectedError=NULL;
87 pRoutines->pDestructor=NULL;
88 pRoutines->pDrawParameters=NULL;
89 pRoutines->pDrawParametersFromPrior=NULL;
90 pRoutines->pNumberFreeParametersTheta=NULL;
91 pRoutines->pConvertFreeParametersToTheta=NULL;
92 pRoutines->pConvertThetaToFreeParameters=NULL;
93 pRoutines->pStatesChanged=NULL;
94 pRoutines->pThetaChanged=NULL;
95 pRoutines->pTransitionMatrixParametersChanged=NULL;
96 pRoutines->pValidTheta=NULL;
97 pRoutines->pInitializeForwardRecursion=NULL;
98 //pRoutines->pPermuteTheta=NULL;
99 pRoutines->pModelType=NULL;
100 pRoutines->pIsDegenerate=NULL;
101 //pGetNormalizingPermutation=NULL;
102 pRoutines->pNormalizeRegimes=NULL;
103 }
104
105 return pRoutines;
106 }
107 /*******************************************************************************/
108 /*******************************************************************************/
109 /*******************************************************************************/
110
111
112 /*******************************************************************************/
113 /******************************** Lag Routines *********************************/
114 /*******************************************************************************/
115 /*
116 base_prob : T x nbaseststates or null pointer
117 prob : T x nstates
118 sv : valid pointer to TMarkovStateVariable structure
119 */
120 TVector* sv_BaseProbabilities(TVector *base_prob, TVector *prob, TMarkovStateVariable *sv)
121 {
122 int k, t, T=dw_DimA(prob);
123 if (!base_prob)
124 {
125 base_prob=dw_CreateArray_vector(T);
126 for (t=T-1; t >= 0; t--)
127 InitializeVector(base_prob[t]=CreateVector(sv->nbasestates),0);
128 }
129 else
130 for (t=T-1; t >= 0; t--)
131 InitializeVector(base_prob[t],0);
132 for (t=T-1; t >= 0; t--)
133 for (k=sv->nstates-1; k >= 0; k--)
134 ElementV(base_prob[t],sv->lag_index[k][0])+=ElementV(prob[t],k);
135 return(base_prob);
136 }
137
138 /*
139 prob : T x nstates
140 sv : valid pointer to TMarkovStateVariable structure
141 */
142 TVector* sv_FullBaseProbabilities(TVector *prob, TMarkovStateVariable *sv)
143 {
144 TVector *full_base_prob, *base_prob=sv_BaseProbabilities((TVector*)NULL,prob,sv);
145 while (sv->n_state_variables == 1)
146 {
147 sv=sv->state_variable[0];
148 full_base_prob=sv_BaseProbabilities((TVector*)NULL,base_prob,sv);
149 dw_FreeArray(base_prob);
150 base_prob=full_base_prob;
151 }
152 return base_prob;
153 }
154
155 /*
156 Assumes:
157 Q : m x m matrix where m = n^(nlags_encoded + 1)
158 bQ : n x n matrix
159 nlags_encoded : positive integer
160
161 Returns:
162 One upon success and zero otherwise.
163
164 Results:
165 Computes the grand transition matrix Q from the base transition matrix bQ
166 given the number of lags encoded.
167 */
168 void ConvertBaseTransitionMatrix(TMatrix Q, TMatrix bQ, int nlags_encoded)
169 {
170 int n=RowM(bQ), a, b, c, d, e, i, j, k, m;
171 PRECISION p;
172
173 for (b=1, i=nlags_encoded-1; i > 0; i--) b*=n;
174 a=n*b;
175 InitializeMatrix(Q,0.0);
176 for (j=0; j < n; j++)
177 for (i=0; i < n; i++)
178 for (p=ElementM(bQ,i,j), k=0; k < b; k++)
179 for (c=b*j+k, d=i*a+c, e=n*c, m=0; m < n; m++)
180 ElementM(Q,d,e+m)=p;
181 }
182
183 /*
184 Assumes:
185 nbasestates : positive
186 nlags : non-negative
187 nstates : nbasestates^(nlags+1)
188
189 Returns:
190 Pointer to lag index upon sucess and null upon failurer. Returned pointer
191 must be freed by calling routine.
192
193 Results:
194 Allocates and fills lag index. Note that for 0 <= k < nstates and
195 0 <= j <= nlags, lag_index[k][j] is equal to s(t-j) given that the time t
196 grand state is k. The ordering of the lags is
197
198 0 ... 0 0
199 0 ... 0 1
200 . . .
201 . . .
202 . . .
203 0 ... 0 h-1
204 0 ... 1 0
205 0 ... 1 1
206 . . .
207 . . .
208 . . .
209 0 ... 1 h-1
210 . . .
211 . . .
212 . . .
213 h-1 ... h-1 0
214 h-1 ... h-1 1
215 . . .
216 . . .
217 . . .
218 h-1 ... h-1 h-1
219
220 */
221 int** CreateLagIndex(int nbasestates, int nlags, int nstates)
222 {
223 int **lag_index;
224 int j, k;
225
226 lag_index=dw_CreateRectangularArray_int(nstates,nlags+1);
227 for (j=nlags; j >= 0; j--) lag_index[0][j]=0;
228 for (k=1; k < nstates; k++)
229 {
230 for (j=nlags; j >= 0; j--)
231 if (lag_index[k-1][j] < nbasestates-1)
232 {
233 lag_index[k][j]=lag_index[k-1][j]+1;
234 break;
235 }
236 else
237 lag_index[k][j]=0;
238 for (--j; j >= 0; j--) lag_index[k][j]=lag_index[k-1][j];
239 }
240
241 return lag_index;
242 }
243 /*******************************************************************************/
244 /*******************************************************************************/
245 /*******************************************************************************/
246
247
248 /*******************************************************************************/
249 /**************************** TMarkovStateVariable *****************************/
250 /*******************************************************************************/
251
252 /************* TMarkovStateVariable Constructors and Destructors **************/
253 /*
254 Assumes:
255 sv: valid pointer to TMarkovStateVariable structure or null pointer
256
257 Results:
258 Frees all memory allocated to sv.
259 */
260 void FreeMarkovStateVariable(TMarkovStateVariable *sv)
261 {
262 int i;
263 if (sv)
264 {
265 if (sv->nlags_encoded > 0) FreeMatrix(sv->Q);
266
267 if (sv->n_state_variables != 1) FreeMatrix(sv->baseQ);
268
269 for (i=sv->n_state_variables-1; i >= 0; i--) sv->QA[i]=(TMatrix)NULL;
270 dw_FreeArray(sv->QA);
271
272 dw_FreeArray(sv->index);
273
274 dw_FreeArray(sv->lag_index);
275
276 if (sv->routines)
277 {
278 if (sv->info && sv->routines->FreeInfo) sv->routines->FreeInfo(sv->info);
279 dw_free(sv->routines);
280 }
281
282 dw_FreeArray(sv->state_variable);
283
284 dw_free(sv);
285 }
286 }
287
288 /*
289 Assumes:
290 nbasestates and nobs must be positive. nfree and nlags must be non-
291 negative. routines must be a pointer to a valid QRoutines structure and
292 info must be null or a valid pointer to a structure compatible with
293 routines.
294
295 Returns:
296 Returns a pointer to a valid TMarkovStateVariable structure. Upon failure,
297 the program terminates.
298
299 Notes:
300 routines and info are owned by the returned TMarkovStateVariable structure,
301 which will be responsible for their destruction. If info is not null and
302 the field routines->FreeInfo is not set, a memory leak will occur.
303 */
304 TMarkovStateVariable* CreateMarkovStateVariable_Single(int nbasestates, int nfree, int nlags, QRoutines *routines, void *info)
305 {
306 TMarkovStateVariable *sv;
307 int i, terminal_errors;
308
309 //=== Set to terminate on memory error ===
310 terminal_errors=dw_SetTerminalErrors(MEM_ERR | ARG_ERR);
311
312 if ((nbasestates <= 0) || (nfree < 0) || (nlags < 0) || (!routines)) dw_Error(ARG_ERR);
313
314 if (!(sv=(TMarkovStateVariable*)dw_malloc(sizeof(TMarkovStateVariable)))) dw_Error(MEM_ERR);
315
316 //=== Set flags ===
317 sv->t0=0;
318 sv->t1=-1;
319
320 //=== Sizes and lags===
321 sv->nlags_encoded=nlags;
322 sv->nbasestates=nbasestates;
323 for (sv->nstates=nbasestates, i=nlags; i > 0; i--) sv->nstates*=nbasestates;
324 sv->nfree=nfree;
325 sv->lag_index=CreateLagIndex(sv->nbasestates,sv->nlags_encoded,sv->nstates);
326
327 //=== Routines and info ===
328 sv->routines=routines;
329 sv->info=info;
330
331 //=== Multiple state variables ===
332 sv->parent=(TMarkovStateVariable*)NULL;
333 sv->n_state_variables=0;
334 sv->state_variable=(TMarkovStateVariable**)NULL;
335
336 //=== Initialize Index ===
337 sv->index=(int**)NULL;
338
339 //=== Transition matrix ===
340 sv->baseQ=CreateMatrix(sv->nbasestates,sv->nbasestates);
341 sv->Q=(sv->nlags_encoded > 0) ? CreateMatrix(sv->nstates,sv->nstates) : sv->baseQ;
342
343 //=== Initialize QA ===
344 sv->QA=(TMatrix*)NULL;
345
346 //=== Free parameters ===
347 sv->q=(PRECISION*)NULL;
348
349 //=== Reset terminal errors ===
350 dw_SetTerminalErrors(terminal_errors);
351
352 return sv;
353 }
354
355 /*
356 state_variable is an array of valid pointers to TMarkovStateVariable
357 structures. It must have been created via a call of the form
358
359 dw_CreateArray_pointer(n_state_variables,(void (*)(void*))FreeMarkovStateVariable);
360
361 This array will be owned by the created TMarkovStateVariable structure and
362 will be destroyed when this structure is destroyed.
363 */
364 TMarkovStateVariable* CreateMarkovStateVariable_Multiple(int nlags, TMarkovStateVariable **state_variable)
365 {
366 int i, k, terminal_errors;
367 TMarkovStateVariable *sv;
368
369 //=== Set to terminate only on memory error ===
370 terminal_errors=dw_SetTerminalErrors(MEM_ERR | ARG_ERR);
371
372 if ((nlags < 0) || !state_variable) dw_Error(ARG_ERR);
373
374 for (i=0; i < dw_DimA(state_variable)-1; i++)
375 if (!state_variable[i]) dw_Error(ARG_ERR);
376
377 if (!(sv=(TMarkovStateVariable*)dw_malloc(sizeof(TMarkovStateVariable)))) dw_Error(MEM_ERR);
378
379 //=== Set flags ===
380 sv->t0=0;
381 sv->t1=-1;
382
383 //=== Sizes and lags===
384 sv->nlags_encoded=nlags;
385 for (sv->nbasestates=state_variable[0]->nstates, i=dw_DimA(state_variable)-1; i > 0; i--) sv->nbasestates*=state_variable[i]->nstates;
386 for (sv->nstates=sv->nbasestates, i=nlags; i > 0; i--) sv->nstates*=sv->nbasestates;
387 for (sv->nfree=state_variable[0]->nfree, i=dw_DimA(state_variable)-1; i > 0; i--) sv->nfree+=state_variable[i]->nfree;
388 sv->lag_index=CreateLagIndex(sv->nbasestates,sv->nlags_encoded,sv->nstates);
389
390 //=== Routines and info ===
391 sv->routines=(QRoutines*)NULL;
392 sv->info=(void*)NULL;
393
394 //=== Multiple state variables ===
395 sv->parent=(TMarkovStateVariable*)NULL;
396 sv->n_state_variables=dw_DimA(state_variable);
397 sv->state_variable=state_variable;
398 for (i=dw_DimA(state_variable)-1; i >= 0; i--) state_variable[i]->parent=sv;
399
400 //=== Initialize Index ===
401 sv->index=dw_CreateRectangularArray_int(sv->nbasestates,sv->n_state_variables);
402 for (i=sv->nbasestates-1, k=sv->n_state_variables-1; k >= 0; k--)
403 sv->index[i][k]=state_variable[k]->nstates-1;
404 for (i--; i >= 0; i--)
405 {
406 memcpy(sv->index[i],sv->index[i+1],sv->n_state_variables*sizeof(int));
407 for (k=sv->n_state_variables-1; k >= 0; k--)
408 if (--(sv->index[i][k]) >= 0)
409 break;
410 else
411 sv->index[i][k]=state_variable[k]->nstates-1;
412 }
413
414 //=== Transition matrix ===
415 sv->baseQ=(sv->n_state_variables != 1) ? CreateMatrix(sv->nbasestates,sv->nbasestates) : sv->state_variable[0]->Q;
416 sv->Q=(sv->nlags_encoded > 0) ? CreateMatrix(sv->nstates,sv->nstates) : sv->baseQ;
417
418 //=== Initialize QA ===
419 sv->QA=dw_CreateArray_matrix(sv->n_state_variables);
420 for (k=sv->n_state_variables-1; k >= 0; k--)
421 sv->QA[k]=state_variable[k]->Q;
422
423 //=== Free parameters ===
424 sv->q=(PRECISION*)NULL;
425
426 //=== Reset terminal errors ===
427 dw_SetTerminalErrors(terminal_errors);
428
429 return sv;
430 }
431
432 /*
433 Creates a TMarkovStateVariable with the same base structure as sv, but with a
434 possibly different number of lags encoded.
435 */
436 TMarkovStateVariable* CreateMarkovStateVariable_base(int nlags_encoded, TMarkovStateVariable *sv)
437 {
438 TMarkovStateVariable **sv_array;
439 void *dup_info;
440 QRoutines *dup_routines;
441 int k;
442 if (sv->n_state_variables > 0)
443 {
444 sv_array=(TMarkovStateVariable**)dw_CreateArray_pointer(sv->n_state_variables,(void (*)(void*))FreeMarkovStateVariable);
445 for (k=sv->n_state_variables-1; k >= 0; k--)
446 if (!(sv_array[k]=CreateMarkovStateVariable_base(sv->state_variable[k]->nlags_encoded,sv->state_variable[k])))
447 {
448 dw_FreeArray(sv_array);
449 return (TMarkovStateVariable*)NULL;
450 }
451 return CreateMarkovStateVariable_Multiple(nlags_encoded,sv_array);
452 }
453 else
454 if (sv->routines->DuplicateInfo && (dup_info=sv->routines->DuplicateInfo(sv->info)))
455 {
456 if ((dup_routines=DuplicateQRoutines(sv->routines)))
457 return CreateMarkovStateVariable_Single(sv->nbasestates,sv->nfree,nlags_encoded,dup_routines,dup_info);
458 else
459 if (sv->routines->FreeInfo) sv->routines->FreeInfo(dup_info);
460 }
461
462 return (TMarkovStateVariable*)NULL;
463 }
464
465 /*
466 Creates a mulitple TMarkovStateVariable structure whose base structure is sv,
467 but with mulitple lags encoded.
468 */
469 TMarkovStateVariable* CreateMarkovStateVariable_lags(int nlags_encoded, TMarkovStateVariable *sv)
470 {
471 TMarkovStateVariable **sv_array;
472 if ((sv_array=(TMarkovStateVariable**)dw_CreateArray_pointer(1,(void (*)(void*))FreeMarkovStateVariable)))
473 if ((sv_array[0]=DuplicateMarkovStateVariable(sv)))
474 return CreateMarkovStateVariable_Multiple(nlags_encoded,sv_array);
475 return (TMarkovStateVariable*)NULL;
476 }
477
478 /******************* Base TMarkovStateVariable Routines ********************/
479 /*
480 Assumes:
481 q - a pointer to a real array of length sv->nfree
482 sv - a pointer to a properly initialized TMarkovStateVariable structure
483
484 Results:
485 Recursively initializies the free parameters.
486 */
487 void sv_SetupFreeParameters(PRECISION *q, TMarkovStateVariable *sv)
488 {
489 int k;
490 sv->q=q;
491 for (k=0; k < sv->n_state_variables; q+=sv->state_variable[k]->nfree, k++)
492 sv_SetupFreeParameters(q,sv->state_variable[k]);
493 }
494
495 /*
496 Set sv->t1 to minus one for all state variables in sv, which has the effect of
497 making the transition matrices invalid for all t.
498 */
499 void sv_InvalidateTransitionMatrix(TMarkovStateVariable *sv)
500 {
501 int k;
502 for (k=sv->n_state_variables-1; k >=0; k--)
503 sv_InvalidateTransitionMatrix(sv->state_variable[k]);
504 sv->t1=-1;
505 }
506
507 /*
508 Assumes:
509 t : 0 <= t <= model->nobs
510 sv : pointer to valid TMarkovStateVariable structure
511 model : pointer to valid TStateModel structure
512
513 Returns:
514 One upon success and zero on failure.
515
516 Results:
517 Upon success, all time t transition matrices are computed. Sets sv->t0 and
518 sv->t1.
519
520 Note:
521 The element of the time t transition matrix in row i and col j is the
522 probability that s[t]=i given that s[t-1]=j, Y[t-1], Z[t-1], theta and q.
523 */
524 int sv_ComputeTransitionMatrix(int t, TMarkovStateVariable *sv, TStateModel *model)
525 {
526 int k;
527
528 if ((sv->t0 <= t) && (t <= sv->t1)) return 1;
529
530 if (sv->n_state_variables > 0)
531 {
532 sv->t0=0;
533 sv->t1=INT_MAX;
534 for (k=sv->n_state_variables-1; k >= 0; k--)
535 if (!sv_ComputeTransitionMatrix(t,sv->state_variable[k],model))
536 {
537 sv->t1=-1;
538 return 0;
539 }
540 else
541 {
542 if (sv->t0 < sv->state_variable[k]->t0) sv->t0=sv->state_variable[k]->t0;
543 if (sv->t1 > sv->state_variable[k]->t1) sv->t1=sv->state_variable[k]->t1;
544 }
545 if (sv->n_state_variables > 1) MatrixTensor(sv->baseQ,sv->QA);
546 if (sv->nlags_encoded > 0) ConvertBaseTransitionMatrix(sv->Q,sv->baseQ,sv->nlags_encoded);
547 return 1;
548 }
549 else
550 if (sv->routines->ComputeTransitionMatrix(t,sv,model)) return 1;
551
552 sv->t1=-1;
553 return 0;
554 }
555
556 /*
557 Assumes:
558 sv : pointer to valid TMarkovStateVariable structure
559
560 Returns:
561 The natural logarithm of the properly scaled prior evaluated at sv->q.
562
563 Notes:
564 Assumes the priors on the Markov state variables are independent.
565 */
566 PRECISION sv_LogPrior(TMarkovStateVariable *sv)
567 {
568 int k;
569 PRECISION log_prior;
570
571 if (sv->n_state_variables > 0)
572 {
573 for (log_prior=0.0, k=sv->n_state_variables-1; k >= 0; k--)
574 log_prior+=sv_LogPrior(sv->state_variable[k]);
575 return log_prior;
576 }
577 else
578 return sv->routines->pLogPrior(sv);
579 }
580
581 /*
582 Assumes:
583 p : vector of length sv->nstates
584 sv : pointer to valid TMarkovStateVariable structure.
585
586 Returns:
587 One upon success and zero upon failure.
588
589 Results:
590 The value of p[i] is the probability that s0 is equal to i.
591
592 Notes:
593 If sv->nlags_encoded > 0, then it must be the case that t0 <= 0 <= t1.
594 */
595 int sv_Probability_s0(TVector p, TMarkovStateVariable *sv)
596 {
597 int i, k;
598 TVector q, r, *u;
599 if (sv->n_state_variables > 0)
600 {
601 if (sv->nlags_encoded == 0)
602 r=p;
603 else
604 if ((sv->t1 < 0) || (sv->t0 > 0))
605 return 0;
606 else
607 r=CreateVector(sv->nbasestates);
608 InitializeVector(r,1.0);
609 for (k=sv->n_state_variables-1; k >= 0; k--)
610 if (!sv_Probability_s0(q=CreateVector(sv->state_variable[k]->nstates),sv->state_variable[k]))
611 {
612 FreeVector(q);
613 return 0;
614 }
615 else
616 {
617 for (i=sv->nbasestates-1; i >= 0; i--) ElementV(r,i)*=ElementV(q,sv->index[i][k]);
618 FreeVector(q);
619 }
620
621 if (sv->nlags_encoded > 0)
622 {
623 u=dw_CreateArray_vector(sv->nlags_encoded+1);
624 u[i=sv->nlags_encoded]=EquateVector((TVector)NULL,r);
625 for (i-- ; i >= 0; i--) u[i]=ProductMV((TVector)NULL,sv->baseQ,u[i+1]);
626 InitializeVector(p,1.0);
627 for (k=sv->nlags_encoded; k >= 0; k--)
628 for (i=sv->nstates-1; i >= 0; i--)
629 ElementV(p,i)*=ElementV(u[k],sv->lag_index[i][k]);
630 dw_FreeArray(u);
631 FreeVector(r);
632 }
633
634 PRECISION x=0.0;
635 for (i=sv->nstates-1; i >= 0; i--) x+=ElementV(p,i);
636 if (fabs(x - 1.0) > 1e-7) { printf("invalid probabilities - %lf",x); getchar(); }
637
638 return 1;
639 }
640 else
641 return sv->routines->Probability_s0(p,sv);
642 }
643
644 /*
645 Assumes:
646 S : integer array of length model->nobs + 1 satisfying 0 <= S[t] < sv->nstates.
647 sv : pointer to valid TMarkovStateVariable structure
648 model : pointer to valid TStateModel structure
649
650 Returns:
651 The natural logrithm of
652
653 p(q_old | Y[T],Z[T],S[T],theta,q_new)/p(q_new | Y[T],Z[T],S[T],theta,q_old)
654
655 where p( | ) is the proposal density, q_old is the value of sv->q upon entry
656 and q_new is the value of sv->q upon exit.
657
658 Results:
659 Draws sv->q from the propoal density p(q_new | Y[T], Z[T], S[T], theta, q_old).
660
661 Notes:
662 Sets sv->t1 to -1.
663 */
664 PRECISION sv_DrawProposalTransitionMatrixParameters(int *S, TMarkovStateVariable *sv, TStateModel *model)
665 {
666 int t, k, *s;
667 PRECISION log_proposal_ratio=0.0;
668 sv->t1=-1;
669 if (sv->n_state_variables > 0)
670 {
671 if (!(s=(int*)dw_malloc((model->nobs+1)*sizeof(int)))) return 0;
672 for (k=sv->n_state_variables-1; k >= 0; k--)
673 {
674 for (t=model->nobs; t >= 0; t--)
675 s[t]=sv->state_variable[k]->lag_index[sv->index[sv->lag_index[S[t]][0]][k]][0];
676 log_proposal_ratio+=sv_DrawProposalTransitionMatrixParameters(s,sv->state_variable[k],model);
677 }
678 dw_free(s);
679 return log_proposal_ratio;
680 }
681 else
682 return sv->routines->DrawProposalTransitionMatrixParameters ?
683 sv->routines->DrawProposalTransitionMatrixParameters(S,sv,model) : MINUS_INFINITY;
684 }
685
686 /*
687 Assumes:
688 S : integer array of length model->nobs + 1 satisfying 0 <= S[t] < sv->nstates.
689 sv : pointer to valid TMarkovStateVariable structure
690 model : pointer to valid TStateModel structure
691
692 Returns:
693 One upon success and zero otherwise.
694
695 Results:
696 Draws sv->q from the conditional posterior density
697 p(q | Y[T], Z[T], S[T], theta).
698
699 Notes:
700 Sets sv->t1 to -1.
701 */
702 int sv_DrawTransitionMatrixParameters(int *S, TMarkovStateVariable *sv, TStateModel *model)
703 {
704 int t, k, *s;
705 sv->t1=-1;
706 if (sv->n_state_variables > 0)
707 {
708 if (!(s=(int*)dw_malloc((model->nobs+1)*sizeof(int)))) return 0;
709 for (k=sv->n_state_variables-1; k >= 0; k--)
710 {
711 for (t=model->nobs; t >= 0; t--)
712 s[t]=sv->state_variable[k]->lag_index[sv->index[sv->lag_index[S[t]][0]][k]][0];
713 if (!sv_DrawTransitionMatrixParameters(s,sv->state_variable[k],model))
714 {
715 dw_free(s);
716 return 0;
717 }
718 }
719 dw_free(s);
720 return 1;
721 }
722 else
723 return sv->routines->DrawTransitionMatrixParameters ? sv->routines->DrawTransitionMatrixParameters(S,sv,model) : 0;
724 }
725
726 /*
727 Assumes:
728 sv : pointer to valid TMarkovStateVariable structure
729
730 Returns:
731 One upon success and zero otherwise.
732
733 Results:
734 Draws sv->q from the prior density p(q).
735
736 Notes:
737 Sets sv->t1 to -1.
738 */
739 int sv_DrawTransitionMatrixParametersFromPrior(TMarkovStateVariable *sv)
740 {
741 int k;
742 sv->t1=-1;
743 if (sv->n_state_variables > 0)
744 {
745 for (k=sv->n_state_variables-1; k >= 0; k--)
746 if (!sv_DrawTransitionMatrixParametersFromPrior(sv->state_variable[k])) return 0;
747 return 1;
748 }
749 else
750 return sv->routines->pDrawTransitionMatrixParametersFromPrior ? sv->routines->pDrawTransitionMatrixParametersFromPrior(sv) : 0;
751 }
752
753 /*
754 Assumes:
755 sv : pointer to valid TMarkovStateVariable structure
756 model : pointer to valid TStateModel structure
757
758 Returns:
759 One upon success and zero upon failure.
760
761 Results:
762 Sets sv->q to some default value. Sets sv->t1 to -1.
763 */
764 int sv_DefaultTransitionMatrixParameters(TMarkovStateVariable *sv, TStateModel *model)
765 {
766 int k;
767 sv->t1=-1;
768 if (sv->n_state_variables > 0)
769 {
770 for (k=sv->n_state_variables-1; k >= 0; k--)
771 if (!sv_DefaultTransitionMatrixParameters(sv->state_variable[k],model)) return 0;
772 return 1;
773 }
774 else
775 return sv->routines->DefaultTransitionMatrixParameters ? sv->routines->DefaultTransitionMatrixParameters(sv,model) : 0;
776 }
777
778 /*
779 Assumes:
780 sv : pointer to valid TMarkovStateVariable structure
781
782 Returns:
783 One if all the required routines have been defined and zero otherwise.
784 */
785 int sv_ValidRoutines(TMarkovStateVariable *sv)
786 {
787 int k;
788 if (sv->n_state_variables > 0)
789 {
790 for (k=sv->n_state_variables-1; k >= 0; k--)
791 if (!sv_ValidRoutines(sv->state_variable[k])) return 0;
792 return 1;
793 }
794 else
795 return (sv->routines && sv->routines->Probability_s0 && sv->routines->ComputeTransitionMatrix && sv->routines->pLogPrior) ? 1 : 0;
796 }
797
798 /*
799 Assumes:
800 sv : pointer to valid TMarkovStateVariable structure
801
802 Returns:
803 One if all the routines needed for Metropolis-Hasting draws of q have been
804 defined and zero otherwise.
805 */
806 int sv_ValidMetropolisHastings(TMarkovStateVariable *sv)
807 {
808 int k;
809 if (sv->n_state_variables > 0)
810 {
811 for (k=sv->n_state_variables-1; k >= 0; k--)
812 if (!sv_ValidMetropolisHastings(sv->state_variable[k])) return 0;
813 return 1;
814 }
815 else
816 return (sv->routines && sv->routines->DrawProposalTransitionMatrixParameters) ? 1 : 0;
817 }
818
819 /*
820 Assumes:
821 sv : pointer to valid TMarkovStateVariable structure
822
823 Returns:
824 One if all the routines needed for direct draws of q have been
825 defined and zero otherwise.
826 */
827 int sv_ValidDirectDraw(TMarkovStateVariable *sv)
828 {
829 int k;
830 if (sv->n_state_variables > 0)
831 {
832 for (k=sv->n_state_variables-1; k >= 0; k--)
833 if (!sv_ValidDirectDraw(sv->state_variable[k])) return 0;
834 return 1;
835 }
836 else
837 return (sv->routines && sv->routines->DrawTransitionMatrixParameters) ? 1 : 0;
838 }
839
840 /*
841 Assumes:
842 p : array of integers representing a permutation of dimension nstates.
843 sv : pointer to a valid TMarkovStateVariable structure.
844
845 Returns:
846 One upon success and zero otherwise.
847
848 Results:
849 Permutes the transistion matrix parameters
850
851 Notes:
852 The permutation represented by p maps i to p[i]. Furthermore, this
853 permutation must generate valid permutations on the base states arising from
854 encoded lags or independent Markov state variables. This means
855 1) sv->lag_index[i][k]=sv->lag_index[j][k] implies p[i]=p[j].
856 2) sv->index[i][k]=sv->index[j][k] implies p[i]=[j].
857
858 Sets sv->t1 to -1.
859 */
860 int sv_NormalizeRegimes(int *p, int t, TMarkovStateVariable *sv, TStateModel *model)
861 {
862 int i, k, *q, rtrn=0;
863 TPermutation P;
864 sv->t1=-1;
865 if (sv->n_state_variables > 0)
866 if (!(q=dw_malloc(sv->nbasestates*sizeof(int))))
867 dw_Error(MEM_ERR);
868 else
869 {
870 if (sv->nbasestates < sv->nstates)
871 for (k=sv->n_state_variables-1; k >= 0; k--)
872 {
873 for (i=sv->nstates-1; i >= 0; i--) q[sv->index[sv->lag_index[i][0]][k]]=sv->index[sv->lag_index[p[i]][0]][k];
874 if (!sv_NormalizeRegimes(q,t,sv->state_variable[k],model)) break;
875 }
876 else
877 for (k=sv->n_state_variables-1; k >= 0; k--)
878 {
879 for (i=sv->nstates-1; i >= 0; i--) q[sv->index[i][k]]=sv->index[p[i]][k];
880 if (!sv_NormalizeRegimes(q,t,sv->state_variable[k],model)) break;
881 }
882 if (k < 0) rtrn=1;
883 dw_free(q);
884 }
885 else
886 if (sv->routines->Update_q_from_BaseTransitionMatrix)
887 {
888 if (sv->nbasestates < sv->nstates)
889 {
890 if (!(q=dw_malloc(sv->nbasestates*sizeof(int))))
891 dw_Error(MEM_ERR);
892 else
893 {
894 for (i=sv->nstates-1; i >= 0; i--) q[sv->lag_index[i][0]]=sv->lag_index[p[i]][0];
895 if ((P=InitializePermutation((TPermutation)NULL,q,sv->nbasestates)))
896 {
897 if (ProductMP(sv->baseQ,TransposeProductPM(sv->baseQ,P,sv->baseQ),P))
898 rtrn=sv->routines->Update_q_from_BaseTransitionMatrix(t,sv,model);
899 FreePermutation(P);
900 }
901 else
902 dw_Error(MEM_ERR);
903 dw_free(q);
904 }
905 }
906 else
907 if ((P=InitializePermutation((TPermutation)NULL,p,sv->nbasestates)))
908 {
909 if (ProductMP(sv->baseQ,TransposeProductPM(sv->baseQ,P,sv->baseQ),P))
910 rtrn=sv->routines->Update_q_from_BaseTransitionMatrix(t,sv,model);
911 FreePermutation(P);
912 }
913 else
914 dw_Error(MEM_ERR);
915 }
916 return rtrn;
917 }
918 /*******************************************************************************/
919 /*******************************************************************************/
920 /*******************************************************************************/
921
922 /*******************************************************************************/
923 /********************************* TStateModel *********************************/
924 /*******************************************************************************/
925
926 /*************************** TStateModel Destructors ***************************/
927 /*
928 Frees TStateModel
929 */
930 void FreeStateModel(TStateModel *model)
931 {
932 if (model)
933 {
934 if (model->routines)
935 {
936 if (model->routines->pDestructor) model->routines->pDestructor(model->theta);
937 dw_free(model->routines);
938 }
939 if (model->q) dw_free(model->q);
940 FreeMarkovStateVariable(model->sv);
941 dw_FreeArray(model->C);
942 dw_FreeArray(model->V);
943 dw_FreeArray(model->Z);
944 FreeVector(model->L);
945 dw_FreeArray(model->SP);
946 Free_metropolis_theta(model->metropolis_theta);
947 dw_free(model);
948 }
949 }
950 /*******************************************************************************/
951
952 /************************** TStateModel Constructors ***************************/
953 /*
954 Creates TStateModel structure. The structures sv, routines, and theta become the
955 property of the the TStateModel structure. The structures sv and routines will
956 be destroyed by the TStateModel destructor. If the pDestructor field of the
957 routines structure has been set, then the structure theta will be destroyed by
958 TStateModel destructor.
959 */
960 TStateModel* CreateStateModel(int nobs, TMarkovStateVariable *sv, ThetaRoutines *routines, void *theta)
961 {
962 int t, n;
963 TStateModel *model;
964
965 if ((nobs < 1) || !sv || !routines )
966 {
967 printf("CreateStateModel(): Invalid arguments\n");
968 dw_exit(0);
969 }
970
971 if (!sv_ValidRoutines(sv))
972 {
973 printf("CreateStateModel(): Invalid TMarkovStateVariable routines\n");
974 dw_exit(0);
975 }
976
977 if (!(routines->pNumberFreeParametersTheta))
978 {
979 printf("CreateStateModel(): routines->pNumberFreeParametersTheta() must be supplied\n");
980 dw_exit(0);
981 }
982
983 // Uncomment if simulation will be used
984 if (!sv_ValidMetropolisHastings(sv) && !sv_ValidDirectDraw(sv))
985 {
986 printf("CreateStateModel(): Simulation not available\n");
987 dw_exit(0);
988 }
989
990 if (!(model=(TStateModel*)dw_malloc(sizeof(TStateModel))))
991 {
992 printf("CreateStateModel(): Out of memory\n");
993 dw_exit(0);
994 }
995
996 //=== Markov state variable ===
997 model->q=(PRECISION*)dw_malloc(sv->nfree*sizeof(PRECISION));
998 sv_SetupFreeParameters(model->q,sv);
999 model->sv=sv;
1000 model->use_metropolis_hasting=sv_ValidDirectDraw(sv) ? 0 : 1;
1001 model->metropolis_draws_q=0;
1002 model->metropolis_jumps_q=0;
1003
1004 //=== Model specific parameters and routines ===
1005 model->theta=theta;
1006 model->routines=routines;
1007
1008 //=== State vector ===
1009 model->fobs=1;
1010 model->nobs=nobs;
1011 dw_InitializeArray_int(model->S=dw_CreateArray_int(nobs+1),0);
1012
1013 //=== Notification flags ===
1014 model->ForwardRecursionFailed=0;
1015
1016 //=== Common work space ===
1017 model->t0=-1;
1018 model->SP_Computed=0;
1019 model->C=dw_CreateArray_vector(nobs+1);
1020 model->Z=dw_CreateArray_vector(nobs+1);
1021 model->V=dw_CreateArray_vector(nobs+1);
1022 model->SP=dw_CreateArray_vector(nobs+1);
1023 for (t=nobs; t >= 0; t--)
1024 {
1025 model->C[t]=CreateVector(sv->nstates);
1026 model->Z[t]=CreateVector(sv->nstates);
1027 model->V[t]=CreateVector(sv->nstates);
1028 model->SP[t]=CreateVector(sv->nstates);
1029 }
1030 model->L=CreateVector(nobs+1);
1031
1032 //== Metropolis infomation for theta
1033 model->metropolis_theta=Create_metropolis_theta(NumberFreeParametersTheta(model));
1034
1035 //== Simulation workspace
1036 model->max_log_posterior=MINUS_INFINITY;
1037 n=NumberFreeParametersTheta(model);
1038 model->max_posterior_theta=(n > 0) ? CreateVector(n) : (TVector)NULL;
1039 model->max_posterior_q=(sv->nfree > 0) ? CreateVector(sv->nfree) : (TVector)NULL;
1040
1041 //=== Degenerate draws of states
1042 model->reject_degenerate_draws=0;
1043 model->n_degenerate_draws=0;
1044 model->total_degenerate_draws=0;
1045
1046 //== Set control variables
1047 model->NormalizeStates=0;
1048
1049 //=== Set Transition matrix to prior mean ===
1050 DefaultTransitionMatrixParameters(model);
1051
1052 return model;
1053 }
1054 /*******************************************************************************/
1055
1056 /************************** TStateModel Notifications **************************/
1057 void StatesChanged(TStateModel *model)
1058 {
1059 if (model->routines->pStatesChanged) model->routines->pStatesChanged(model);
1060 }
1061
1062 void TransitionMatrixParametersChanged(TStateModel *model)
1063 {
1064 if (model->routines->pTransitionMatrixParametersChanged) model->routines->pTransitionMatrixParametersChanged(model);
1065 sv_InvalidateTransitionMatrix(model->sv);
1066 model->t0=-1;
1067 model->SP_Computed=0;
1068 model->ForwardRecursionFailed=0;
1069 }
1070
1071 void ThetaChanged(TStateModel *model)
1072 {
1073 if (model->routines->pThetaChanged) model->routines->pThetaChanged(model);
1074 model->t0=-1;
1075 model->SP_Computed=0;
1076 model->ForwardRecursionFailed=0;
1077 }
1078 /*******************************************************************************/
1079
1080 /**************************** TStateModel Functions ****************************/
1081 /*
1082 Assumes:
1083 model is a pointer to a properly initialized TStateModel.
1084
1085 Returns:
1086 One upon success or zero upon failure.
1087
1088 Results:
1089 Computes the following:
1090
1091 C[t][i] = ln(P(y[t] | Y[t-1], Z[t], s[t]=i, theta, q)) for 0 < t <= tau and 0 <= i < nstates
1092 V[t][i] = P(s[t]=i | Y[t], Z[t], theta, q) for 0 <= t <= tau and 0 <= i < nstates
1093 Z[t][i] = P(s[t]=i | Y[t-1], Z[t-1], theta, q) for 0 < t <= tau and 0 <= i < nstates
1094 L[t] = ln(P(Y[t] | Z[t], theta, q)) for 0 <= t <= tau
1095
1096 Sets model->t0 to tau upon success. Upon failure, model->ForwardRecursionFailed is set.
1097
1098 Notes:
1099 Because z is exogenous, P(z[u] | Y[u-1], Z[u-1], S[u], theta, q) = P(z[u] | Z[u-1]) and P(Z[t] | theta, q) = P(Z[t]). So
1100
1101 P(Y[t] | Z[t], theta, q) = P(Y[t], Z[t] | theta, q)/P(Z[t] | theta, q)
1102
1103 = Product(P(y[u], z[u] | Y[u-1], Z[u-1], theta, q), 0 < u <= t)/P(Z[t])
1104
1105 = Product(Sum(P(y[u], z[u], s[u] | Y[u-1], Z[u-1], theta, q), 0 <= s[u] < nstates), 0 < u <= t)/P(Z[t])
1106
1107 = Product(Sum(P(y[u] | Y[u-1], Z[u], s[u], theta, q)*P(z[u] | Y[u-1], Z[u-1], s[u], theta, q)
1108 *P(s[u] | Y[u-1], Z[u-1], theta, q), 0 <= s[u] < nstates), 0 < u <= t)/P(Z[t])
1109
1110 = Product(P(z[u] | Z[u-1])*Sum(P(y[u] | Y[u-1], Z[u], s[u], theta, q)
1111 *P(s[u] | Y[u-1], Z[u-1], theta, q), 0 <= s[u] < nstates), 0 < u <= t)/P(Z[t])
1112
1113 = Product(Sum(P(y[u] | Y[u-1], Z[u], s[u], theta, q)*P(s[u] | Y[u-1], Z[u-1], theta, q), 0 <= s[u] < nstates), 0 < u <= t)
1114
1115 So L[t] is computed using this formula.
1116 */
1117 int ForwardRecursion(int tau, TStateModel *model)
1118 {
1119 int s, t;
1120 PRECISION scale;
1121 TMarkovStateVariable *sv=model->sv;
1122
1123 //====== If tau <= t0, then we are done ======//
1124 if (tau <= model->t0) return 1;
1125
1126 //====== If ForwardRecursion() has already failed, do not try again ======//
1127 if (model->ForwardRecursionFailed) return 0;
1128
1129 //====== Initializes forward recursion if t0 < 0 ======//
1130 if (model->t0 < 0)
1131 {
1132 if (model->routines->pInitializeForwardRecursion)
1133 if (!model->routines->pInitializeForwardRecursion(model))
1134 {
1135 model->ForwardRecursionFailed=1;
1136 return 0;
1137 }
1138 ElementV(model->L,0)=0;
1139 if (!Probability_s0(model->V[0],model))
1140 {
1141 model->ForwardRecursionFailed=1;
1142 return 0;
1143 }
1144 model->t0=0;
1145 }
1146
1147 //====== forward recursion ======//
1148 for (t=model->t0+1; t <= tau; t++)
1149 {
1150 //------ compute Q(t) if necessary ------
1151 if (((t < sv->t0) || (sv->t1 < t)) && !sv_ComputeTransitionMatrix(t,model->sv,model))
1152 {
1153 model->ForwardRecursionFailed=1;
1154 return 0;
1155 }
1156
1157 //------ compute Z[t] ------
1158 ProductMV(model->Z[t],sv->Q,model->V[t-1]);
1159
1160 //------ compute log conditional probabilities and scale ------
1161 scale=MINUS_INFINITY;
1162 for (s=sv->nstates-1; s >= 0; s--)
1163 {
1164 if (ElementV(model->Z[t],s) > 0.0)
1165 {
1166 scale=AddScaledLogs(1.0,scale,ElementV(model->Z[t],s),ElementV(model->C[t],s)=LogConditionalLikelihood(s,t,model));
1167 ElementV(model->V[t],s)=log(ElementV(model->Z[t],s)) + ElementV(model->C[t],s);
1168 }
1169 else
1170 ElementV(model->V[t],s)=ElementV(model->C[t],s)=MINUS_INFINITY;
1171 }
1172
1173 //------ update L ------
1174 ElementV(model->L,t)=ElementV(model->L,t-1)+scale;
1175
1176 //------ scale V[t] ------
1177 for (s=sv->nstates-1; s >= 0; s--)
1178 if (ElementV(model->V[t],s) != MINUS_INFINITY)
1179 ElementV(model->V[t],s)=exp(ElementV(model->V[t],s) - scale);
1180 else
1181 ElementV(model->V[t],s)=0.0;
1182
1183 //------ valid forward recursion through t ------
1184 model->t0=t;
1185 }
1186
1187 return 1;
1188 }
1189
1190 int ComputeTransitionMatrix(int t, TStateModel *model)
1191 {
1192 return sv_ComputeTransitionMatrix(t,model->sv,model);
1193 }
1194
1195 int Probability_s0(TVector p, TStateModel *model)
1196 {
1197 return ComputeTransitionMatrix(0,model) ? sv_Probability_s0(p,(model)->sv) : 0;
1198 }
1199
1200 /*
1201 Assumes:
1202 model : pointer to valid TStateModel
1203
1204 Returns:
1205 Returns one upon success and zero upon failure.
1206
1207 Results:
1208 Fills SP for 0 <= t <= nobs and 0 <= i < nstates.
1209
1210 SP[t][i] = P(s[t] = i | Y[T], Z[T], theta, q)
1211
1212 Notes:
1213 Calls ForwardRecursion() if necessary. The time parameter t is base one.
1214 The computations use the following facts:
1215
1216 P(s[t]=k | Y[T], Z[T], theta, q)
1217 = Sum(P(s[t]=k, s[t+1]=i | Y[T], Z[T], theta, q), 0 <= i < nstates)
1218
1219 P(s[t]=k, s[t+1]=i | Y[T], Z[T], theta, q)
1220 = P(s[t]=k | Y[T], Z[T], theta, q, s[t+1]=i)
1221 * P(s[t+1]=i | Y[T], Z[T], theta, q)
1222
1223 P(s[t]=k | Y[T], Z[T], theta, q, s[t+1]=i)
1224 = P(s[t]=k | Y[t], Z[t], theta, q, s[t+1]=i)
1225
1226 P(s[t]=k | Y[t], Z[t], theta, q, s[t+1]=i) = Q[i][k]
1227 * P(s[t]=k | Y[t], Z[t], theta, q) / P(s[t+1]=i | Y[t], Z[t], theta, q)
1228
1229 The third of these facts follows from
1230
1231 P(s[t] | Y[t], Z[t], theta, t, s[t+1])
1232 = P(s[t] | Y[T], Z[T], theta, t, S(t+1,T))
1233
1234 where S(t+1,T)={s[t+1],...,s[T]}. This is proven in the related paper.
1235
1236 */
1237 int ComputeSmoothedProbabilities(TStateModel *model)
1238 {
1239 int nstates=model->sv->nstates, i, k, t;
1240
1241 //====== Smoothed probabilities have already been computed ======
1242 if (model->SP_Computed) return 1;
1243
1244 //====== Check for valid forward recursion through time t ======
1245 if ((model->t0 < model->nobs) && !ForwardRecursion(model->nobs,model)) return 0;
1246
1247 //====== Compute SP via backward recursion ======
1248 EquateVector(model->SP[model->nobs],model->V[model->nobs]);
1249 for (t=model->nobs-1; t >= 0; t--)
1250 {
1251 //------ compute Q(t) if necessary ------
1252 if (((t < model->sv->t0) || (model->sv->t1 < t)) && !sv_ComputeTransitionMatrix(t+1,model->sv,model)) return 0;
1253
1254 // s[t] = k and s[t+1] = i
1255 for (k=nstates-1; k >= 0; k--)
1256 {
1257 for (ElementV(model->SP[t],k)=0.0, i=nstates-1; i >= 0; i--)
1258 if (ElementV(model->Z[t+1],i) > 0.0)
1259 ElementV(model->SP[t],k)+=ElementV(model->SP[t+1],i)*ElementM(model->sv->Q,i,k)/ElementV(model->Z[t+1],i);
1260 ElementV(model->SP[t],k)*=ElementV(model->V[t],k);
1261 }
1262 }
1263
1264 model->SP_Computed=1;
1265 return 1;
1266 }
1267
1268 /*
1269 Computes
1270
1271 p[t][s] = P(s[t] = s | Y[tau], Z[tau], theta, q)
1272 */
1273 TVector* RealTimeSmoothedProbabilities(TVector *p, int tau, TStateModel *model)
1274 {
1275 int nstates=model->sv->nstates, i, k, t;
1276
1277 if (!p)
1278 {
1279 p=dw_CreateArray_vector(tau+1);
1280 for (t=tau; t >= 0; t--)
1281 p[t]=CreateVector(model->sv->nstates);
1282 }
1283 else
1284 if (dw_DimA(p) <= tau)
1285 {
1286 dw_Error(SIZE_ERR);
1287 return (TVector*)NULL;
1288 }
1289
1290 //====== Check for valid forward recursion through time tau ======
1291 if ((model->t0 < tau) && !ForwardRecursion(tau,model)) return 0;
1292
1293 //====== Compute smoothed probabilities via backward recursion ======
1294 EquateVector(p[tau],model->V[tau]);
1295 for (t=tau-1; t >= 0; t--)
1296 {
1297 //------ compute Q(t) if necessary ------
1298 if (((t < model->sv->t0) || (model->sv->t1 < t)) && !sv_ComputeTransitionMatrix(t+1,model->sv,model)) return 0;
1299
1300 // s[t] = k and s[t+1] = i
1301 for (k=nstates-1; k >= 0; k--)
1302 {
1303 for (ElementV(p[t],k)=0.0, i=nstates-1; i >= 0; i--)
1304 if (ElementV(model->Z[t+1],i) > 0.0)
1305 ElementV(p[t],k)+=ElementV(p[t+1],i)*ElementM(model->sv->Q,i,k)/ElementV(model->Z[t+1],i);
1306 ElementV(p[t],k)*=ElementV(model->V[t],k);
1307 }
1308 }
1309
1310 return p;
1311 }
1312
1313 /*
1314 Assumes:
1315 model is a pointer to a properly initialized TStateModel.
1316
1317 Returns:
1318 1 upon success and 0 otherwise.
1319
1320 Results:
1321 Draws the discrete Markov state variable from the posterior distribution,
1322 conditional on q and theta. The state variable values are stored in
1323 model->S.
1324
1325 Notes:
1326 Calls ForwardRecursion() if necessary.
1327 */
1328 int DrawStates(TStateModel *model)
1329 {
1330 int i, j, t, k=0, rtrn=1;
1331 PRECISION scale, u, s;
1332 TMarkovStateVariable *sv=model->sv;
1333 int *regime_counts=(int*)dw_malloc(sv->nstates*sizeof(int));
1334
1335 //====== Check for valid forward recursion through time model->nobs ======
1336 if ((model->t0 < model->nobs) && !ForwardRecursion(model->nobs,model)) return 0;
1337
1338 //====== Backward recursion ======
1339 BACKWARD_RECURSION:
1340 for (i=sv->nstates-1; i >=0; i--) regime_counts[i]=0;
1341
1342 if ((u=dw_uniform_rnd()) >= (s=ElementV(model->V[t=model->nobs],i=sv->nstates-1)))
1343 while (--i > 0)
1344 if (u < (s+=ElementV(model->V[t],i))) break;
1345
1346 //------ track count of states ------
1347 regime_counts[model->S[t]=i]++;
1348
1349 for (t--; t >= 0; t--)
1350 {
1351 //------ compute Q(t+1) if necessary ------
1352 if (((t < sv->t0) || (sv->t1 < t)) && !sv_ComputeTransitionMatrix(t+1,model->sv,model)) return 0;
1353
1354 scale=1.0/ElementV(model->Z[t+1],j=i);
1355 i=sv->nstates-1;
1356 if ((u=dw_uniform_rnd()) >= (s=ElementV(model->V[t],i)*ElementM(sv->Q,j,i)*scale))
1357 while (--i > 0)
1358 if (u < (s+=ElementV(model->V[t],i)*ElementM(sv->Q,j,i)*scale)) break;
1359
1360 //------ track count of states ------
1361 regime_counts[model->S[t]=i]++;
1362 }
1363
1364 //------ degenerate states ------
1365 if (IsDegenerate(regime_counts,model) && (++k < model->reject_degenerate_draws)) goto BACKWARD_RECURSION;
1366
1367 if (k > 0)
1368 {
1369 model->n_degenerate_draws++;
1370 model->total_degenerate_draws+=k;
1371 if (model->reject_degenerate_draws && (k == model->reject_degenerate_draws))
1372 {
1373 rtrn=0;
1374 printf("DrawStates(): Reached max iteration count (%d)\n",k);
1375 }
1376 }
1377
1378 //====== State change notification ======
1379 StatesChanged(model);
1380
1381 //====== Free memory ======
1382 dw_free(regime_counts);
1383
1384 return rtrn;
1385 }
1386
1387
1388 /*
1389 Assumes:
1390 model is a pointer to a properly initialized TStateModel structure.
1391
1392 Returns:
1393 1 upon success and 0 otherwise
1394
1395 Results:
1396 Draws the vector of states S from the distribution defined by the transition
1397 matrices. The transition matrices depend on model->q and the data.
1398 */
1399 int DrawStatesFromTransitionMatrices(TStateModel *model)
1400 {
1401 int rtrn=0, s, t;
1402 TMarkovStateVariable *sv=model->sv;
1403 TVector p;
1404
1405 if ((p=CreateVector(sv->nstates)))
1406 {
1407 if (sv->routines->Probability_s0(p,sv))
1408 {
1409 model->S[0]=s=DrawDiscrete(p);
1410 if (sv->routines->ComputeTransitionMatrix)
1411 {
1412 rtrn=1;
1413 for (t=1; t <= model->nobs; t++)
1414 if (!sv->routines->ComputeTransitionMatrix(t,sv,model))
1415 {
1416 rtrn=0;
1417 break;
1418 }
1419 else
1420 {
1421 ColumnVector(p,sv->Q,s);
1422 model->S[t]=s=DrawDiscrete(p);
1423 }
1424 }
1425 }
1426 FreeVector(p);
1427 }
1428
1429 //===== State change notification ======
1430 StatesChanged(model);
1431
1432 return rtrn;
1433 }
1434
1435 void ResetMetropolisHastingsCounts_q(TStateModel *model)
1436 {
1437 model->metropolis_jumps_q=model->metropolis_draws_q=0;
1438 }
1439
1440 /*
1441 Assumes:
1442 model: pointer to a properly initialized TStateModel structure
1443
1444 Returns:
1445 One upon success and zero upon failure. Failure indicates a problem in
1446 obtaining the proposal draw.
1447
1448 Results:
1449 Draws the transition matrix from the posterior distribution, conditional on
1450 the states and theta.
1451 */
1452 int DrawTransitionMatrixParameters_MetropolisHastings(TStateModel *model)
1453 {
1454 PRECISION log_proposal_ratio, log_posterior_old, log_posterior_new;
1455 PRECISION *q;
1456
1457 //== Save old transition matrix parameters
1458 q=(PRECISION*)dw_malloc(model->sv->nfree*sizeof(PRECISION));
1459 memcpy(q,model->q,model->sv->nfree*sizeof(PRECISION));
1460
1461 //== Compute P(q | Y, Z, S, theta), which is proportional to the posterior.
1462 log_posterior_old=LogPosterior(model);
1463
1464 //== Draw proposal and call TransitionMatrixParametersChanged()
1465 log_proposal_ratio=sv_DrawProposalTransitionMatrixParameters(model->S,model->sv,model);
1466 TransitionMatrixParametersChanged(model);
1467
1468 //== Compute new posteriorkernel
1469 log_posterior_new=LogPosterior(model);
1470
1471 //== Reject draw?
1472 if (log(dw_uniform_rnd()) > log_posterior_new - log_posterior_old + log_proposal_ratio)
1473 {
1474 memcpy(model->q,q,model->sv->nfree*sizeof(PRECISION));
1475 TransitionMatrixParametersChanged(model);
1476 }
1477 else
1478 model->metropolis_jumps_q++;
1479
1480 //== Increment number of metropolis draws
1481 model->metropolis_draws_q++;
1482
1483 // Clean up
1484 dw_free(q);
1485
1486 return 1;
1487 }
1488
1489 int DrawTransitionMatrixParameters(TStateModel *model)
1490 {
1491 if (model->use_metropolis_hasting)
1492 return DrawTransitionMatrixParameters_MetropolisHastings(model);
1493 else
1494 return sv_DrawTransitionMatrixParameters(model->S,model->sv,model);
1495 }
1496
1497 /*
1498 Assumes:
1499 model: pointer to a properly initialized TStateModel structure
1500
1501 Results:
1502 Draws the transition matrix sv->Q from the prior distribution.
1503 */
1504 int DrawTransitionMatrixParametersFromPrior(TStateModel *model)
1505 {
1506 int rtrn;
1507
1508 //====== Draw transition matrix parameters using recursive call ======
1509 rtrn=sv_DrawTransitionMatrixParametersFromPrior(model->sv);
1510
1511 //====== Transition matrix change notification ======
1512 TransitionMatrixParametersChanged(model);
1513
1514 return rtrn;
1515 }
1516
1517 /*
1518 Assumes:
1519 model: pointer to a properly initialized TStateModel structure
1520
1521 Results:
1522 Draws the transition matrix sv->Q from the prior distribution.
1523 */
1524 int DefaultTransitionMatrixParameters(TStateModel *model)
1525 {
1526 int rtrn;
1527
1528 //====== Set default transition matrix parameters using recursive call ======
1529 rtrn=sv_DefaultTransitionMatrixParameters(model->sv,model);
1530
1531 //====== Transition matrix change notification ======
1532 TransitionMatrixParametersChanged(model);
1533
1534 return rtrn;
1535 }
1536
1537 void DrawTheta(TStateModel *model)
1538 {
1539 //====== Draw theta ======
1540 if (model->routines->pDrawParameters)
1541 {
1542 model->routines->pDrawParameters(model);
1543 ThetaChanged(model);
1544 }
1545 else
1546 Draw_metropolis_theta(model);
1547 }
1548
1549 void DrawAll(TStateModel *model)
1550 {
1551 PRECISION tmp;
1552
1553 if (!DrawStates(model)) dw_UserError("DrawAll(): Error drawing path of regimes");
1554 DrawTransitionMatrixParameters(model);
1555 DrawTheta(model);
1556
1557 if ((tmp=LogPosterior_StatesIntegratedOut(model)) > model->max_log_posterior)
1558 {
1559 model->max_log_posterior=tmp;
1560 if (model->max_posterior_theta) ConvertThetaToFreeParameters(model,pElementV(model->max_posterior_theta));
1561 if (model->max_posterior_q) ConvertQToFreeParameters(model,pElementV(model->max_posterior_q));
1562 }
1563 }
1564 /*******************************************************************************/
1565 /*******************************************************************************/
1566 /*******************************************************************************/
1567
1568
1569 /*******************************************************************************/
1570 /**************************** Regime Normalization *****************************/
1571 /*******************************************************************************/
1572 /*
1573 The integer pointer permutation is the normalizing permutation or a null
1574 pointer. Returns one if the parameters are not normalized and zero otherwise.
1575
1576 The normalized parameters in regime k are equal to the un-normalized
1577 parameters in regime permutation[k]
1578 */
1579 int AreRegimesNormalized(TPermutation p, TStateModel *model)
1580 {
1581 int rtrn;
1582 if (!p)
1583 {
1584 p=CreatePermutation(model->sv->nstates*sizeof(int));
1585 rtrn=ComputeNormalizingPermutation(p,model);
1586 FreePermutation(p);
1587 return rtrn;
1588 }
1589 else
1590 if (UseP(p) > 0) return 0;
1591 return 1;
1592 }
1593
1594 int NormalizeTransitionMatrices(int *p, TStateModel *model, PRECISION *buffer)
1595 {
1596 PRECISION *f=(PRECISION*)NULL;
1597 int rtrn=0;
1598 if (buffer)
1599 {
1600 f=(PRECISION*)dw_malloc(NumberFreeParametersQ(model)*sizeof(PRECISION));
1601 ConvertQToFreeParameters(model,f);
1602 }
1603 if (sv_ComputeTransitionMatrix(0,model->sv,model))
1604 rtrn=sv_NormalizeRegimes(p,0,model->sv,model);
1605 if (buffer)
1606 {
1607 ConvertQToFreeParameters(model,buffer);
1608 ConvertFreeParametersToQ(model,f);
1609 dw_free(f);
1610 }
1611 return rtrn;
1612 }
1613
1614 /*
1615 Normalizes the parameters. The integer pointer
1616 */
1617 int NormalizeRegimes(int *p, TStateModel *model, PRECISION *buffer)
1618 {
1619 int rtrn=0, *q=p;
1620 if (model->routines->pNormalizeRegimes)
1621 {
1622 if (q || (rtrn=ComputeNormalizingPermutation(q=dw_malloc(model->sv->nstates*sizeof(int)),model)))
1623 if (model->routines->pNormalizeRegimes(q,model,buffer) && NormalizeTransitionMatrices(q,model,buffer))
1624 rtrn=1;
1625 if (p != q) dw_free(q);
1626 }
1627 return rtrn;
1628 }
1629 /*******************************************************************************/
1630 /*******************************************************************************/
1631 /*******************************************************************************/
1632
1633
1634 /*******************************************************************************/
1635 /*********************** Impulse responses and forecasts ***********************/
1636 /*******************************************************************************/
1637 /*
1638 */
1639 TMatrix ImpluseResponse(TMatrix IR, int i, int T, int horizon, TStateModel *model)
1640 {
1641 TVector y, *Y1, *Y2, p;
1642 int s, t;
1643
1644 if (!model->routines->pEyt || !model->routines->pEyt_i || (T > model->nobs)) return (TMatrix)NULL;
1645
1646 if (model->t0 < T) ForwardRecursion(T,model);
1647 p=EquateVector((TVector)NULL,model->V[T]);
1648 ComputeTransitionMatrix(T,model);
1649 ProductMV(p,model->sv->Q,p);
1650
1651 Y1=dw_CreateArray_vector(horizon);
1652 Y2=dw_CreateArray_vector(horizon);
1653
1654 Y1[0]=ProductVS((TVector)NULL,y=model->routines->pEyt_i((TVector)NULL,T,(TVector*)NULL,i,0,T+1,model),ElementV(p,0));
1655 Y2[0]=ProductVS((TVector)NULL,model->routines->pEyt(y,T,(TVector*)NULL,0,T+1,model),ElementV(p,0));
1656 for (s=model->sv->nstates-1; s > 0; s--)
1657 {
1658 UpdateV(1.0,Y1[0],ElementV(p,s),model->routines->pEyt_i(y,T,(TVector*)NULL,i,s,T+1,model));
1659 UpdateV(1.0,Y2[0],ElementV(p,s),model->routines->pEyt(y,T,(TVector*)NULL,s,T+1,model));
1660 }
1661
1662 if (!IR)
1663 IR=CreateMatrix(horizon,DimV(y));
1664 else
1665 if ((RowM(IR) < horizon) || (ColM(IR) != DimV(y))) goto EXIT;
1666
1667 SubtractVV(y,Y1[0],Y2[0]);
1668 InsertRowVector(IR,y,0);
1669
1670 for (t=1; t < horizon; t++)
1671 {
1672 ProductMV(p,model->sv->Q,p);
1673 Y1[t]=ProductVS((TVector)NULL,model->routines->pEyt(y,T,Y1,s,T+1+t,model),ElementV(p,0));
1674 Y2[t]=ProductVS((TVector)NULL,model->routines->pEyt(y,T,Y2,s,T+1+t,model),ElementV(p,0));
1675 for (s=model->sv->nstates-1; s > 0; s--)
1676 {
1677 UpdateV(1.0,Y1[t],ElementV(p,s),model->routines->pEyt(y,T,Y1,s,T+1+t,model));
1678 UpdateV(1.0,Y2[t],ElementV(p,s),model->routines->pEyt(y,T,Y2,s,T+1+t,model));
1679 }
1680 SubtractVV(y,Y1[t],Y2[t]);
1681 InsertRowVector(IR,y,t);
1682 }
1683
1684 EXIT:
1685 dw_FreeArray(Y2);
1686 FreeVector(y);
1687 dw_FreeArray(Y1);
1688 FreeVector(p);
1689
1690 return IR;
1691 }
1692
1693 TMatrix ForecastMean(TMatrix F, int T, int horizon, TStateModel *model)
1694 {
1695 TVector y, *Y, p;
1696 int s, t;
1697
1698 if (!model->routines->pEyt || (T > model->nobs)) return (TMatrix)NULL;
1699
1700 if (model->t0 < T) ForwardRecursion(T,model);
1701 p=EquateVector((TVector)NULL,model->V[T]);
1702 ComputeTransitionMatrix(T,model);
1703 ProductMV(p,model->sv->Q,p);
1704
1705 Y=dw_CreateArray_vector(horizon);
1706
1707 Y[0]=ProductVS((TVector)NULL,y=model->routines->pEyt((TVector)NULL,T,(TVector*)NULL,0,T+1,model),ElementV(p,0));
1708 for (s=model->sv->nstates-1; s > 0; s--)
1709 UpdateV(1.0,Y[0],ElementV(p,s),model->routines->pEyt(y,T,(TVector*)NULL,s,T+1,model));
1710
1711 if (!F)
1712 F=CreateMatrix(horizon,DimV(y));
1713 else
1714 if ((RowM(F) < horizon) || (ColM(F) != DimV(y))) goto EXIT;
1715
1716 InsertRowVector(F,Y[0],0);
1717
1718 for (t=1; t < horizon; t++)
1719 {
1720 ProductMV(p,model->sv->Q,p);
1721 Y[t]=ProductVS((TVector)NULL,model->routines->pEyt(y,T,Y,s,T+1+t,model),ElementV(p,0));
1722 for (s=model->sv->nstates-1; s > 0; s--)
1723 UpdateV(1.0,Y[t],ElementV(p,s),model->routines->pEyt(y,T,Y,s,T+1+t,model));
1724 InsertRowVector(F,Y[t],t);
1725 }
1726
1727 EXIT:
1728 FreeVector(y);
1729 dw_FreeArray(Y);
1730 FreeVector(p);
1731
1732 return F;
1733 }
1734
1735 TMatrix ForecastRandom(__attribute__ ((unused)) TMatrix F, __attribute__ ((unused)) int T, __attribute__ ((unused)) int horizon, __attribute__ ((unused)) TStateModel *model)
1736 {
1737 return (TMatrix)NULL;
1738 }
1739 /*******************************************************************************/
1740 /*******************************************************************************/
1741 /*******************************************************************************/
1742
1743
1744 /*******************************************************************************/
1745 /******************************* Normalization ********************************/
1746 /*******************************************************************************/
1747 /* int SetStateNormalizationMethod(int (*pGetNormalization)(int*, struct TStateModel_tag*),int (*pPermuteTheta)(int*, struct TStateModel_tag*),TStateModel *model) */
1748 /* { */
1749 /* if (pGetNormalization && pPermuteTheta) */
1750 /* { */
1751 /* model->NormalizeStates=1; */
1752 /* model->routines->pGetNormalization=pGetNormalization; */
1753 /* model->routines->pPermuteTheta=pPermuteTheta; */
1754 /* } */
1755 /* else */
1756 /* { */
1757 /* model->NormalizeStates=0; */
1758 /* model->routines->pGetNormalization=NULL; */
1759 /* model->routines->pPermuteTheta=NULL; */
1760 /* } */
1761 /* return 1; */
1762 /* } */
1763
1764 /*
1765 Returns 1 if states successfully normalized and zero otherwise.
1766 */
1767 /* int NormalizeStates(TStateModel *model) */
1768 /* { */
1769 /* int *p, rtrn=0; */
1770
1771 /* if (!(model->NormalizeStates)) return 1; */
1772
1773 /* if (p=(int*)dw_malloc(model->sv->nstates)) */
1774 /* { */
1775 /* if (model->routines->pGetNormalization(p,model)) */
1776 /* if (Permute_SV(p,model->sv)) */
1777 /* if (model->routiens->pPermuteTheta(p,model)) */
1778 /* rtrn=1; */
1779 /* dw_free(p); */
1780 /* } */
1781
1782 /* return rtrn; */
1783 /* return 1; */
1784 /* } */
1785
1786
1787 /*******************************************************************************/
1788 /**************************** Compute Probabilities ****************************/
1789 /*******************************************************************************/
1790 /*
1791 Assumes:
1792 t : 1 <= t <= nobs
1793 model : pointer to valid TStateModel
1794
1795 Returns:
1796 Returns the natural logrithm of
1797
1798 P(y[t] | Y[t-1], Z[t], theta, q).
1799
1800 If forward recursion cannot be completed through time t, returns minus
1801 infinity. Note that minus infinity is also a valid return value.
1802
1803 Notes:
1804 Calls ForwardRecursion() if necessary. The time parameter t is base one.
1805 Computation is based on the following:
1806
1807 P(y[t] | Y[t-1], Z[t], theta, q) =
1808 Sum(P(s[t]=s | Y[t-1], Z[t], theta, q)
1809 * P(y[t] | Y[t-1], Z[t], s[t], theta, q), 0 <= s[t] < nstates)
1810
1811 and
1812
1813 P(s[t]=s | Y[t-1], Z[t], theta, q) = P(s[t]=s | Y[t-1], Z[t-1], theta, q)
1814 */
1815 PRECISION LogConditionalLikelihood_StatesIntegratedOut(int t, TStateModel *model)
1816 {
1817 int s;
1818 PRECISION u, x;
1819
1820 //====== Check for valid forward recursion through time t ======
1821 if ((model->t0 < t) && !ForwardRecursion(t,model)) return MINUS_INFINITY;
1822
1823 if ((u=ElementV(model->Z[t],0)) > 0.0)
1824 x=ElementV(model->C[t],0) + log(u);
1825 else
1826 x=MINUS_INFINITY;
1827
1828 for (s=model->sv->nstates-1; s > 0; s--)
1829 if ((u=ElementV(model->Z[t],s)) > 0.0)
1830 x=AddLogs(x,ElementV(model->C[t],s) + log(u));
1831
1832 return x;
1833 }
1834
1835 /*
1836 Assumes:
1837 t : 1 <= t <= nobs
1838 model : pointer to valid TStateModel
1839
1840 Returns:
1841 Returns
1842
1843 E[y[t] | Y[t-1], Z[t], theta, Q]
1844
1845 If forward recursion cannot be completed through time t, returns minus
1846 infinity. Note that minus infinity is also a valid return value.
1847
1848 Notes:
1849 Calls ForwardRecursion() if necessary. The time parameter t is base one.
1850 Computation is based on the following:
1851
1852 P(y[t] | Y[t-1], Z[t], theta, Q) =
1853 Sum(P(s[t]=s | Y[t-1], Z[t], theta, Q)
1854 * P(y[t] | Y[t-1], Z[t], theta, Q, s), 0 <= s < nstates)
1855
1856 and
1857
1858 P(s[t]=s | Y[t-1], Z[t], theta, Q) = P(s[t]=s | Y[t-1], Z[t-1], theta, Q)
1859 */
1860 TVector ExpectationSingleStep_StatesIntegratedOut(TVector y, int t, TStateModel *model)
1861 {
1862 int s;
1863 TVector y_tmp;
1864
1865 //====== Check for valid forward recursion through time t ======
1866 if ((model->t0 < t) && !ForwardRecursion(t,model)) return (TVector)NULL;
1867
1868 y=ExpectationSingleStep(y,0,t,model);
1869 ProductVS(y,y,ElementV(model->Z[t],0));
1870
1871 y_tmp=CreateVector(DimV(y));
1872 for (s=model->sv->nstates-1; s > 0; s--)
1873 {
1874 ExpectationSingleStep(y_tmp,s,t,model);
1875 ProductVS(y_tmp,y_tmp,ElementV(model->Z[t],s));
1876 AddVV(y,y,y_tmp);
1877 }
1878 FreeVector (y_tmp);
1879
1880 return y;
1881 }
1882
1883 TVector ExpectedError(TVector epsilon, __attribute__ ((unused)) int t, __attribute__ ((unused)) TStateModel *model)
1884 {
1885
1886
1887 return epsilon;
1888 }
1889
1890 /*
1891 Assumes:
1892 s : 0 <= s < nstates
1893 t : 0 <= t <= nobs
1894 model : pointer to valid TStateModel
1895
1896 Returns:
1897 Upon success, returns
1898
1899 P(s[t] = s | Y[t], Z[t], theta, q)
1900
1901 and -1 otherwise.
1902
1903 Notes:
1904 Calls ForwardRecursion() if necessary. The time parameter t is base one.
1905 */
1906 PRECISION ProbabilityStateConditionalCurrent(int s, int t, TStateModel *model)
1907 {
1908 //====== Check for valid forward recursion through time t ======
1909 if ((model->t0 < t) && !ForwardRecursion(t,model)) return -1.0;
1910
1911 return ElementV(model->V[t],s);
1912 }
1913
1914 /*
1915 Assumes:
1916 s : 0 <= s < nbasestates
1917 t : 0 <= t <= nobs
1918 model : pointer to valid TStateModel
1919
1920 Returns:
1921 Upon success, returns the probability that the base state is s given Y[t],
1922 Z[t], theta, and q. Upon failure returns -1. Note that this probability
1923 is the sum over all k such that lag_index[k][0]=s of
1924
1925 P(s[t] = k | Y[t], Z[t], theta, q)
1926
1927 Notes:
1928 Calls ForwardRecursion() if necessary. The time parameter t is base one.
1929 */
1930 PRECISION ProbabilityBaseStateConditionalCurrent(int s, int t, TStateModel *model)
1931 {
1932 PRECISION p;
1933 int i, m;
1934 //====== Check for valid forward recursion through time t ======
1935 if ((model->t0 < t) && !ForwardRecursion(t,model)) return -1.0;
1936
1937 if (model->sv->nlags_encoded == 0)
1938 return ElementV(model->V[t],s);
1939 else
1940 {
1941 i=(int)pow(model->sv->nbasestates,model->sv->nlags_encoded);
1942 for (p=0.0, m=(s+1)*i, i*=s; i < m; i++)
1943 p+=ElementV(model->V[t],i);
1944 return p;
1945 }
1946 }
1947
1948 /*
1949 Assumes:
1950 s : 0 <= s < nstates
1951 t : 1 <= t <= nobs
1952 model : pointer to valid TStateModel
1953
1954 Returns:
1955 Upon success, returns
1956
1957 P(s[t] | Y[t-1], Z[t-1], theta, q)
1958
1959 and -1 otherwize.
1960
1961 Notes:
1962 Calls ForwardRecursion() if necessary. The time parameter t is base one.
1963 */
1964 PRECISION ProbabilityStateConditionalPrevious(int s, int t, TStateModel *model)
1965 {
1966 //====== Check for valid forward recursion through time t ======
1967 if ((model->t0 < t) && !ForwardRecursion(t,model)) return -1.0;
1968
1969 return ElementV(model->Z[t],s);
1970 }
1971
1972 /*
1973 Assumes:
1974 p : vector of length model->sv->nobs+1 or null pointer
1975 s : 0 <= s < nstates
1976 model : pointer to valid TStateModel
1977
1978 Returns:
1979 Upon success, the vector P is returned and upon failure a null pointer is
1980 returned. If P is initially the null pointer, P is created.
1981
1982 Results:
1983
1984 P[t] = P(s[t] = s | Y[T], Z[T], theta, Q)
1985
1986 for 0 <= t <= T.
1987
1988 Notes:
1989 Calls ForwardRecursion() if necessary. The time parameter t is base one.
1990 The computations use the following facts:
1991
1992 P(s[t]=k | Y[T], Z[T], theta, Q)
1993 = Sum(P(s[t]=k, s[t+1]=i | Y[T], Z[T], theta, Q), 0 <= i < nstates)
1994
1995 P(s[t]=k, s[t+1]=i | Y[T], Z[T], theta, Q)
1996 = P(s[t]=k | Y[T], Z[T], theta, Q, s[t+1]=i)
1997 * P(s[t+1]=i | Y[T], Z[T], theta, Q)
1998
1999 P(s[t]=k | Y[t], Z[t], theta, Q, s[t+1]=i)
2000 = P(s[t]=k | Y[T], Z[T], theta, Q, s[t+1]=i)
2001
2002 P(s[t]=k | Y[t], Z[t], theta, Q, s[t+1]=i) = Q[i][k]
2003 * P(s[t]=k | Y[t], Z[t], theta, Q) / P(s[t+1]=i | Y[t], Z[t], theta, Q)
2004
2005 The third of these facts follows from
2006
2007 P(s[t] | Y[t], Z[t], theta, Q, s[t+1])
2008 = P(s[t] | Y[T], Z[T], theta, Q, S(t+1,T))
2009
2010 where S(t+1,T)={s[t+1],...,s[T]}. This is proven in the related paper.
2011
2012 */
2013 TVector ProbabilitiesState(TVector p, int s, TStateModel *model)
2014 {
2015 int t;
2016
2017 if (!model->SP_Computed && !ComputeSmoothedProbabilities(model)) return (TVector)NULL;
2018
2019 if (!p)
2020 { if (!(p=CreateVector(model->nobs+1))) return (TVector)NULL; }
2021 else
2022 if (DimV(p) != model->nobs+1)
2023 {
2024 dw_Error(SIZE_ERR);
2025 return (TVector)NULL;
2026 }
2027
2028 for (t=model->nobs; t >= 0; t--) ElementV(p,t)=ElementV(model->SP[t],s);
2029
2030 return p;
2031 }
2032
2033 /*
2034 Assumes:
2035 S : integer array of length model->sv->nobs+1
2036 model : pointer to valid TStateModel
2037
2038 Returns:
2039 If the transition matrix is valid, returns the natural logrithm of
2040 P(S[T] | Y[T], Z[T], theta, Q). If the transition matrix is invalid, return
2041 minus infinity. Note that minus infinity is also a valid return value.
2042
2043 Notes:
2044 Calls ForwardRecursion() if necessary. The time parameter t is base one.
2045 The computations use the following facts:
2046
2047 P(S[T] | Y[T], Z[T], theta, Q)
2048 = Product(P(s[t] | Y[T], Z[T], theta, Q, S(t+1,T)),1 <= t <= T)
2049
2050 P(s[t] | Y[t], Z[t], theta, Q, s[t+1])
2051 = P(s[t] | Y[T], Z[T], theta, Q, S(t+1,T))
2052
2053 P(s[t] | Y[t], Z[t], theta, Q, s[t+1]) = Q[s(t+1)][s(t)]
2054 * P(s[t] | Y[t], Z[t], theta, Q) / P(s[t+1] | Y[t], Z[t], theta, Q)
2055
2056 where S(t+1,T)={s[t+1],...,s[T]}. The second of these facts is proven in
2057 the related paper.
2058 */
2059 PRECISION LogProbabilityStates(__attribute__ ((unused)) int *S, __attribute__ ((unused)) TStateModel *model)
2060 {
2061 printf("LogProbabilityStates() not implemented\n");
2062 dw_exit(0);
2063
2064 /**
2065 PRECISION rtrn;
2066 TMarkovStateVariable *sv=model->sv;
2067 TMatrix Q=sv->Q;
2068 int t=model->nobs;
2069
2070 //====== Check for valid forward recursion through time t ======
2071 if ((model->t0 < model->nobs) && !ForwardRecursion(model->nobs,model)) return MINUS_INFINITY;
2072
2073 //====== Log probability ======
2074 rtrn=log(ElementV(model->V[t],S[t]));
2075 while (--t >= 0)
2076 if (ElementV(model->Z[t+1],S[t+1]) > 0.0)
2077 rtrn+=log(ElementM(Q,S[t+1],S[t])*ElementV(model->V[t],S[t])/ElementV(model->Z[t+1],S[t+1]));
2078 else
2079 return MINUS_INFINITY;
2080
2081 return rtrn;
2082
2083 //====== Probability ======
2084 * rtrn=ElementV(model->V[t],S[t]); */
2085 /* while (--t >= 0) */
2086 /* rtrn*=ElementM(Q,S[t+1],S[t])*ElementV(model->V[t],S[t])/ElementV(model->Z[t+1],S[t+1]); */
2087 }
2088
2089 /*
2090 Assumes
2091 model: pointer to valid TStateModel structure
2092
2093 Returns
2094 The natural logrithm of
2095
2096 P(S[T] | Theta, Q)
2097 */
2098 PRECISION LogPrior_S(TStateModel *model)
2099 {
2100 //int t, *S=model->S;
2101 //TMatrix Q=model->sv->Q;
2102 //PRECISION p=-log(model->sv->nstates); // This assumes that P(s0 = i) = P(s0 = j) for all i and j.
2103 //for (t=model->nobs; t > 0; t--)
2104 // p+=log(ElementM(Q,S[t],S[t-1]));
2105 //return p;
2106
2107 PRECISION p;
2108 int t, *S=model->S;
2109 if ((model->t0 < 0) && !Probability_s0(model->V[0],model)) return MINUS_INFINITY;
2110 p=log(ElementV(model->V[0],S[0]));
2111 for (t=1; t <= model->nobs; t++)
2112 {
2113 if (!sv_ComputeTransitionMatrix(t,model->sv,model)) return MINUS_INFINITY;
2114 p+=log(ElementM(model->sv->Q,S[t],S[t-1]));
2115 }
2116 return p;
2117 }
2118
2119 /*
2120 Assumes:
2121 model : pointer to valid TStateModel structure
2122
2123 Returns:
2124 The natural logrithm of
2125
2126 P(Y[T] | Z[T], S[T], theta, q)
2127
2128 Notes:
2129 The data is assumed to be the time t observations for fobs <= t <= nobs.
2130
2131 */
2132 PRECISION LogLikelihood(TStateModel *model)
2133 {
2134 int t, t0=model->t0, *S=model->S;
2135 PRECISION loglikelihood=0.0;
2136 for (t=model->fobs; t <= t0; t++)
2137 loglikelihood+=(ElementV(model->Z[t],S[t]) > 0) ? ElementV(model->C[t],S[t]) : LogConditionalLikelihood(S[t],t,model);
2138 for ( ; t <= model->nobs; t++)
2139 loglikelihood+=LogConditionalLikelihood(S[t],t,model);
2140 return loglikelihood;
2141 }
2142
2143 /*
2144 Assumes:
2145 model : pointer to valid TStateModel structure
2146
2147 Returns:
2148 Upon sucess, returns the natural logrithm of
2149
2150 P(Y[T] | Z[t], theta, Q)
2151
2152 and minus infinity otherwise. Note that minus infinity is also a valid
2153 return value.
2154
2155 Notes:
2156 Calls ForwardRecursion() if necessary. The time parameter t is base one.
2157 The data is assumed to be the time t observations for fobs <= t <= nobs.
2158 */
2159 PRECISION LogLikelihood_StatesIntegratedOut(TStateModel *model)
2160 {
2161 //====== Check for valid forward recursion through time t ======
2162 if ((model->t0 < model->nobs) && !ForwardRecursion(model->nobs,model)) return MINUS_INFINITY;
2163
2164 return ElementV(model->L,model->nobs) - ElementV(model->L,model->fobs - 1);
2165 }
2166
2167 /*
2168 Assumes:
2169 model : pointer to valid TStateModel structure
2170
2171 Returns:
2172 Upon sucess, returns the natural logrithm of
2173
2174 P(Y[T] | Z[t], theta, Q)
2175
2176 and minus infinity otherwise. Note that minus infinity is also a valid
2177 return value.
2178
2179 Notes:
2180 Calls ForwardRecursion() if necessary. The time parameter t is base one.
2181 */
2182 PRECISION LogPosterior_StatesIntegratedOut(TStateModel *model)
2183 {
2184 //====== Check for valid forward recursion through time t ======
2185 if ((model->t0 < model->nobs) && !ForwardRecursion(model->nobs,model)) return MINUS_INFINITY;
2186
2187 return ElementV(model->L,model->nobs) - ElementV(model->L,model->fobs - 1) + LogPrior(model);
2188 }
2189 /*******************************************************************************/
2190 /*******************************************************************************/
2191 /*******************************************************************************/
2192
2193
2194 /*******************************************************************************/
2195 /************************** Free parameters routines ***************************/
2196 /*******************************************************************************/
2197 void ConvertFreeParametersToQ(TStateModel *model, PRECISION *f)
2198 {
2199 if (model->sv->nfree > 0)
2200 {
2201 memcpy(model->q,f,model->sv->nfree*sizeof(PRECISION));
2202 TransitionMatrixParametersChanged(model);
2203 }
2204 }
2205
2206 void ConvertQToFreeParameters(TStateModel *model, PRECISION *f)
2207 {
2208 if (model->sv->nfree > 0) memcpy(f,model->q,model->sv->nfree*sizeof(PRECISION));
2209 }
2210
2211 void ConvertFreeParametersToTheta(TStateModel *model, PRECISION *f)
2212 {
2213 if (model->routines->pConvertFreeParametersToTheta)
2214 {
2215 model->routines->pConvertFreeParametersToTheta(model,f);
2216 ThetaChanged(model);
2217 }
2218 }
2219 /*******************************************************************************/
2220 /*******************************************************************************/
2221 /*******************************************************************************/
2222
2223
2224 /*******************************************************************************/
2225 /****************************** Utility Routines *******************************/
2226 /*******************************************************************************/
2227 /*
2228 Assumes:
2229 v : An n vector or null pointer
2230 P : An n x n transition matrix. It must be the case that P(i,j) >= 0 for
2231 every i and j and P(0,j) + ... + P(n-1,j) = 1 for every j.
2232
2233 Results:
2234 Computes the ergodic distribution of the transition matrix P if it exists.
2235 The ergodic distribution will exist if there is a unique vector v such that
2236 the elements of v are non-negative, sum to one and (P - I)v = 0.
2237
2238 Notes:
2239 If w is the n dimensional row vector of ones, then w(P - I) = 0. This
2240 implies that there exists a non-zero v such that (P - I)v = 0. It is easy
2241 to show that if (P - I)v = 0 and v1 is the positive component of v and v2 is
2242 the negative component of v, then both (P - I)v1 = 0 and (P - I)v2 = 0. So
2243 there is always exists a v such that the elements of v are non-negative, sum
2244 to one, (P - I)v = 0. However, a unique such element might not exist.
2245
2246 This routine does not check for uniqueness.
2247
2248 This version uses the LU decomposition, which is fast and fairly stable.
2249 */
2250 TVector Ergodic(TVector v, TMatrix P)
2251 {
2252 TVector rtrn;
2253 TMatrix IP;
2254 TPermutation S;
2255 PRECISION sum;
2256 int i, j, k;
2257
2258 if (!P)
2259 {
2260 dw_Error(NULL_ERR);
2261 return (TVector)NULL;
2262 }
2263 if (RowM(P) != ColM(P))
2264 {
2265 dw_Error(SIZE_ERR);
2266 return (TVector)NULL;
2267 }
2268 if (!v)
2269 {
2270 if (!(rtrn=CreateVector(RowM(P))))
2271 return (TVector)NULL;
2272 }
2273 else
2274 if (RowM(P) != DimV(v))
2275 {
2276 dw_Error(SIZE_ERR);
2277 return (TVector)NULL;
2278 }
2279 else
2280 rtrn=v;
2281
2282 IP=EquateMatrix((TMatrix)NULL,P);
2283 for (i=RowM(P)-1; i >= 0; i--)
2284 ElementM(IP,i,i)-=1.0;
2285 S=CreatePermutation(RowM(P));
2286
2287 if (LU(S,IP,IP))
2288 {
2289 for (k=0; k < RowM(P); k++)
2290 if (fabs(ElementM(IP,k,k)) < SQRT_MACHINE_EPSILON) break;
2291
2292 if (k < RowM(P))
2293 {
2294 for (i=DimV(rtrn)-1; i > k; i--)
2295 ElementV(rtrn,i)=0.0;
2296 ElementV(rtrn,i--)=1.0;
2297 for ( ; i >= 0; i--)
2298 {
2299 for (sum=-ElementM(IP,i,k), j=k-1; j > i; j--) sum-=ElementM(IP,i,j)*ElementV(rtrn,j);
2300 ElementV(rtrn,i)=sum/ElementM(IP,i,i);
2301 }
2302
2303 for (sum=1.0, i=k-1; i >= 0; i--)
2304 if (ElementV(rtrn,i) < 0.0)
2305 ElementV(rtrn,i)=0.0;
2306 else
2307 sum+=ElementV(rtrn,i);
2308
2309 ProductSV(rtrn,1.0/sum,rtrn);
2310 FreePermutation(S);
2311 FreeMatrix(IP);
2312 return rtrn;
2313 }
2314 }
2315
2316 FreePermutation(S);
2317 FreeMatrix(IP);
2318
2319 if (!v) FreeVector(rtrn);
2320 return (TVector) NULL;
2321 }
2322
2323 /*
2324 Assumes:
2325 There are DimV(p) states, denoted by 0, ... , Dim(p)-1. The probability of
2326 state i occuring is given by p[i]. It must be the case that the sum of the
2327 p[i] is equal to one.
2328
2329 Returns:
2330 A random draw of one of the states.
2331 */
2332 int DrawDiscrete(TVector p)
2333 {
2334 int i=DimV(p)-1;
2335 PRECISION u=dw_uniform_rnd(), s=ElementV(p,i);
2336 while (i > 0)
2337 if (u < s)
2338 return i;
2339 else
2340 s+=ElementV(p,--i);
2341 return 0;
2342 }
2343
2344 /*
2345 Y : null pointer or vector array of dimension m.
2346 P : vector array of dimension a*b.
2347 X : vector array of dimension a*b. Each vector is of dimension n.
2348 a : size of first variable.
2349 b : size of second variable.
2350 c : which variable to integrate out (1 or 2)
2351
2352 Assumes that
2353
2354 s = (u,v) = u*b + v
2355
2356 P(s) gives the probablity of state s occuring. X[s] is the value of a random
2357 vector given that state s occured.
2358
2359 If c is one, then m=b and u is integrated out and if c is two, then m=a and v
2360 is integrated out. If Y is null it is created and if Y[] is null, it is
2361 created.
2362 */
2363 TVector* IntegrateStatesSingleV(TVector *Y, TVector P, TVector *X, int a, int b, int c)
2364 {
2365 int s, u, v, n=DimV(X[0]);
2366 PRECISION sum, p;
2367 if (c == 1)
2368 {
2369 if (!Y) Y=dw_CreateArray_vector(b);
2370 for (v=b-1; v >= 0; v--)
2371 {
2372 if (!Y[v]) Y[v]=CreateVector(n);
2373 InitializeVector(Y[v],0.0);
2374 for (sum=0.0,s=(a-1)*b+v; s >= 0; s-=b)
2375 {
2376 sum+=(p=ElementV(P,s));
2377 LinearCombinationV(Y[v],1.0,Y[v],p,X[s]);
2378 }
2379 if (sum > 0) ProductVS(Y[v],Y[v],1.0/sum);
2380 }
2381 }
2382 else
2383 {
2384 if (!Y) Y=dw_CreateArray_vector(a);
2385 for (u=a-1; u >= 0; u--)
2386 {
2387 if (!Y[u]) Y[u]=CreateVector(n);
2388 InitializeVector(Y[u],0.0);
2389 for (sum=0.0, v=b-1, s=u*b+v; v >= 0; v--, s--)
2390 {
2391 sum+=(p=ElementV(P,s));
2392 LinearCombinationV(Y[u],1.0,Y[u],p,X[s]);
2393 }
2394 if (sum > 0) ProductVS(Y[u],Y[u],1.0/sum);
2395 }
2396 }
2397 return Y;
2398 }
2399
2400 /*
2401 Y : null pointer or vector array of dimension m.
2402 P : vector array of dimension a*b.
2403 X : vector array of dimension a*b. Each vector is of dimension n.
2404 a : size of first variable.
2405 b : size of second variable.
2406 c : which variable to integrate out (1 or 2)
2407
2408 Assumes that
2409
2410 s = (u,v) = u*b + v
2411
2412 P(s) gives the probablity of state s occuring. X[s] is the value of a random
2413 vector given that state s occured.
2414
2415 If c is one, then m=b and u is integrated out and if c is two, then m=a and v
2416 is integrated out. If Y is null it is created and if Y[] is null, it is
2417 created.
2418 */
2419 TMatrix* IntegrateStatesSingleM(TMatrix *Y, TVector P, TMatrix *X, int a, int b, int c)
2420 {
2421 int s, u, v, m=RowM(X[0]), n=ColM(X[0]);
2422 PRECISION sum, p;
2423 if (c == 1)
2424 {
2425 if (!Y) Y=dw_CreateArray_matrix(b);
2426 for (v=b-1; v >= 0; v--)
2427 {
2428 if (!Y[v]) Y[v]=CreateMatrix(m,m);
2429 InitializeMatrix(Y[v],0.0);
2430 for (sum=0.0,s=(a-1)*b+v; s >= 0; s-=b)
2431 {
2432 sum+=(p=ElementV(P,s));
2433 LinearCombinationM(Y[v],1.0,Y[v],p,X[s]);
2434 }
2435 if (sum > 0) ProductMS(Y[v],Y[v],1.0/sum);
2436 }
2437 }
2438 else
2439 {
2440 if (!Y) Y=dw_CreateArray_matrix(a);
2441 for (u=a-1; u >= 0; u--)
2442 {
2443 if (!Y[u]) Y[u]=CreateMatrix(m,n);
2444 InitializeMatrix(Y[u],0.0);
2445 for (sum=0.0, v=b-1, s=u*b+v; v >= 0; v--, s--)
2446 {
2447 sum+=(p=ElementV(P,s));
2448 LinearCombinationM(Y[u],1.0,Y[u],p,X[s]);
2449 }
2450 if (sum > 0) ProductMS(Y[u],Y[u],1.0/sum);
2451 }
2452 }
2453 return Y;
2454 }
2455
2456 /*
2457 Y : null pointer or vector array of dimension T x m, where m is a or b.
2458 P : vector array of dimension T x (a*b).
2459 X : vector array of dimension a*b. Each vector is of dimension n.
2460 a : size of first variable.
2461 b : size of second variable.
2462 c : which variable to integrate out (1 or 2)
2463
2464 Assumes that
2465
2466 s = (u,v) = u*b + v
2467
2468 P[t](s) gives the probablity of state s occuring at time t. X[t][s] is the
2469 value of a random vector given that state s occured at time t.
2470
2471 If c is one, then m=b and u is integrated out and if c is two, then m=a and v
2472 is integrated out. If Y is null, it is created.
2473 */
2474 TVector** IntegrateStatesV(TVector **Y, TVector* P, TVector **X, int a, int b, int c)
2475 {
2476 int t, T=dw_DimA(P);
2477 if (!Y) Y=dw_CreateRectangularArray_vector(T,(c == 1) ? b : a);
2478 for (t=T-1; t >= 0; t--) Y[t]=IntegrateStatesSingleV(Y[t],P[t],X[t],a,b,c);
2479 return Y;
2480 }
2481
2482 /*
2483 Q : null pointer or vector of dimension m.
2484 P : vectorof dimension a*b.
2485 a : size of first variable.
2486 b : size of second variable.
2487 c : which variable to integrate out (1 or 2)
2488
2489 Assumes that
2490
2491 s = (u,v) = u*b + v
2492
2493 P[t](s) gives the probablity of state s occuring at time t.
2494
2495 If c is one, then m=b and u is integrated out and if c is two, then m=a and v
2496 is integrated out. If Y is null, it is created.
2497 */
2498 TVector IntegrateStatesSingle(TVector Q, TVector P, int a, int b, int c)
2499 {
2500 int u, v, s;
2501 if (c == 1)
2502 {
2503 if (!Q) Q=CreateVector(b);
2504 InitializeVector(Q,0.0);
2505 for (v=b-1; v >= 0; v--)
2506 for (s=(a-1)*b+v; s >= 0; s-=b)
2507 ElementV(Q,v)+=ElementV(P,s);
2508 }
2509 else
2510 {
2511 if (!Q) Q=CreateVector(a);
2512 InitializeVector(Q,0.0);
2513 for (u=a-1; u >= 0; u--)
2514 for (v=b-1, s=u*b+v; v >= 0; v--, s--)
2515 ElementV(Q,u)+=ElementV(P,s);
2516 }
2517 return Q;
2518 }
2519
2520 /*
2521 Q : null pointer or vector array of dimension T x m
2522 P : vector array of dimension T x (a*b).
2523 a : size of first variable.
2524 b : size of second variable.
2525 c : which variable to integrate out (1 or 2)
2526
2527 Assumes that
2528
2529 s = (u,v) = u*b + v
2530
2531 P[t](s) gives the probablity of state s occuring at time t.
2532
2533 If c is one, then m=b and u is integrated out and if c is two, then m=a and v
2534 is integrated out. If Q is null, it is created.
2535 */
2536 TVector* IntegrateStates(TVector *Q, TVector* P, int a, int b, int c)
2537 {
2538 int t, T=dw_DimA(P);
2539 if (!Q) Q=dw_CreateArray_vector(T);
2540 for (t=T-1; t >= 0; t--) Q[t]=IntegrateStatesSingle(Q[t],P[t],a,b,c);
2541 return Q;
2542 }
2543 /*******************************************************************************/
2544 /*******************************************************************************/
2545 /*******************************************************************************/
2546