-
Notifications
You must be signed in to change notification settings - Fork 3
/
make_saver.R
348 lines (278 loc) · 7.8 KB
/
make_saver.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
#' Run multiple simulations at once
#'
#' The `run_multiple` function allows running multiple simulations at once.
#' When available, users can take advantage of parallel computing to speed up
#' the process.
#'
#' @param m,ndays,seed See [run].
#' @param saver An object of class [epiworld_saver].
#' @param nsims Integer. Number of replicats
#' @param ... List of strings (characters) specifying what to save (see details).
#' @param fn A file name pattern.
#' @param nthreads Integer. Number of threads (parallel computing.)
#' @param reset When `TRUE` (default,) resets the simulation.
#' @param verbose When `TRUE` (default,) prints a progress bar.
#'
#' @details
#' Currently, the following elements can be saved:
#'
#' - `total_hist` History of the model (total numbers per time).
#' - `virus_info` Information about `viruses`.
#' - `virus_hist` Changes in `viruses`.
#' - `tool_info` Information about `tools`.
#' - `tool_hist` Changes in `tools`.
#' - `transmission` Transmission events.
#' - `transition` Transition matrices.
#' - `reproductive` Reproductive number.
#' - `generation` Estimation of generation time.
#'
#' @returns
#' - In the case of `make_saver`, an list of class `epiworld_saver`.
#' @examples
#' model_sir <- ModelSIRCONN(
#' name = "COVID-19",
#' prevalence = 0.01,
#' n = 1000,
#' contact_rate = 2,
#' transmission_rate = 0.9, recovery_rate = 0.1
#' )
#'
#' # Generating a saver
#' saver <- make_saver("total_hist", "reproductive")
#'
#' # Running and printing
#' run_multiple(model_sir, ndays = 100, nsims = 50, saver = saver, nthreads = 2)
#'
#' # Retrieving the results
#' ans <- run_multiple_get_results(model_sir)
#'
#' head(ans$total_hist)
#' head(ans$reproductive)
#'
#' # Plotting
#' multi_sir <- run_multiple_get_results(model_sir)$total_hist
#' multi_sir <- multi_sir[multi_sir$date <= 20,]
#' plot(multi_sir)
#'
#' @export
#' @returns
#' - The `run_multiple` function runs a specified number of simulations and
#' returns a model object of class [epiworld_model].
run_multiple <- function(
m, ndays, nsims,
seed = sample.int(1e4, 1),
saver = make_saver(),
reset = TRUE,
verbose = TRUE,
nthreads = 1L
) UseMethod("run_multiple")
#' @export
run_multiple.epiworld_model <- function(
m, ndays, nsims,
seed = sample.int(1e4, 1),
saver = make_saver(),
reset = TRUE,
verbose = TRUE,
nthreads = 1L
) {
if (!inherits(saver, "epiworld_saver"))
stop("-saver- should be of class \"epiworld_saver\"")
# If the saver is greater than 1, then
# we need to delete the files from the previous run
fnames <- list.files(
path = dirname(saver$fn),
full.names = TRUE
)
if (length(fnames)) {
unlink(fnames, expand = FALSE)
}
run_multiple_cpp(
m,
ndays,
nsims,
seed,
saver$ptr,
reset,
verbose,
nthreads
)
attr(m, "saver") <- saver
invisible(m)
}
#' @export
#' @rdname run_multiple
#' @returns
#' - The `run_multiple_get_results` function returns a named list with the
#' data specified by `make_saver`.
#' @importFrom utils read.table
run_multiple_get_results <- function(m) {
if (!inherits(m, "epiworld_model"))
stop("-m- must be of class `epiworld_model`.")
# Get the filepath
saver <- attr(m, "saver")
if (!length(saver))
stop("No -saver- found. -run_multiple_get_results- can only be used after using -run_multiple-.")
output <- vector("list", length(saver$what))
names(output) <- saver$what
for (i in saver$what) {
# Listing the files
fnames <- list.files(
path = dirname(saver$fn),
pattern = sprintf("%s\\.csv", i),
full.names = TRUE
)
# Reading the files
output[[i]] <- lapply(fnames, utils::read.table, sep = " ", header = TRUE)
# Getting number of simulation
output[[i]] <- lapply(seq_along(fnames), function(j) {
if (nrow(output[[i]][[j]]) > 0)
cbind(sim_num = j, output[[i]][[j]])
else
NULL
})
# Putting all together
output[[i]] <- do.call(rbind, output[[i]])
# If there are no observations, then
err_msg <- tryCatch({
class(output[[i]]) <- c("epiworld_multiple_save_i", class(output[[i]]))
}, error = function(e) e
)
if (inherits(err_msg, "error")) {
warning(
"When retrieving the saved results, for the case of ",
i, ", there were no observations."
)
class(output[[i]]) <- c(
"epiworld_multiple_save_i",
class(output[[i]])
)
}
attr(output[[i]], "what") <- i
}
structure(output, class = c("epiworld_multiple_save", class(output)))
}
#' @export
plot.epiworld_multiple_save <- function(x, y = NULL, ...) {
# what <- attr(x, "what")
lapply(x, plot)
}
#' @export
plot.epiworld_multiple_save_i <- function(x, y = NULL, ...) {
what <- attr(x, "what")
if (nrow(x) == 0) {
warning(
"When plotting the saved results, for the case of ",
what, ", there were no observations."
)
return(NULL)
}
# If it is not reproductive number, then...
if (what != "reproductive") {
oldpar <- graphics::par(
mfrow = c(2, floor(length(unique(x$state))/2))
)
on.exit(graphics::par(oldpar))
for (what in unique(x$state)) {
graphics::boxplot(
counts ~ date,
data = x[x$state == what,,drop=FALSE],
main = what,
xlab = "Date",
ylab = "Counts",
border = "black",
las = 2
)
}
} else {
plot.epiworld_multiple_save_reproductive_number(x, ...)
}
}
#' @export
plot.epiworld_multiple_save_reproductive_number <- function(x, y = NULL, ...) {
# Identifying sims
sims <- sort(unique(x[["sim_num"]]))
totals <- NULL
for (s in sims) {
# Subsetting the data
x_tmp <- x[x[["sim_num"]] == s,, drop = FALSE]
# Computing daily values
totals <- rbind(
totals,
plot.epiworld_repnum(x_tmp, plot = FALSE)
)
}
graphics::boxplot(
avg ~ date,
data = totals,
main = "Reproductive Number",
xlab = "Source Exposure Date",
ylab = "rt",
border = "black",
las = 2
)
invisible(totals)
}
#' @export
#' @rdname run_multiple
#' @aliases epiworld_saver
make_saver <- function(
...,
fn = ""
) {
what <- list(...)
# Any missmatch?
available <- c(
"total_hist",
"virus_info",
"virus_hist",
"tool_info",
"tool_hist",
"transmission",
"transition",
"reproductive",
"generation"
)
not_in_available <- which(!(what %in% available))
if (length(not_in_available)) {
stop(
"The following elements in -what- are not supported: \"",
paste(what[not_in_available], collapse = "\" , \""),
"\""
)
}
what_bool <- as.list(available %in% what)
names(what_bool) <- available
# Checking the filename
file_output <- TRUE
# Using tempfile to generate directories
id <- basename(tempfile("epiworldR-"))
if (fn == "") {
fp <- file.path(tempdir(), id)
dir.create(fp)
fn <- file.path(fp, "%05lu-episim")
file_output <- FALSE
} else if (!dir.exists(dirname(fn))) {
stop("The directory \"", dirname(fn), "\" does not exists.")
}
what_bool$fn <- fn
# Generating the saver
structure(
list(
ptr = do.call(make_saver_cpp, what_bool),
fn = fn,
file_output = file_output,
what = available[which(available %in% what)],
id = id
),
class = "epiworld_saver"
)
}
#' @export
print.epiworld_saver <- function(x, ...) {
cat("A saver for -run_multiple-\n")
cat("Saves the following:", paste(x$what, sep = ", "), "\n")
cat("To file :", ifelse(x$file_output, "yes", "no"), "\n")
if (x$file_output)
cat("Saver pattern :", x$fn)
invisible(x)
}