samer@0
|
1 function [T,I]=sample_transmat_hdp(A0,B0,A1,B1,K,L,T0)
|
samer@0
|
2 % sample_transmat_hdp - Sample 1st order Markov transition matrix using HDP
|
samer@0
|
3 %
|
samer@0
|
4 % sample_transmat_hdp ::
|
samer@0
|
5 % nonneg ~'Shape parameter for base Dirichlet Gamma prior',
|
samer@0
|
6 % nonneg ~'Scale parameter for base Dirichlet Gamma prior',
|
samer@0
|
7 % nonneg ~'Shape parameter for sub Dirichlet Gamma prior',
|
samer@0
|
8 % nonneg ~'Scale parameter for sub Dirichlet Gamma prior',
|
samer@0
|
9 % natural ~'size of alphabet',
|
samer@0
|
10 % natural ~'num of transition matrices to produce',
|
samer@0
|
11 % -> [[K,K,L]] ~ 'lots of transition matrices',
|
samer@0
|
12 % [[L,3]] ~ 'entropy rate, redundancy, and predinfo rate for all'.
|
samer@0
|
13 %
|
samer@0
|
14 % An extra optional argument of type [[K,K]] can be added, which
|
samer@0
|
15 % is used as a sort of bias for the sampled matrices.
|
samer@0
|
16
|
samer@0
|
17 if nargin<7, T0=ones(K,K); end
|
samer@0
|
18
|
samer@0
|
19 Alpha0=gamrnd(A0,B0,1,1,L);
|
samer@0
|
20 Alpha1=gamrnd(A1,B1,1,1,L);
|
samer@0
|
21
|
samer@0
|
22
|
samer@0
|
23 % base distributions
|
samer@0
|
24 H0=sample_dir(repmat(Alpha0/K,[K,1,1]));
|
samer@0
|
25 HT=stoch(repmat(H0,[1,K,1])).*repmat(T0/sum(T0(:)),[1,1,L]);
|
samer@0
|
26 T=sample_dir(repmat(Alpha1,[K,K,1]).*HT);
|
samer@0
|
27
|
samer@0
|
28 if any(sum(H0)<0.99)
|
samer@0
|
29 disp('normalisation problem in H')
|
samer@0
|
30 keyboard
|
samer@0
|
31 end
|
samer@0
|
32 if nargout>=2
|
samer@0
|
33 I=zeros(K,3);
|
samer@0
|
34 for i=1:L
|
samer@0
|
35 I(i,:)=mc_global_info(T(:,:,i));
|
samer@0
|
36 end
|
samer@0
|
37 end
|
samer@0
|
38 end
|
samer@0
|
39
|
samer@0
|
40 % taken from stats/models/dirichlet.m>stoch_gamma
|
samer@0
|
41 function y=sample_dir(beta)
|
samer@0
|
42 x=randg(beta);
|
samer@0
|
43 z=sum(x,1);
|
samer@0
|
44 y=x./repmat(z,size(x,1),1);
|
samer@0
|
45 bad=find(z==0);
|
samer@0
|
46 for i=1:length(bad)
|
samer@0
|
47 beta_i=beta(:,bad(i)); % misbehaving params
|
samer@0
|
48 k=(beta_i==max(beta_i)); % entries with max beta
|
samer@0
|
49 y(:,bad(i))=mnrnd(1,stoch(k));
|
samer@0
|
50 end
|
samer@0
|
51 end
|
samer@0
|
52
|
samer@0
|
53 function [Y,Z]=stoch(X),
|
samer@0
|
54 Z=sum(X,1);
|
samer@0
|
55 Y=X./repmat(Z,size(X,1),1);
|
samer@0
|
56 end
|
samer@0
|
57
|
samer@0
|
58
|