1## Copyright (C) 2008, 2009 VZLU Prague, a.s.
3## This file is part of Octave.
5## Octave is free software; you can redistribute it and/or modify it
6## under the terms of the GNU General Public License as published by
7## the Free Software Foundation; either version 3 of the License, or (at
8## your option) any later version.
10## Octave is distributed in the hope that it will be useful, but
11## WITHOUT ANY WARRANTY; without even the implied warranty of
12## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13## General Public License for more details.
15## You should have received a copy of the GNU General Public License
16## along with Octave; see the file COPYING. If not, see
17## <http://www.gnu.org/licenses/>.
19## Author: Jaroslav Hajek <highegg@gmail.com>
22## @deftypefn{Function File} {} fminunc (@var{fcn}, @var{x0}, @var{options})
23## @deftypefnx{Function File} {[@var{x}, @var{fvec}, @var{info}, @var{output}, @var{grad}, @var{hess}]} = fminunc (@var{fcn}, @dots{})
24## Solve a unconstrained optimization problem defined by the function @var{fcn}.
25## @var{fcn} should accepts a vector (array) defining the unknown variables,
26## and return the objective function value, optionally with gradient.
27## In other words, this function attempts to determine a vector @var{x} such
28## that @code{@var{fcn} (@var{x})} is a local minimum.
29## @var{x0} determines a starting guess. The shape of @var{x0} is preserved
30## in all calls to @var{fcn}, but otherwise it is treated as a column vector.
31## @var{options} is a structure specifying additional options.
32## Currently, @code{fminunc} recognizes these options:
33## @code{"FunValCheck"}, @code{"OutputFcn"}, @code{"TolX"},
34## @code{"TolFun"}, @code{"MaxIter"}, @code{"MaxFunEvals"},
35## @code{"GradObj"}, @code{"FinDiffType"}.
37## If @code{"GradObj"} is @code{"on"}, it specifies that @var{fcn},
38## called with 2 output arguments, also returns the Jacobian matrix
39## of right-hand sides at the requested point. @code{"TolX"} specifies
40## the termination tolerance in the unknown variables, while
41## @code{"TolFun"} is a tolerance for equations. Default is @code{1e-7}
42## for both @code{"TolX"} and @code{"TolFun"}.
44## For description of the other options, see @code{optimset}.
46## On return, @var{fval} contains the value of the function @var{fcn}
47## evaluated at @var{x}, and @var{info} may be one of the following values:
51## Converged to a solution point. Relative gradient error is less than specified
54## Last relative step size was less that TolX.
56## Last relative decrease in func value was less than TolF.
58## Iteration limit exceeded.
60## The trust region radius became excessively small.
63## Optionally, fminunc can also yield a structure with convergence statistics
64## (@var{output}), the output gradient (@var{grad}) and approximate hessian
67## Note: If you only have a single nonlinear equation of one variable, using
68## @code{fminbnd} is usually a much better idea.
69## @seealso{fminbnd, optimset}
72## PKG_ADD: __all_opts__ ("fminunc");
74function [x, fval, info, output, grad, hess] = fminunc (fcn, x0, options = struct ())
76 ## Get default options if requested.
77 if (nargin == 1 && ischar (fcn) && strcmp (fcn, 'defaults'))
78 x = optimset ("MaxIter", 400, "MaxFunEvals", Inf, \
79 "GradObj", "off", "TolX", 1.5e-8, "TolFun", 1.5e-8,
80 "OutputFcn", [], "FunValCheck", "off",
81 "FinDiffType", "central");
85 if (nargin < 2 || nargin > 3 || ! ismatrix (x0))
90 fcn = str2func (fcn, "global");
96 has_grad = strcmpi (optimget (options, "GradObj", "off"), "on");
97 cdif = strcmpi (optimget (options, "FinDiffType", "central"), "central");
98 maxiter = optimget (options, "MaxIter", 400);
99 maxfev = optimget (options, "MaxFunEvals", Inf);
100 outfcn = optimget (options, "OutputFcn");
102 funvalchk = strcmpi (optimget (options, "FunValCheck", "off"), "on");
105 ## Replace fcn with a guarded version.
106 fcn = @(x) guarded_eval (fcn, x);
109 ## These defaults are rather stringent. I think that normally, user
110 ## prefers accuracy to performance.
112 macheps = eps (class (x0));
114 tolx = optimget (options, "TolX", sqrt (macheps));
115 tolf = optimget (options, "TolFun", sqrt (macheps));
118 ## FIXME: TypicalX corresponds to user scaling (???)
127 ## Initial evaluation.
128 fval = fcn (reshape (x, xsiz));
131 if (! isempty (outfcn))
132 optimvalues.iter = niter;
133 optimvalues.funccount = nfev;
134 optimvalues.fval = fval;
135 optimvalues.searchdirection = zeros (n, 1);
137 stop = outfcn (x, optimvalues, state);
150 while (niter < maxiter && nfev < maxfev && ! info)
154 ## Calculate function value and gradient (possibly via FD).
156 [fval, grad] = fcn (reshape (x, xsiz));
160 grad = __fdjac__ (fcn, reshape (x, xsiz), fval, cdif)(:);
161 nfev += (1 + cdif) * length (x);
165 ## Initialize by identity matrix.
168 ## Use the damped BFGS formula.
173 theta = 0.8 / max (1 - sy / sBs, 0.8);
174 r = theta * y + (1-theta) * Bs;
175 hesr = cholupdate (hesr, r / sqrt (s'*r), "+");
176 [hesr, info] = cholupdate (hesr, Bs / sqrt (sBs), "-");
182 ## Second derivatives approximate the hessian.
183 d2f = norm (hesr, 'columns').';
187 ## FIXME: something better?
188 delta = factor * max (xn, 1);
191 ## FIXME: maybe fixed lower and upper bounds?
192 dg = max (0.1*dg, d2f);
194 ## FIXME -- why tolf*n*xn? If abs (e) ~ abs(x) * eps is a vector
195 ## of perturbations of x, then norm (hesr*e) <= eps*xn, i.e. by
196 ## tolf ~ eps we demand as much accuracy as we can expect.
197 if (norm (grad) <= tolf*n*xn)
206 while (! suc && niter <= maxiter && nfev < maxfev && ! info)
208 s = - __doglegm__ (hesr, grad, dg, delta);
212 delta = min (delta, sn);
215 fval1 = fcn (reshape (x + s, xsiz)) (:);
219 ## Scaled actual reduction.
220 actred = (fval - fval1) / (abs (fval1) + abs (fval));
226 ## Scaled predicted reduction, and ratio.
227 t = 1/2 * sumsq (w) + grad'*s;
229 prered = -t/(abs (fval) + abs (fval + t));
230 ratio = actred / prered;
237 if (ratio < min(max(0.1, 0.8*lastratio), 0.9))
240 if (delta <= 1e1*macheps*xn)
241 ## Trust region became uselessly small.
248 if (abs (1-ratio) <= 0.1)
250 elseif (ratio >= 0.5)
251 delta = max (delta, 1.4142*sn);
256 ## Successful iteration.
266 ## FIXME: should outputfcn be only called after a successful iteration?
267 if (! isempty (outfcn))
268 optimvalues.iter = niter;
269 optimvalues.funccount = nfev;
270 optimvalues.fval = fval;
271 optimvalues.searchdirection = s;
273 stop = outfcn (x, optimvalues, state);
280 ## Tests for termination conditions. A mysterious place, anything
281 ## can happen if you change something here...
283 ## The rule of thumb (which I'm not sure M*b is quite following)
284 ## is that for a tolerance that depends on scaling, only 0 makes
285 ## sense as a default value. But 0 usually means uselessly long
286 ## iterations, so we need scaling-independent tolerances wherever
289 ## The following tests done only after successful step.
291 ## This one is classic. Note that we use scaled variables again,
292 ## but compare to scaled step, so nothing bad.
295 ## Again a classic one.
296 elseif (actred < tolf)
304 ## Restore original shapes.
305 x = reshape (x, xsiz);
307 output.iterations = niter;
308 output.successful = nsuciter;
309 output.funcCount = nfev;
317## An assistant function that evaluates a function handle and checks for
319function [fx, gx] = guarded_eval (fun, x)
327 if (! (isreal (fx) && isreal (jx)))
328 error ("fminunc:notreal", "fminunc: non-real value encountered");
329 elseif (complexeqn && ! (isnumeric (fx) && isnumeric(jx)))
330 error ("fminunc:notnum", "fminunc: non-numeric value encountered");
331 elseif (any (isnan (fx(:))))
332 error ("fminunc:isnan", "fminunc: NaN value encountered");
336%!function f = rosenb (x)
338%! f = sumsq (1 - x(1:n-1)) + 100 * sumsq (x(2:n) - x(1:n-1).^2);
340%! [x, fval, info, out] = fminunc (@rosenb, [5, -5]);
343%! assert (x, ones (1, 2), tol);
344%! assert (fval, 0, tol);
346%! [x, fval, info, out] = fminunc (@rosenb, zeros (1, 4));
349%! assert (x, ones (1, 4), tol);
350%! assert (fval, 0, tol);