-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path00-global.R
303 lines (255 loc) · 12.9 KB
/
00-global.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
# environment variables -----------------------------------------------------------------------
if (file.exists("~/.Renviron")) readRenviron("~/.Renviron") ## GITHUB_PAT, etc.
if (file.exists("LandWeb.Renviron")) readRenviron("LandWeb.Renviron") ## database credentials
# use renv for package management -------------------------------------------------------------
if (!grepl("renv", .libPaths()[1])) {
source("renv/activate.R")
}
# project setup (includes package installation etc.) ------------------------------------------
prjDir <- SpaDES.project::findProjectPath()
stopifnot(identical(normalizePath(prjDir), normalizePath(getwd())))
source("01a-globalvars.R")
## set new temp dir in scratch directory (existing /tmp too small for large callr ops in postprocessing)
## see https://github.com/r-lib/callr/issues/172
if (grepl("for-cast[.]ca", .nodename) && !grepl("larix", .nodename)) {
newTmpDir <- file.path("/mnt/scratch", .user, basename(prjDir), "tmp")
tmpdir::setTmpDir(newTmpDir, rmOldTempDir = TRUE)
}
options(
Ncpus = .ncores,
repos = c(CRAN = "https://cloud.r-project.org")
)
# source("01-setup.R") ## package installation; now done using `renv`
library("data.table")
library("plyr")
library("pryr")
library("reproducible")
library("SpaDES.core")
library("googledrive")
library("httr")
library("LandR")
library("LandWebUtils")
library("notifications")
library("sessioninfo")
# configure project ---------------------------------------------------------------------------
source("02-configure.R")
# begin simulations ---------------------------------------------------------------------------
do.call(SpaDES.core::setPaths, paths)
if (config$args[["delayStart"]] > 0) {
message(crayon::green("\nStaggered job start: delaying by", config$args[["delayStart"]], "minutes."))
Sys.sleep(config$args[["delayStart"]]*60)
}
objects1 <- list()
parameters1 <- list(
.globals = config$params[[".globals"]],
LandWeb_preamble = config$params[["LandWeb_preamble"]]
)
preambleFile <- file.path(paths[["outputPath"]], paste0(
"simOutPreamble_", config$context[["studyAreaName"]], ".qs"
))
simOutPreamble <- Cache(simInitAndSpades,
times = list(start = 0, end = 1),
params = parameters1, ## TODO: use config$params
modules = c("LandWeb_preamble"), ## TODO: use config$modules
objects = objects1,
paths = paths,
debug = 1,
omitArgs = c("debug", "paths", ".plotInitialTime"),
useCloud = config$args[["cloud"]][["useCloud"]],
cloudFolderID = config$args[["cloud"]][["cacheDir"]],
userTags = c(config$context[["studyAreaName"]], config$context[["runName"]], "preamble"))
if (isTRUE(attr(simOutPreamble, ".Cache")[["newCache"]])) {
simOutPreamble@.xData[["._sessionInfo"]] <- SpaDES.project::projectSessionInfo(prjDir)
saveRDS(simOutPreamble$ml, file.path(paths[["outputPath"]], "ml_preamble.rds")) ## TODO: use `qs::qsave()`
saveSimList(simOutPreamble, preambleFile, fileBackend = 2)
}
# Species layers ------------------------------------------------------------------------------
config$params[[".globals"]][[".plots"]] <- c("png") ## TODO: change in config
config$params[["Biomass_speciesData"]][[".plots"]] <- c("png") ## TODO: change in config
parameters2 <- list(
.globals = config$params[[".globals"]],
Biomass_speciesData = config$params[["Biomass_speciesData"]]
)
objects2 <- list(
#nonTreePixels = simOutPreamble[["nonTreePixels"]], ## TODO: confirm no longer required
rasterToMatchLarge = simOutPreamble[["rasterToMatchLarge"]],
sppColorVect = simOutPreamble[["sppColorVect"]],
sppEquiv = simOutPreamble[["sppEquiv"]],
studyAreaLarge = simOutPreamble[["studyAreaLarge"]],
studyAreaReporting = simOutPreamble[["studyAreaReporting"]]
)
sppLayersFile <- file.path(paths[["outputPath"]], paste0(
"simOutSpeciesLayers_", config$context[["studyAreaName"]], ".qs"
))
simOutSpeciesLayers <- Cache(simInitAndSpades,
times = list(start = 0, end = 1),
params = parameters2, ## TODO: use config$params
modules = c("Biomass_speciesData"), ## TODO: use config$modules
objects = objects2,
paths = paths,
debug = 1,
omitArgs = c("debug", "paths", ".plotInitialTime"),
useCloud = config$args[["cloud"]][["useCloud"]],
cloudFolderID = config$args[["cloud"]][["cacheDir"]],
userTags = c(config$context[["studyAreaName"]], config$context[["runName"]], "speciesLayers"))
if (isTRUE(attr(simOutSpeciesLayers, ".Cache")[["newCache"]])) {
simOutSpeciesLayers@.xData[["._sessionInfo"]] <- SpaDES.project::projectSessionInfo(prjDir)
saveSimList(simOutSpeciesLayers, sppLayersFile, fileBackend = 2)
}
if (config$context[["mode"]] != "postprocess") {
# Boreal data prep + main sim -----------------------------------------------------------------
parameters2a <- list(
.globals = config$params[[".globals"]],
Biomass_borealDataPrep = config$params[["Biomass_borealDataPrep"]]
)
objects2a <- list(
cloudFolderID = config$args[["cloud"]][["cacheDir"]],
rstLCC = simOutPreamble[["LCC"]],
rasterToMatch = simOutPreamble[["rasterToMatch"]],
rasterToMatchLarge = simOutPreamble[["rasterToMatchLarge"]],
speciesLayers = simOutSpeciesLayers[["speciesLayers"]],
speciesParams = simOutPreamble[["speciesParams"]],
speciesTable = simOutPreamble[["speciesTable"]],
sppColorVect = simOutPreamble[["sppColorVect"]],
sppEquiv = simOutPreamble[["sppEquiv"]],
standAgeMap = simOutPreamble[["CC TSF"]],
studyArea = simOutPreamble[["studyArea"]],
studyAreaLarge = simOutPreamble[["studyAreaLarge"]],
studyAreaReporting = simOutPreamble[["studyAreaReporting"]]
)
dataPrepFile <- file.path(paths[["outputPath"]], paste0("simOutDataPrep_", config$context[["studyAreaName"]], ".qs"))
simOutDataPrep <- Cache(simInitAndSpades,
times = list(start = 0, end = 1),
params = parameters2a, ## TODO: use config$params
modules = c("Biomass_borealDataPrep"), ## TODO: use config$modules
objects = objects2a,
paths = paths,
debug = 1,
omitArgs = c("debug", "paths", ".plotInitialTime"),
useCloud = config$args[["cloud"]][["useCloud"]],
cloudFolderID = config$args[["cloud"]][["cacheDir"]],
userTags = c(config$context[["studyAreaName"]], config$context[["runName"]], "dataPrep"))
if (isTRUE(attr(simOutDataPrep, ".Cache")[["newCache"]])) {
simOutDataPrep@.xData[["._sessionInfo"]] <- SpaDES.project::projectSessionInfo(prjDir)
## TODO: enforce correct species table types (LandR#90)
if (is(simOutDataPrep$species$postfireregen, "character")) {
simOutDataPrep$species$postfireregen <- as.factor(simOutDataPrep$species$postfireregen)
}
saveSimList(simOutDataPrep, dataPrepFile, fileBackend = 2)
}
source("10-main-sim.R")
} else {
## postprocessing --------------------------------------------------------------------------------
if (grepl("Manning", config$context[["runName"]])) {
config$params[["timeSeriesTimes"]] <- 450:500
}
modules4 <- if (grepl("provMB", config$context[["studyAreaName"]])) {
list(
"burnSummaries", ## TODO: add to config
"HSI_Caribou_MB", ## TODO: add to config
"LandMine", ## TODO: add to config - using 'multi' mode
"LandWeb_summary"
)
} else {
list(
"burnSummaries", ## TODO: add to config
"LandMine", ## TODO: add to config - using 'multi' mode
"LandWeb_summary"
)
}
## don't cache the init event
config$params[["HSI_Caribou_MB"]][[".useCache"]] <- c(".inputObjects", "postprocess")
config$params[["LandWeb_summary"]][[".useCache"]] <- c(".inputObjects", "animation", "postprocess")
## NOTE: previous .useParallel value is too low for this module
config$params[[".globals"]][[".useParallel"]] <- getOption("map.useParallel")
config$params[["LandWeb_summary"]][[".useParallel"]] <- getOption("map.useParallel")
## adjust N reps as needed:
if (config$context[["studyAreaName"]] == "LandWeb_full") {
config$params[["LandWeb_summary"]][["reps"]] <- 1L:50L
}
getOption("map.maxNumCores")
options(map.maxNumCores = .ncores)
parameters4 <- list(
.globals = config$params[[".globals"]],
burnSummaries = list( ## TODO: add to config
reps = 1L:15L,
simOutputPath = "outputs",
.studyAreaName = config$context[["studyAreaName"]]
),
HSI_caribou_MB = config$params[["HSI_Caribou_MB"]], ## TODO: add to config
LandMine = list( ## TODO: add to config
mode = "multi",
reps = 1L:15L,
simOutputPath = "outputs",
.studyAreaName = config$context[["studyAreaName"]]
),
LandWeb_summary = config$params[["LandWeb_summary"]]
)
objects4 <- list(
ml = simOutPreamble[["ml"]],
speciesLayers = simOutSpeciesLayers[["speciesLayers"]],
sppColorVect = simOutPreamble[["sppColorVect"]],
sppEquiv = simOutPreamble[["sppEquiv"]]
)
outputs4 <- NULL
fsim <- simFile("simOutSummaries", paths[["outputPath"]], NULL, "qs")
tryCatch({
simOutSummaries <- Cache(simInitAndSpades,
times = list(start = 0, end = 1),
params = parameters4, ## TODO: use config$params
modules = modules4, ## TODO: use config$modules
#outputs = outputs4,
objects = objects4,
paths = paths,
loadOrder = unlist(modules4), ## TODO: use config$modules
#cl = cl, ## TODO: get parallel processing working !!!
debug = list(file = list(file = file.path(config$paths[["logPath"]], "summaries.log"),
append = TRUE), debug = 1),
useCloud = FALSE, ## TODO param useCloud??
cloudFolderID = config$args[["cloud"]][["cacheDir"]],
omitArgs = c("debug", "paths"),
userTags = c(config$context[["runName"]], "postprocess"))
cat(capture.output(warnings()), file = file.path(config$paths[["logPath"]], "warnings_postprocess.txt"), sep = "\n")
}, error = function(e) {
if (requireNamespace("slackr") & file.exists("~/.slackr")) {
slackr::slackr_setup()
slackr::slackr_msg(
paste0("ERROR in post-processing `", config$context[["runName"]],
"` on host `", config$context[["machine"]], "`.\n",
"```\n", e$message, "\n```"),
channel = config$args[["notifications"]][["slackChannel"]], preformatted = FALSE
)
stop(e$message)
}
})
if (isTRUE(attr(simOutSummaries, ".Cache")[["newCache"]])) {
simOutSummaries@.xData[["._sessionInfo"]] <- SpaDES.project::projectSessionInfo(prjDir)
message("Saving simulation to: ", fsim)
saveSimList(sim = simOutSummaries, filename = fsim, fileBackend = 2)
# save simulation info ------------------------------------------------------------------------
relOutputPath <- SpaDES.config:::.getRelativePath(paths[["outputPath"]], prjDir)
rrFile <- file.path(relOutputPath, "INFO.md")
cat(SpaDES.config::printRunInfo(config$context), file = rrFile, sep = "")
cat(SpaDES.project::reproducibilityReceipt(), file = rrFile, sep = "\n", append = TRUE)
# save simulation stats -----------------------------------------------------------------------
elapsed <- elapsedTime(simOutSummaries)
data.table::fwrite(elapsed, file.path(config$paths[["logPath"]], "elapsedTime_summaries.csv"))
qs::qsave(elapsed, file.path(config$paths[["logPath"]], "elapsedTime_summaries.qs"))
if (!isFALSE(getOption("spades.memoryUseInterval"))) {
memory <- memoryUse(simOutSummaries, max = TRUE)
data.table::fwrite(memory, file.path(config$paths[["logPath"]], "memoryUsed_summaries.csv"))
qs::qsave(memory, file.path(config$paths[["logPath"]], "memoryUsed_summaries.qs"))
}
}
# archive and upload --------------------------------------------------------------------------
source("R/upload.R")
# end-of-sim notifications --------------------------------------------------------------------
if (requireNamespace("slackr") & file.exists("~/.slackr")) {
slackr::slackr_setup()
slackr::slackr_msg(
paste0("Post-processing for `", config$context[["runName"]], "` completed on host `", Sys.info()[["nodename"]], "`."),
channel = config$args[["notifications"]][["slackChannel"]], preformatted = FALSE
)
}
}
#source("11-post-sim.R")