-
Notifications
You must be signed in to change notification settings - Fork 1
/
S2.rmd
280 lines (226 loc) · 9.26 KB
/
S2.rmd
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
<!--
%\VignetteEngine{knitr}
%\VignetteIndexEntry{Second clutch Bayesian analysis}
-->
Supplementary Materials S2 to
Karagicheva J., Liebers, M., Rakhimberdiev, E., Hallinger K.K., Saveliev A., A., Winkler, D. W. 2016 Differences in size between first and replacement clutches match the seasonal decline in single clutches in Tree Swallows _Tachycineta bicolor_. - Ibis 158(3): 607-613
Depends: R (>= 3.2.0), JAGS (>=4.0.0)
Authors: Eldar Rakhimberdiev <[email protected]> and Julia Karagicheva <[email protected]>
Date: 24.11.2015
License: GNU GPL v3.0
Permanent address: https://github.com/eldarrak/second_clutch/blob/master/S2.rmd
## 1. Get data from Github
```{r, eval = F}
library(RCurl)
text <-getURL("https://raw.githubusercontent.com/eldarrak/second_clutch/master/raw_data.csv",
ssl.verifypeer = FALSE, followlocation = TRUE)
raw_data<-read.csv(text=text, stringsAsFactors =F)
str(raw_data)
```
In the data frame we have following columns:
1. ```$nseason``` - Year
2. ```$jd``` - julian date
3. ```$datediff``` - difference between second and first clutches
4. ```$nclutch``` - observed clutch size
5. ```$FirstClutchDoubleBreeders``` - 1 if this is the first clutch of a double breeder, otherwise 0.
Note, that ```$datediff``` is 0 for all the first clutches.
## 2. Format data for the analysis
```{r, eval = F}
Res<-data.frame(Year=as.numeric(as.factor(raw_data$nseason)),
DayFirst=scale(raw_data$jd, scale=F), DayDiff=raw_data$datediff,
DoubleBreeders=DoubleBreeders,
Clutch=raw_data$nclutch)
```
Here we make variable ```$Year``` that is just a numeric year starting from 1.
We also center ```$jd``` but not scale it
```{r, eval = F}
plot(jitter(log(Res$Clutch))~Res$DayFirst)
```
## 3. Main model w/o variable selection
### Bayesian model
```{r, eval = F, tidy=FALSE}
sink("two_truncated_Poisson_model.jags")
cat("
model {
# model
for (row in 1:nrow) {
log(lamda[row])<-
Intercept+InterceptDoubleBreeders*DoubleBreeders[row]+ # Intercept fixed
InterceptYear[year[row]]+ #Intercept random
(Slope+SlopeYear[year[row]])*DayFirst[row] + # slope for first clutches
(Slope+SlopeYear[year[row]]+ SlopeSecondClutch)*DayDiff[row]
}
for (t in 1:nyears) {
InterceptYear[t]~dnorm(0, tau_intercept)
SlopeYear[t]~dnorm(0, tau_slope)
}
#priors
#w_int_double~dbern(0.5)
#w_int~dbern(0.5)
#w_slope~dbern(0.5)
Intercept ~ dunif(-10,10)
InterceptDoubleBreeders ~ dunif(-10,10)
Slope ~dunif(-0.5,0.5)
SlopeSecondClutch ~dunif(-1,1)
tau_intercept<-pow(sigma_intercept, -2)
sigma_intercept ~ dunif(0,0.5)
tau_slope<-pow(sigma_slope, -2)
sigma_slope ~ dunif(0,1)
# likelihood
for(row in 1:nrow) {
Clutch[row] ~ dpois(lamda[row]) T(3,)
}
}
",fill = TRUE)
sink()
```
### Inits and data
```{r, eval = F}
nyears=length(unique(Res$Year))
Data <- list("nrow"=nrow(Res), "nyears"=nyears, "year"=Res$Year, "DayFirst"=Res$DayFirst,
"DayDiff"=Res$DayDiff, "Clutch"=Res$Clutch,
"FirstClutch"=Res$FirstClutch,
"DoubleBreeders"=Res$DoubleBreeders)
inits <- function() list("Intercept" = runif(1,-1,3),
"InterceptDoubleBreeders"= runif(1,-1,3),
"InterceptYear" = runif(nyears,-1,1),
"Slope" =-runif(1,-0.5, 0.5),
"SlopeYear" =runif(nyears,-1,1),
"SlopeSecondClutch" =runif(1,-1,1),
"sigma_intercept"=runif(1, 0,0.5),
"sigma_slope"=runif(1,0,1))
# Parameters monitored
params <- c("Intercept", "InterceptDoubleBreeders", "InterceptYear",
"Slope", "SlopeYear", "SlopeSecondClutch", "sigma_intercept", "sigma_slope")
```
### Model run
This will take consideravle amount of time (a few hours), lower ```n.iter``` if you want it to finish faster!
```{r, eval = F, tidy=F}
library(R2jags)
# Call JAGS from R (few hours)
out <- jags.parallel(Data, inits, params, "two_truncated_Poisson_model.jags",
n.chains = 5, n.thin = 500, n.iter = 250000, n.burnin = 50000)
save(out, file="model_output.RData")
```
### Exploring results
```{r, eval = F}
print(out)
# ok, now overall slope and intercept
Intercept_pred<-quantile(out$BUGSoutput$sims.list$Intercept, c(0.025, 0.5, 0.075))
Slope_pred<-quantile(out$BUGSoutput$sims.list$Slope, c(0.025, 0.5, 0.075))
XX<-seq(min(Res$DayFirst)-10, max(Res$DayFirst)+10)
Y_main<-Intercept_pred[2]+Slope_pred[2]*XX
# now CI
Y_lower<-apply(out$BUGSoutput$sims.list$Slope %*% XX +
out$BUGSoutput$sims.list$Intercept[,1],
2, quantile, c(0.025))
Y_upper<-apply(out$BUGSoutput$sims.list$Slope %*% XX +
out$BUGSoutput$sims.list$Intercept[,1],
2, quantile, c(0.975))
Y_second_clutch<-apply(out$BUGSoutput$sims.list$Slope %*% XX +
out$BUGSoutput$sims.list$Intercept[,1]+
out$BUGSoutput$sims.list$InterceptDoubleBreeders[,1]+
out$BUGSoutput$sims.list$SlopeSecondClutch %*% XX,
2, quantile, c(0.5))
Y_second_clutch_upper<-apply(out$BUGSoutput$sims.list$Slope %*% XX +
out$BUGSoutput$sims.list$Intercept[,1]+
out$BUGSoutput$sims.list$InterceptDoubleBreeders[,1]+
out$BUGSoutput$sims.list$SlopeSecondClutch %*% XX,
2, quantile, c(0.975))
Y_second_clutch_lower<-apply(out$BUGSoutput$sims.list$Slope %*% XX +
out$BUGSoutput$sims.list$Intercept[,1]+
out$BUGSoutput$sims.list$InterceptDoubleBreeders[,1]+
out$BUGSoutput$sims.list$SlopeSecondClutch %*% XX,
2, quantile, c(0.025))
pdf("figure1.pdf")
plot(jitter(Res$Clutch)~jitter(Res$DayFirst), pch=".", cex=2,
xlab="Time (days)", ylab="Clutch size", las=1, type="n", xlim=range(Res$DayFirst+Res$DayDiff))
points(jitter(Clutch)~jitter(DayFirst), pch=21, col=grey(0.2),
data=Res[Res$DoubleBreeders==1 & Res$DayDiff==0,], bg=grey(0.4))
points(jitter(Clutch)~jitter(DayFirst+DayDiff), pch=21, col=grey(0.2),
data=Res[Res$DayDiff>0,], bg=grey(0.9))
points(jitter(Clutch)~jitter(DayFirst), pch=".", cex=2, col=grey(0.2),
data=Res[!Res$DoubleBreeders==1,])
polygon(c(XX, rev(XX)), exp(c(Y_upper, rev(Y_lower)))
, col=grey(0.4, 0.5), border=grey(0.1), lwd=2)
polygon(c(XX, rev(XX)), exp(c(Y_second_clutch_upper, rev(Y_second_clutch_lower))),
col=grey(0.6, alpha=0.5), border=grey(0.99), lwd=2)
lines(exp(Y_main)~XX, lwd=3, col=grey(0.1))
lines(exp(Y_second_clutch)~XX, col=grey(0.99), lwd=3, lty=1)
box()
dev.off()
```
## 4. Model with variable selection
For the variables `Intercept_first_clutch_double`, `InterceptYear`, `SlopeYear`) introduce additional parameters that can take values only of 1 or 0.
### Bayesian model
```{r, eval = F, tidy=F}
sink("two_truncated_Poisson_model_with_MS.jags")
cat("
model {
# model
for (row in 1:nrow) {
log(lamda[row])<-
Intercept+w_int_double*InterceptDoubleBreeders*DoubleBreeders[row]+
w_int*InterceptYear[year[row]]+ #intercept
(Slope+w_slope*SlopeYear[year[row]])*DayFirst[row] + # slope for first clutches
(Slope+w_slope*SlopeYear[year[row]]+ w_slope_second*SlopeSecondClutch)*DayDiff[row]
}
for (t in 1:nyears) {
InterceptYear[t]~dnorm(0, tau_intercept)
SlopeYear[t]~dnorm(0, tau_slope)
}
#priors
w_int_double~dbern(0.5)
w_int~dbern(0.5)
w_slope~dbern(0.5)
w_slope_second~dbern(0.5)
Intercept ~ dunif(-10,10)
InterceptDoubleBreeders ~ dunif(-10,10)
Slope ~dunif(-0.5,0.5)
SlopeSecondClutch ~dunif(-1,1)
tau_intercept<-pow(sigma_intercept, -2)
sigma_intercept ~ dunif(0,0.5)
tau_slope<-pow(sigma_slope, -2)
sigma_slope ~ dunif(0,1)
# likelihood
for(row in 1:nrow) {
Clutch[row] ~ dpois(lamda[row]) T(3,)
}
}
",fill = TRUE)
sink()
```
###Inits and data
```{r, eval = F}
nyears=length(unique(Res$Year))
Data <- list("nrow"=nrow(Res), "nyears"=nyears, "year"=Res$Year, "DayFirst"=Res$DayFirst,
"DayDiff"=Res$DayDiff, "Clutch"=Res$Clutch,
"DoubleBreeders"=Res$DoubleBreeders)
inits <- function() list("Intercept" = runif(1,-1,3),
"InterceptDoubleBreeders"= runif(1,-1,3),
"InterceptYear" = runif(nyears,-1,1),
"Slope" =-runif(1,-0.5, 0.5),
"SlopeYear" =runif(nyears,-1,1),
"SlopeSecondClutch" =runif(1,-1,1),
"sigma_intercept"=runif(1, 0,0.5),
"sigma_slope"=runif(1,0,1),
"w_int"=rbinom(1, 1, 0.5),
"w_int_double"=rbinom(1, 1, 0.5),
"w_slope"=rbinom(1, 1, 0.5),
"w_slope_second"=rbinom(1, 1, 0.5))
# Parameters monitored
params <- c("Intercept", "InterceptDoubleBreeders", "InterceptYear",
"Slope", "SlopeYear", "SlopeSecondClutch",
"sigma_intercept", "sigma_slope",
"w_int", "w_int_double","w_slope",
"w_slope_second")
```
### Model run
This will take consideravle amount of time (~0.5 hour), lower ```n.iter``` if you want it to finish faster!
```{r, eval = F}
library(R2jags)
# Call JAGS from R (~0.5 hour)
out_ms <- jags.parallel(Data, inits, params, "two_truncated_Poisson_model_with_MS.jags",
n.chains = 5, n.thin = 500, n.iter = 500000, n.burnin = 50000)
save(out_ms, file="model_selection_output.RData")
```