Debian Codegraph @

contrib/ms-sbvar/switch_dw/switching/dw_dirichlet_restrictions.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_dirichlet_restrictions.h"
19 #include "dw_switch.h"
20 #include "dw_switchio.h"
21 #include "dw_matrix_array.h"
22 #include "dw_error.h"
23 #include "dw_array.h"
24 #include "dw_rand.h"
25 #include "dw_std.h"
26
27 #include <stdlib.h>
28 #include <memory.h>
29 #include <math.h>
30 #include <limits.h>
31
32
33 void FreeDirichletRestrictions(TDirichletRestrictions *restrictions)
34 {
35 if (restrictions)
36 {
37 if (restrictions->B) dw_free(restrictions->B);
38 if (restrictions->b) dw_free(restrictions->b);
39 if (restrictions->Prior_B) dw_free(restrictions->Prior_B);
40 if (restrictions->Prior_b) dw_free(restrictions->Prior_b);
41 FreeMatrix(restrictions->Prior);
42 dw_FreeArray(restrictions->DirichletDim);
43 dw_FreeArray(restrictions->NonZeroIndex);
44 FreeMatrix(restrictions->MQ);
45 dw_free(restrictions);
46 }
47 }
48
49 /*
50 Assumes
51 nstates : positive integer
52 Prior : nstates x nstates matrix
53 DirichletDim : integer array
54 NonZeroIndex : nstates x nstates integer matrix
55 MQ : nstates x nstates matrix
56
57 Returns
58 A valid pointer to a TDirichletRestrictions structure.
59
60 Notes
61 This is the basic constructor for the TDirichletRestrictions structure. Upon
62 error, this procedure terminates the program.
63 */
64 TDirichletRestrictions* CreateDirichletRestrictions(int nstates, TMatrix Prior, int* DirichletDim,
65 int** NonZeroIndex, TMatrix MQ)
66 {
67 TDirichletRestrictions *restrictions;
68 int i, j, k, q, total_Dirichlet_parameters=0, terminal_errors;
69
70 if ((nstates <= 0))
71 {
72 printf("CreateMarkovStateVariable(): number of states must be positive\n");
73 dw_exit(0);
74 }
75
76 if (!dirichlet_restrictions_CheckRestrictions(DirichletDim,NonZeroIndex,MQ,Prior,nstates))
77 {
78 printf("CreateMarkovStateVariable_Single(): Error in restrictions\n");
79 dw_exit(0);
80 }
81
82 if (!(restrictions=(TDirichletRestrictions*)dw_malloc(sizeof(TDirichletRestrictions))))
83 {
84 printf("CreateMarkovStateVariable(): out of memory\n");
85 dw_exit(0);
86 }
87
88 //=== Set to terminate on memory error ===
89 terminal_errors=dw_SetTerminalErrors(MEM_ERR);
90
91 //=== Compute total number of quasi-free transition matrix parameters
92 for (k=dw_DimA(DirichletDim)-1; k >= 0; k--) total_Dirichlet_parameters+=DirichletDim[k];
93
94 // Workspace for quasi-free variables
95 restrictions->B=(PRECISION*)dw_malloc(total_Dirichlet_parameters*sizeof(PRECISION));
96 restrictions->b=(PRECISION**)dw_malloc(dw_DimA(DirichletDim)*sizeof(PRECISION*));
97 for (q=k=0; k < dw_DimA(DirichletDim); k++)
98 {
99 restrictions->b[k]=restrictions->B + q;
100 q+=DirichletDim[k];
101 }
102
103 //=== Sizes ===
104 restrictions->nstates=nstates;
105 restrictions->total_Dirichlet_parameters=total_Dirichlet_parameters;
106
107 //=== Prior information ===
108 restrictions->Prior=EquateMatrix((TMatrix)NULL,Prior);
109
110 restrictions->Prior_B=(PRECISION*)dw_malloc(total_Dirichlet_parameters*sizeof(PRECISION));
111 for (i=total_Dirichlet_parameters-1; i >= 0; i--) restrictions->Prior_B[i]=1.0;
112 for (j=nstates-1; j >= 0; j--)
113 for (i=nstates-1; i >= 0; i--)
114 if ((k=NonZeroIndex[i][j]) >= 0)
115 restrictions->Prior_B[k]+=ElementM(Prior,i,j)-1.0;
116
117 restrictions->Prior_b=(PRECISION**)dw_malloc(dw_DimA(DirichletDim)*sizeof(PRECISION*));
118 for (q=k=0; k < dw_DimA(DirichletDim); k++)
119 {
120 restrictions->Prior_b[k]=restrictions->Prior_B + q;
121 q+=DirichletDim[k];
122 }
123
124 //=== Restrictions ===
125 restrictions->DirichletDim=(int*)dw_CopyArray(NULL,DirichletDim);
126 restrictions->NonZeroIndex=(int**)dw_CopyArray(NULL,NonZeroIndex);
127 restrictions->MQ=EquateMatrix((TMatrix)NULL,MQ);
128
129 //=== Control variables ===
130 restrictions->UseErgodic=0;
131
132 //=== Dirichlet scale
133 restrictions->scale=1;
134
135 //=== Set Constants ===
136 dirichlet_restrictions_SetLogPriorConstant(restrictions);
137
138 //=== Reset terminal errors ===
139 dw_SetTerminalErrors(terminal_errors);
140
141 return restrictions;
142 }
143
144 TDirichletRestrictions* DuplicateDirichletRestrictions(TDirichletRestrictions *restrictions)
145 {
146 int q, k;
147 TDirichletRestrictions *new_restrictions;
148
149 if (!(new_restrictions=(TDirichletRestrictions*)dw_malloc(sizeof(TDirichletRestrictions)))) return (TDirichletRestrictions*)NULL;
150 memcpy(new_restrictions,restrictions,sizeof(TDirichletRestrictions));
151
152 //=== Quasi-free workspace ===
153 new_restrictions->B=(PRECISION*)dw_malloc(restrictions->total_Dirichlet_parameters*sizeof(PRECISION));
154 new_restrictions->b=(PRECISION**)dw_malloc(dw_DimA(restrictions->DirichletDim)*sizeof(PRECISION*));
155 for (q=k=0; k < dw_DimA(restrictions->DirichletDim); k++)
156 {
157 new_restrictions->b[k]=new_restrictions->B + q;
158 q+=restrictions->DirichletDim[k];
159 }
160 memcpy(new_restrictions->B,restrictions->B,restrictions->total_Dirichlet_parameters*sizeof(PRECISION));
161
162 //=== Prior information ===
163 new_restrictions->Prior=EquateMatrix((TMatrix)NULL,restrictions->Prior);
164 new_restrictions->Prior_B=(PRECISION*)dw_malloc(restrictions->total_Dirichlet_parameters*sizeof(PRECISION));
165 new_restrictions->Prior_b=(PRECISION**)dw_malloc(dw_DimA(restrictions->DirichletDim)*sizeof(PRECISION*));
166 for (q=k=0; k < dw_DimA(restrictions->DirichletDim); k++)
167 {
168 new_restrictions->Prior_b[k]=new_restrictions->Prior_B + q;
169 q+=restrictions->DirichletDim[k];
170 }
171 memcpy(new_restrictions->Prior_B,restrictions->Prior_B,restrictions->total_Dirichlet_parameters*sizeof(PRECISION));
172
173 //=== Restrictions ===
174 new_restrictions->DirichletDim=(int*)dw_CopyArray(NULL,restrictions->DirichletDim);
175 new_restrictions->NonZeroIndex=(int**)dw_CopyArray(NULL,restrictions->NonZeroIndex);
176 new_restrictions->MQ=EquateMatrix((TMatrix)NULL,restrictions->MQ);
177
178 return new_restrictions;
179 }
180
181 TMarkovStateVariable* CreateMarkovStateVariable_Mixture(int nstates, int nlags_encoded, TMatrix Prior)
182 {
183 int i, j;
184 TDirichletRestrictions *restrictions;
185 int* DirichletDim;
186 int** NonZeroIndex;
187 TMatrix MQ;
188 NonZeroIndex=dw_CreateRectangularArray_int(nstates,nstates);
189 for (i=nstates-1; i >= 0; i--)
190 for (j=nstates-1; j >= 0; j--)
191 NonZeroIndex[i][j]=i;
192 MQ=InitializeMatrix(CreateMatrix(nstates,nstates),1.0);
193 DirichletDim=dw_CreateArray_int(1);
194 DirichletDim[0]=nstates;
195 restrictions=CreateDirichletRestrictions(nstates,Prior,DirichletDim,NonZeroIndex,MQ);
196 dw_FreeArray(NonZeroIndex);
197 FreeMatrix(MQ);
198 dw_FreeArray(DirichletDim);
199 return CreateMarkovStateVariable_Single(nstates,restrictions->total_Dirichlet_parameters - dw_DimA(restrictions->DirichletDim),
200 nlags_encoded,dirichlet_restrictions_CreateQRoutines(),(void*)restrictions);
201 }
202
203 TMarkovStateVariable* CreateMarkovStateVariable_NoRestrictions(int nstates, int nlags_encoded, TMatrix Prior)
204 {
205 int i, j;
206 TDirichletRestrictions *restrictions;
207 int* DirichletDim;
208 int** NonZeroIndex;
209 TMatrix MQ;
210 NonZeroIndex=dw_CreateRectangularArray_int(nstates,nstates);
211 for (i=nstates-1; i >= 0; i--)
212 for (j=nstates-1; j >= 0; j--)
213 NonZeroIndex[i][j]=i+nstates*j;
214 InitializeMatrix(MQ=CreateMatrix(nstates,nstates),1.0);
215 DirichletDim=dw_CreateArray_int(nstates);
216 for (i=nstates-1; i >= 0; i--) DirichletDim[i]=nstates;
217 restrictions=CreateDirichletRestrictions(nstates,Prior,DirichletDim,NonZeroIndex,MQ);
218 dw_FreeArray(NonZeroIndex);
219 FreeMatrix(MQ);
220 dw_FreeArray(DirichletDim);
221 return CreateMarkovStateVariable_Single(nstates,restrictions->total_Dirichlet_parameters - dw_DimA(restrictions->DirichletDim),
222 nlags_encoded,dirichlet_restrictions_CreateQRoutines(),(void*)restrictions);
223 }
224
225 TMarkovStateVariable* CreateMarkovStateVariable_Exclusion(int nstates, int nlags_encoded, TMatrix Prior, TMatrix Exclusion)
226 {
227 int i, j, k, q;
228 TDirichletRestrictions *restrictions;
229 int* DirichletDim;
230 int** NonZeroIndex;
231 TMatrix MQ;
232 dw_InitializeArray_int(NonZeroIndex=dw_CreateRectangularArray_int(nstates,nstates),-1);
233 MQ=InitializeMatrix(CreateMatrix(nstates,nstates),0.0);
234 DirichletDim=dw_CreateArray_int(nstates);
235 for (k=j=0; j < nstates; j++)
236 {
237 for (q=i=0; i < nstates; i++)
238 if (ElementM(Exclusion,i,j) > 0)
239 {
240 NonZeroIndex[i][j]=k++;
241 ElementM(MQ,i,j)=1.0;
242 q++;
243 }
244 DirichletDim[j]=q;
245 }
246 restrictions=CreateDirichletRestrictions(nstates,Prior,DirichletDim,NonZeroIndex,MQ);
247 dw_FreeArray(NonZeroIndex);
248 FreeMatrix(MQ);
249 dw_FreeArray(DirichletDim);
250 return CreateMarkovStateVariable_Single(nstates,restrictions->total_Dirichlet_parameters - dw_DimA(restrictions->DirichletDim),
251 nlags_encoded,dirichlet_restrictions_CreateQRoutines(),(void*)restrictions);
252 }
253
254 TMarkovStateVariable* CreateMarkovStateVariable_SimpleRestrictions(int nstates, int nlags_encoded, TMatrix Prior, TMatrix* Restriction)
255 {
256 int i, j, k, q;
257 TDirichletRestrictions *restrictions;
258 int* DirichletDim;
259 int** NonZeroIndex;
260 TMatrix MQ;
261 dw_InitializeArray_int(NonZeroIndex=dw_CreateRectangularArray_int(nstates,nstates),-1);
262 InitializeMatrix(MQ=CreateMatrix(nstates,nstates),0.0);
263 DirichletDim=dw_CreateArray_int(nstates);
264 for (q=k=0; k < nstates; k++)
265 {
266 DirichletDim[k]=ColM(Restriction[k]);
267 for (i=0; i < nstates; i++)
268 {
269 for (j=0; j < ColM(Restriction[k]); j++)
270 if (ElementM(Restriction[k],i,j) > 0)
271 {
272 NonZeroIndex[i][k]=q+j;
273 ElementM(MQ,i,k)=ElementM(Restriction[k],i,j);
274 break;
275 }
276 }
277 q+=DirichletDim[k];
278 }
279 restrictions=CreateDirichletRestrictions(nstates,Prior,DirichletDim,NonZeroIndex,MQ);
280 dw_FreeArray(NonZeroIndex);
281 FreeMatrix(MQ);
282 dw_FreeArray(DirichletDim);
283 return CreateMarkovStateVariable_Single(nstates,restrictions->total_Dirichlet_parameters - dw_DimA(restrictions->DirichletDim),
284 nlags_encoded,dirichlet_restrictions_CreateQRoutines(),(void*)restrictions);
285 }
286
287 TMarkovStateVariable* CreateMarkovStateVariable_ConstantState(int nlags_encoded)
288 {
289 TDirichletRestrictions *restrictions;
290 int* DirichletDim;
291 int** NonZeroIndex;
292 TMatrix MQ, Prior;
293 dw_InitializeArray_int(NonZeroIndex=dw_CreateRectangularArray_int(1,1),0);
294 InitializeMatrix(MQ=CreateMatrix(1,1),1.0);
295 dw_InitializeArray_int(DirichletDim=dw_CreateArray_int(1),1);
296 InitializeMatrix(Prior=CreateMatrix(1,1),1.0);
297 restrictions=CreateDirichletRestrictions(1,Prior,DirichletDim,NonZeroIndex,MQ);
298 dw_FreeArray(NonZeroIndex);
299 FreeMatrix(MQ);
300 dw_FreeArray(DirichletDim);
301 FreeMatrix(Prior);
302 return CreateMarkovStateVariable_Single(1,restrictions->total_Dirichlet_parameters - dw_DimA(restrictions->DirichletDim),
303 nlags_encoded,dirichlet_restrictions_CreateQRoutines(),(void*)restrictions);
304 }
305
306 /*******************************************************************************/
307 /*********************** TDirichletRestrictions Routines ***********************/
308 /*******************************************************************************/
309 QRoutines* dirichlet_restrictions_CreateQRoutines(void)
310 {
311 QRoutines* pRoutines=CreateQRoutines_empty();
312
313 if (pRoutines)
314 {
315 pRoutines->ComputeTransitionMatrix=dirichlet_restrictions_ComputeTransitionMatrix;
316 pRoutines->pLogPrior=dirichlet_restrictions_LogPrior_q;
317 pRoutines->Probability_s0=dirichlet_restrictions_Probability_s0;
318
319 pRoutines->DrawTransitionMatrixParameters=dirichlet_restrictions_DrawTransitionMatrixParameters;
320 pRoutines->DrawProposalTransitionMatrixParameters=dirichlet_restrictions_DrawProposalTransitionMatrixParameters;
321 pRoutines->pDrawTransitionMatrixParametersFromPrior=dirichlet_restrictions_DrawTransitionMatrixParametersFromPrior;
322
323 pRoutines->FreeInfo=(void (*)(void*))FreeDirichletRestrictions;
324 pRoutines->DuplicateInfo=(void* (*)(void*))DuplicateDirichletRestrictions;
325
326 pRoutines->WriteSpecification=WriteSpecification_dirichlet_restrictions;
327
328 pRoutines->DefaultTransitionMatrixParameters=dirichlet_restrictions_DefaultTransitionMatrixParameters;
329 pRoutines->Update_q_from_BaseTransitionMatrix=dirichlet_restrictions_Update_q_from_BaseTransitionMatrix;
330 }
331
332 return pRoutines;
333 }
334
335 //------------------------------ Required routines ------------------------------
336
337 /*
338 Assumes:
339 t : ignored
340 sv : pointer to valid TMarkovStateVariable structure.
341 model : ignored
342
343 Results:
344 Computes the all transition matrices from the free parameters sv->q. Sets
345 sv->t0 and sv->t1.
346
347 Returns:
348 Pointer to sv->baseQ upon success and null otherwise.
349 */
350 int dirichlet_restrictions_ComputeTransitionMatrix(__attribute__ ((unused)) int t, TMarkovStateVariable *sv, __attribute__ ((unused)) TStateModel *model)
351 {
352 TDirichletRestrictions *restrictions=(TDirichletRestrictions*)(sv->info);
353 int i, j, k;
354
355 if (!dirichlet_restrictions_Populate_B(sv->q,restrictions))
356 {
357 sv->t1=-1;
358 return 0;
359 }
360
361 for (j=sv->nbasestates-1; j >= 0; j--)
362 for (i=sv->nbasestates-1; i >= 0; i--)
363 ElementM(sv->baseQ,i,j)=((k=restrictions->NonZeroIndex[i][j]) >= 0) ? ElementM(restrictions->MQ,i,j)*restrictions->B[k] : 0.0;
364
365 if (sv->nlags_encoded > 0) ConvertBaseTransitionMatrix(sv->Q,sv->baseQ,sv->nlags_encoded);
366
367 sv->t0=0;
368 sv->t1=INT_MAX;
369
370 return 1;
371 }
372
373 PRECISION dirichlet_restrictions_LogPrior_q(TMarkovStateVariable *sv)
374 {
375 TDirichletRestrictions *restrictions=(TDirichletRestrictions*)(sv->info);
376 PRECISION *q, log_prior=restrictions->LogPriorConstant;
377 int k, m=dw_DimA(restrictions->DirichletDim);
378
379 // Accumulate Dirichlet kernel
380 for (q=sv->q, k=0; k < m; q+=restrictions->DirichletDim[k]-1, k++)
381 log_prior+=LogDirichlet_kernel(q,restrictions->Prior_b[k],restrictions->DirichletDim[k]);
382
383 return log_prior;
384 }
385
386 /*
387 Assumes:
388 p : vector of length sv->nstates.
389 sv : pointer to valid TMarkovStateVariable structure
390
391 Returns:
392 One upon success and zero upon failure.
393
394 Results:
395 If p is null, it is created. The p[i] is the probability that s0 is equal
396 to i.
397 */
398 int dirichlet_restrictions_Probability_s0(TVector p, TMarkovStateVariable *sv)
399 {
400 TDirichletRestrictions *restrictions=(TDirichletRestrictions*)(sv->info);
401 if (restrictions->UseErgodic)
402 {
403 return 0;
404 }
405 else
406 {
407 InitializeVector(p,1.0/(PRECISION)(sv->nstates));
408 return 1;
409 }
410 }
411
412 //----------------------------- Simulation routines -----------------------------
413 /*
414 Assumes:
415 S : integer array of length model->nobs + 1 satisfying 0 <= S[t] < sv->nstates.
416 sv : pointer to valid TMarkovStateVariable structure
417 model : pointer to valid TStateModel structure
418
419 Returns:
420 ln(p(q_old | S[T])) - ln(p(q_new | S[T])) where p( | ) is the conditional
421 proposal density.
422
423 Results:
424 Draws sv->q from the proposal density conditional on the values of S. Sets
425 sv->t1 to -1 which invalidates the transition matrices.
426 */
427 PRECISION dirichlet_restrictions_DrawProposalTransitionMatrixParameters(int *S, TMarkovStateVariable *sv, TStateModel *model)
428 {
429 TDirichletRestrictions *restrictions=(TDirichletRestrictions*)(sv->info);
430 PRECISION *q, log_proposal_ratio=0.0;
431 int k, t, m=dw_DimA(restrictions->DirichletDim);
432
433 // Set Dirichlet parameters
434 memcpy(restrictions->B,restrictions->Prior_B,restrictions->total_Dirichlet_parameters*sizeof(PRECISION));
435 for (t=model->nobs; t > 0; t--)
436 if ((k=restrictions->NonZeroIndex[S[t]][S[t-1]]) >= 0)
437 restrictions->B[k]+=1.0;
438
439 // Rescale if necessary
440 if (restrictions->scale != 1.0)
441 for (k=restrictions->total_Dirichlet_parameters-1; k >= 0; k--) restrictions->B[k]*=restrictions->scale;
442
443 // Compute p(q_old | S[T])
444 for (q=sv->q, k=0; k < m; q+=restrictions->DirichletDim[k]-1, k++)
445 log_proposal_ratio-=LogDirichlet_kernel(q,restrictions->b[k],restrictions->DirichletDim[k]);
446
447 // Draw b[j] and compute p(q_new | S[T])
448 for (k=dw_DimA(restrictions->DirichletDim)-1; k >= 0; k--)
449 log_proposal_ratio+=DrawDirichlet_kernel(restrictions->b[k],restrictions->b[k],restrictions->DirichletDim[k]);
450
451 // Populate q
452 dirichlet_restrictions_Populate_q(sv->q,restrictions);
453
454 // Set sv->t1
455 sv->t1=-1;
456
457 return log_proposal_ratio;
458 }
459
460 /*
461 Assumes:
462 S : integer array of length model->nobs + 1 satisfying 0 <= S[t] < sv->nstates.
463 sv : pointer to valid TMarkovStateVariable structure
464 model : pointer to valid TStateModel structure
465
466 Returns:
467 Always returns one.
468
469 Results:
470 Draws sv->q from the conditional posterior density
471 p(q | Y[T], Z[T], S[T], theta) = p(q | S[T]).
472 */
473 int dirichlet_restrictions_DrawTransitionMatrixParameters(int *S, TMarkovStateVariable *sv, TStateModel *model)
474 {
475 TDirichletRestrictions *restrictions=(TDirichletRestrictions*)(sv->info);
476 int k, t;
477
478 // Set Dirichlet parameters
479 memcpy(restrictions->B,restrictions->Prior_B,restrictions->total_Dirichlet_parameters*sizeof(PRECISION));
480 for (t=model->nobs; t > 0; t--)
481 if ((k=restrictions->NonZeroIndex[S[t]][S[t-1]]) >= 0)
482 restrictions->B[k]+=1.0;
483
484 // Draw b[k]
485 for (k=dw_DimA(restrictions->DirichletDim)-1; k >= 0; k--)
486 DrawDirichlet(restrictions->b[k],restrictions->b[k],restrictions->DirichletDim[k]);
487
488 // Populate q
489 dirichlet_restrictions_Populate_q(sv->q,restrictions);
490
491 // Set sv->t1
492 sv->t1=-1;
493
494 return 1;
495 }
496
497 /*
498 Assumes:
499 sv : pointer to valid TMarkovStateVariable structure
500
501 Returns:
502 Always returns one.
503
504 Results:
505 Draws sv->q from the prior density p(q), which is assumed to be Dirichlet.
506 */
507 int dirichlet_restrictions_DrawTransitionMatrixParametersFromPrior(TMarkovStateVariable *sv)
508 {
509 TDirichletRestrictions *restrictions=(TDirichletRestrictions*)(sv->info);
510 int k;
511
512 // Draw b[k] from prior
513 for (k=dw_DimA(restrictions->DirichletDim)-1; k >= 0; k--)
514 DrawDirichlet(restrictions->b[k],restrictions->Prior_b[k],restrictions->DirichletDim[k]);
515
516 // Populate q
517 dirichlet_restrictions_Populate_q(sv->q,restrictions);
518
519 // Set sv->t1
520 sv->t1=-1;
521
522 return 1;
523 }
524
525 //--------------------------- Miscelleanous routines ----------------------------
526
527 /*
528 Assumes:
529 sv : pointer to valid TMarkovStateVariable structure
530 model : ignored
531
532 Returns:
533 One, failure cannot occur,
534
535 Results:
536 Sets sv->q to its prior mean.
537 */
538 int dirichlet_restrictions_DefaultTransitionMatrixParameters(TMarkovStateVariable *sv, __attribute__ ((unused)) TStateModel *model)
539 {
540 dirichlet_restrictions_SetTransitionMatrixParametersToPriorMean(sv->q,(TDirichletRestrictions*)(sv->info));
541 return 1;
542 }
543
544 /*
545 Assumes
546 sv->baseQ has been updated and that sv->n_state_variables = 1.
547
548 Returns
549 One upon success and zero upon failure
550
551 Results
552 Updates sv->q from sv->baseQ. If necessary, sv->Q is computed. Both sv->t0
553 and sv->t1 are also updated.
554
555 Notes
556 If any of the elements of sv->q[i] is negative or their sum differs from one
557 by more than DimV(sv->b[i])*MACHINE_EPSILON, then the routine returns zero.
558
559 If any element of the updated sv->Q differs from the original sv->Q by more
560 than SQRT_MACHINE_EPSILON, then the routine returns zero.
561
562 Because of the checking done, care should be taken in calling this routine
563 in instances where efficiency is important.
564 */
565 int dirichlet_restrictions_Update_q_from_BaseTransitionMatrix(__attribute__ ((unused)) int t, TMarkovStateVariable *sv, __attribute__ ((unused)) TStateModel *model)
566 {
567 int i, j, k;
568 PRECISION sum, *scale;
569 TDirichletRestrictions *restrictions=(TDirichletRestrictions*)(sv->info);
570
571 // Compute B
572 scale=(PRECISION*)dw_malloc(restrictions->total_Dirichlet_parameters*sizeof(PRECISION));
573 for (k=restrictions->total_Dirichlet_parameters-1; k >= 0; k--) scale[k]=restrictions->B[k]=0.0;
574 for (i=restrictions->nstates-1; i >= 0; i--)
575 for (j=restrictions->nstates-1; j >= 0; j--)
576 if ((k=restrictions->NonZeroIndex[i][j]) >= 0)
577 {
578 restrictions->B[k]+=ElementM(sv->baseQ,i,j);
579 scale[k]+=ElementM(restrictions->MQ,i,j);
580 }
581 for (k=restrictions->total_Dirichlet_parameters-1; k >= 0; k--)
582 if (scale[k] > 0)
583 restrictions->B[k]/=scale[k];
584 dw_free(scale);
585
586 // Check computed B
587 for (i=dw_DimA(restrictions->DirichletDim)-1; i >= 0; i--)
588 {
589 for (sum=0.0, j=restrictions->DirichletDim[i]-1; j >= 0; j--)
590 if (restrictions->b[i][j] < 0)
591 {
592 sv->t1=-1;
593 return 0;
594 }
595 else
596 sum+=restrictions->b[i][j];
597 if (fabs(sum-1.0) > SQRT_MACHINE_EPSILON)
598 {
599 sv->t1=-1;
600 return 0;
601 }
602 for (sum=1/sum, j=restrictions->DirichletDim[i]-1; j >= 0; j--) restrictions->b[i][j]/=sum;
603 }
604
605 // Check computed Q
606 for (i=restrictions->nstates-1; i >= 0; i--)
607 for (j=restrictions->nstates-1; j >= 0; j--)
608 {
609 if ((k=restrictions->NonZeroIndex[i][j]) >= 0) ElementM(sv->baseQ,i,j)-=ElementM(restrictions->MQ,i,j)*restrictions->B[k];
610 if (fabs(ElementM(sv->baseQ,i,j)) > SQRT_MACHINE_EPSILON)
611 {
612 sv->t1=-1;
613 return 0;
614 }
615 else
616 ElementM(sv->baseQ,i,j)=(k >= 0) ? ElementM(restrictions->MQ,i,j)*restrictions->B[k] : 0.0;
617 }
618
619 // Success
620 dirichlet_restrictions_Populate_q(sv->q,restrictions);
621 if (sv->nlags_encoded > 0) ConvertBaseTransitionMatrix(sv->Q,sv->baseQ,sv->nlags_encoded);
622 sv->t0=0;
623 sv->t1=INT_MAX;
624
625 return 1;
626 }
627 /*******************************************************************************/
628 /*******************************************************************************/
629 /*******************************************************************************/
630
631 /*******************************************************************************/
632 /****************************** Utility Routines *******************************/
633 /*******************************************************************************/
634 TMatrix dirichlet_restrictions_CreatePriorFromDuration(int nbasestates, PRECISION duration)
635 {
636 int i;
637 TMatrix Prior=InitializeMatrix(Prior=CreateMatrix(nbasestates,nbasestates),1.0);
638 PRECISION d=(nbasestates - 1)*duration;
639 for (i=nbasestates-1; i >= 0; i--)
640 ElementM(Prior,i,i)=d;
641 return Prior;
642 }
643
644 void dirichlet_restrictions_SetLogPriorConstant(TDirichletRestrictions *restrictions)
645 {
646 PRECISION sum, x;
647 int i, j;
648 restrictions->LogPriorConstant=0.0;
649 for (i=dw_DimA(restrictions->DirichletDim)-1; i >= 0; i--)
650 {
651 for (sum=0.0, j=restrictions->DirichletDim[i]-1; j >= 0; j--)
652 {
653 sum+=(x=restrictions->Prior_b[i][j]);
654 restrictions->LogPriorConstant-=dw_log_gamma(x);
655 }
656 restrictions->LogPriorConstant+=dw_log_gamma(sum);
657 }
658 }
659
660 /*
661 Assumes:
662 q : array of length restrictions->total_Dirichlet_parameters - dw_DimA(restrictions->DirichletDim)
663 restrictions : pointer to valid TDirichletRestrictions structure
664
665 Results:
666 The elements of q, which are the free parameters, are set to the prior mean
667 */
668 void dirichlet_restrictions_SetTransitionMatrixParametersToPriorMean(PRECISION *q, TDirichletRestrictions *restrictions)
669 {
670 int i, j;
671 PRECISION sum;
672 for (j=dw_DimA(restrictions->DirichletDim)-1; j >= 0; j--)
673 {
674 for (sum=restrictions->Prior_b[j][0], i=restrictions->DirichletDim[j]-1; i > 0; i--) sum+=restrictions->Prior_b[j][i];
675 for (sum=1.0/sum, i=restrictions->DirichletDim[j]-1; i >= 0; i--)
676 restrictions->b[j][i]=sum*restrictions->Prior_b[j][i];
677 }
678 dirichlet_restrictions_Populate_q(q,restrictions);
679 }
680
681 /*
682 Assumes:
683 q : array of length restrictions->total_Dirichlet_parameters - dw_DimA(restrictions->DirichletDim)
684 restrictions : pointer to valid TDirichletRestrictions structure
685
686 Returns:
687 One upon success and zero upon failure.
688
689 Results:
690 Populates the Dirichlet parameters in restrictions->B and restrictions->b from
691 the array of free parameters q.
692
693 Notes:
694 The elements of restrictions->b[k] are restrictions to be non-negative and their
695 sum must be one. Checking is performed to ensure that this holds, up to
696 some tolerance.
697 */
698 int dirichlet_restrictions_Populate_B(PRECISION *q, TDirichletRestrictions *restrictions)
699 {
700 int i, j, k, m=dw_DimA(restrictions->DirichletDim);
701 PRECISION scale;
702 for (i=0; i < m; i++)
703 if ((k=restrictions->DirichletDim[i]-1) > 0)
704 {
705 memcpy(restrictions->b[i],q,k*sizeof(PRECISION));
706
707 for (scale=1.0, j=k-1; j >= 0; j--)
708 if (q[j] < 0)
709 return 0;
710 else
711 scale-=q[j];
712
713 q+=k;
714
715 if (scale < 0)
716 if (scale < -restrictions->DirichletDim[i]*MACHINE_EPSILON)
717 return 0;
718 else
719 restrictions->b[i][k]=0.0;
720 else
721 restrictions->b[i][k]=scale;
722 }
723 else
724 restrictions->b[i][k]=1.0;
725 return 1;
726 }
727
728 /*
729 Assumes:
730 q : (restrictions->total_Dirichlet_parameters - dw_DimA(restrictions->DirichletDim)) array
731 restrictions : pointer to valid TDirichletRestrictions structure
732
733 Results:
734 Populates the free parameters in the array q from the quasi-free parameters
735 in restrictions->B.
736
737 Notes:
738 The elements of restrictions->b[k] are restrictioned to be non-negative and their sum
739 must be one. No checking is performed to ensure this.
740 */
741 void dirichlet_restrictions_Populate_q(PRECISION *q, TDirichletRestrictions *restrictions)
742 {
743 int i, k;
744 for (i=0; i < dw_DimA(restrictions->DirichletDim); i++)
745 if ((k=restrictions->DirichletDim[i]-1) > 0)
746 {
747 memcpy(q,restrictions->b[i],k*sizeof(PRECISION));
748 q+=k;
749 }
750 }
751
752 /*
753 Checks that DirichletDim, NonZeroIndex, and MQ satisfies the appropriate
754 conditions. Returns 1 if the conditions are satisfied and 0 otherwise.
755 */
756 int dirichlet_restrictions_CheckRestrictions(int* DirichletDim, int** NonZeroIndex, TMatrix MQ, TMatrix Prior, int nstates)
757 {
758 int i, j, k, q, r, total_Dirichlet_parameters;
759 PRECISION alpha, sum, common_sum=0.0, total_sum;
760
761 //=== Check for null pointer and sizes
762 if (!Prior || (RowM(Prior) != nstates) || (ColM(Prior) != nstates)) return 0;
763 if (!MQ || (RowM(MQ) != nstates) || (ColM(MQ) != nstates)) return 0;
764 if (!DirichletDim)
765 return 0;
766 if (!NonZeroIndex || (dw_DimA(NonZeroIndex) != nstates))
767 return 0;
768 else
769 for (i=nstates-1; i >= 0; i--)
770 if (dw_DimA(NonZeroIndex[i]) != nstates) return 0;
771
772 //=== Checks DirichletDim[i] > 0
773 //=== Computes total_Dirichlet_parameters = DirichletDim[0] + ... + DirichletDim[dw_DimA(DirichletDim)-1]
774 for (total_Dirichlet_parameters=0, i=dw_DimA(DirichletDim)-1; i >= 0; i--)
775 if (DirichletDim[i] <= 0)
776 return 0;
777 else
778 total_Dirichlet_parameters+=DirichletDim[i];
779
780 //=== Checks -1 <= NonZeroIndex[i][j] < total_Dirichlet_parameters.
781 //=== Checks NonZeroIndex[i][j] >= 0, ==> MQ[i][j] > 0.
782 //=== Checks NonZeroIndex[i][j] = -1, ==> MQ[i][j] = 0.
783 for (j=0; j < nstates; j++)
784 for (i=0; i < nstates; i++)
785 if ((NonZeroIndex[i][j] < -1) || (total_Dirichlet_parameters <= NonZeroIndex[i][j]))
786 return 0;
787 else
788 if (NonZeroIndex[i][j] >= 0)
789 {
790 if (ElementM(MQ,i,j) <= 0.0) return 0;
791 }
792 else
793 {
794 if (ElementM(MQ,i,j) != 0.0) return 0;
795 }
796
797 //=== Check that column sums are correct
798 for (j=0; j < nstates; j++)
799 {
800 total_sum=0.0;
801 for (q=r=k=0; k < total_Dirichlet_parameters; k++)
802 if (k == q)
803 {
804 common_sum=0.0;
805 for (i=0; i < nstates; i++)
806 if (NonZeroIndex[i][j] == k)
807 common_sum+=ElementM(MQ,i,j);
808 q+=DirichletDim[r++];
809 total_sum+=common_sum;
810 }
811 else
812 {
813 sum=0.0;
814 for (i=0; i < nstates; i++)
815 if (NonZeroIndex[i][j] == k)
816 sum+=ElementM(MQ,i,j);
817 if (fabs(sum - common_sum) > SQRT_MACHINE_EPSILON) return 0;
818 }
819 if (fabs(total_sum - 1.0) > SQRT_MACHINE_EPSILON) return 0;
820 }
821
822 //=== Check that prior elements are positive
823 for (i=0; i < nstates; i++)
824 for (j=0; j < nstates; j++)
825 if (ElementM(Prior,i,j) <= 0) return 0;
826
827 //=== Check that prior elements are large enough given the restrictions
828 for (q=total_Dirichlet_parameters-1; q >= 0; q--)
829 {
830 alpha=1.0;
831 for (j=0; j < nstates; j++)
832 for (i=0; i < nstates; i++)
833 if (NonZeroIndex[i][j] == q)
834 alpha+=ElementM(Prior,i,j)-1.0;
835 if (alpha <= 0) return 0;
836 }
837
838 return 1;
839 }
840
841 /*
842 Assumes:
843 b : n dimensional array
844 alpha : n dimensional array with positive elements
845 n : positive integer
846
847 Results:
848 Fills the vector b with a draw from the Dirichlet distribution with
849 parameters given by alpha. The density of the Dirichlet distribution is
850
851
852 Gamma(Sum(alpha[i], 0 <= i < n))
853 -------------------------------------- Product(b[i]^(alpha[i]-1), 0 <= i < n)
854 Product(Gamma(alpha[i]), 0 <= i < n)
855
856 Notes:
857 The arguments b and alpha do not have to be distinct.
858
859 A gamma deviate is positive with probability one. This code calls
860 dw_gamma_rnd(), but does not check if the returned value is positive.
861 If all calls of dw_gamma_rnd() returned zero, then the return vector would
862 identically zero, which is not a permissible value for a Dirichlet random
863 vector.
864 */
865 void DrawDirichlet(PRECISION *b, PRECISION *alpha, int n)
866 {
867 int i;
868 PRECISION scale=0.0;
869 for (i=n-1; i >= 0; i--) scale+=(b[i]=dw_gamma_rnd(alpha[i]));
870 if (scale > 0)
871 for (scale=1.0/scale, i=n-1; i >= 0; i--) b[i]*=scale;
872 }
873
874 /*
875 Assumes:
876 b : n dimensional array
877 alpha : n dimensional array with positive elements
878 n : positive integer
879
880 Results:
881 Fills the vector b with a draw from the Dirichlet distribution with
882 parameters given by alpha. The density of the Dirichlet distribution is
883
884
885 Gamma(Sum(alpha[i], 0 <= i < n))
886 -------------------------------------- Product(b[i]^(alpha[i]-1), 0 <= i < n)
887 Product(Gamma(alpha[i]), 0 <= i < n)
888
889 Returns:
890 Returns the value of
891
892 ln(Product(b[i]^(alpha[i]-1), 0 <= i < n))
893
894 evaluated at the draw.
895
896 Notes:
897 The arguments b and alpha do not have to be distinct.
898
899 A gamma deviate is positive with probability one. This code calls
900 dw_gamma_rnd(), but does not check if the returned value is positive.
901 A return of zero would cause this routine to crash.
902 */
903 PRECISION DrawDirichlet_kernel(PRECISION *b, PRECISION *alpha, int n)
904 {
905 int i;
906 PRECISION log_kernel, sum_alpha, scale, a;
907 for (log_kernel=sum_alpha=scale=0.0, i=n-1; i >= 0; i--)
908 {
909 a=alpha[i]-1;
910 scale+=(b[i]=dw_gamma_rnd(alpha[i]));
911 sum_alpha+=a;
912 log_kernel+=a*log(b[i]);
913 }
914 for (scale=1.0/scale, i=n-1; i >= 0; i--) b[i]*=scale;
915 return log_kernel + log(scale)*sum_alpha;
916 }
917
918 /*
919 Assumes:
920 q : n-1 dimensional array
921 alpha : n dimensional array with positive elements
922
923 Results:
924 Fills q with a draw from the Dirichlet distribution with parameters given by
925 alpha. The density of the Dirichlet distribution is
926
927 Gamma(Sum(alpha[i],0 <= i < n))
928 -------------------------------------- Product(q[i]^(alpha[i] - 1), 0 <= i < n)
929 Product(Gamma(alpha[i]), 0 <= i < n)
930
931 Notes:
932 Only the first n-1 elements are returned. The nth element will be equal to
933 one minus the sum of the first n-1 elements.
934 */
935 void DrawDirichlet_free(PRECISION *q, PRECISION *alpha, int n)
936 {
937 int i;
938 PRECISION scale=dw_gamma_rnd(alpha[n-1]);
939
940 for (i=n-2; i >= 0; i--)
941 scale+=(q[i]=dw_gamma_rnd(alpha[i]));
942
943 if (scale > 0)
944 for (scale=1.0/scale, i=n-2; i >= 0; i--) q[i]*=scale;
945 }
946
947 /*
948 Assumes:
949 q : n-1 dimensional array with non-negative elements whose sum is less
950 than or equal to one.
951 alpha : n dimensional array with positive elements
952
953 Returns:
954 The log value of the Dirichlet density with parameters alpha evaluated at q.
955 Return MINUS_INFINITY if the restrictions on q are violated.
956
957 Notes:
958 The Dirichlet density is given by
959
960 Gamma(Sum(alpha[i],0 <= i < n))
961 -------------------------------------- Product(q[i]^(alpha[i] - 1), 0 <= i < n)
962 Product(Gamma(alpha[i]), 0 <= i < n)
963 */
964 PRECISION LogDirichlet_pdf(PRECISION *q, PRECISION *alpha, int n)
965 {
966 PRECISION sum_q=1.0, sum_alpha=alpha[n-1], log_pdf=-dw_log_gamma(alpha[n-1]);
967 int i;
968 for (i=n-2; i >= 0; i--)
969 if (q[i] > 0.0)
970 {
971 sum_q-=q[i];
972 sum_alpha+=alpha[i];
973 log_pdf+=(alpha[i]-1.0)*log(q[i]) - dw_log_gamma(alpha[i]);
974 }
975 else
976 if (alpha[i] != 1.0)
977 {
978 log_pdf=(alpha[i]-1.0);
979 for ( ; i >= 0; i--)
980 if (q[i] > 0.0)
981 sum_q-=q[i];
982 else
983 log_pdf+=(alpha[i]-1.0);
984 if (sum_q <= 0.0)
985 log_pdf+=alpha[n-1]-1.0;
986 return (log_pdf > 0) ? MINUS_INFINITY : PLUS_INFINITY;
987 }
988 if (sum_q > 0.0)
989 return log_pdf + (alpha[n-1]-1.0)*log(sum_q) + dw_log_gamma(sum_alpha);
990 else
991 if (alpha[n-1] == 1.0)
992 return log_pdf + dw_log_gamma(sum_alpha);
993 else
994 return (alpha[n-1] > 1.0) ? MINUS_INFINITY : PLUS_INFINITY;//}
995 }
996
997 /*
998 Assumes:
999 q : n-1 dimensional vector with non-negative elements whose sum is less
1000 than or equal to one.
1001 alpha : n dimensional array with positive elements
1002
1003 Returns:
1004 The log value of a Dirichlet kernal with parameters alpha evaluated at q.
1005 Returns MINUS_INFINITY if the restrictions on q are violated.
1006
1007 Notes:
1008 The Dirichlet density is given by
1009
1010 Gamma(Sum(alpha[i],0 <= i < n))
1011 -------------------------------------- Product(q[i]^(alpha[i]-1), 0 <= i < n)
1012 Product(Gamma(alpha[i]), 0 <= i < n)
1013
1014 The kernal returned is given by
1015
1016 ln(Product(q[i]^(alpha[i]-1), 0 <= i < n))
1017
1018 q[n-1] in the above formulas is defined to be 1 - Sum(q[i], 0 <= i < n-1).
1019
1020 It is more efficient to evaluate the kernel than the pdf since the gamma
1021 functions do not have to be evaluated.
1022 */
1023 PRECISION LogDirichlet_kernel(PRECISION *q, PRECISION *alpha, int n)
1024 {
1025 PRECISION sum=1.0, log_kernel=0.0;
1026 int i;
1027 for (i=n-2; i >= 0; i--)
1028 if (q[i] > 0.0)
1029 {
1030 sum-=q[i];
1031 log_kernel+=(alpha[i]-1.0)*log(q[i]);
1032 }
1033 else
1034 if (alpha[i] != 1.0)
1035 {
1036 log_kernel=(alpha[i]-1.0);
1037 for ( ; i >= 0; i--)
1038 if (q[i] > 0.0)
1039 sum-=q[i];
1040 else
1041 log_kernel+=(alpha[i]-1.0);
1042 if (sum <= 0.0)
1043 log_kernel+=alpha[n-1]-1.0;
1044 return (log_kernel > 0) ? MINUS_INFINITY : PLUS_INFINITY;
1045 }
1046 if (sum > 0.0)
1047 return log_kernel + (alpha[n-1]-1.0)*log(sum);
1048 else
1049 if (alpha[n-1] == 1.0)
1050 return log_kernel;
1051 else
1052 return (alpha[n-1] > 1.0) ? MINUS_INFINITY : PLUS_INFINITY;
1053 }
1054
1055 /*
1056 Assumes:
1057 q : (m-n)-dimensional array
1058 alpha : m-dimensional array with positive elements greater
1059
1060 Results:
1061 Fills the q with independent draws from the Dirichlet distribution with
1062 parameters given by alpha.
1063
1064 Notes:
1065 m is equal to the sum of the elements of dirichlet_dims.
1066 */
1067 void DrawIndependentDirichlet_free(PRECISION *q, PRECISION *alpha, int *dirichlet_dims, int n)
1068 {
1069 int i, j, k;
1070 for (i=j=k=0; i < n; j+=dirichlet_dims[i], k+=dirichlet_dims[i]-1, i++)
1071 DrawDirichlet_free(q+k,alpha+j,dirichlet_dims[i]);
1072 }
1073
1074 /*
1075 Assumes:
1076 q : (m-n)-dimensional array
1077 alpha : m-dimensional array with positive elements
1078
1079 Returns:
1080 The sum of the log values of the Dirichlet densities with parameters alpha
1081 evaluated at q.
1082
1083 Notes:
1084 m is equal to the sum of the elements of dirichlet_dims.
1085 */
1086 PRECISION LogIndependentDirichlet_pdf(PRECISION *q, PRECISION *alpha, int *dirichlet_dims, int n)
1087 {
1088 int i, j, k;
1089 PRECISION log_pdf=0.0;
1090 for (i=j=k=0; i < n; j+=dirichlet_dims[i], k+=dirichlet_dims[i]-1, i++)
1091 log_pdf+=LogDirichlet_pdf(q+k,alpha+j,dirichlet_dims[i]);
1092 return log_pdf;
1093 }
1094 /*******************************************************************************/
1095 /*******************************************************************************/
1096 /*******************************************************************************/