File: doRNG.R

package info (click to toggle)
r-cran-dorng 1.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 452 kB
  • sloc: sh: 13; makefile: 2
file content (53 lines) | stat: -rw-r--r-- 1,405 bytes parent folder | download
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
library(doRNG)
library(doParallel)

if( .Platform$OS.type == "unix" ){
  registerDoParallel(2)

  # single %dorng% loops are reproducible
  r1 <- foreach(i=1:4, .options.RNG=1234) %dorng% { runif(1) }
  r2 <- foreach(i=1:4, .options.RNG=1234) %dorng% { runif(1) }
  identical(r1, r2)
  # the sequence os RNG seed is stored as an attribute
  attr(r1, 'rng')
  
  # sequences of %dorng% loops are reproducible
  set.seed(1234)
  s1 <- foreach(i=1:4) %dorng% { runif(1) }
  s2 <- foreach(i=1:4) %dorng% { runif(1) }
  # two consecutive (unseed) %dorng% loops are not identical
  identical(s1, s2)
  
  # But the whole sequence of loops is reproducible
  set.seed(1234)
  s1.2 <- foreach(i=1:4) %dorng% { runif(1) }
  s2.2 <- foreach(i=1:4) %dorng% { runif(1) }
  identical(s1, s1.2) && identical(s2, s2.2)
  # it gives the same result as with .options.RNG
  identical(r1, s1)
  
}

# Works with SNOW-like and MPI clusters
# SNOW-like cluster
cl <- makeCluster(2)
registerDoParallel(cl)

s1 <- foreach(i=1:4, .options.RNG=1234) %dorng% { runif(1) }
s2 <- foreach(i=1:4, .options.RNG=1234) %dorng% { runif(1) }
identical(s1, s2)

stopCluster(cl)
registerDoSEQ()

# MPI cluster
library(doMPI)
cl <- startMPIcluster(2)
registerDoMPI(cl)

s1 <- foreach(i=1:4, .options.RNG=1234) %dorng% { runif(1) }
s2 <- foreach(i=1:4, .options.RNG=1234) %dorng% { runif(1) }
identical(s1, s2)

closeCluster(cl)
registerDoSEQ()