overload_mclapply: Overload 'parallel::mclapply' With 'bettermc::mclapply'

Description Usage Arguments Value Lifecycle Examples

View source: R/overload_mclapply.R

Description

Enable the use of bettermc::mclapply by third-party packages originally using mclapply from the parallel package, e.g. doMC or rstan. This is achieved by replacing the mclapply-function in various environments. undo_overload_mclapply re-installs the original parallel::mclapply.

Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
overload_mclapply(
  parallel_namespace = FALSE,
  parallel_package = FALSE,
  imports = character(),
  defaults = list(),
  fixed_args = list()
)

undo_overload_mclapply(
  parallel_namespace = FALSE,
  parallel_package = FALSE,
  imports = character()
)

Arguments

parallel_namespace

should mclapply be overloaded in the namespace of the parallel package (namespace:parallel)? Use this if the third-party package calls mclapply using the double colon operator, e.g. as in rstan::sampling.

parallel_package

should mclapply be overloaded on the search path iff the parallel package is attached (package:parallel)? This should generally not be required.

imports

the name of packages for which mclapply should be overloaded in their imports, e.g. "doMC" for doMC:imports. If the package is not already loaded, it will be loaded first. The special value "all" means all loaded packages. Use this if the third-party package imports mclapply in its NAMESPACE file, e.g. as the doMC package does.

defaults

a list named by one or more of the formal arguments of bettermc::mclapply providing new defaults for the overloaded function.

fixed_args

a list named by one or more of the formal arguments of bettermc::mclapply, which will fix these to the provided values in the overloaded function.

Value

These functions return NULL invisibly and are called for their side effects.

Lifecycle

options:
   alt='[Experimental]'

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
if (tolower(Sys.info()[["sysname"]]) != "windows") {
  doMC::registerDoMC(2L)

  # fix mc.set.seed arg to NA in order to avoid modifications by doMC:::doMC
  overload_mclapply(imports = "doMC", fixed_args = list(mc.set.seed = NA))

  set.seed(123)
  ret1 <- foreach::`%dopar%`(foreach::foreach(i = 1:4), runif(1))
  set.seed(123)
  ret2 <- foreach::`%dopar%`(foreach::foreach(i = 1:4), runif(1))
  stopifnot(identical(ret1, ret2))

  undo_overload_mclapply(imports = "doMC")

  # back to using parallel::mclapply under the hood -> seeding has no effect
  set.seed(123)
  ret1 <- foreach::`%dopar%`(foreach::foreach(i = 1:4), runif(1))
  set.seed(123)
  ret2 <- foreach::`%dopar%`(foreach::foreach(i = 1:4), runif(1))
  stopifnot(!identical(ret1, ret2))
}

gfkse/bettermcExt documentation built on Dec. 20, 2021, 10:41 a.m.