% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/future.R, R/futureAssign.R,
%   R/futureAssign_OP.R, R/futureCall.R
\name{future}
\alias{future}
\alias{futureCall}
\alias{futureAssign}
\alias{\%<-\%}
\alias{\%->\%}
\title{Create a future}
\usage{
future(
  expr,
  envir = parent.frame(),
  substitute = TRUE,
  lazy = FALSE,
  seed = FALSE,
  globals = TRUE,
  packages = NULL,
  stdout = TRUE,
  conditions = "condition",
  earlySignal = FALSE,
  label = NULL,
  gc = FALSE,
  ...
)

futureAssign(
  x,
  value,
  envir = parent.frame(),
  substitute = TRUE,
  lazy = FALSE,
  seed = FALSE,
  globals = TRUE,
  packages = NULL,
  stdout = TRUE,
  conditions = "condition",
  earlySignal = FALSE,
  label = NULL,
  gc = FALSE,
  ...,
  assign.env = envir
)

x \%<-\% value

futureCall(
  FUN,
  args = list(),
  envir = parent.frame(),
  lazy = FALSE,
  seed = FALSE,
  globals = TRUE,
  packages = NULL,
  stdout = TRUE,
  conditions = "condition",
  earlySignal = FALSE,
  label = NULL,
  gc = FALSE,
  ...
)
}
\arguments{
\item{expr, value}{An \R \link[base]{expression}.}

\item{envir}{The \link{environment} from where global objects should be
identified.}

\item{substitute}{If TRUE, argument \code{expr} is
\code{\link[base]{substitute}()}:ed, otherwise not.}

\item{lazy}{If FALSE (default), the future is resolved
eagerly (starting immediately), otherwise not.}

\item{seed}{(optional) If TRUE, the random seed, that is, the state of the
random number generator (RNG) will be set such that statistically sound
random numbers are produced (also during parallelization).
If FALSE (default), it is assumed that the future expression does neither
need nor use random numbers generation.
To use a fixed random seed, specify a L'Ecuyer-CMRG seed (seven integer)
or a regular RNG seed (a single integer).  If the latter, then a
L'Ecuyer-CMRG seed will be automatically created based on the given seed.
Furthermore, if FALSE, then the future will be monitored to make sure it
does not use random numbers.  If it does and depending on the value of
option \code{\link[=future.options]{future.rng.onMisuse}}, the check is
ignored, an informative warning, or error will be produced.
If \code{seed} is NULL, then the effect is as with \code{seed = FALSE}
but without the RNG check being performed.}

\item{globals}{(optional) a logical, a character vector, or a named list
to control how globals are handled.
For details, see section 'Globals used by future expressions'
in the help for \code{\link[=future]{future()}}.}

\item{packages}{(optional) a character vector specifying packages
to be attached in the \R environment evaluating the future.}

\item{stdout}{If TRUE (default), then the standard output is captured,
and re-outputted when \code{value()} is called.
If FALSE, any output is silenced (by sinking it to the null device as
it is outputted).
Using \code{stdout = structure(TRUE, drop = TRUE)} causes the captured
standard output to be dropped from the future object as soon as it has
been relayed. This can help decrease the overall memory consumed by
captured output across futures.
Using \code{stdout = NA} (not recommended) avoids intercepting the standard
output; behavior of such unhandled standard output depends on the future}

\item{conditions}{A character string of conditions classes to be captured
and relayed.  The default is to relay all conditions, including messages
and warnings.  To drop all conditions, use \code{conditions = character(0)}.
Errors are always relayed.
Attribute \code{exclude} can be used to ignore specific classes, e.g.
\code{conditions = structure("condition", exclude = "message")} will capture
all \code{condition} classes except those that inherits from the \code{message} class.
Using \code{conditions = structure(..., drop = TRUE)} causes any captured
conditions to be dropped from the future object as soon as it has
been relayed, e.g. by \code{value(f)}. This can help decrease the overall
memory consumed by captured conditions across futures.
Using \code{conditions = NULL} (not recommended) avoids intercepting conditions,
except from errors; behavior of such unhandled conditions depends on the
future backend and the environment from which R runs.}

\item{earlySignal}{Specified whether conditions should be signaled as soon
as possible or not.}

\item{label}{An optional character string label attached to the future.}

\item{gc}{If TRUE, the garbage collector run (in the process that
evaluated the future) only after the value of the future is collected.
Exactly when the values are collected may depend on various factors such
as number of free workers and whether \code{earlySignal} is TRUE (more
frequently) or FALSE (less frequently).
\emph{Some types of futures ignore this argument.}}

\item{\dots}{Additional arguments passed to \code{\link[=Future]{Future()}}.}

\item{x}{the name of a future variable, which will hold the value
of the future expression (as a promise).}

\item{assign.env}{The \link[base]{environment} to which the variable
should be assigned.}

\item{FUN}{A \link[base]{function} to be evaluated.}

\item{args}{A \link[base]{list} of arguments passed to function \code{FUN}.}
}
\value{
\code{f <- future(expr)} creates a \link{Future} \code{f} that evaluates expression \code{expr}, the value of the future is retrieved using \code{v <- value(f)}.

\code{x \%<-\% value} (a future assignment) and
\code{futureAssign("x", value)} create a \link{Future} that evaluates
expression \code{expr} and binds its value (as a
\link[base:delayedAssign]{promise}) to
a variable \code{x}.  The value of the future is automatically retrieved
when the assigned variable (promise) is queried.
The future itself is returned invisibly, e.g.
\code{f <- futureAssign("x", expr)} and \code{f <- (x \%<-\% expr)}.
Alternatively, the future of a future variable \code{x} can be retrieved
without blocking using \code{f <- \link{futureOf}(x)}.
Both the future and the variable (promise) are assigned to environment
\code{assign.env} where the name of the future is \verb{.future_<name>}.

\code{f <- futureCall(FUN, args)} creates a \link{Future} \code{f} that calls function \code{FUN} with arguments \code{args}, where the value of the future is retrieved using \code{x <- value(f)}.
}
\description{
\if{html}{\figure{logo.png}{options: style='float: right;' alt='logo' width='120'}}
Creates a future that evaluates an \R expression or
a future that calls an \R function with a set of arguments.
How, when, and where these futures are evaluated can be configured
using \code{\link[=plan]{plan()}} such that it is evaluated in parallel on,
for instance, the current machine, on a remote machine, or via a
job queue on a compute cluster.
Importantly, any \R code using futures remains the same regardless
on these settings and there is no need to modify the code when
switching from, say, sequential to parallel processing.
}
\details{
The state of a future is either unresolved or resolved.
The value of a future can be retrieved using \code{v <- \link{value}(f)}.
Querying the value of a non-resolved future will \emph{block} the call
until the future is resolved.
It is possible to check whether a future is resolved or not
without blocking by using \code{\link{resolved}(f)}.

For a future created via a future assignment
(\code{x \%<-\% value} or \code{futureAssign("x", value)}), the value
is bound to a promise, which when queried will internally call
\code{\link[=value]{value()}}  on the future and which will then be resolved
into a regular variable bound to that value.  For example, with future
assignment \code{x \%<-\% value}, the first time variable \code{x} is
queried the call blocks if (and only if) the future is not yet resolved.
As soon as it is resolved, and any succeeding queries, querying \code{x}
will immediately give the value.

The future assignment construct \code{x \%<-\% value} is not a formal
assignment per se, but a binary infix operator on objects \code{x}
and expression \code{value}.  However, by using non-standard evaluation,
this constructs can emulate an assignment operator similar to
\code{x <- value}. Due to \R's precedence rules of operators,
future expressions often need to be explicitly bracketed, e.g.
\code{x \%<-\% { a + b }}.

The \code{futureCall()} function works analogously to
\code{\link[base]{do.call}()}, which calls a function with a set of
arguments.  The difference is that \code{do.call()} returns the value of
the call whereas \code{futureCall()} returns a future.
}
\section{Eager or lazy evaluation}{

By default, a future is resolved using \emph{eager} evaluation
(\code{lazy = FALSE}).  This means that the expression starts to
be evaluated as soon as the future is created.

As an alternative, the future can be resolved using \emph{lazy}
evaluation (\code{lazy = TRUE}).  This means that the expression
will only be evaluated when the value of the future is requested.
\emph{Note that this means that the expression may not be evaluated
at all - it is guaranteed to be evaluated if the value is requested}.

For future assignments, lazy evaluation can be controlled via the
\verb{\%lazy\%} operator, e.g. \code{x \%<-\% { expr } \%lazy\% TRUE}.
}

