-
-
Notifications
You must be signed in to change notification settings - Fork 478
/
inhalers.stan
108 lines (97 loc) · 2.27 KB
/
inhalers.stan
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// Inhaler: ordered categorical data
//# http://www.openbugs.net/Examples/Inhalers.html
//# FIXME ii:
//# specify using categorical distribution directly
//# done (but x ~ categorical[p], in which x starts
//# from 0).
data {
int<lower=0> N;
int<lower=0> T;
int<lower=0> G;
int<lower=0> Npattern;
array[16, 2] int<lower=0> Ncum;
array[16, 2] int<lower=0> pattern;
int<lower=0> Ncut;
array[2, 2] int treat;
array[2, 2] int period;
array[2, 2] int carry;
}
transformed data {
// Construct individual response data from contingency table
array[N] int group;
array[N, T] int response;
for (i in 1 : Ncum[1, 1]) {
group[i] = 1;
for (t in 1 : T) {
response[i, t] = pattern[1, t];
}
}
for (i in (Ncum[1, 1] + 1) : Ncum[1, 2]) {
group[i] = 2;
for (t in 1 : T) {
response[i, t] = pattern[1, t];
}
}
for (k in 2 : Npattern) {
for (i in (Ncum[k - 1, 2] + 1) : Ncum[k, 1]) {
group[i] = 1;
for (t in 1 : T) {
response[i, t] = pattern[k, t];
}
}
for (i in (Ncum[k, 1] + 1) : Ncum[k, 2]) {
group[i] = 2;
for (t in 1 : T) {
response[i, t] = pattern[k, t];
}
}
}
}
parameters {
real<lower=0> sigmasq;
real beta;
real pi;
real kappa;
real a0;
array[N] real b;
ordered[Ncut] a;
}
transformed parameters {
real<lower=0> sigma;
sigma = sqrt(sigmasq);
}
model {
array[N, T, Ncut] real Q;
array[N, T] vector[Ncut + 1] p;
array[G, T] real mu;
for (g in 1 : G) {
for (t in 1 : T) {
// logistic mean for group g in period t
mu[g, t] = beta * treat[g, t] * .5 + pi * period[g, t] * .5
+ kappa * carry[g, t];
}
}
for (i in 1 : N) {
for (t in 1 : T) {
for (j in 1 : Ncut) {
Q[i, t, j] = inv_logit(-(a[j] + mu[group[i], t] + b[i]));
}
p[i, t, 1] = 1 - Q[i, t, 1];
for (j in 2 : Ncut) {
p[i, t, j] = Q[i, t, j - 1] - Q[i, t, j];
}
p[i, t, Ncut + 1] = Q[i, t, Ncut];
response[i, t] ~ categorical(p[i, t]);
}
}
b ~ normal(0, sigma);
beta ~ normal(0, 1000);
pi ~ normal(0, 1000);
kappa ~ normal(0, 1000);
a0 ~ normal(0, 1000);
sigmasq ~ inv_gamma(0.001, 0.001);
}
generated quantities {
real log_sigma;
log_sigma = log(sigma);
}