/
cache.R
732 lines (665 loc) · 25.9 KB
/
cache.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
if (!isGeneric(".robustDigest")) {
setGeneric(
".robustDigest",
function(object, objects, length = Inf, algo = "xxhash64") {
standardGeneric(".robustDigest")
})
}
#' \code{.robustDigest} for \code{simList} class objects
#'
#' This is intended to be used within the \code{Cache} function, but can be
#' used to evaluate what a \code{simList} would look like once it is
#' converted to a repeatably digestible object.
#'
#' See \code{\link[reproducible]{robustDigest}}. This method strips out stuff
#' from a simList class object that would make it otherwise not
#' reproducibly digestible between sessions, operating systems,
#' or machines. This will likely still not allow identical digest
#' results across R versions.
#'
#' @inheritParams reproducible::.robustDigest
#'
#' @author Eliot McIntire
#' @exportMethod .robustDigest
#' @importFrom fastdigest fastdigest
#' @importFrom reproducible asPath .orderDotsUnderscoreFirst .robustDigest .sortDotsUnderscoreFirst
#' @importMethodsFrom reproducible .robustDigest
#' @include simList-class.R
#' @aliases Cache
#' @rdname robustDigest
#' @seealso \code{\link[reproducible]{robustDigest}}
#'
setMethod(
".robustDigest",
signature = "simList",
definition = function(object, objects, length, algo,
quick, classOptions) {
outerObjs <- ls(object@.xData, all.names = TRUE)
moduleEnvirs <- mget(outerObjs[outerObjs %in% unlist(modules(object))],
envir = object@.xData)
moduleObjs <- lapply(moduleEnvirs, function(me) ls(me, all.names = TRUE))
allObjsInSimList <- append(list(".xData" = outerObjs), moduleObjs)
allEnvsInSimList <- append(list(object@.xData), moduleEnvirs)
ord <- .orderDotsUnderscoreFirst(allObjsInSimList)
allObjsInSimList <- allObjsInSimList[ord]
allEnvsInSimList <- allEnvsInSimList[ord]
names(allEnvsInSimList) <- names(allObjsInSimList)
isObjectEmpty <- if (!missing(objects)) {
if (!is.null(objects)) {
FALSE
} else {
TRUE
}
} else {
TRUE
}
if (!isObjectEmpty) {
# objects may be provided in a namespaced format: modName:objName --
# e.g., coming from .parseModule
objects1 <- strsplit(objects, split = ":")
lens <- unlist(lapply(objects1, length))
objects1ByMod <- unlist(lapply(objects1[lens > 1], function(x) x[1]))
mods <- unique(objects1ByMod)
objects2 <- lapply(mods, function(mod) {
unlist(lapply(objects1[lens > 1][objects1ByMod == mod], function(x) x[[2]]))
})
names(objects2) <- mods
objects <- append(list(".xData" = unlist(objects1[lens == 1])), objects2)
} else {
objects <- allObjsInSimList
}
envirHash <- Map(objs = allObjsInSimList, name = names(allObjsInSimList),
function(objs, name) {
objectsToDigest <- sort(objs, method = "radix")
objectsToDigest <- objectsToDigest[objectsToDigest %in%
objects[[name]]]
.robustDigest(mget(objectsToDigest, envir = allEnvsInSimList[[name]]),
quick = quick,
length = length)
})
#names(envirHash) <- names(allObjsInSimList)
lens <- unlist(lapply(envirHash, function(x) length(x) > 0))
envirHash <- envirHash[lens]
# Copy all parts except environment, clear that, then convert to list
objectTmp <- object
object <- Copy(object, objects = FALSE, queues = FALSE)
object <- as(object, "simList_")
# Replace the .list slot with the hashes of the slots
object@.Data <- envirHash
# Remove paths (i.e., dirs) as they are not relevant -- it is only the files that are relevant
# i.e., if the same file is located in a different place, that is ok
object@paths <- list()
# don't cache contents of output because file may already exist
object@outputs$file <- basename(object@outputs$file)
if (NROW(object@inputs))
object@inputs$file <- unlist(.robustDigest(object@inputs$file,
quick = quick,
length = length))
deps <- object@depends@dependencies
for (i in seq_along(deps)) {
if (!is.null(deps[[i]])) {
object@depends@dependencies[[i]] <- lapply(
slotNames(object@depends@dependencies[[i]]), function(x) {
slot(object@depends@dependencies[[i]], x)
})
names(object@depends@dependencies[[i]]) <- slotNames(deps[[i]])
object@depends@dependencies[[i]][["timeframe"]] <- as.Date(deps[[i]]@timeframe)
}
}
# Sort the params and .list with dots first, to allow Linux and Windows to be compatible
if (!is.null(classOptions$params)) if (length(classOptions$params)) {
object@params <- list(classOptions$params)
names(object@params) <- classOptions$modules
}
if (!is.null(classOptions$modules)) if (length(classOptions$modules)) {
object@modules <- list(classOptions$modules)
object@depends@dependencies <- object@depends@dependencies[classOptions$modules]
}
object@params <- lapply(object@params, function(x) .sortDotsUnderscoreFirst(x))
object@params <- .sortDotsUnderscoreFirst(object@params)
nonDotList <- grep(".list", slotNames(object), invert = TRUE, value = TRUE)
obj <- list()
obj$.list <- object@.Data
if (length(obj$.list)) {
obj$.list[[1]]$._startClockTime <- NULL
obj$.list[[1]]$._timestamp <- NULL
}
obj[nonDotList] <- lapply(nonDotList, function(x) fastdigest(slot(object, x)))
if (!is.null(classOptions$events))
if (FALSE %in% classOptions$events) obj$events <- NULL
if (!is.null(classOptions$current))
if (FALSE %in% classOptions$current) obj$current <- NULL
if (!is.null(classOptions$completed))
if (FALSE %in% classOptions$completed) obj$completed <- NULL
if (!is.null(classOptions$simtimes))
if (FALSE %in% classOptions$simtimes) obj$simtimes <- NULL
obj
})
if (!isGeneric(".tagsByClass")) {
setGeneric(".tagsByClass", function(object) {
standardGeneric(".tagsByClass")
})
}
#' tagsByClass for simList class objects
#'
#' See \code{\link[reproducible]{.tagsByClass}}. Adds current \code{moduleName},
#' \code{eventType}, \code{eventTime}, and \code{function:spades} as userTags
#'
#' @inheritParams reproducible::.tagsByClass
#'
#' @author Eliot McIntire
#' @exportMethod .tagsByClass
#' @importFrom reproducible .tagsByClass
#' @importFrom reproducible .grepSysCalls
#' @importMethodsFrom reproducible .tagsByClass
#' @include simList-class.R
#' @seealso \code{\link[reproducible]{.tagsByClass}}
#' @rdname tagsByClass
#'
setMethod(
".tagsByClass",
signature = "simList",
definition = function(object) {
cur <- object@current
if (NROW(cur)) {
userTags <- c(
paste0("module:", cur$moduleName),
paste0("eventType:", cur$eventType),
paste0("eventTime:", cur$eventTime),
paste0("function:spades")
) # add this because it will be an outer function, if there are events occurring
} else {
scalls <- sys.calls()
parseModuleFrameNum <- .grepSysCalls(scalls, "^.parseModule")[2]
if (!is.na(parseModuleFrameNum)) {
inObj <- .grepSysCalls(scalls, pattern = "^.inputObjects")
if (any(!is.na(inObj))) {
userTags <- c("function:.inputObjects")
userTags1 <- tryCatch(paste0("module:", get("m", sys.frame(parseModuleFrameNum))),
error = function(x) NULL)
userTags <- c(userTags, userTags1)
}
} else {
userTags <- NULL
}
}
userTags
})
if (!isGeneric(".cacheMessage")) {
setGeneric(".cacheMessage", function(object, functionName, fromMemoise) {
standardGeneric(".cacheMessage")
})
}
#' cacheMessage for simList class objects
#'
#' See \code{\link[reproducible]{.cacheMessage}}.
#'
#' @importFrom reproducible .cacheMessage
#' @importMethodsFrom reproducible .cacheMessage
#' @inheritParams reproducible::.cacheMessage
#' @rdname cacheMessage
#' @include simList-class.R
#' @seealso \code{\link[reproducible]{.cacheMessage}}
#' @exportMethod .cacheMessage
setMethod(
".cacheMessage",
signature = "simList",
definition = function(object, functionName,
fromMemoise = getOption("reproducible.useMemoise", TRUE)) {
cur <- current(object)
if (NROW(cur)) {
whichCached <- grep(".useCache", object@params)
useCacheVals <- lapply(whichCached, function(x) {
object@params[[x]]$.useCache
})
whCurrent <- match(cur$moduleName, names(object@params)[whichCached])
fromWhere <- c("cached", "memoised")[fromMemoise + 1]
if (isTRUE(useCacheVals[[whCurrent]])) {
if (isTRUE(fromMemoise)) {
cat(crayon::blue(" Loading memoised copy of", cur$moduleName, "module\n"))
} else if (!is.na(fromMemoise)){
cat(crayon::blue(" Using cached copy of", cur$moduleName, "module\n",
"adding to memoised copy"))
} else {
cat(crayon::blue(" Using ", fromWhere," copy of", cur$moduleName, "module\n"))
}
} else {
if (isTRUE(fromMemoise)) {
cat(crayon::blue(" Using memoised copy of", cur$eventType, "event in",
cur$moduleName, "module\n"))
} else if (!is.na(fromMemoise)){
cat(crayon::blue(" Using cached copy of", cur$eventType, "event in",
cur$moduleName, "module. Adding to memoised copy.\n"))
} else {
cat(crayon::blue(" Using ", fromWhere," copy of", cur$eventType, "event in",
cur$moduleName, "module\n"))
}
}
} else {
.cacheMessage(NULL, functionName, fromMemoise = fromMemoise)
}
})
#########################################################
if (!isGeneric(".checkCacheRepo")) {
setGeneric(".checkCacheRepo", function(object, create = FALSE) {
standardGeneric(".checkCacheRepo")
})
}
#' checkCacheRepo for simList class objects
#'
#' See \code{\link[reproducible]{.checkCacheRepo}}.
#'
#' @export
#' @exportMethod .checkCacheRepo
#' @importFrom reproducible .checkCacheRepo
#' @importFrom reproducible .grepSysCalls
#' @importMethodsFrom reproducible .checkCacheRepo
#' @include simList-class.R
#' @inheritParams reproducible::.checkCacheRepo
#' @rdname checkCacheRepo
#' @seealso \code{\link[reproducible]{.checkCacheRepo}}
setMethod(
".checkCacheRepo",
signature = "list",
definition = function(object, create) {
object <- .findSimList(object)
whSimList <- unlist(lapply(object, is, "simList"))
if (any(whSimList)) {
# just take the first simList, if there are >1
cacheRepo <- object[whSimList][[1]]@paths$cachePath
} else {
doEventFrameNum <- .grepSysCalls(sys.calls(), "(^doEvent)|(^.parseModule)")[2]
if (!is.na(doEventFrameNum)) {
sim <- get("sim", envir = sys.frame(doEventFrameNum))
cacheRepo <- sim@paths$cachePath
} else {
cacheRepo <- .getOption("reproducible.cachePath")
#checkPath(cacheRepo, create = TRUE) #SpaDES dependency
}
}
checkPath(path = cacheRepo, create = create)
})
if (!isGeneric(".addChangedAttr")) {
setGeneric(".addChangedAttr", function(object, preDigest, origArguments, ...) {
standardGeneric(".addChangedAttr")
})
}
##########################################
#' \code{.addChangedAttr} for simList class objects
#'
#' This will evaluate which elements in the simList object changed following
#' this Cached function call. It will add a named character string as an
#' attribute \code{attr(x, ".Cache")$changed}, indicating which ones changed.
#' When this function is subsequently called again, only these changed objects
#' will be returned. All other \code{simList} objects will remain unchanged.
#'
#' @seealso \code{\link[reproducible]{.addChangedAttr}}.
#'
#' @importFrom reproducible .addChangedAttr
#' @importMethodsFrom reproducible .addChangedAttr
#' @inheritParams reproducible::.addChangedAttr
#' @include simList-class.R
#' @seealso \code{\link[reproducible]{.addChangedAttr}}
#' @exportMethod .addChangedAttr
#' @export
#' @rdname addChangedAttr
setMethod(
".addChangedAttr",
signature = "simList",
definition = function(object, preDigest, origArguments, ...) {
dots <- list(...)
whSimList <- which(unlist(lapply(origArguments, is, "simList")))[1]
# remove the "newCache" attribute, which is irrelevant for digest
if (!is.null(attr(object, ".Cache")$newCache)) attr(object, ".Cache")$newCache <- NULL
postDigest <-
.robustDigest(object, objects = dots$objects,
length = dots$length,
algo = dots$algo,
quick = dots$quick,
classOptions = dots$classOptions)
changed <- if (length(postDigest$.list)) {
internalSimList <- unlist(lapply(preDigest[[whSimList]]$.list,
function(x) !any(startsWith(names(x), "doEvent"))))
whSimList2 <- if (is.null(internalSimList)) {
1
} else {
which(internalSimList)
}
isNewObj <- !names(postDigest$.list[[whSimList2]]) %in%
names(preDigest[[whSimList]]$.list[[whSimList2]])
newObjs <- names(postDigest$.list[[whSimList2]])[isNewObj]
newObjs <- newObjs[!startsWith(newObjs, "._")]
existingObjs <- names(postDigest$.list[[whSimList2]])[!isNewObj]
post <- lapply(postDigest$.list[[whSimList2]][existingObjs], fastdigest::fastdigest)
pre <- lapply(preDigest[[whSimList]]$.list[[whSimList2]][existingObjs], fastdigest::fastdigest)
changedObjs <- names(post[!(unlist(post) %in% unlist(pre))])
c(newObjs, changedObjs)
} else {
character()
}
attr(object, ".Cache")$changed <- changed
object
})
if (!isGeneric(".preDigestByClass")) {
setGeneric(".preDigestByClass", function(object) {
standardGeneric(".preDigestByClass")
})
}
if (!isGeneric(".prepareOutput")) {
setGeneric(".prepareOutput", function(object) {
standardGeneric(".prepareOutput")
})
}
##########################################
#' \code{.prepareOutput} for simList
#'
#' See \code{\link[reproducible]{.prepareOutput}}.
#'
#' @importFrom reproducible .prepareOutput
#' @importMethodsFrom reproducible .prepareOutput
#' @inheritParams reproducible::.prepareOutput
#' @include simList-class.R
#' @seealso \code{\link[reproducible]{.prepareOutput}}
#' @exportMethod .prepareOutput
#' @export
#' @rdname prepareOutput
setMethod(
".prepareOutput",
signature = "simList",
definition = function(object, cacheRepo, ...) {
tmpl <- list(...)
tmpl <- .findSimList(tmpl)
# only take first simList -- may be a problem:
whSimList <- which(unlist(lapply(tmpl, is, "simList")))[1]
simListInput <- !isTRUE(is.na(whSimList))
if (simListInput) {
origEnv <- tmpl[[whSimList]]@.xData
isListOfSimLists <- if (is.list(object)) {
if (is(object[[1]], "simList")) TRUE else FALSE
} else {
FALSE
}
if (isListOfSimLists) {
object2 <- list()
for (i in seq_along(object)) {
# need to keep the list(...) slots ...
# i.e., Caching of simLists is mostly about objects in .xData
object2[[i]] <- Copy(tmpl[[whSimList]], objects = FALSE)
object2[[i]]@.xData <- object[[i]]@.xData
object2[[i]]@completed <- object[[i]]@completed
object2[[i]]@simtimes <- object[[i]]@simtimes
object2[[i]]@current <- object[[i]]@current
object2[[i]]@events <- object[[i]]@events
lsOrigEnv <- ls(origEnv, all.names = TRUE)
keepFromOrig <- !(lsOrigEnv %in% ls(object2[[i]]@.xData, all.names = TRUE))
# list2env(mget(lsOrigEnv[keepFromOrig], envir = origEnv),
# envir = object2[[i]]@.xData)
list2env(mget(lsOrigEnv[keepFromOrig], envir = tmpl[[whSimList]]@.xData),
envir = object2[[i]]@.xData)
}
} else {
# need to keep the tmpl slots ...
# i.e., Caching of simLists is mostly about objects in .xData
# makes soft copy of all objects, i.e., they have the identical objects, which are pointers only
object2 <- Copy(tmpl[[whSimList]], objects = FALSE)
currModules <- currentModule(tmpl[[whSimList]])
# Convert to numeric index, as some modules don't have names
hasCurrModule <- match(currModules, modules(tmpl[[whSimList]]))
if (length(currModules) == 0) currModules <- modules(tmpl[[whSimList]])
createOutputs <- if (length(hasCurrModule)) {
tmpl[[whSimList]]@depends@dependencies[[hasCurrModule]]@outputObjects$objectName
} else {
aa <- lapply(tmpl[[whSimList]]@depends@dependencies, function(dep)
dep@outputObjects$objectName)
unique(unlist(aa))
}
createOutputs <- na.omit(createOutputs)
createOutputs <- c(createOutputs, currModules) # add the environments for each module - allow local objects
# take only the ones that the file changed, based on attr(object, ".Cache")$changed
changedOutputs <- createOutputs[createOutputs %in% attr(object, ".Cache")$changed]
expectsInputs <- if (length(hasCurrModule)) {
tmpl[[whSimList]]@depends@dependencies[[hasCurrModule]]@inputObjects$objectName
} else {
aa <- lapply(tmpl[[whSimList]]@depends@dependencies, function(dep)
dep@inputObjects$objectName)
unique(unlist(aa))
}
# Copy all objects from createOutputs only -- all others take from tmpl[[whSimList]]
lsObjectEnv <- ls(object@.xData, all.names = TRUE)
list2env(mget(lsObjectEnv[lsObjectEnv %in% changedOutputs | lsObjectEnv %in% expectsInputs],
envir = object@.xData), envir = object2@.xData)
if (length(object2@current)==0) { # means it is not in a spades call
object2@completed <- object@completed
}
if (NROW(current(object2)) == 0) {
# this is usually a spades call, i.e., not an event or module doEvent call
object2@events <- object@events
object2@simtimes <- object@simtimes
} else {
# if this is FALSE, it means that events were added by the event
eventsAddedByThisModule <- events(object)$moduleName==current(object2)$moduleName
if (isTRUE(any(eventsAddedByThisModule))) {
if (!isTRUE(all.equal(object@events, object2@events))) {
b <- object@events
b <- lapply(b, function(x) {x[["order"]] <- 2; x})
d <- object2@events
d <- lapply(d, function(x) {x[["order"]] <- 1; x})
a <- do.call(unique,
args = list(append(b[eventsAddedByThisModule], d)))
# a <- do.call(unique,
# args = list(append(object@events[eventsAddedByThisModule], object2@events)))
a1 <- rbindlist(a)
f1 <- a[order(a1$eventTime, a1$eventPriority, a1$order)]
object2@events <- lapply(f1, function(f) {f$order <- NULL; f})
# object2@events <- do.call(unique,
# args = list(append(object@events[eventsAddedByThisModule], object2@events)))
}
}
#object2@events <- unique(rbindlist(list(object@events, object2@events)))
}
object2@current <- object@current
# This is for objects that are not in the return environment yet because they are unrelated to the
# current module -- these need to be copied over
lsOrigEnv <- ls(origEnv, all.names = TRUE)
keepFromOrig <- !(lsOrigEnv %in% ls(object2@.xData, all.names = TRUE))
list2env(mget(lsOrigEnv[keepFromOrig], envir = origEnv), envir = object2@.xData)
}
if (!is.null(attr(object, "removedObjs"))) {
if (length(attr(object, "removedObjs"))) {
rm(list = attr(object, "removedObjs"), envir = object2@.xData)
}
}
attrsToGrab <- setdiff(names(attributes(object)), names(attributes(object2)))
for(atts in attrsToGrab) {
attr(object2, atts) <- attr(object, atts)
}
# attr(object2, "tags") <- attr(object, "tags")
# attr(object2, "call") <- attr(object, "call")
# attr(object2, "function") <- attr(object, "function")
#
return(object2)
} else {
return(object)
}
})
################################################################################
#' Pre-digesting method for \code{simList}
#'
#' Takes a snapshot of simList objects.
#'
#' See \code{\link[reproducible]{.preDigestByClass}}.
#'
#' @author Eliot McIntire
#' @export
#' @exportMethod .preDigestByClass
#' @importFrom reproducible .preDigestByClass
#' @importMethodsFrom reproducible .preDigestByClass
#' @inheritParams reproducible::.preDigestByClass
#' @include simList-class.R
#' @seealso \code{\link[reproducible]{.preDigestByClass}}
#' @rdname preDigestByClass
setMethod(
".preDigestByClass",
signature = "simList",
definition = function(object) {
obj <- ls(object@.xData, all.names = TRUE)
return(obj)
})
if (!isGeneric(".addTagsToOutput")) {
setGeneric(".addTagsToOutput", function(object, outputObjects, FUN) {
standardGeneric(".addTagsToOutput")
})
}
#' addTagsToOutput for simList class objects
#'
#' See \code{\link[reproducible]{.addTagsToOutput}}.
#'
#' @inheritParams reproducible::.addTagsToOutput
#'
#' @author Eliot McIntire
#' @exportMethod .addTagsToOutput
#' @export
#' @importFrom reproducible .addTagsToOutput
#' @importMethodsFrom reproducible .addTagsToOutput
#' @include simList-class.R
#' @rdname addTagsToOutput
#' @seealso \code{\link[reproducible]{.addTagsToOutput}}
#'
setMethod(
".addTagsToOutput",
signature = "simList",
definition = function(object, outputObjects, FUN, preDigestByClass) {
if (!is.null(outputObjects)) {
outputToSave <- object
outputToSave@.xData <- new.env()
outputToSave@.envir <- outputToSave@.xData
# Some objects are conditionally produced from a module's outputObject
whExist <- outputObjects %in% ls(object@.xData, all.names = TRUE)
list2env(mget(outputObjects[whExist], envir = object@.xData), envir = outputToSave@.xData)
attr(outputToSave, "tags") <- attr(object, "tags")
attr(outputToSave, "call") <- attr(object, "call")
if (isS4(FUN))
attr(outputToSave, "function") <- attr(object, "function")
} else {
outputToSave <- object
}
# Some objects are removed from a simList
if (!is.null(preDigestByClass)) {
lsInObj <- ls(object@.xData, all.names = TRUE)
removedObjs <- unlist(preDigestByClass)[!(unlist(preDigestByClass) %in% lsInObj)]
attr(outputToSave, "removedObjs") <- removedObjs
}
outputToSave
})
if (!isGeneric(".objSizeInclEnviros")) {
setGeneric(".objSizeInclEnviros", function(object) {
standardGeneric(".objSizeInclEnviros")
})
}
#' objSizeInclEnviros for simList class objects
#'
#' See \code{\link[reproducible]{.objSizeInclEnviros}}.
#'
#' @importFrom reproducible .objSizeInclEnviros
#' @importFrom utils object.size
#' @importMethodsFrom reproducible .objSizeInclEnviros
#' @inheritParams reproducible::.objSizeInclEnviros
#' @include simList-class.R
#' @seealso \code{\link[reproducible]{.objSizeInclEnviros}}
#' @exportMethod .objSizeInclEnviros
#' @export
#' @rdname objSizeInclEnviros
setMethod(
".objSizeInclEnviros",
signature = "simList",
definition = function(object) {
object.size(as.list(object@.xData, all.names = TRUE)) + object.size(object)
})
#' Find simList in a nested list
#'
#' This is recursive, so it will find the all simLists even if they are deeply nested.
#'
#' @param x any object, used here only when it is a list with at least one
#' \code{simList} in it
#' @rdname findSimList
.findSimList <- function(x) {
if (is.list(x)) {
out <- lapply(x, .findSimList)
out <- unlist(out, recursive = TRUE, use.names = FALSE) # get rid of NULL
if (is.null(out)) out <- list(NULL)
} else {
out <- inherits(x, "simList")
if (out) {
out <- x
} else {
out <- NULL
}
}
return(out)
}
if (!exists("objSize")) {
objSize <- function(..., quick) UseMethod("objSize")
}
#' Object size for simLists
#'
#' Recursively, runs \code{object\.size} on the simList environment.
#' Currently, this will not assess object.size of the other elements
#'
#' @inheritParams reproducible::objSize
#' @importFrom reproducible objSize
#' @export
#' @examples
#' a <- simInit(objects = list(d = 1:10, b = 2:20))
#' objSize(a)
#' object.size(a)
objSize.simList <- function(x, quick = getOption("reproducible.quick", FALSE)) {
xObjName <- deparse(substitute(x))
aa <- objSize(x@.xData, quick = quick)
bb <- as(x, "simList_")
bb@.Data <- list()
bbOs <- list(simList = object.size(bb))
aa <- append(aa, bbOs)
return(aa)
}
#' Make simList correctly work with memoise
#'
#' Because of the environment slot, \code{simList} objects don't
#' correctly memoise a \code{simList}. This method for
#' \code{simList} converts the object to a \code{simList_} first.
#'
#' @return A \code{simList_} object or a \code{simList}, in the case
#' of \code{unmakeMemoiseable}.
#'
#' @importFrom reproducible makeMemoiseable
#' @inheritParams reproducible::makeMemoiseable
#' @rdname makeMemoiseable
#' @include simList-class.R
#' @seealso \code{\link[reproducible]{makeMemoiseable}}
#' @export
makeMemoiseable.simList <- function(x) {
as(x, "simList_")
}
#' @importFrom reproducible unmakeMemoiseable
#' @inheritParams reproducible::unmakeMemoiseable
#' @export
#' @rdname makeMemoiseable
unmakeMemoiseable.simList_ <- function(x) {
as(x, "simList")
}
#' Attach missing attributes from x to y
#'
#' This is an internal helper.
#'
#' @keywords internal
#' @param x an object with attributes
#' @param y an object with attributes
#' @rdname keepAttrs
.keepAttrs <- function(x, y, omitAttrs = c(".envir", ".list", ".xData", ".Data")) {
keepAttrs <- setdiff(names(attributes(x)), names(attributes(y)))
keepAttrs <- setdiff(keepAttrs, omitAttrs)
keepAttrs <- keepAttrs[keepAttrs != "names"]
for (att in keepAttrs) {
attr(y, att) <- attr(x, att)
}
return(y)
}