Debian Codegraph @

contrib/ms-sbvar/switch_dw/switching/dw_switch.h

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 #ifndef __MARKOV_SWITCHING__
19 #define __MARKOV_SWITCHING__
20
21 #ifdef __cplusplus
22 extern "C"
23 {
24 #endif
25
26 #define __SWITCHING_VER_200__
27
28 #include "dw_matrix.h"
29 #include <stdio.h>
30
31
32 //=== Declaring structures so pointers can be defined ===
33 struct TMarkovStateVariable_tag;
34 struct TStateModel_tag;
35 struct TMetropolis_theta_tag;
36
37
38 /*******************************************************************************/
39 /********************************** QRoutines **********************************/
40 /*******************************************************************************/
41 typedef struct
42 {
43 // required routines
44 int (*Probability_s0)(TVector p, struct TMarkovStateVariable_tag*);
45 int (*ComputeTransitionMatrix)(int t, struct TMarkovStateVariable_tag*, struct TStateModel_tag*);
46 PRECISION (*pLogPrior)(struct TMarkovStateVariable_tag*);
47
48 // simulation routines
49 PRECISION (*DrawProposalTransitionMatrixParameters)(int*, struct TMarkovStateVariable_tag*, struct TStateModel_tag*);
50 int (*DrawTransitionMatrixParameters)(int*, struct TMarkovStateVariable_tag*, struct TStateModel_tag*);
51 int (*pDrawTransitionMatrixParametersFromPrior)(struct TMarkovStateVariable_tag*);
52
53 // memory management
54 void (*FreeInfo)(void*);
55 void* (*DuplicateInfo)(void*);
56
57 // io routines
58 int (*WriteSpecification)(FILE*, struct TMarkovStateVariable_tag*, char*);
59
60 // miscellaneous routines
61 int (*DefaultTransitionMatrixParameters)(struct TMarkovStateVariable_tag*, struct TStateModel_tag*);
62 int (*Update_q_from_BaseTransitionMatrix)(int, struct TMarkovStateVariable_tag*, struct TStateModel_tag*);
63
64 } QRoutines;
65
66 //=== Constructors ===
67 QRoutines* CreateQRoutines_empty(void);
68 QRoutines* DuplicateQRoutines(QRoutines *routines);
69
70 /*******************************************************************************/
71 /*******************************************************************************/
72 /*******************************************************************************/
73
74
75 /*******************************************************************************/
76 /******************************** ThetaRoutines ********************************/
77 /*******************************************************************************/
78 typedef struct
79 {
80 //=== Computes ln(P(y[t] | Y[t-1], Z[t], theta, q, s[t] = s)) ===
81 PRECISION (*pLogConditionalLikelihood)(int s, int t, struct TStateModel_tag *model);
82
83 //=== Computes Log of the prior on the model specific parameters ===
84 PRECISION (*pLogPrior)(struct TStateModel_tag *);
85
86 //=== Computes E[y[t] | Y[t-1], Z[t], theta, q, s[t] = s] ===
87 TVector (*pExpectationSingleStep)(TVector y, int s, int t, struct TStateModel_tag *model);
88
89 //=== Computes E[epsilon[t] | Y[T], Z[T], theta, q, s[t] = s] ===
90 TVector (*pExpectedError)(TVector epsilon, int s, int t, struct TStateModel_tag *model);
91
92 //=== Computes E[y[t] | Y[t-1], Z[t], theta, q, s[t] = s], works even for t > T, ===
93 //=== data[tau] = Y[T+tau+1], assumes exogeneous variable z[t] is deterministic ===
94 TVector (*pEyt)(TVector y, int T, TVector *data, int s, int t, struct TStateModel_tag *model);
95
96 //=== Computes E[y[t] | Y[t-1], Z[t], theta, q, s[t] = s, shock(i)], shock(i) is the unit ===
97 //=== value of the model specific ith shock, works even for t > T, data[tau] = Y[T+tau+1], ===
98 //=== assumes exogeneous variable z[t] is deterministic ===
99 TVector (*pEyt_i)(TVector y, int T, TVector *data, int i, int s, int t, struct TStateModel_tag *model);
100
101 //=== Makes random draw of y[t] given Y[t-1], Z[t], theta, q, s[t] = s, works for t > T, ===
102 //=== data[tau] = Y[T+tau+1], assumes exogeneous variable z[t] is deterministic ===
103 TVector (*pyt_draw)(TVector y, int T, TVector *data, int s, int t, struct TStateModel_tag *model);
104
105 //=== Destructs parameters ===
106 void (*pDestructor)(void *);
107
108 //=== Draws parameters conditional states and transition probability ===
109 void (*pDrawParameters)(struct TStateModel_tag *);
110 void (*pDrawParametersFromPrior)(struct TStateModel_tag *);
111
112 //=== Converts between free parameters and model specific parameters ===
113 int (*pNumberFreeParametersTheta)(struct TStateModel_tag*);
114 void (*pConvertFreeParametersToTheta)(struct TStateModel_tag*, PRECISION*);
115 void (*pConvertThetaToFreeParameters)(struct TStateModel_tag*, PRECISION*);
116
117 //=== Notification routines ===
118 void (*pStatesChanged)(struct TStateModel_tag*);
119 void (*pThetaChanged)(struct TStateModel_tag*);
120 void (*pTransitionMatrixParametersChanged)(struct TStateModel_tag*);
121 int (*pValidTheta)(struct TStateModel_tag*);
122
123 //=== Allows for initialization of data structures before forward recursion ===
124 int (*pInitializeForwardRecursion)(struct TStateModel_tag*);
125
126 //=== Permutes the elements of theta ===
127 /* int (*pPermuteTheta)(int*, struct TStateModel_tag*); */
128 /* int (*pGetNormalization)(int*, struct TStateModel_tag*); */
129 /* int (*pNormalizeRegimes)(struct TStateModel_tag*); // sets array normalized_regimes and returns 1 if normalization is necessary */
130 /* PRECISION (*pLogConstant_RegimeNormalization)(struct TStateModel_tag*); // */
131
132 //=== Identifies model type ===
133 char* (*pModelType)(void);
134
135 //=== Checks if draw of regimes is degenerate
136 int (*pIsDegenerate)(int*, struct TStateModel_tag*);
137
138 //=== Normalizing regimes
139 int (*pComputeNormalizingPermutation)(int*, struct TStateModel_tag*);
140 int (*pNormalizeRegimes)(int*, struct TStateModel_tag*, PRECISION*);
141 int (*pComputeRegimeNormalizationLogConstant)(struct TStateModel_tag*);
142
143 } ThetaRoutines;
144
145 //=== Constructors ===
146 ThetaRoutines* CreateThetaRoutines_empty(void);
147
148 /*******************************************************************************/
149 /*******************************************************************************/
150 /*******************************************************************************/
151
152
153 /*******************************************************************************/
154 /**************************** TMarkovStateVariable *****************************/
155 /*******************************************************************************/
156 typedef struct TMarkovStateVariable_tag
157 {
158 //=== Flags ===================================================================
159 // The transition matrix Q is valid for t0 <= t <= t1.
160 int t0, t1;
161
162 //=== Lag encoding ============================================================
163 // Number of lags encoded. Must be non-negative.
164 int nlags_encoded;
165
166 // Number of base states. Note that nbasestates^(nlags_encoded+1) = nstates.
167 int nbasestates;
168
169 // nstates x (nlags_encoded + 1). lag_index[k][j] is the value of the jth
170 // lag when the overall state is k.
171 int** lag_index;
172
173 // Base transition matrix. This is filled via a call to
174 // sv_ComputeTransitionMatrix)(t,*,*). If n_state_variables is 1, then
175 // baseQ = state_variable[0]->Q (as pointers!)
176 TMatrix baseQ;
177
178 //=== Sizes ===================================================================
179 // Equal to nbasestates^(nlags_encoded + 1).
180 int nstates;
181
182 // Number of free parameters in transition matrix (either Q or baseQ).
183 int nfree;
184
185 //=== Transition matrix =======================================================
186 // Q(i,j) is the probability that s(t+1) = i given s(t)=j. This is filled via
187 // a call to sv_ComputeTransitionMatrix)(t,*,*). If nlags_encoded is 0, then
188 // Q = baseQ (as pointers!)
189 TMatrix Q;
190
191 //=== Free parameters =========================================================
192 // Free parameters. This memory is tightly managed and NOT owned by the
193 // structure!
194 PRECISION *q;
195
196 //=== Parent Markov state variable ============================================
197 // Either parent state variable or null pointer.
198 struct TMarkovStateVariable_tag *parent;
199
200 //=== Multiple state variables ================================================
201 // number of independent state_variables
202 int n_state_variables;
203
204 // Independent state variables. Must have been created via a call to
205 // dw_CreateArray_pointer(n_state_variables,(void (*)(void*))FreeMarkovStateVariable);
206 struct TMarkovStateVariable_tag **state_variable;
207
208 // nbasestates x n_state_variables. index[k][j] is the value of the jth state
209 // variable when the basestate state is k.
210 int** index;
211
212 // QA[j] = state_variable[j]->Q (as pointers!). Currently, this is only used
213 // in computing Kronecker products of transistion matrices.
214 TMatrix *QA;
215
216 //=== Routines ================================================================
217 // See QRoutines for list of available functions.
218 QRoutines *routines;
219
220 // Information for manipulating free transition matrix parameters.
221 void *info;
222
223 } TMarkovStateVariable;
224
225 //=== Constructors and destructors ===
226 void FreeMarkovStateVariable(TMarkovStateVariable *sv);
227 TMarkovStateVariable* CreateMarkovStateVariable_Single(int nstates, int nfree, int nlags, QRoutines *routines, void *info);
228 TMarkovStateVariable* CreateMarkovStateVariable_Multiple(int nlags, TMarkovStateVariable **state_variables);
229 TMarkovStateVariable* CreateMarkovStateVariable_base(int nlags_encoded, TMarkovStateVariable *sv);
230 TMarkovStateVariable* CreateMarkovStateVariable_lags(int nlags_encoded, TMarkovStateVariable *sv);
231 #define DuplicateMarkovStateVariable(sv) CreateMarkovStateVariable_base((sv)->nlags_encoded,sv)
232
233 //=== Base routines ===
234 void sv_SetupFreeParameters(PRECISION *q, TMarkovStateVariable *sv);
235 void sv_InvalidateTransitionMatrix(TMarkovStateVariable *sv);
236 int sv_ComputeTransitionMatrix(int t, TMarkovStateVariable *sv, struct TStateModel_tag *model);
237 PRECISION sv_LogPrior(TMarkovStateVariable *sv);
238 int sv_Probability_s0(TVector p, TMarkovStateVariable *sv);
239
240 PRECISION sv_DrawProposalTransitionMatrixParameters(int *S, TMarkovStateVariable *sv, struct TStateModel_tag *model);
241 int sv_DrawTransitionMatrixParameters(int *S, TMarkovStateVariable *sv, struct TStateModel_tag *model);
242 int sv_DrawTransitionMatrixParametersFromPrior(TMarkovStateVariable *sv);
243 int sv_DefaultTransitionMatrixParameters(TMarkovStateVariable *sv, struct TStateModel_tag *model);
244
245 int sv_ValidRoutines(TMarkovStateVariable *sv);
246 int sv_ValidMetropolisHastings(TMarkovStateVariable *sv);
247 int sv_ValidDirectDraw(TMarkovStateVariable *sv);
248
249 //=== Lag routines ===
250 void ConvertBaseTransitionMatrix(TMatrix Q, TMatrix baseQ, int nlags_encoded);
251 int** CreateLagIndex(int nbasestates, int nlags, int nstates);
252 TVector* sv_BaseProbabilities(TVector *base_prob, TVector *prob, TMarkovStateVariable *sv);
253 TVector* sv_FullBaseProbabilities(TVector *prob, TMarkovStateVariable *sv);
254
255 //=== Normalization routines ===
256 int sv_NormalizeRegimes(int *p, int t, TMarkovStateVariable *sv, struct TStateModel_tag *model);
257 /*******************************************************************************/
258 /*******************************************************************************/
259 /*******************************************************************************/
260
261 /*******************************************************************************/
262 /********************************* TStateModel *********************************/
263 /*******************************************************************************/
264 typedef struct TStateModel_tag
265 {
266 //=== Markov state variable ===
267 TMarkovStateVariable *sv;
268 PRECISION *q; // free transition matrix parameters
269 int* S; // integer array of length nobs+1
270
271 // Metropolis-Hasting information for q
272 int use_metropolis_hasting;
273 int metropolis_jumps_q;
274 int metropolis_draws_q;
275
276 // Regime normalization
277 int kill_unnormalized;
278 PRECISION regime_normalization_logconstant;
279 int *normalized_regimes; // integer array of lenth sv->nstates. If s_t is the internal representation
280 // of the regime and s_hat_t is the external representation of the regime, then
281 // s_t = normalized_regimes[s_hat_t].
282
283 //=== Data bounds ===
284 int fobs; // first observation for the purpose of computing LogLikelihood_StatesIntegratedOut()
285 int nobs; // number of observations
286
287 //=== Simulation information ===
288 PRECISION max_log_posterior;
289 TVector max_posterior_theta;
290 TVector max_posterior_q;
291
292 //=== Notification flags ===
293 int ForwardRecursionFailed;
294
295 //=== Common work space ===
296 int SP_Computed; // SP[t](i) is valid for 0 <= t <= nobs and 0 <= i < nstates
297 int t0; // C[t], V[t], Z[t], and L(t) are valid for t <= t0
298 TVector *C; // C[t](i) = ln(P(y[t] | Y[t-1], Z[t], s[t]=i, theta, q)) for 0 < t <= nobs, 0 <= i < nstates, and Z[t][i] > 0.0
299 TVector *V; // V[t](i) = P(s[t] = i | Y[t], Z[t], theta, q) 0 <= t <= nobs and 0 <= i < nstates
300 TVector *Z; // Z[t](i) = P(s[t] = i | Y[t-1], Z[t-1], theta, q) 0 < t <= nobs and 0 <= i < nstates
301 TVector L; // L(t) = ln(P(Y[t] | Z[t], theta, q)) 0 <= t <= nobs
302 //TMatrix *W; // W[t](i,j) = P(s[t-1]=i | Y[t], Z[t], theta, q, s[t]=j) 0 < t < nobs, 0 <= i,j < nstates
303 TVector *SP; // SP[t](i) = P(s[t] = i | Y[T], Z[T], theta, q) 0 <= t <= nobs, 0 <= i < nstates
304
305 //=== Model specific parameters and routines to handle them ===
306 void *theta;
307 ThetaRoutines *routines;
308
309 // Metropolis information for theta
310 struct TMetropolis_theta_tag *metropolis_theta;
311
312 //=== Control variables ===
313 int NormalizeStates;
314
315 //=== Degenerate draws of states
316 int reject_degenerate_draws; // if positive, reject degenerate draws of states. value determines how many attempts to make before exiting
317 int degenerate_draws_cutoff; // number of draws needed for each state in order not to be degenerate
318 int n_degenerate_draws; // counter for number of degenerate draws of states
319 int total_degenerate_draws; // counter for total number of degenerate draws
320
321 } TStateModel;
322
323 //=== Constructors/Destructors ===
324 void FreeStateModel(TStateModel *model);
325 TStateModel* CreateStateModel(int nobs, TMarkovStateVariable *sv, ThetaRoutines *routines, void *theta);
326
327 //=== Notification routines ===
328 void StatesChanged(TStateModel *model);
329 void TransitionMatrixParametersChanged(TStateModel *model);
330 void ThetaChanged(TStateModel *model);
331 #define ValidTheta(model) (((model)->routines->pValidTheta) ? (model)->routines->pValidTheta(model) : 1)
332
333 //=== Transition matrix routines ===
334 int ComputeTransitionMatrix(int t, TStateModel *model);
335 int Probability_s0(TVector p, TStateModel *model);
336 TVector* BaseProbabilities(TVector *base_prob, TVector *prob, TStateModel *model);
337
338 //=== Simulation routines ===
339 int ForwardRecursion(int t, TStateModel *model);
340 #define InitializeForwardRecursion(model) (((model)->routines->pInitializeForwardRecursion) ? (model)->routines->pInitializeForwardRecursion(model) : 1)
341 int ComputeSmoothedProbabilities(TStateModel *model);
342 int DrawStates(TStateModel *model);
343 #define IsDegenerate(regime_counts,model) (((model)->routines->pIsDegenerate) ? (model)->routines->pIsDegenerate(regime_counts,model) : 0)
344 int DrawStatesFromTransitionMatrices(TStateModel *model);
345 int DrawTransitionMatrixParameters(TStateModel *model);
346 void ResetMetropolisHastingsCounts_q(TStateModel *model);
347 int DrawTransitionMatrixParameters_MetropolisHastings(TStateModel *model);
348 int DrawTransitionMatrixParametersFromPrior(TStateModel *model);
349 int DefaultTransitionMatrixParameters(TStateModel *model);
350 void DrawTheta(TStateModel *model);
351 void DrawThetaFromPrior(TStateModel *model);
352 void DrawAll(TStateModel *model);
353
354 //=== Regime normalization ===
355 #define ComputeNormalizingPermutation(permutation,model) (((model)->routines->pComputeNormalizingPermutation) ? (model)->routines->pComputeNormalizingPermutation(permutation,model) : 0)
356 #define ComputeRegimeNormalizationLogConstant(model) (((model)->routines->pComputeRegimeNormalizationConstant) ? (model)->routines->pComputeRegimeNormalizationConstant(model) : 0)
357 int AreRegimesNormalized(int *permutation, TStateModel *model);
358 int NormalizeRegimes(int *permutation, TStateModel *model, PRECISION *buffer);
359
360 //=== Impulse responses and forecasts ===
361 TMatrix ImpluseResponse(TMatrix IR, int i, int T, int horizon, TStateModel *model);
362 TMatrix ForecastMean(TMatrix F, int T, int horizon, TStateModel *model);
363 TMatrix ForecastRandom(TMatrix F, int T, int horizon, TStateModel *model);
364 #define Eyt(y,T,data,s,t,model) ((model)->routines->pEyt ? (model)->routines->pEyt(y,T,data,s,t,model) : (TVector)NULL)
365 #define Eyt_i(y,T,data,i,s,t,model) ((model)->routines->pEyt_i ? (model)->routines->pEyt_i(y,T,data,i,s,t,model) : (TVector)NULL)
366 #define yt_draw(y,T,data,s,t,model) ((model)->routines->pyt_draw ? (model)->routines->pyt_draw(y,T,data,s,t,model) :(TVector)NULL)
367
368
369 //=== Probability routines ===
370 // ln(P(y[t] | Y[t-1], Z[t], s[t], theta, q))
371 #define LogConditionalLikelihood(s,t,model) ((model)->routines->pLogConditionalLikelihood(s,t,model))
372
373 // ln(P(y[t] | Y[t-1], Z[t], theta, q))
374 PRECISION LogConditionalLikelihood_StatesIntegratedOut(int t, TStateModel *model);
375
376 // E[y[t] | Y[t-1], Z[t], s[t], theta, q]
377 #define ExpectationSingleStep(y,s,t,model) ((model)->routines->pExpectationSingleStep(y,s,t,model))
378
379 // E[y[t] | Y[t-1], Z[t], theta, q]
380 TVector ExpectationSingleStep_StatesIntegratedOut(TVector y, int t, TStateModel *model);
381
382 // E[epsilon[t] | Y[T], Z[t], theta, q]
383 TVector ExpectedError(TVector epsilon, int t, TStateModel *model);
384
385 // ln(P(q))
386 #define LogPrior_q(model) sv_LogPrior((model)->sv)
387
388 // ln(P(theta))
389 #define LogPrior_theta(model) ((model)->routines->pLogPrior(model))
390
391 // ln(P(theta, q))
392 #define LogPrior(model) (LogPrior_theta(model) + LogPrior_q(model))
393
394 // ln(P(S[T] | theta, q))
395 PRECISION LogPrior_S(TStateModel *model);
396
397 // ln(P(Y[T] | Z[T], S[T], theta, q)) - Assumes that the data is for fobs <= t <= nobs
398 PRECISION LogLikelihood(TStateModel *model);
399
400 // ln(P(Y[T] | Z[T], S[T], theta, q) * P(S[T] | theta, q) * P(theta, q))
401 #define LogPosterior(model) (LogLikelihood(model) + LogPrior_S(model) + LogPrior(model))
402
403 // ln(P(Y[T] | Z[T], theta, q)) - Assumes that the data is for fobs <= t <= nobs
404 PRECISION LogLikelihood_StatesIntegratedOut(TStateModel *model);
405
406 // ln(P(Y[T] | Z[T], theta, q) * P(theta, q))
407 PRECISION LogPosterior_StatesIntegratedOut(TStateModel *model);
408
409 // P(s[t] = s | Y[t], Z[t], theta, q)
410 PRECISION ProbabilityStateConditionalCurrent(int s, int t, TStateModel *model);
411
412 // P(s[t] = s | Y[t-1], Z[t-1], theta, q)
413 PRECISION ProbabilityStateConditionalPrevious(int s, int t, TStateModel *model);
414
415 // Sum(P(s[t] = k | Y[t], Z[t], theta, q), where lag_index[k][0] = s)
416 PRECISION ProbabilityBaseStateConditionalCurrent(int s, int t, TStateModel *model);
417
418 // ln(P(S[T] = S | Y[T], Z[T], theta, q))
419 PRECISION LogProbabilityStates(int *S, TStateModel *model);
420
421 // p[t] = P(s[t] = s | Y[T], Z[T], theta, q)
422 TVector ProbabilitiesState(TVector p, int s, TStateModel *model);
423
424 // p[t][s] = P(s[t] = s | Y[tau], Z[tau], theta, q)
425 TVector* RealTimeSmoothedProbabilities(TVector *p, int tau, TStateModel *model);
426
427 //=== Free parameters routines ===
428 #define NumberFreeParametersQ(model) ((model)->sv->nfree)
429 void ConvertQToFreeParameters(TStateModel *model, PRECISION *f);
430 void ConvertFreeParametersToQ(TStateModel *model, PRECISION *f);
431
432 #define NumberFreeParametersTheta(model) ((model)->routines->pNumberFreeParametersTheta(model))
433 #define ConvertThetaToFreeParameters(model,f) ((model)->routines->pConvertThetaToFreeParameters(model,f))
434 void ConvertFreeParametersToTheta(TStateModel *model, PRECISION *f);
435
436 //=== Miscellaneous Routines ===
437 #define ModelType(model) ((model)->routines->pModelType ? (model)->routines->pModelType() : (char*)NULL)
438
439 /*******************************************************************************/
440 /*******************************************************************************/
441 /*******************************************************************************/
442
443 //=== Utility routines ===
444 TVector Ergodic(TVector v, TMatrix P);
445 int DrawDiscrete(TVector p);
446 TVector* IntegrateStatesSingleV(TVector *Y, TVector P, TVector *X, int a, int b, int c);
447 TMatrix* IntegrateStatesSingleM(TMatrix *Y, TVector P, TMatrix *X, int a, int b, int c);
448 TVector** IntegrateStatesV(TVector **Y, TVector* P, TVector **X, int a, int b, int c);
449 TVector IntegrateStatesSingle(TVector Q, TVector P, int a, int b, int c);
450 TVector* IntegrateStates(TVector *Q, TVector* P, int a, int b, int c);
451 /*******************************************************************************/
452 /*******************************************************************************/
453 /*******************************************************************************/
454
455
456 //=== Obsolete names ===
457 #define ProbabilityStateGivenCurrentData(s,t,model) ProbabilityStateConditionalCurrent(s,t,model)
458 #define ProbabilityStateGivenPreviousData(s,t,model) ProbabilityStateConditionalPrevious(s,t,model)
459 #define ProbabilityStateGivenAllData(P,s,model) ProbabilitiesState(P,s,model)
460 //PRECISION ProbabilityStatesGivenData(TStateModel *model);
461 #define LogLikelihoodGivenParameters(model) LogLikelihood_StatesIntegratedOut(model)
462 #define LogConditionalProbabilityStates(S, model) LogProbabilityStates(S, model)
463 #define LogConditionalPrior_S(model) LogPrior_S(model)
464 //PRECISION LogMarginalPosterior(TStateModel *model);
465 //void DrawAllParameters(TMarkovStateVariable *sv);
466 //void DrawAllParametersAndNormalizeStates(TMarkovStateVariable *sv);
467 //PRECISION ComputeMarginalLogLikelihood(TMarkovStateVariable *sv);
468 /*******************************************************************************/
469 /*******************************************************************************/
470 /*******************************************************************************/
471
472 #ifdef __cplusplus
473 }
474 #endif
475
476 #endif
477
478 /***************************** TMarkovStateVariable *****************************
479 The TMarkovStateVariable type can represent either a single Markov state
480 variable or a collection of independent Markov state variables.
481
482 The transition matrix Q is generated for a single Markov state variable via
483 the routines DrawTransitionMatrixFromPrior_SV() or DrawTransitionMatrix_SV().
484 Calls to these functions by multiple independent Markov state variables result
485 in recursive call to these functions.
486
487 The vector of states S is generated only by a TStateModel structure containing
488 the TMarkovStateVariable structure. The state is only generated at the top
489 level and can be propagated downward with a call to PropagateStates_SV().
490
491 The following set of fields are set for both types.
492 ===============================================================================
493 int UseErgodic
494 Uses the ergodic distribution if non-zero and uses the uniform distribution
495 otherwise.
496
497 int nstates
498 Number of states. Always positive.
499
500 int nobs
501 Number of observations. Always positive.
502
503 int* S
504 S[t] is the state at time t, for 0 <= t <= nobs. S is created via a call
505 to dw_CreateArray_int(). It is guaranteed that 0 <= S[t] < nstates.
506
507 TMatrix Q
508 Markov transition matrix.
509
510 struct TMarkovStateVariable_tag *parent
511 Parent of the Markov state variable. If the Markov state variable has no
512 parent, then parent is a null pointer.
513
514 int n_state_variables
515 Number of state variables. Will be equal to zero for single Markov state
516 variables and larger than one in the case of multiple independent Markov
517 state variables. A value of one can be used to encode additional lagged
518 values of the states.
519
520 struct TMarkovStateVariable_tag **state_variable
521 An array of markov state variables of length n_state_variables. When
522 creating a mulitple Markov state variable via a call to the routine
523 CreateMarkovStateVariable_Multiple(), the last argument which is a pointer
524 to a pointer to a TMarkovStateVariable must have been created with
525
526 dw_CreateArray_pointer(n_state_variables,(void (*)(void*))FreeMarkovStateVariable);
527
528 Furthermore, the structure receives ownership of this argument and is
529 responsible for its freeing.
530
531 int** Index
532 This is a nstates x n_state_variables rectangular array of integers. State
533 s corresponds to state_variable[i] being equal to Index[s][i].
534
535 int** SA
536 An array of integer pointers of length n_state_variables. The pointers SA[i]
537 and state_variable[i]->S point to the same address.
538
539 TMatrix* QA
540 An array of matrices of length n_state_variables. The matrix QA[i] is
541 is the matrix state_variable[i]->Q.
542
543 ===============================================================================
544 The TMarkovStateVariable routines must follow the following specification.
545
546 TMatrix (*ComputeTransitionMatrix)(TMatrix Q, int t, TMarkovStateVariable *sv)
547 Upon success, sv->Q will contain the transistion matrix valid at time t. The
548 fields sv->t0 and sv->t1 will be updated so that sv->t0 <= t <= sv->t1 and
549 the transition matrix will be valid for all t between sv->t0 and sv->t1,
550 inclusive. The matrix sv->Q will be return. Upon failure, a null pointer
551 will be returned.
552
553 ===============================================================================
554 The following fields are set only for single Markov state variables and are
555 set to null for multiple independent Markov state variables.
556
557 TVector B
558 The vector B is the vector of quasi-free parameters.
559
560 TVector *b
561 Array of vectors of length DimA(FreeDim). The element b[k] is of length
562 FreeDim[k]. Non-standard memory management is used so that
563
564 &(b[k][i])=&B[FreeDim[0] + ... + FreeDim[k-1] + i])
565
566 The elements of b[k] are non-negative and their sum equals one up to
567 DimV(b[k])*MACHINE_EPSILON.
568
569 TMatrix Prior
570 Prior Dirichlet parameters for Q.
571
572 TVector *Prior_b
573 The Dirichlet prior parametrs for b. Array of vectors of length
574 DimA(FreeDim). The element Prior_b[k] is of length FreeDim[k].
575 Non-standard memory management is used so that
576
577 &(Prior_b[k][i])=&B[FreeDim[0] + ... + FreeDim[k-1] + i])
578
579 TVector Prior_B
580 The Dirichlet prior parameters for B. This vector is created and
581 initialized by CreateMarkovStateVariable(). The element B[k]-1 is the sum
582 of Prior[i][j]-1 over all (i,j) such that NonZeroIndex[i][j] == k.
583
584 int* FreeDim
585 FreeDim[k] is the length of the kth free Dirichlet vector. The length of B
586 must be equal to FreeDim[0] + ... + FreeDim[dw_DimA(FreeDim)-1].
587
588 int** NonZeroIndex
589 Defines the relationship between Q and B.
590 --
591 | MQ[i][j]*B[NonZeroIndex[i][j]] if NonZeroIndex[i][j] >= 0
592 Q[i][j] = |
593 | 0.0 if NonZeroIndex[i][j] == -1
594 --
595 TMatrix MQ
596 Coefficients for the elements of Q in terms of the free parameters B.
597
598
599 int nlags_encoded; // Number of lags encoded in the restrictions
600 int nbasestates; // Number of base states nbasestates^(nlags_encoded) = nstates
601 int** lag_index; // nstates x (nlags_encoded + 1) lag_index[i][j] is the value of the jth lag when the overall state is k
602
603
604 ==================================================================================
605 Old stuff
606
607 TVector* ba
608 For single Markov state variables, ba[i] = b[i]. For multiple state
609 variables ba[i] = state_variable[k]->ba[j] where
610
611 i = j + dw_DimA(state_variable[0]->ba) + ... + dw_DimA(state_variable[k-1]->ba)
612
613 TVector* Prior_ba
614 For single Markov state variables, Prior_ba[i] = Prior_b[i]. For multiple
615 state variables Prior_ba[i] = state_variable[k]->Prior_ba[j] where
616
617 i = j + dw_DimA(state_variable[0]->Prior_ba) + ... + dw_DimA(state_variable[k-1]->Prior_ba)
618
619
620 ===============================================================================
621
622
623 ===============================================================================
624 Normalization:
625 In general, a permutation of the states, together with the corresponding
626 permutation of the rows and columns of the transition matrix and the model
627 dependent parameters theta, does not change the value of the likelihood
628 function and so presents a normalization problem. However, some permutations
629 of the states are not permissible in that they may violate the restrictions
630 placed on the transition matrix or restrictions on the model dependent
631 parameters. Furthermore, even if a permutation did not cause a violation of
632 any restrictions, a non-symmetric prior on the model dependent parameters
633 could cause the value of the likelihood to change.
634
635 ********************************************************************************/
636
637
638 /*******************************************************************************/
639 /************************** QRoutines Specifications ***************************/
640 /********************************************************************************
641 int ComputeTransitionMatrix(int t, TMarkovStateVariable *sv, TStateModel *model)
642 Assumes:
643 t : 0 <= t <= model->nobs
644 sv : pointer to valid TMarkovStateVariable structure
645 model : pointer to valid TStateModel structure
646 Returns:
647 One upon success and zero on failure.
648 Results:
649 Upon success, all time t transition matrices are computed. Sets sv->t0 and
650 sv->t1.
651
652 PRECISION LogPrior_q(TMarkovStateVariable *sv)
653 Assumes:
654 sv : pointer to valid TMarkovStateVariable structure
655 Returns:
656 The natural logarithm of the properly scaled prior evaluated at sv->q.
657
658 int Probability_s0(TVector p, TMarkovStateVariable *sv)
659 Assumes:
660 p : vector of length sv->nstates
661 sv : pointer to valid TMarkovStateVariable structure
662 Returns:
663 One upon success and zero upon failure.
664 Results:
665 The value of p[i] is the probability that s0 is equal to i.
666
667 ---------------------------------------------------------------------------------
668
669 PRECISION DrawProposalTransitionMatrixParameters(int *S, TMarkovStateVariable *sv, TStateModel *model)
670 Assumes:
671 S : integer array of length model->nobs + 1 satisfying 0 <= S[t] < sv->nstates.
672 sv : pointer to valid TMarkovStateVariable structure
673 model : pointer to valid TStateModel structure
674 Returns:
675 The natural logrithm of
676 p(q_old | Y[T],Z[T],S[T],theta,q_new)/p(q_new | Y[T],Z[T],S[T],theta,q_old)
677 where p( | ) is the proposal density, q_old is the value of sv->q upon entry
678 and q_new is the value of sv->q upon exit.
679 Results:
680 Draws sv->q from the propoal density p(q_new | Y[T], Z[T], S[T], theta, q_old).
681
682 DrawTransitionMatrixParameters(int *S, TMarkovStateVariable *sv, TStateModel *model)
683 Assumes:
684 S : integer array of length model->nobs + 1 satisfying 0 <= S[t] < sv->nstates.
685 sv : pointer to valid TMarkovStateVariable structure
686 model : pointer to valid TStateModel structure
687 Returns:
688 One upon success and zero otherwise.
689 Results:
690 Draws sv->q from the conditional posterior density p(q | Y[T], Z[T], S[T], theta).
691
692 ---------------------------------------------------------------------------------
693
694 FreeInfo(void *info)
695 Assumes:
696 info : pointer to valid structure of appropriate type or null.
697 Results:
698 Properly frees info structure if it is not null.
699
700 DuplicateInfo(void *info)
701 Assumes:
702 info : pointer to valid structure of appropriate type or null.
703 Returns:
704 Pointer valid sturcture of appropriate type upon success and null otherwise.
705 Results:
706 If info is not null, creates new pointer to a structure of the appropriate
707 type and duplicates info.
708
709 int (*WriteSpecification)(FILE*, struct TMarkovStateVariable_tag*, char*);
710
711 ---------------------------------------------------------------------------------
712
713 DefaultTransitionMatrixParameters(TMarkovStateVariable *sv, TStateModel *model)
714 Assumes:
715 sv : pointer to valid TMarkovStateVariable structure
716 model : pointer to valid TStateModel structure
717 Returns:
718 One upon success and zero upon failure.
719 Results:
720 Sets sv->q to some default value.
721
722 Update_q_from_BaseTransitionMatrix(int t, TMarkovStateVariable *sv, TStateModel *model)
723 Assumes:
724 t : 0 <= t <= model->nobs
725 sv : pointer to valid TMarkovStateVariable structure
726 model : pointer to valid TStateModel structure
727 Returns:
728 One upon success and zero on failure.
729 Results:
730 Converts sv->baseQ, which is assumed to be valid for time t, to sv->q. Sets
731 sv->t0 and sv->t1.
732 *******************************************************************************/
733 /*******************************************************************************/
734 /*******************************************************************************/