parallelParams: Setting the parameters for parallel computation

Description Usage Arguments Value Note Examples

View source: R/param_setters.R

Description

parallelParams sets the parameters for parallel computation and registers the cluster. Newly registered clusters should be stopped after the computations are performed.

Usage

1
2
3
4
5
6
parallelParams(
  cl = NULL,
  method = c("auto", "snow", "multicore"),
  ncores = parallel::detectCores() - 1L,
  ...
)

Arguments

cl

an object of class "cluster" (default: NULL)

method

character string of the chosen parallelization method; if 'auto' (default), 'snow' is chosen on Windows and 'multicore' otherwise

ncores

integer; the number of cores

...

options to be passed to the function spawning the workers. See 'Details' in makeCluster and mclapply for snow- and multicore-parallelization, respectively (for multicore, one can use the "preschedule", "set.seed", "silent" options, e.g. options = list(preschedule = FALSE).

Value

parallelParams returns a list with five elements:

Note

If cl_new = TRUE, you should stop the cluster after the computations (see Examples).

Examples

 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
# create a function  which computes the range of values in each column of
# a matrix and can run in single-core or parallel mode
rangeColumns <- function(x, parallel = FALSE) {
    # 
    stopifnot(require(doParallel))
    ob <- getDoBackend() # store active backend
    #
    # parallel argument can be a logical or a direct call to parallelParams
    # or a .(key = value)-type call
    parallel <- argumentDeparser(substitute(parallel), "parallelParams", 
                                 null_params = list(ncores = 0L))
    #
    # stop cluster on exit if it was created by parallelParams
    if (parallel$cl_new) {
        on.exit(stopCluster(parallel$cl))
    }
    on.exit(setDoBackend(ob), add = TRUE)
    #
    # call foreach and compute range
    out <- foreach(xi = iter(x, by = "col"), .combine = "cbind",
                   .options.snow = parallel$snow_options,
                   .options.multicore = parallel$mc_options) %dopar% 
                   range(xi)
    #
    # return with sensible dimension names
    dimnames(out) <- list(range = c("min", "max"), colnames(x))
    out
}
    
# create a toy data matrix
mat <- matrix(rnorm(100), 25, 4)
colnames(mat) <- paste0("column", 1:4)

# compute the range of values in each column and print to the console
ranges_parallel <- rangeColumns(mat, 
                                parallel = .(method = "snow", ncores = 2L))
ranges_parallel

# compare to single-core calculation
ranges_single <- apply(mat, 2, range)
stopifnot(identical(unname(ranges_parallel), 
                    unname(ranges_single)))

tdeenes/eegR documentation built on April 19, 2021, 4:17 p.m.