-
Notifications
You must be signed in to change notification settings - Fork 13
/
module-define.R
749 lines (707 loc) · 31 KB
/
module-define.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
#' Defaults values used in defineModule
#'
#' Where individual elements are missing in \code{defineModule},
#' these defaults will be used.
#' @export
#'
moduleDefaults <- list(
timeunit = "year",
name = NA_character_,
description = NA_character_,
keywords = NA_character_,
authors = person("unknown"),
childModules = character(0),
version = quote(as.numeric_version(x$version)),
extent = quote(raster::extent(rep(NA_real_, 4))),
timeframe = quote(as.POSIXlt(c(NA, NA))),
citation = list(),
documentation = list(),
reqdPkgs = list()
)
################################################################################
#' Define a new module.
#'
#' Specify a new module's metadata as well as object and package dependencies.
#' Packages are loaded during this call. Any or all of these can be missing, with missing
#' values set to defaults
#'
#' @section Required metadata elements:
#'
#' \tabular{ll}{
#' \code{name} \tab Module name. Must match the filename (without the \code{.R} extension).
#' This is currently not parsed by SpaDES;
#' it is for human readers only. \cr
#' \code{description} \tab Brief description of the module.
#' This is currently not parsed by SpaDES;
#' it is for human readers only. \cr
#' \code{keywords} \tab Author-supplied keywords.
#' This is currently not parsed by SpaDES;
#' it is for human readers only. \cr
#' \code{childModules} \tab If this contains any character vector, then it will
#' be treated as a parent module. If this is a parent module,
#' then only this list entry will be read. For normal,
#' i.e., 'child modules', this should be \code{character(0)} or
#' \code{NA}.
#' If a character vector is provided, then these must be the
#' names of the modules located in the same file path as this
#' parent module that will be loaded during the \code{simInit}.\cr
#' \code{authors} \tab Module author information (as a vector of \code{\link{person}}
#' objects. This is currently not parsed by SpaDES;
#' it is for human readers only.\cr
#' \code{version} \tab Module version number (will be coerced to \code{\link{numeric_version}}
#' if a character or numeric are supplied).
#' The module developer should update manually this with each change
#' that is made to the module. See \url{http://semver.org/}
#' for a widely accepted standard for version numbering.\cr
#' \code{spatialExtent} \tab The spatial extent of the module supplied via
#' \code{raster::extent}. This is currently unimplemented.
#' Once implemented, this should define what spatial region this
#' module is scientifically reasonable to be used in.\cr
#' \code{timeframe} \tab Vector (length 2) of POSIXt dates specifying the temporal extent
#' of the module. Currently unimplemented.
#' Once implemented, this should define what time frame this
#' module is scientifically reasonable to be used for.\cr
#' \code{timeunit} \tab Time scale of the module (e.g., "day", "year"). This
#' MUST be specified. It indicates what '1' unit of time
#' means for this module. \code{SpaDES} interprets this
#' and if modules have different \code{timeunit} values
#' then it will correctly schedule each module, using the
#' smallest (currently the default) timeunit as the
#' 'model' timeunit in the \code{spades} call.\cr
#' \code{citation} \tab List of character strings specifying module citation information.
#' Alternatively, a list of filenames of \code{.bib} or similar files.
#' This is currently not parsed by SpaDES;
#' it is for human readers only.\cr
#' \code{documentation} \tab List of filenames referring to module documentation sources.
#' This is currently not parsed by SpaDES;
#' it is for human readers only.\cr\cr
#' \code{reqdPkgs} \tab List of R package names required by the module. These
#' packages will be loaded when \code{simInit} is called.
#' \code{\link[reproducible]{Require}} will be used internally
#' to load if available, and install if not available.
#' Because \code{\link[reproducible]{Require}} can also download from
#' GitHub.com, these packages can specify package names stored
#' on GitHub, e.g., \code{"PredictiveEcology/SpaDES.core@development"}. \cr
#' \code{parameters} \tab A data.frame specifying the parameters used in the module.
#' Usually produced by \code{rbind}-ing the outputs of multiple
#' \code{\link{defineParameter}} calls. These parameters indicate
#' the default values that will be used unless a module user
#' overrides them with the \code{params} argument in the
#' \code{\link{simInit}} call. The minimum and maximum are
#' currently used by the \code{SpaDES.shiny::shine} function and the
#' \code{POM} function, and they should indicate the range
#' of values that are reasonable scientifically.\cr
#' \code{inputObjects} \tab A \code{data.frame} specifying the data objects expected as
#' inputs to the module,
#' with columns \code{objectName} (class \code{character}),
#' \code{objectClass} (class \code{character}),
#' \code{sourceURL} (class \code{character}), and \code{other}
#' (currently spades does nothing with this column).
#' This data.frame identifies the objects that are expected,
#' but does not do any loading of that object into the simList.
#' The \code{sourceURL} gives the developer the opportunity
#' to identify the source of a data file that can be used
#' with the model. This URL will be
#' used if the user calls \code{downloadData} (or
#' \code{downloadModule(..., data = TRUE)}. If the raw data
#' must be modified, the developer can use create a
#' function called \code{.inputObjects} in their module. That
#' function will be run during the \code{simInit} call. The
#' developer should ensure that if the object is supplied
#' by the module user as an argument in the \code{simInit}, then
#' the \code{.inputObjects} should not be run, i.e., use an
#' \code{(is.null(sim$xxx)))}.\cr
#' \code{outputObjects} \tab A \code{data.frame} specifying the data objects output by
#' the module, with columns identical to those in
#' \code{inputObjects}. Like \code{inputObjects} above,
#' this only identifies the objects that this module will output
#' into the \code{simList}.
#' The module developer must create the necessary functions
#' that will cause these objects to be put into the
#' \code{simList}.\cr
#' }
#'
#' @inheritParams objs
#'
#' @param x A list with a number of named elements, referred to as the metadata. See details.
#'
#' @return Updated \code{simList} object.
#'
#' @author Alex Chubaty
#' @export
#' @importFrom raster extent
#' @importFrom utils person as.person
#' @include simList-class.R
#' @rdname defineModule
#' @seealso moduleDefaults
#'
#' @examples
#' \dontrun{
#' ## a default version of the defineModule is created with a call to newModule
#' newModule("test", path = tempdir())
#'
#' ## view the resulting module file
#' if (interactive()) file.edit(file.path(tempdir(), "test", "test.R"))
#'
#' # The default defineModule created by newModule is currently (SpaDES version 1.3.1.9044):
#' defineModule(sim, list(
#' name = "test",
#' description = "insert module description here",
#' keywords = c("insert key words here"),
#' authors = c(person(c("First", "Middle"), "Last",
#' email = "email@example.com", role = c("aut", "cre"))),
#' childModules = character(0),
#' version = list(SpaDES = "1.3.1.9044", test = "0.0.1"),
#' spatialExtent = raster::extent(rep(NA_real_, 4)),
#' timeframe = as.POSIXlt(c(NA, NA)),
#' timeunit = NA_character_, # e.g., "year",
#' citation = list("citation.bib"),
#' documentation = list("README.txt", "test.Rmd"),
#' reqdPkgs = list(),
#' parameters = rbind(
#' #defineParameter("paramName", "paramClass", value, min, max,
#' # "parameter description")),
#' defineParameter(".plotInitialTime", "numeric", NA, NA, NA,
#' "This describes the simulation time at which the first plot event should occur"),
#' defineParameter(".plotInterval", "numeric", NA, NA, NA,
#' "This describes the simulation time at which the first plot event should occur"),
#' defineParameter(".saveInitialTime", "numeric", NA, NA, NA,
#' "This describes the simulation time at which the first save event should occur"),
#' defineParameter(".saveInterval", "numeric", NA, NA, NA,
#' "This describes the simulation time at which the first save event should occur")
#' ),
#' inputObjects = bind_rows(
#' expectsInput(objectName = NA_character_, objectClass = NA_character_,
#' sourceURL = NA_character_, desc = NA_character_, other = NA_character_)
#' ),
#' outputObjects = bind_rows(
#' createsOutput(objectName = NA_character_, objectClass = NA_character_,
#' desc = NA_character_, other = NA_character_)
#' )
#' ))
#'
#' }
#'
setGeneric("defineModule", function(sim, x) {
standardGeneric("defineModule")
})
#' @export
#' @rdname defineModule
setMethod(
"defineModule",
signature(sim = "simList", x = "list"),
definition = function(sim, x) {
# check that all metadata elements are present
metadataRequired <- slotNames(new(".moduleDeps"))
metadataProvided <- metadataRequired %in% names(x)
metadataMissing <- metadataRequired[!metadataProvided]
if (!all(metadataProvided)) {
warning(paste0(
"The \'", x$name, "\' module is missing the metadata for:\n",
paste(" - ", metadataMissing, collapse = "\n"), "\n",
"Using default values, which may not be desireable.\n",
"See moduleDefaults"
))
}
## enforce/coerce types for the user-supplied param list
lapply(c("name", "description", "keywords"), function(z) {
x[[z]] <<- if (is.null(x[[z]]) || (length(x[[z]]) == 0)) {
moduleDefaults[[z]]
} else {
as.character(x[[z]])
}
})
x$childModules <- if (is.null(x$childModules)) {
moduleDefaults$childModules
} else {
if (isTRUE(is.na(x$childModules))) {
moduleDefaults$childModules
} else {
x$childModules %>% as.character() %>% na.omit() %>% as.character() # nolint
}
}
x$authors <- if (is.null(x$authors) || is.na(x$authors)) {
moduleDefaults$authors
} else {
as.person(x$authors)
}
## maintain backwards compatibility with SpaDES versions prior to 1.3.1.9044
## where `version` was a single `numeric_version` value instead of named list
x$version <- if (is.null(names(x$version))) {
eval(moduleDefaults$version) ## SpaDES < 1.3.1.9044
} else {
as.numeric_version(x$version[[x$name]]) ## SpaDES >= 1.3.1.9044
}
x$spatialExtent <- if (!is(x$spatialExtent, "Extent")) {
if (is.null(x$spatialExtent)) {
eval(moduleDefaults$extent)
} else {
if (is.na(x$spatialExtent)) {
moduleDefaults$extent
} else {
extent(x$spatialExtent)
}
}
}
x$timeframe <- if (is.null(x$timeframe) || is.na(x$timeframe)) {
eval(moduleDefaults$timeframe)
} else if (!is.numeric.POSIXt(x$timeframe)) {
as.POSIXlt(x$timeframe)
} %>% `[`(1:2) # nolint
if (is.null(x$timeunit) || is.na(x$timeunit)) {
x$timeunit <- moduleDefaults$timeunit
}
lapply(c("citation", "documentation", "reqdPkgs"), function(z) {
x[[z]] <<- if (is.null(x[[z]])) {
moduleDefaults[[z]]
} else {
as.list(x[[z]])
}
})
if (is.null(x$parameters)) {
x$parameters <- defineParameter()
} else {
if (is(x$parameters, "data.frame")) {
if (!all(colnames(x$parameters) %in% colnames(defineParameter())) ||
!all(colnames(defineParameter()) %in% colnames(x$parameters))) {
stop("invalid data.frame `parameters` in module `", x$name, "`")
}
} else {
x$parameters <- defineParameter()
}
}
if (is.null(x$inputObjects)) {
x$inputObjects <- ._inputObjectsDF()
} else {
if (is(x$inputObjects, "data.frame")) {
if (!all(colnames(x$inputObjects) %in% colnames(._inputObjectsDF())) ||
!all(colnames(._inputObjectsDF()) %in% colnames(x$inputObjects))) {
stop("invalid data.frame `inputObjects` in module `", x$name, "`:\n",
"provided: ", paste(colnames(x$inputObjects), collapse = ", "),
"expected: ", paste(colnames(._inputObjectsDF()), collapse = ", "))
}
} else {
x$inputObjects <- ._inputObjectsDF()
}
}
if (NROW(x$inputObjects)) {
if (is.null(x$inputObjects$sourceURL)) {
x$inputObjects$sourceURL <- rep(NA_character_, NROW(x$inputObjects))
}
ids <- which(x$inputObjects$sourceURL == "")
if (length(ids)) {
x$inputObjects$sourceURL[ids] <- NA_character_
}
}
if (is.null(x$outputObjects)) {
x$outputObjects <- ._outputObjectsDF()
} else {
if (is(x$outputObjects, "data.frame")) {
if (!all(colnames(x$outputObjects) %in% colnames(._outputObjectsDF())) ||
!all(colnames(._outputObjectsDF()) %in% colnames(x$outputObjects))) {
stop("invalid data.frame `outputObjects` in module `", x$name, "`:",
"provided: ", paste(colnames(x$outputObjects), collapse = ", "), "\n",
"expected: ", paste(colnames(._outputObjectsDF()), collapse = ", "))
}
} else {
x$outputObjects <- ._outputObjectsDF()
}
}
## check that documentation actually exists locally
docs <- sapply(x$documentation, na.omit) %>%
(function(x) if (length(x)) character(0) else as.character(x))
if (length(docs)) {
lapply(docs, function(y) {
if (!file.exists(file.path(modulePath(sim), y))) {
stop("Module documentation file ", y, " not found in modulePath.")
}
})
}
## check that children actually exist locally, and add to list of child modules
if (length(x$childModules)) {
lapply(x$childModules, function(y) {
if (file.exists(file.path(modulePath(sim), y))) {
z <- y %>% lapply(., `attributes<-`, list(type = "child"))
modules(sim) <- append_attr(sim@modules, z)
} else {
stop("Module ", y, "(a child module of ", x$name, ") not found in modulePath.")
}
})
}
## create module deps object and add to sim deps
m <- do.call(new, c(".moduleDeps", x))
return(.addDepends(sim, m))
})
################################################################################
#' Define a parameter used in a module
#'
#' Used to specify a parameter's name, value, and set a default.
#'
#' @note Be sure to use the correct NA type: logical (\code{NA}), integer (\code{NA_integer_}),
#' real (\code{NA_real_}), complex (\code{NA_complex_}), or character (\code{NA_character_}).
#' See \code{\link{NA}}.
#'
#' @param name Character string giving the parameter name.
#' @param class Character string giving the parameter class.
#' @param default The default value to use when none is specified by the user.
#' Non-standard evaluation is used for the expression.
#' @param min With \code{max}, used to define a suitable range of values.
#' Non-standard evaluation is used for the expression.
#' @param max With \code{min}, used to define a suitable range of values.
#' Non-standard evaluation is used for the expression.
#' @param desc Text string providing a brief description of the parameter.
#'
#' @return data.frame
#'
#' @author Alex Chubaty
#' @export
#' @rdname defineParameter
#'
#' @seealso \code{\link{P}}, \code{\link{params}} for accessing these parameters in
#' a module.
#' @examples
#' parameters = rbind(
#' defineParameter("lambda", "numeric", 1.23, desc = "intrinsic rate of increase"),
#' defineParameter("P", "numeric", 0.2, 0, 1, "probability of attack")
#' )
#'
#' \dontrun{
#' # Create a new module, then access parameters using \code{P}
#' tmpdir <- file.path(tempdir(), "test")
#' checkPath(tmpdir, create = TRUE)
#'
#' # creates a new, "empty" module -- it has defaults for everything that is required
#' newModule("testModule", tmpdir)
#'
#' # Look at new module code -- see defineParameter
#' file.edit(file.path(tmpdir, "testModule", "testModule.R"))
#'
#' # initialize the simList
#' mySim <- simInit(modules = "testModule",
#' paths = list(modulePath = tmpdir))
#'
#' # Access one of the parameters -- because this line is not inside a module
#' # function, we must specify the module name. If used within a module,
#' # we can omit the module name
#' P(mySim, "testModule")$.useCache
#'
#' }
#'
#'
setGeneric("defineParameter", function(name, class, default, min, max, desc) {
standardGeneric("defineParameter")
})
#' @rdname defineParameter
setMethod("defineParameter",
signature(name = "character", class = "character", default = "ANY",
min = "ANY", max = "ANY", desc = "character"),
definition = function(name, class, default, min, max, desc) {
# for non-NA values warn if `default`, `min`, and `max` aren't the specified type
# we can't just coerece these because it wouldn't allow for character,
# e.g., start(sim)
anyNAs <- c(is.na(default), is.na(min), is.na(max))
if (!all(anyNAs)) {
# if some or all are NA -- need to check
if (!all(is(c(default, min, max)[!anyNAs], class))) {
#if (!all(is(default, class), is(min, class), is(max, class))) {
# any messages here are captured if this is run from .parseModule
# It will append module name
message(crayon::magenta("defineParameter: '", name, "' is not of specified type '",
class, "'.", sep = ""))
}
}
# previously used `substitute()` instead of `I()`,
# but it did not allow for a vector to be passed with `c()`
df <- data.frame(
paramName = name, paramClass = class, default = I(list(default)),
min = I(list(min)), max = I(list(max)), paramDesc = desc,
stringsAsFactors = FALSE)
return(df)
})
#' @rdname defineParameter
setMethod("defineParameter",
signature(name = "character", class = "character",
default = "ANY", min = "missing", max = "missing",
desc = "character"),
definition = function(name, class, default, desc) {
NAtypes <- c("character", "complex", "integer", "logical", "numeric") # nolint
if (class %in% NAtypes) {
# coerce `min` and `max` to same type as `default`
min <- as(NA, class)
max <- as(NA, class)
} else {
min <- NA
max <- NA
}
df <- data.frame(
paramName = name, paramClass = class, default = I(list(default)),
min = I(list(substitute(min))), max = I(list(substitute(max))),
paramDesc = desc, stringsAsFactors = FALSE
)
return(df)
})
#' @rdname defineParameter
setMethod(
"defineParameter",
signature(name = "missing", class = "missing", default = "missing",
min = "missing", max = "missing", desc = "missing"),
definition = function() {
df <- data.frame(
paramName = character(0), paramClass = character(0),
default = I(list()), min = I(list()), max = I(list()),
paramDesc = character(0), stringsAsFactors = FALSE)
return(df)
})
################################################################################
#' Define an input object that the module expects.
#'
#' Used to specify an input object's name, class, description, source url and
#' other specifications.
#'
#' @param objectName Character string to define the input object's name.
#'
#' @param objectClass Character string to specify the input object's class.
#'
#' @param desc Text string providing a brief description of the input object.
#'
#' @param sourceURL Character string to specify an URL to reach the input object,
#' default is \code{NA}.
#'
#' @param ... Other specifications of the input object.
#'
#' @return A \code{data.frame} suitable to be passed to \code{inputObjects} in a
#' module's metadata.
#'
#' @author Yong Luo
#' @export
#' @rdname expectsInput
#'
#' @examples
#' inputObjects <- dplyr::bind_rows(
#' expectsInput(objectName = "inputObject1", objectClass = "character",
#' desc = "this is for example", sourceURL = "not available"),
#' expectsInput(objectName = "inputObject2", objectClass = "numeric",
#' desc = "this is for example", sourceURL = "not available",
#' otherInformation = "I am the second input object")
#' )
#'
setGeneric("expectsInput",
function(objectName, objectClass, desc, sourceURL, ...) {
standardGeneric("expectsInput")
})
#' @export
#' @rdname expectsInput
setMethod(
"expectsInput",
signature = signature(objectName = "ANY", objectClass = "ANY",
desc = "ANY", sourceURL = "ANY"),
definition = function(objectName, objectClass, desc, sourceURL, ...) {
return(expectsInput(as.character(objectName), as.character(objectClass),
as.character(desc), as.character(sourceURL), ...))
})
#' @export
#' @rdname expectsInput
setMethod(
"expectsInput",
signature = signature(objectName = "character", objectClass = "character",
desc = "character", sourceURL = "character"),
definition = function(objectName, objectClass, desc, sourceURL, ...) {
returnDataframe <- data.frame(cbind(objectName, objectClass, desc, sourceURL),
stringsAsFactors = FALSE)
templist <- list(...)
if (length(templist) > 0) {
for (i in 1:length(templist)) {
returnDataframe <- data.frame(cbind(returnDataframe, I(list(templist[[i]])),
stringsAsFactors = FALSE))
names(returnDataframe)[ncol(returnDataframe)] <- names(templist)[i]
}
}
return(returnDataframe)
})
#' @export
#' @rdname expectsInput
setMethod(
"expectsInput",
signature = signature(objectName = "character", objectClass = "character",
desc = "character", sourceURL = "missing"),
definition = function(objectName, objectClass, desc, ...) {
return(expectsInput(objectName, objectClass, desc, sourceURL = NA_character_, ...))
})
################################################################################
#' Define an output object of a module
#'
#' Used to specify an output object's name, class, description and other specifications.
#'
#' @param objectName Character string to define the output object's name.
#'
#' @param objectClass Character string to specify the output object's class.
#'
#' @param desc Text string providing a brief description of the output object.
#'
#' @param ... Other specifications of the output object.
#'
#' @return A \code{data.frame} suitable to be passed to \code{outputObjects} in
#' a module's metadata.
#'
#' @author Yong Luo
#' @export
#' @rdname createsOutput
#'
#' @examples
#' outputObjects <- dplyr::bind_rows(
#' createsOutput(objectName = "outputObject1", objectClass = "character",
#' desc = "this is for example"),
#' createsOutput(objectName = "outputObject2", objectClass = "numeric",
#' desc = "this is for example",
#' otherInformation = "I am the second output object")
#' )
#'
setGeneric(
"createsOutput",
function(objectName, objectClass, desc, ...) {
standardGeneric("createsOutput")
})
#' @export
#' @rdname createsOutput
setMethod(
"createsOutput",
signature = signature(objectName = "ANY", objectClass = "ANY",
desc = "ANY"),
definition = function(objectName, objectClass, desc, ...) {
return(createsOutput(as.character(objectName), as.character(objectClass),
as.character(desc)))
})
#' @export
#' @rdname createsOutput
setMethod(
"createsOutput",
signature = signature(objectName = "character", objectClass = "character",
desc = "character"),
definition = function(objectName, objectClass, desc, ...) {
returnDataframe <- data.frame(cbind(objectName, objectClass, desc),
stringsAsFactors = FALSE)
templist <- list(...)
if (length(templist) > 0) {
for (i in 1:length(templist)) {
returnDataframe <- data.frame(cbind(returnDataframe, I(list(templist[[i]])),
stringsAsFactors = FALSE))
names(returnDataframe)[ncol(returnDataframe)] <- names(templist)[i]
}
}
return(returnDataframe)
})
#' An internal function for coercing a data.frame to inputs()
#'
#' @param inputDF A data.frame with partial columns to pass to inputs<-
#' @param startTime Numeric time. The start(sim).
#'
#' @keywords internal
#' @importFrom data.table setnames
#' @importFrom tools file_ext
#' @rdname fillInputRows
.fillInputRows <- function(inputDF, startTime) {
factorCols <- sapply(inputDF, is.factor)
if (any(factorCols)) {
inputDF[, factorCols] <- sapply(inputDF[, factorCols], as.character)
}
needRenameArgs <- grepl(names(inputDF), pattern = "arg[s]?$")
if (any(needRenameArgs)) {
colnames(inputDF)[needRenameArgs] <- .fileTableInCols[pmatch("arg", .fileTableInCols)]
}
columns <- pmatch(substr(.fileTableInCols, 1, c(3, 5, 1, 3, 5, 5, 3, 5)), names(inputDF))
setnames(inputDF, old = colnames(inputDF)[na.omit(columns)],
new = .fileTableInCols[!is.na(columns)])
if (any(is.na(columns))) {
inputDF[, .fileTableInCols[is.na(columns)]] <- NA
}
if (any(is.na(inputDF[, "loadTime"]))) {
inputDF[is.na(inputDF$loadTime), "loadTime"] <- startTime
}
if (any(is.na(inputDF[, "objectName"]))) {
inputDF[is.na(inputDF$objectName), "objectName"] <- fileName(inputDF[is.na(inputDF$objectName), "file"]) # nolint
}
# correct those for which a specific function is supplied in filelistDT$fun
usesSemiColon <- grep(inputDF[, "fun"], pattern = "::")
if (length(usesSemiColon) > 0) {
loadFun <- inputDF$fun[usesSemiColon]
splitPackFun <- strsplit(split = "::", loadFun)
inputDF$package[usesSemiColon] <- sapply(splitPackFun, function(x) x[1])
inputDF$fun[usesSemiColon] <- sapply(splitPackFun, function(x) x[2])
}
objectsOnly <- is.na(inputDF[, "file"])
if (!all(objectsOnly)) {
inputDF2 <- inputDF[!objectsOnly, ]
if (any(is.na(inputDF2[, "fun"]))) {
.fileExts <- .fileExtensions()
fl <- inputDF2$file
exts <- na.omit(match(file_ext(fl), .fileExts[, "exts"]))
inputDF2$fun[is.na(inputDF2$fun)] <- .fileExts[exts, "fun"]
}
if (any(is.na(inputDF2[, "package"]))) {
.fileExts <- .fileExtensions()
fl <- inputDF2$file
exts <- match(file_ext(fl), .fileExts[, "exts"])
inputDF2$package[is.na(inputDF2$package)] <- .fileExts[exts, "package"]
}
inputDF[!objectsOnly, ] <- inputDF2
}
return(inputDF)
}
#' An internal function for coercing a data.frame to outputs()
#'
#' @param outputDF A data.frame with partial columns to pass to outputs<-
#' @param endTime Numeric time. The end(sim).
#'
#' @keywords internal
#' @importFrom data.table setnames
#' @importFrom tools file_ext
#' @rdname fillOutputRows
.fillOutputRows <- function(outputDF, endTime) {
needRenameArgs <- grepl(names(outputDF), pattern = "arg[s]?$")
if (any(needRenameArgs)) {
colnames(outputDF)[needRenameArgs] <-
.fileTableOutCols[pmatch("arg", .fileTableOutCols)]
}
columns <- pmatch(substr(.fileTableOutCols, 1, c(3, 5, 1, 3, 5, 5, 3)), names(outputDF))
setnames(outputDF, old = colnames(outputDF)[na.omit(columns)],
new = .fileTableOutCols[!is.na(columns)])
if (any(is.na(columns))) {
outputDF[, .fileTableOutCols[is.na(columns)]] <- NA
}
if (any(is.na(outputDF[, "saveTime"]))) {
outputDF[is.na(outputDF$saveTime), "saveTime"] <- endTime
}
# correct those for which a specific function is supplied in filelistDT$fun
usesSemiColon <- grep(outputDF[, "fun"], pattern = "::")
if (length(usesSemiColon) > 0) {
loadFun <- outputDF$fun[usesSemiColon]
splitPackFun <- strsplit(split = "::", loadFun)
outputDF$package[usesSemiColon] <- sapply(splitPackFun, function(x) x[1])
outputDF$fun[usesSemiColon] <- sapply(splitPackFun, function(x) x[2])
}
if (any(is.na(outputDF[, "fun"]))) {
.fileExts <- .saveFileExtensions()
fl <- outputDF$file
exts <- file_ext(fl)
if (any(is.na(fl)) | any(!nzchar(exts, keepNA = TRUE))) {
outputDF$fun[is.na(fl) | (!nzchar(exts, keepNA = TRUE))] <- .fileExts$fun[1]
}
if (any(is.na(outputDF[, "fun"]))) {
exts <- na.omit(match(exts, .fileExts[, "exts"]))
outputDF$fun[is.na(outputDF$fun)] <- .fileExts[exts, "fun"]
}
}
if (any(is.na(outputDF[, "package"]))) {
.fileExts <- .saveFileExtensions()
fl <- outputDF$file
exts <- file_ext(fl)
if (any(is.na(fl)) | any(!nzchar(exts, keepNA = TRUE))) {
outputDF$package[is.na(fl) | (!nzchar(exts, keepNA = TRUE))] <- .fileExts$package[1]
}
if (any(is.na(outputDF[, "package"]))) {
exts <- na.omit(match(file_ext(fl), .fileExts[, "exts"]) )
outputDF$package[is.na(outputDF$package)] <- .fileExts[exts, "package"]
}
}
return(outputDF)
}