-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_targets.R
434 lines (416 loc) · 11.6 KB
/
_targets.R
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# Created by use_targets().
# Follow the comments below to fill in this target script.
# Then follow the manual to check and run the pipeline:
# https://books.ropensci.org/targets/walkthrough.html#inspect-the-pipeline
# Load packages required to define the pipeline:
library(targets)
library(tarchetypes)
library(geotargets)
library(crew)
library(crew.cluster)
library(qs2) #for format = "qs"
library(nanoparquet) #for format = tar_format_nanoparquet()
# Detect whether you're on HPC & not with an Open On Demand session (which cannot submit SLURM jobs).
slurm_host <- Sys.getenv("SLURM_SUBMIT_HOST")
hpc <- grepl("hpc\\.arizona\\.edu", slurm_host) & !grepl("ood", slurm_host)
controller_hpc_light <-
crew.cluster::crew_controller_slurm(
name = "hpc_light",
workers = 5,
# make workers semi-persistent:
tasks_max = 40, # shut down SLURM job after completing 40 targets
seconds_idle = 300, # or when idle for some time
options_cluster = crew_options_slurm(
script_lines = c(
"#SBATCH --account theresam",
#use optimized openBLAS for linear algebra
"export LD_PRELOAD=/opt/ohpc/pub/libs/gnu13/openblas/0.3.21/lib/libopenblas.so",
"module load gdal/3.8.5 R/4.4 eigen/3.4.0"
),
log_output = "logs/crew_log_%A.out",
log_error = "logs/crew_log_%A.err",
memory_gigabytes_per_cpu = 5,
cpus_per_task = 3, #use 3 cpus per worker
time_minutes = 60, #wall time for each worker
partition = "standard"
)
)
controller_hpc_heavy <-
crew.cluster::crew_controller_slurm(
name = "hpc_heavy",
workers = 3,
tasks_max = 20,
seconds_idle = 1000,
options_cluster = crew_options_slurm(
script_lines = c(
"#SBATCH --account theresam",
"export LD_PRELOAD=/opt/ohpc/pub/libs/gnu13/openblas/0.3.21/lib/libopenblas.so",
"module load gdal/3.8.5 R/4.4 eigen/3.4.0"
),
log_output = "logs/crew_heavy_log_%A.out",
log_error = "logs/crew_heavy_log_%A.err",
memory_gigabytes_per_cpu = 5,
cpus_per_task = 8,
time_minutes = 360, #wall time for each worker
partition = "standard"
)
)
controller_local <-
crew::crew_controller_local(
name = "local",
workers = 4,
seconds_idle = 60,
options_local = crew::crew_options_local(
log_directory = "logs/"
)
)
threshold <- c( #ºF
50,
650,
# 1250,
# 1950,
2500
)
# Set target options:
tar_option_set(
trust_timestamps = TRUE, #just check last modified date when deciding whether to re-run
# Packages that your targets need for their tasks.
packages = c(
"fs",
"terra",
"stringr",
"lubridate",
"colorspace",
"purrr",
"ggplot2",
"tidyterra",
"glue",
"car",
"httr2",
"readr",
"sf",
"maps",
"tidyr",
"dplyr",
"broom",
"forcats",
"mgcv"
),
controller = crew::crew_controller_group(
controller_hpc_heavy, controller_hpc_light, controller_local
),
resources = tar_resources(
crew = tar_resources_crew(controller = ifelse(isTRUE(hpc), "hpc_light", "local"))
),
#assume workers have access to the _targets/ data store
storage = "worker",
retrieval = "worker",
memory = "auto",
#allows use of `tar_workspace()` to load dependencies of an errored target for interactive debugging.
workspace_on_error = TRUE
)
# `source()` the R scripts in the R/ folder with your custom functions:
targets::tar_source()
main <- tarchetypes::tar_plan(
years = 1981:2023,
tar_target(
name = prism_tmin,
command = get_prism(years, "tmin"),
pattern = map(years),
deployment = "main",
format = "file",
description = "download PRISM tmin"
),
tar_target(
name = prism_tmax,
command = get_prism(years, "tmax"),
pattern = map(years),
deployment = "main",
format = "file",
description = "download PRISM tmax"
),
tar_terra_vect(
roi,
make_roi(),
deployment = "main",
description = "vector for North East"
),
tar_map( # for each threshold...
values = list(threshold = threshold),
tar_terra_rast(
gdd_doy,
calc_gdd_be_doy(
tmin_dir = prism_tmin, #ºC, but gets converted to ºF
tmax_dir = prism_tmax, #ºC, but gets converted to ºF
roi = roi,
gdd_threshold = threshold, #ºF
gdd_base = 50 #ºF
),
pattern = map(prism_tmin, prism_tmax),
description = "calc DOY to reach threshold GDD"
),
# Combine list of SpatRasters into multi-layer SpatRaster
tar_terra_rast(
gdd_doy_stack,
terra::rast(unname(gdd_doy))
),
#summary statistics across years
tar_target(
doy_range,
range(gdd_doy_stack) |> values() |> range(na.rm = TRUE)
),
tar_terra_rast(
gdd_doy_mean,
#should NAs be removed? NAs are "never reached this threshold", not "missing data"
mean(gdd_doy_stack, na.rm = TRUE)
),
tar_terra_rast(
gdd_doy_min,
min(gdd_doy_stack, na.rm = TRUE)
),
tar_terra_rast(
gdd_doy_max,
max(gdd_doy_stack, na.rm = TRUE)
),
tar_file(
summary_plot,
plot_summary_combined(gdd_doy_min, gdd_doy_mean, gdd_doy_max, doy_range),
packages = c("patchwork", "ggplot2", "tidyterra", "stringr", "glue")
),
tar_terra_rast(
gdd_doy_sd,
stdev(gdd_doy_stack, na.rm = TRUE)
),
tar_file(
sd_plot,
plot_sd_doy(gdd_doy_sd)
),
tar_target(
gam_df,
make_gam_df(gdd_doy_stack, res = 25000),
format = "qs"
),
## GAMs ###
# NOTE: if k_spatial needs to be adjusted for each threshold,
# create a dataframe to pass to `values` arg of `tar_map()`
tar_target(
gam,
fit_bam(gam_df, k_spatial = 1000),
format = "qs",
resources = tar_resources(
crew = tar_resources_crew(controller = ifelse(isTRUE(hpc), "hpc_heavy", "local"))
)
),
# Model diagnostics
tar_file(
smooths,
draw_partial_effects(gam, roi)
),
tar_file(
appraisal,
appraise_gam(gam)
),
tar_target(
k_check,
check_k(gam),
packages = c("mgcv", "dplyr")
)
) #end tar_map()
)
slopes <- tar_plan(
tar_target(
slope_newdata,
#doesn't matter which dataset since all that is used is x,y, and year_scaled
#using very coarse newdata regardless of resolution of original data.
make_slope_newdata(gdd_doy_stack_650, res_m = 25000) |>
dplyr::group_by(group) |>
targets::tar_group(),
#grouped by about 1000 pixels per group
iteration = "group",
format = "qs"
),
tar_map(
values = list(gam = rlang::syms(glue::glue("gam_{threshold}"))),
tar_target(
slopes,
calc_avg_slopes(gam, slope_newdata),
packages = c("marginaleffects", "mgcv"),
resources = tar_resources(
crew = tar_resources_crew(controller = ifelse(isTRUE(hpc), "hpc_heavy", "local"))
),
pattern = map(slope_newdata),
format = tar_format_nanoparquet()
),
tar_target(
slope_range,
range(slopes$estimate),
resources = tar_resources(
crew = tar_resources_crew(controller = ifelse(isTRUE(hpc), "hpc_heavy", "local"))
),
pattern = map(slopes),
format = "qs"
)
)
)
slopes_plots <- tar_plan(
tar_target(
slope_range,
range(!!!rlang::syms(glue::glue("slope_range_gam_{threshold}"))),
description = "range across all thresholds for colorbar",
tidy_eval = TRUE
),
tar_map(
values = list(slopes = rlang::syms(glue::glue("slopes_gam_{threshold}"))),
tar_file(
slopes_plot,
plot_avg_slopes(slopes, slope_range, roi),
packages = c("ggpattern", "ggplot2", "terra", "tidyterra"),
resources = tar_resources(
crew = tar_resources_crew(controller = ifelse(isTRUE(hpc), "hpc_heavy", "local"))
)
)
)
)
# gams <- tarchetypes::tar_plan(
#prep data
# tar_map(
# values = list(threshold = threshold),
# tar_target(
# gam_df,
# make_gam_df(gdd_doy_stack_650, res = 25000),
# format = "qs"
# )
# )
#fit gams
# tar_target(
# gam_650,
# fit_bam(gam_df_650, k_spatial = 1000),
# format = "qs",
# resources = tar_resources(
# crew = tar_resources_crew(controller = ifelse(isTRUE(hpc), "hpc_heavy", "local"))
# )
# ),
#model diagnostics
# tar_file(
# smooths_650,
# draw_partial_effects(gam_650, roi)
# ),
# tar_file(
# appraisal_650,
# appraise_gam(gam_650)
# ),
# tar_target(
# k_check_650,
# check_k(gam_650),
# packages = c("mgcv", "dplyr")
# ),
# tar_target(
# k_check_df,
# bind_rows(!!!rlang::syms(c(
# "k_check_650"
# ))),
# tidy_eval = TRUE,
# description = "Collect results from k_check targets"
# ),
# tar_file(
# k_check_df_csv,
# tar_write_csv(k_check_df, "output/gams/k_check.csv")
# ),
#TODO: consider bigger chunks since not RAM limited, but CPU limited.
# tar_target(
# slope_newdata,
# #doesn't matter which dataset since all that is used is x,y, and year_scaled
# #using very coarse newdata regardless of resolution of original data.
# make_slope_newdata(gdd_doy_stack_650, res_m = 25000) |>
# dplyr::group_by(group) |>
# targets::tar_group(),
# #grouped by about 1000 pixels per group
# iteration = "group",
# format = "qs"
# ),
# tar_target(
# cities_sf,
# make_cities_sf(),
# description = "Example cities for plotting fitted trends"
# ),
# tar_map(
# values = list(gam = rlang::syms(c("gam_650"))),
# tar_target(
# slopes,
# calc_avg_slopes(gam, slope_newdata),
# packages = c("marginaleffects", "mgcv"),
# resources = tar_resources(
# crew = tar_resources_crew(controller = ifelse(isTRUE(hpc), "hpc_heavy", "local"))
# ),
# pattern = map(slope_newdata),
# format = tar_format_nanoparquet()
# ),
# tar_target(
# slope_range,
# range(slopes$estimate),
# resources = tar_resources(
# crew = tar_resources_crew(controller = ifelse(isTRUE(hpc), "hpc_heavy", "local"))
# ),
# pattern = map(slopes),
# format = "qs"
# )#,
# tar_target(
# city_plot,
# plot_city_trend(gam, cities_sf),
# description = "timeseries plot for example cities for each gam"
# )
# ),
# tar_target(
# slope_range,
# range(slope_range_gam_650),
# description = "range across all thresholds for colorbar"
# ),
# tar_map(
# values = list(
# slopes = rlang::syms(c(
# "slopes_gam_650"
# ))#,
# city_plot = rlang::syms(c(
# "city_plot_gam_650"
# ))
# ),
# tar_file(
# slopes_plot,
# plot_avg_slopes(slopes, slope_range, roi),
# packages = c("ggpattern", "ggplot2", "terra", "tidyterra"),
# resources = tar_resources(
# crew = tar_resources_crew(controller = ifelse(isTRUE(hpc), "hpc_heavy", "local"))
# )
# )
# )
# )
# city_slopes <- tar_plan(
# tar_map(
# values = list(gam = rlang::syms(c("gam_50gdd", "gam_400gdd", "gam_800gdd"))),
# tar_target(
# city_slopes,
# calc_city_slopes(cities_sf, gam),
# format = tar_format_nanoparquet(),
# resources = tar_resources(
# crew = tar_resources_crew(controller = ifelse(isTRUE(hpc), "hpc_heavy", "local"))
# ),
# description = "for each GDD threshold, calc avg slope for specific cities"
# )
# )
# )
# city_slopes_plot <- tar_plan(
# tar_combine(
# city_slopes_df,
# city_slopes,
# format = tar_format_nanoparquet(),
# description = "combine predictions from all GDD thresholds for plotting"
# )
# )
tarchetypes::tar_plan(
main,
slopes,
slopes_plots
# gams,
# city_slopes,
# city_slopes_plot
)