# NOT RUN {
negll <- function(par, x, sleep=0, verbose=TRUE){
if(verbose)
cat(par, "\n")
Sys.sleep(sleep)
-sum(dnorm(x=x, mean=par[1], sd=par[2], log=TRUE))
}
set.seed(13); x <- rnorm(1000, 5, 2)
cl <- makeCluster(2) # set the number of processor cores
setDefaultCluster(cl=cl) # set 'cl' as default cluster
optimParallel(par=c(1,1), fn=negll, x=x, lower=c(-Inf, .0001))
optimParallel(par=c(1,1), fn=negll, x=x, sleep=0, verbose=TRUE,
lower=c(-Inf, .0001), parallel=list(loginfo=TRUE))
setDefaultCluster(cl=NULL); stopCluster(cl)
## default values of the argument 'parallel':
options("optimParallel.forward", "optimParallel.loginfo")
# }
# NOT RUN {
## - use all avilable processor cores
## - return cat() output to R prompt
## (may have issues on Windows)
if(tolower(.Platform$OS.type) != "windows"){
cl <- makeCluster(spec=detectCores(), type="FORK", outfile="")
} else
cl <- makeCluster(spec=detectCores(), outfile="")
setDefaultCluster(cl=cl)
## return log information
options(optimParallel.loginfo=TRUE)
## stop if change of f(x) is smaller than 0.01
control <- list(factr=.01/.Machine$double.eps)
optimParallel(par=c(1,1), fn=negll, x=x, sleep=.5, verbose=TRUE,
verbose=TRUE, lower=c(-Inf, .0001), control=control)
## each step invokes 5 parallel calls to negll()
optimParallel(par=c(1,1), fn=negll, x=x, sleep=.5, verbose=TRUE,
lower=c(-Inf, .0001), control=control,
parallel=list(forward=TRUE))
## each step invokes 3 parallel calls to negll()
## passing objects to fn/gr (see section 'Notes')
## ----------------------------------------------
a <- 10
fn <- function(par, b) sum((par-a-b)^2)
## approach 1:
clusterExport(cl, "a")
optimParallel(par=1, fn=fn, b=1)
## approach 2 (recommended):
## rewrite 'fn' such that all necessary objects
## are passed as arguments
fn <- function(par, a, b) sum((par-a-b)^2)
optimParallel(par=1, fn=fn, a=20, b=1)
setDefaultCluster(cl=NULL); stopCluster(cl)
# }
Run the code above in your browser using DataLab