-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample-ants.qmd
129 lines (94 loc) · 2.38 KB
/
example-ants.qmd
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
# example: ants
```{r}
library(tidyverse)
```
```{r}
fun <- function(temp, height, peak_temp, width) {
height * exp( -(temp - peak_temp) ^ 2 / (2 * width ^ 2))
}
```
```{r}
temp <- seq(0, 50, by = 1)
activity <- fun(temp, height = 10, peak_temp = 25, width = 5)
plot(activity ~ temp, type = "l")
```
```{r}
n_nests <- 5
n_obs <- 500
peak_temps <- runif(n_nests, 20, 30)
heights <- rep(runif(1, 5, 20), n_nests)
widths <- rep(runif(1, 3, 5), n_nests)
data_full <- tibble(
nest = sample(seq_len(n_nests), n_obs, replace = TRUE),
temp = runif(n_obs, 10, 50)
) %>%
mutate(
peak_temp = peak_temps[nest],
height = heights[nest],
width = widths[nest],
) %>%
mutate(
expected_activity = fun(temp,
height = height,
peak_temp = peak_temp,
width = width),
observed_activity = expected_activity + rnorm(n = n_obs, 0, 1),
observed_activity = pmax(observed_activity, 0)
)
data_full
```
```{r}
data <- data_full %>%
filter(observed_activity > 0)
data
```
```{r}
data %>%
ggplot(
aes(
x = temp,
y = observed_activity,
colour = nest
)
) +
geom_point()
```
```{r}
library(greta)
peak_temp_mean <- normal(25, 10)
peak_temp_sd <- normal(0, 1, truncation = c(0, Inf))
peak_temp_nest_raw <- normal(0, 1, dim = n_nests)
peak_temp_nest <- peak_temp_mean + peak_temp_sd * peak_temp_nest_raw
height <- normal(20, 10, truncation = c(0, Inf))
width <- normal(10, 10, truncation = c(0, Inf))
peak_temp <- peak_temp_nest[data$nest]
expected_activity <- fun(data$temp,
height = height,
peak_temp = peak_temp,
width = width)
obs_sd <- normal(0, 1, truncation = c(0, Inf))
distribution(data$observed_activity) <- normal(expected_activity,
obs_sd,
truncation = c(0, Inf))
```
```{r}
m <- model(peak_temp_mean, peak_temp_sd, height, width)
draws <- mcmc(m, chains = 10)
```
```{r}
plot(draws)
```
```{r}
coda::gelman.diag(draws, autoburnin = FALSE, multivariate = FALSE)
summary(draws)
```
```{r}
peak_temp_nest_draws <- calculate(peak_temp_nest, values = draws)
plot(peak_temp_nest_draws)
summary(peak_temp_nest_draws)
peak_temps
```
```{r}
width_draws <- calculate(width, values = draws)
plot(width_draws)
```