optim
Generalpurpose Optimization
Generalpurpose optimization based on NelderMead, quasiNewton and conjugategradient algorithms. It includes an option for boxconstrained optimization and simulated annealing.
Usage
optim(par, fn, gr = NULL, ..., method = c("NelderMead", "BFGS", "CG", "LBFGSB", "SANN", "Brent"), lower = Inf, upper = Inf, control = list(), hessian = FALSE)
optimHess(par, fn, gr = NULL, ..., control = list())
Arguments
 par
 Initial values for the parameters to be optimized over.
 fn
 A function to be minimized (or maximized), with first argument the vector of parameters over which minimization is to take place. It should return a scalar result.
 gr
 A function to return the gradient for the
"BFGS"
,"CG"
and"LBFGSB"
methods. If it isNULL
, a finitedifference approximation will be used.For the
"SANN"
method it specifies a function to generate a new candidate point. If it isNULL
a default Gaussian Markov kernel is used.  ...
 Further arguments to be passed to
fn
andgr
.  method
 The method to be used. See ‘Details’. Can be abbreviated.
 lower, upper
 Bounds on the variables for the
"LBFGSB"
method, or bounds in which to search for method"Brent"
.  control
 A list of control parameters. See ‘Details’.
 hessian
 Logical. Should a numerically differentiated Hessian matrix be returned?
Details
Note that arguments after ...
must be matched exactly.
By default optim
performs minimization, but it will maximize
if control$fnscale
is negative. optimHess
is an
auxiliary function to compute the Hessian at a later stage if
hessian = TRUE
was forgotten.
The default method is an implementation of that of Nelder and Mead (1965), that uses only function values and is robust but relatively slow. It will work reasonably well for nondifferentiable functions.
Method "BFGS"
is a quasiNewton method (also known as a variable
metric algorithm), specifically that published simultaneously in 1970
by Broyden, Fletcher, Goldfarb and Shanno. This uses function values
and gradients to build up a picture of the surface to be optimized.
Method "CG"
is a conjugate gradients method based on that by
Fletcher and Reeves (1964) (but with the option of PolakRibiere or
BealeSorenson updates). Conjugate gradient methods will generally
be more fragile than the BFGS method, but as they do not store a
matrix they may be successful in much larger optimization problems.
Method "LBFGSB"
is that of Byrd et. al. (1995) which
allows box constraints, that is each variable can be given a lower
and/or upper bound. The initial value must satisfy the constraints.
This uses a limitedmemory modification of the BFGS quasiNewton
method. If nontrivial bounds are supplied, this method will be
selected, with a warning.
Nocedal and Wright (1999) is a comprehensive reference for the previous three methods.
Method "SANN"
is by default a variant of simulated annealing
given in Belisle (1992). Simulatedannealing belongs to the class of
stochastic global optimization methods. It uses only function values
but is relatively slow. It will also work for nondifferentiable
functions. This implementation uses the Metropolis function for the
acceptance probability. By default the next candidate point is
generated from a Gaussian Markov kernel with scale proportional to the
actual temperature. If a function to generate a new candidate point is
given, method "SANN"
can also be used to solve combinatorial
optimization problems. Temperatures are decreased according to the
logarithmic cooling schedule as given in Belisle (1992, p.\ifelse{latex}{\out{~}}{ } 890);
specifically, the temperature is set to
temp / log(((t1) %/% tmax)*tmax + exp(1))
, where t
is
the current iteration step and temp
and tmax
are
specifiable via control
, see below. Note that the
"SANN"
method depends critically on the settings of the control
parameters. It is not a generalpurpose method but can be very useful
in getting to a good value on a very rough surface.
Method "Brent"
is for onedimensional problems only, using
optimize()
. It can be useful in cases where
optim()
is used inside other functions where only method
can be specified, such as in mle
from package stats4.
Function fn
can return NA
or Inf
if the function
cannot be evaluated at the supplied value, but the initial value must
have a computable finite value of fn
.
(Except for method "LBFGSB"
where the values should always be
finite.)
optim
can be used recursively, and for a single parameter
as well as many. It also accepts a zerolength par
, and just
evaluates the function with that argument.
The control
argument is a list that can supply any of the
following components:
trace
 Nonnegative integer. If positive,
