-
Notifications
You must be signed in to change notification settings - Fork 5
/
trad04-month_models.qmd
190 lines (146 loc) · 6.6 KB
/
trad04-month_models.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
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
---
title: "Modeling each month"
cache: false
---
Here we modify our first modeling workflow to produce a model for each month. In the [previous workflow](trad03_basic_modeling.qmd) we produced one model covering observations covering all times; we then applied the model to the various months.
## Load data
Here we load the observation and background data points. We add a column identifying the month of the year.
```{r}
source("setup.R")
obs = sf::read_sf(file.path("data", "obs", "obs-covariates.gpkg")) |>
sf::st_set_geometry("geometry") |>
dplyr::mutate(month = factor(format(month_id, "%b"), levels = month.abb),
.before = geometry)
bkg = sf::read_sf(file.path("data", "bkg", "bkg-covariates.gpkg")) |>
sf::st_set_geometry("geometry") |>
dplyr::mutate(month = factor(format(month_id, "%b"), levels = month.abb),
.before = geometry)
```
## Do we model every month?
Let's do a quick check by counting each by month. Note that we drop the spatial info so that we can make simply tallies.
```{r}
counts = sf::st_drop_geometry(obs) |>
dplyr::count(month, name = "n_obs") |>
dplyr::left_join(sf::st_drop_geometry(bkg) |> dplyr::count(month, name = "n_bkg"),
by = 'month') |>
print(n = 12)
```
So the colder months have fewer observations than the warmer months. We already knew that, but it will be interesting to see how that manifests itself in the models.
### Build the monthly models
Since we are building 12 models (rather than one) it is useful to create a function that computes a model for any month, and then iterate through the months of the year.
```{r}
# A function for making one month's model
#
# @param tbl a data frame of one month's observations
# @param key a data frame that holds the current iteration's month name
# @param bkg a complete data frame of background data (which we filter for the given month)
# @param path the path where the model is saved
# @return a model, which is also saved in "data/model/v2/v2.<monthname>"
model_month = function(tbl, key, bkg = NULL, path = "."){
bkg = bkg |>
dplyr::filter(month == key$month) |>
sf::st_drop_geometry() |>
dplyr::select(dplyr::all_of(c("sst", "u_wind", "v_wind"))) |>
na.omit()
obs = tbl |>
sf::st_drop_geometry() |>
dplyr::select(dplyr::all_of(c("sst", "u_wind", "v_wind"))) |>
na.omit()
# these are the predictor variables row bound
x = dplyr::bind_rows(obs, bkg)
# and the flag indicating presence/background
flag = c(rep(1, nrow(obs)), rep(0, nrow(bkg)))
model_path = file.path(path, paste0("v2.", key$month, ".rds"))
model = maxnet::maxnet(flag, x) |>
maxnetic::write_maxnet(model_path)
model
}
path = file.path("data", "model", "v2")
ok = dir.create(path, recursive = TRUE, showWarnings = FALSE)
models = obs |>
dplyr::group_by(month) |>
dplyr::group_map(model_month, bkg = bkg, path = path) |>
rlang::set_names(levels(obs$month))
```
We can look at the response plots for every month, but for demonstration purposes, we'll just show one month. It is interesting to compare this respinse to that for the [basic model](trad03-basic_modeling.qmd).
```{r}
plot(models[['Jun']], type = 'cloglog')
```
## Predict with rasters
First we load the raster databases as these are lightweight to pass into a function that iterates through the months.
### Load the raster databases (`sst` and `u_wind` and `v_wind`)
We also make sure they are in date order and add a "month" variable to each.
```{r}
sst_path = "data/oisst"
sst_db = oisster::read_database(sst_path) |>
dplyr::arrange(date) |>
dplyr::mutate(month = format(date, "%b"))
nbs_path = "data/nbs"
wind_db = nbs::read_database(nbs_path) |>
dplyr::arrange(date)|>
dplyr::mutate(month = format(date, "%b"))
u_wind_db = wind_db |>
dplyr::filter(param == "u_wind")
v_wind_db = wind_db |>
dplyr::filter(param == "v_wind")
```
### Iterate through the months making predictions
Now we can build an iterator function that will make a prediction for each month. Let's narrow our predictions to just those for a particular year, 2019, and read the rasters in all at once.
```{r}
dates = as.Date(c("2019-01-01", "2019-12-31"))
x = read_predictors(
sst_db = dplyr::filter(sst_db, dplyr::between(date, dates[1], dates[2])),
u_wind_db = dplyr::filter(u_wind_db, dplyr::between(date, dates[1], dates[2])),
v_wind_db = dplyr::filter(v_wind_db, dplyr::between(date, dates[1], dates[2])) )
```
Now we can iterate through the months.
```{r}
date_sequence = seq(from = dates[1], to = dates[2], by = "month")
pred_rasters = lapply(names(models),
function(mon){
ix = which(month.abb %in% mon)
predict(models[[mon]], dplyr::slice(x, time, ix, drop), type = "cloglog")
})
pred_rasters = do.call(c, append(pred_rasters, list(along = list(time = date_sequence))))
```
Let's plot them.
```{r}
coast = rnaturalearth::ne_coastline(scale = 'large', returnclass = 'sf') |>
sf::st_geometry() |>
sf::st_crop(pred_rasters)
plot_coast = function() {
plot(coast, col = 'green', add = TRUE)
}
plot(pred_rasters, hook = plot_coast)
```
Let's see what we can discern from the predict abilities. We can extract the predicted values at the observed locations. Having those in hand allows us to compute pAUC for each month.
```{r}
pred_obs = stars::st_extract(pred_rasters,
dplyr::filter(obs, dplyr::between(month_id, dates[1], dates[2])),
time_column = "month_id") |>
dplyr::mutate(month = factor(format(month_id, "%b"), levels = month.abb)) |>
dplyr::group_by(month)
paucs = dplyr::group_map(pred_obs,
function(x, y) {
ix = month.abb %in% y$month
s = dplyr::slice(pred_rasters, "time", ix)
pauc = maxnetic::pAUC(s,x)
dplyr::tibble(month = y$month,
auc = pauc$area,
pauc = list(pauc))
})|>
dplyr::bind_rows() |>
print(n = 12)
```
Note that last element, `pauc`, is the result returned by the `maxnetic::pAUC()` function which we can plot.
```{r, warning = FALSE}
pp = paucs |>
dplyr::group_by(month) |>
dplyr::group_map(
function(tbl, key){
plot(tbl$pauc[[1]], title = key$month, xlab = "", ylab = "")
}
)
patchwork::wrap_plots(pp, ncol = 4)
```
Well, it would be easy to become dispirited by this result. It would be reasonable to expect AUC values to improve if we built monthly models rather than a single model applied to any month. But it seems to not be the dramatic improvement hoped for. Darn!