% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/optimParallel.R
\docType{package}
\name{optimParallel}
\alias{optimparallel}
\alias{optimParallel-package}
\alias{optimParallel-Package}
\alias{OptimParallel-package}
\alias{OptimParallel-Package}
\alias{optimparallel-package}
\alias{optimparallel-Package}
\alias{optimParallel}
\title{parallel version of the L-BFGS-B method of \code{\link[stats]{optim}}}
\usage{
optimParallel(
  par,
  fn,
  gr = NULL,
  ...,
  lower = -Inf,
  upper = Inf,
  control = list(),
  hessian = FALSE,
  parallel = list()
)
}
\arguments{
\item{par}{see the documentation of \code{\link[stats]{optim}}.}

\item{fn}{see the documentation of \code{\link[stats]{optim}}.}

\item{gr}{see the documentation of \code{\link[stats]{optim}}.}

\item{...}{see the documentation of \code{\link[stats]{optim}}.
See section 'Notes' for more information.}

\item{lower}{see the documentation of \code{\link[stats]{optim}}.}

\item{upper}{see the documentation of \code{\link[stats]{optim}}.}

\item{control}{see the documentation of \code{\link[stats]{optim}}.}

\item{hessian}{see the documentation of \code{\link[stats]{optim}}.}

\item{parallel}{is a list of additional control parameters and can supply any of the following components:
\describe{
\item{\code{cl}}{ an object of class \code{"cluster"} specifying the cluster to be used for parallel execution.
See \code{\link[parallel]{makeCluster}} for more information.
If the argument is not specified or \code{NULL}, the default cluster is used.
See \code{\link[parallel]{setDefaultCluster}} for information on how to set up a default cluster.} 
 \item{\code{forward}}{ logical vector of length 1. If \code{FALSE} (default when loading the package), a numeric central difference approximation of the gradient defined as
\eqn{(fn(x+\epsilon)-fn(x-\epsilon))/(2\epsilon)} is used, which corresponds to the gradient approximation used in \code{\link[stats]{optim}}.
If \code{TRUE}, a numeric forward difference approximation of the gradient essentially defined as
\eqn{(fn(x+\epsilon)-fn(x))/\epsilon} is used. This reduces the number of function calls from \eqn{1+2p} to \eqn{1+p} and can be useful if the number of available cores is smaller than \eqn{1+2p} or if the memory limit is reached. Note that the numeric central difference approximation is more accurate than the numeric forward difference approximation.}
\item{\code{loginfo}}{ logical vector of length 1 with default value \code{FALSE} when loading the package. If \code{TRUE},
additional log information containing the evaluated parameters as well as return values of \code{fn} and \code{gr} is returned.}
}}
}
\value{
Same as the return value of \code{\link[stats]{optim}}. See the documentation thereof for more information.\cr
If \code{parallel=list(loginfo=TRUE)}, additional log information containing the evaluated parameters as well as
the return values of \code{fn} and \code{gr} is returned.
}
\description{
Provides a parallel version of the L-BFGS-B method of optim(). The main function of the package is optimParallel(), which has the same usage and output as optim(). Using optimParallel() can significantly reduce the optimization time.

The function provides a parallel version of the L-BFGS-B method of \code{\link[stats]{optim}}.
If the evaluation time of the objective function \code{fn} is more than 0.1 sceconds, \code{optimParallel} can significantly reduce the optimization time. 
For a \eqn{p}-parameter optimization the speed increase is about factor \eqn{1+2p} when no analytic gradient is specified and \eqn{1+2p} processor cores are available.
}
\details{
\code{optimParallel} is a wrapper to \code{\link[stats]{optim}} and relies on the lexical scoping mechanism of R
and the R package \pkg{parallel} to evaluate \code{fn}
and its (approximate) gradient in parallel.\cr\cr
Some default values of the argument \code{parallel} can be set via\cr\code{options("optimParallel.forward", "optimParallel.loginfo")}.
}
\section{Notes}{

\describe{
\item{1.}{If \code{fn} or \code{gr} depend on functions or methods from loaded packages,
it may be necessary to explicitly load those packages in all processes of the cluster.
For \code{cl} of class \code{"cluster"} one can use \code{clusterEvalQ(cl, search())} to check
whether all required packages are on the search paths of all processes.
If, for example, the R package \pkg{spam} is required and missing on those search paths,
it can be added via \code{clusterEvalQ(cl, library("spam"))}.} 
\item{2.}{If \code{fn} or \code{gr} have more than one argument,
it may be necessary to pass those to \code{optimParallel} via the \code{...} argument.
An illustration is given in the section 'Examples'. }
\item{3.}{We recommend that all R objects used by \code{fn} and/or \code{gr} are passed to \code{fn} and/or \code{gr} via arguments.
In certain cases it may also work that \code{fn} and/or \code{gr} use objects from the \code{.GlobalEnv} (without having corresponding arguments).
In that case it can be necessary to pass those objects to all processes of the used cluster via \code{\link[parallel]{clusterExport}}.
An illustration is given in the section 'Examples'.} 
\item{4.}{Using parallel R code inside \code{fn} and \code{gr} can work if suitable clusters are setup (one cluster for \code{optimParallel} and one for the parallel execution of \code{fn} and \code{gr}).}
\item{5.}{Using \code{optimParallel} with \eqn{n} parallel processes increases the memory usage by about factor \eqn{n} compared to a call to \code{\link[stats]{optim}}.
If the memory limit is reached this may severely slowdown the optimization.
Strategies to reduce memory usage are
(1) kill all unused processes on the computer,
(2) revise the code of \code{fn} and/or \code{gr} to reduce its memory usage, and
(3) reduce the number of parallel processes by specifying the argument \code{parallel=list(forward=TRUE)} and/or
setting up a cluster with less parallel processes.}
}
}

\section{Issues and bug report}{

A list of known issues of \code{optimParallel} can be found at \url{https://github.com/florafauna/optimParallel-R/issues}.
Please report issues not listed there to\eqn{\,} \email{flora.fauna.gerber@gmail.com}. Do not forget to include
an R script reproducing the issue and the output of \code{sessionInfo()}.
}

\examples{
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")

\dontrun{
## - 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) }
}
\references{
F. Gerber, R. Furrer (2019)
optimParallel: An R package providing a parallel version of the L-BFGS-B optimization method.
The R Journal, 11(1):352-358, https://doi.org/10.32614/RJ-2019-030
Also available as vignette of this package \code{vignette("optimParallel")}.
}
\seealso{
Useful links:
\itemize{
  \item \url{https://github.com/florafauna/optimParallel-R}
  \item Report bugs at \url{https://github.com/florafauna/optimParallel-R/issues}
}


\code{\link[stats]{optim}},
\code{\link[parallel]{makeCluster}},
\code{\link[parallel]{setDefaultCluster}},
\code{\link[parallel]{stopCluster}},
\code{\link[parallel]{detectCores}}.
}
\author{
Florian Gerber, \email{flora.fauna.gerber@gmail.com}, \url{https://user.math.uzh.ch/gerber/}.
}
\keyword{internal}