\section{Globals used by future expressions}{

Global objects (short \emph{globals}) are objects (e.g. variables and
functions) that are needed in order for the future expression to be
evaluated while not being local objects that are defined by the future
expression. For example, in
\preformatted{
  a <- 42
  f <- future({ b <- 2; a * b })
}
variable \code{a} is a global of future assignment \code{f} whereas
\code{b} is a local variable.
In order for the future to be resolved successfully (and correctly),
all globals need to be gathered when the future is created such that
they are available whenever and wherever the future is resolved.

The default behavior (\code{globals = TRUE}),
is that globals are automatically identified and gathered.
More precisely, globals are identified via code inspection of the
future expression \code{expr} and their values are retrieved with
environment \code{envir} as the starting point (basically via
\code{get(global, envir = envir, inherits = TRUE)}).
\emph{In most cases, such automatic collection of globals is sufficient
and less tedious and error prone than if they are manually specified}.

However, for full control, it is also possible to explicitly specify
exactly which the globals are by providing their names as a character
vector.
In the above example, we could use
\preformatted{
  a <- 42
  f <- future({ b <- 2; a * b }, globals = "a")
}

Yet another alternative is to explicitly specify also their values
using a named list as in
\preformatted{
  a <- 42
  f <- future({ b <- 2; a * b }, globals = list(a = a))
}
or
\preformatted{
  f <- future({ b <- 2; a * b }, globals = list(a = 42))
}

Specifying globals explicitly avoids the overhead added from
automatically identifying the globals and gathering their values.
Furthermore, if we know that the future expression does not make use
of any global variables, we can disable the automatic search for
globals by using
\preformatted{
  f <- future({ a <- 42; b <- 2; a * b }, globals = FALSE)
}

Future expressions often make use of functions from one or more packages.
As long as these functions are part of the set of globals, the future
package will make sure that those packages are attached when the future
is resolved.  Because there is no need for such globals to be frozen
or exported, the future package will not export them, which reduces
the amount of transferred objects.
For example, in
\preformatted{
  x <- rnorm(1000)
  f <- future({ median(x) })
}
variable \code{x} and \code{median()} are globals, but only \code{x}
is exported whereas \code{median()}, which is part of the \pkg{stats}
package, is not exported.  Instead it is made sure that the \pkg{stats}
package is on the search path when the future expression is evaluated.
Effectively, the above becomes
\preformatted{
  x <- rnorm(1000)
  f <- future({
    library("stats")
    median(x)
  })
}
To manually specify this, one can either do
\preformatted{
  x <- rnorm(1000)
  f <- future({
    median(x)
  }, globals = list(x = x, median = stats::median)
}
or
\preformatted{
  x <- rnorm(1000)
  f <- future({
    library("stats")
    median(x)
  }, globals = list(x = x))
}
Both are effectively the same.

Although rarely needed, a combination of automatic identification and manual
specification of globals is supported via attributes \code{add} (to add
false negatives) and \code{ignore} (to ignore false positives) on value
\code{TRUE}.  For example, with
\code{globals = structure(TRUE, ignore = "b", add = "a")} any globals
automatically identified except \code{b} will be used in addition to
global \code{a}.

When using future assignments, globals can be specified analogously
using the \code{\link{\%globals\%}} operator, e.g.
\preformatted{
  x <- rnorm(1000)
  y \%<-\% { median(x) } \%globals\% list(x = x, median = stats::median)
}
}

\examples{
## Evaluate futures in parallel
plan(multisession)

## Data
x <- rnorm(100)
y <- 2 * x + 0.2 + rnorm(100)
w <- 1 + x ^ 2


## EXAMPLE: Regular assignments (evaluated sequentially)
fitA <- lm(y ~ x, weights = w)      ## with offset
fitB <- lm(y ~ x - 1, weights = w)  ## without offset
fitC <- {
  w <- 1 + abs(x)  ## Different weights
  lm(y ~ x, weights = w)
}
print(fitA)
print(fitB)
print(fitC)


## EXAMPLE: Future assignments (evaluated in parallel)
fitA \%<-\% lm(y ~ x, weights = w)      ## with offset
fitB \%<-\% lm(y ~ x - 1, weights = w)  ## without offset
fitC \%<-\% {
  w <- 1 + abs(x)
  lm(y ~ x, weights = w)
}
print(fitA)
print(fitB)
print(fitC)


## EXAMPLE: Explicitly create futures (evaluated in parallel)
## and retrieve their values
fA <- future( lm(y ~ x, weights = w) )
fB <- future( lm(y ~ x - 1, weights = w) )
fC <- future({
  w <- 1 + abs(x)
  lm(y ~ x, weights = w)
})
fitA <- value(fA)
fitB <- value(fB)
fitC <- value(fC)
print(fitA)
print(fitB)
print(fitC)

\dontshow{
## Make sure to "close" an multisession workers on Windows
plan(sequential)
}
## EXAMPLE: futureCall() and do.call()
x <- 1:100
y0 <- do.call(sum, args = list(x))
print(y0)

f1 <- futureCall(sum, args = list(x))
y1 <- value(f1)
print(y1)
}
\seealso{
How, when and where futures are resolved is given by the
\emph{future strategy}, which can be set by the end user using the
\code{\link[=plan]{plan()}} function.  The future strategy must not be
set by the developer, e.g. it must not be called within a package.
}
\author{
The future logo was designed by Dan LaBar and tweaked by Henrik Bengtsson.
}