tracing information on the
progress of the optimization is produced. Higher values may
produce more tracing information: for method
"LBFGSB"
there are six levels of tracing. (To understand exactly what these do see the source code: higher levels give more detail.)
fnscale
fn
and gr
during optimization. If negative,
turns the problem into a maximization problem. Optimization is
performed on fn(par)/fnscale
.
parscale
par/parscale
and these should be
comparable in the sense that a unit change in any element produces
about a unit change in the scaled value. Not used (nor needed)
for method = "Brent"
.
ndeps
par/parscale
scale. Defaults to 1e3
.
maxit
100
for the derivativebased methods, and
500
for "NelderMead"
. For "SANN"
maxit
gives the total number of function
evaluations: there is no other stopping criterion. Defaults to
10000
.
abstol
reltol
reltol * (abs(val) + reltol)
at a step. Defaults to
sqrt(.Machine$double.eps)
, typically about 1e8
.
alpha
, beta
, gamma
"NelderMead"
method. alpha
is the reflection
factor (default 1.0), beta
the contraction factor (0.5) and
gamma
the expansion factor (2.0).
REPORT
"BFGS"
,
"LBFGSB"
and "SANN"
methods if control$trace
is positive. Defaults to every 10 iterations for "BFGS"
and
"LBFGSB"
, or every 100 temperatures for "SANN"
.
type
1
for the FletcherReeves update, 2
for
PolakRibiere and 3
for BealeSorenson.
lmm
"LBFGSB"
method, It defaults to 5
.
factr
"LBFGSB"
method. Convergence occurs when the reduction in the objective is
within this factor of the machine tolerance. Default is 1e7
,
that is a tolerance of about 1e8
.
pgtol
"LBFGSB"
method. It is a tolerance on the projected gradient in the current
search direction. This defaults to zero, when the check is
suppressed.
temp
"SANN"
method. It is the
starting temperature for the cooling schedule. Defaults to
10
.
tmax
"SANN"
method. Defaults to 10
.
Any names given to par
will be copied to the vectors passed to
fn
and gr
. Note that no other attributes of par
are copied over.
The parameter vector passed to fn
has special semantics and may
be shared between calls: the function should not change or copy it.
Value

For
 par
 The best set of parameters found.
 value
 The value of
fn
corresponding topar
.  counts
 A twoelement integer vector giving the number of calls
to
fn
andgr
respectively. This excludes those calls needed to compute the Hessian, if requested, and any calls tofn
to compute a finitedifference approximation to the gradient.  convergence
 An integer code.
0
indicates successful completion (which is always the case for"SANN"
and"Brent"
). Possible error codes are1
 indicates that the iteration limit
maxit
had been reached. 10
 indicates degeneracy of the NelderMead simplex.
51
 indicates a warning from the
"LBFGSB"
method; see componentmessage
for further details. 52
 indicates an error from the
"LBFGSB"
method; see componentmessage
for further details.
 message
 A character string giving any additional information
returned by the optimizer, or
NULL
.  hessian
 Only if argument
hessian
is true. A symmetric matrix giving an estimate of the Hessian at the solution found. Note that this is the Hessian of the unconstrained problem even if the box constraints are active. For
optim
, a list with components:
optimHess
, the description of the hessian
component
applies.
Note
optim
will work with onedimensional par
s, but the
default method does not work well (and will warn). Method
"Brent"
uses optimize
and needs bounds to be available;
"BFGS"
often works well enough if not.
Source
The code for methods "NelderMead"
, "BFGS"
and
"CG"
was based originally on Pascal code in Nash (1990) that was
translated by p2c
and then handoptimized. Dr Nash has agreed
that the code can be made freely available. The code for method "LBFGSB"
is based on Fortran code by Zhu,
Byrd, LuChen and Nocedal obtained from Netlib (file
‘opt/lbfgs_bcm.shar’: another version is in ‘toms/778’). The code for method "SANN"
was contributed by A. Trapletti.
References
Belisle, C. J. P. (1992) Convergence theorems for a class of simulated annealing algorithms on $Rd$. J. Applied Probability, 29, 885895.
Byrd, R. H., Lu, P., Nocedal, J. and Zhu, C. (1995) A limited memory algorithm for bound constrained optimization. SIAM J. Scientific Computing, 16, 11901208.
Fletcher, R. and Reeves, C. M. (1964) Function minimization by conjugate gradients. Computer Journal 7, 148154.
Nash, J. C. (1990) Compact Numerical Methods for Computers. Linear Algebra and Function Minimisation. Adam Hilger.
Nelder, J. A. and Mead, R. (1965) A simplex algorithm for function minimization. Computer Journal 7, 308313.
Nocedal, J. and Wright, S. J. (1999) Numerical Optimization. Springer.
See Also
optimize
for onedimensional minimization and
constrOptim
for constrained optimization.