1 /* Copyright (c) 2007-2008 Massachusetts Institute of Technology
3 * Permission is hereby granted, free of charge, to any person obtaining
4 * a copy of this software and associated documentation files (the
5 * "Software"), to deal in the Software without restriction, including
6 * without limitation the rights to use, copy, modify, merge, publish,
7 * distribute, sublicense, and/or sell copies of the Software, and to
8 * permit persons to whom the Software is furnished to do so, subject to
9 * the following conditions:
11 * The above copyright notice and this permission notice shall be
12 * included in all copies or substantial portions of the Software.
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 #include "nlopt-util.h"
26 /* utility routines to implement the various stopping criteria */
28 static int relstop(double old, double new, double reltol, double abstol)
30 return(fabs(new - old) < abstol
31 || fabs(new - old) < reltol * (fabs(new) + fabs(old)) * 0.5);
34 int nlopt_stop_ftol(const nlopt_stopping *s, const double f, double oldf)
36 return (relstop(oldf, f, s->ftol_rel, s->ftol_abs));
39 int nlopt_stop_f(const nlopt_stopping *s, const double f, double oldf)
41 return (f <= s->minf_max || nlopt_stop_ftol(s, f, oldf));
44 int nlopt_stop_x(const nlopt_stopping *s, const double *x, const double *oldx)
47 for (i = 0; i < s->n; ++i)
48 if (!relstop(oldx[i], x[i], s->xtol_rel, s->xtol_abs[i]))
53 static double sc(double x, double smin, double smax)
55 return smin + x * (smax - smin);
58 /* some of the algorithms rescale x to a unit hypercube, so we need to
59 scale back before we can compare to the tolerances */
60 int nlopt_stop_xs(const nlopt_stopping *s,
61 const double *xs, const double *oldxs,
62 const double *scale_min, const double *scale_max)
65 for (i = 0; i < s->n; ++i)
66 if (relstop(sc(oldxs[i], scale_min[i], scale_max[i]),
67 sc(xs[i], scale_min[i], scale_max[i]),
68 s->xtol_rel, s->xtol_abs[i]))
73 int nlopt_stop_evals(const nlopt_stopping *s)
75 return (s->maxeval > 0 && s->nevals >= s->maxeval);
78 int nlopt_stop_time(const nlopt_stopping *s)
80 return (s->maxtime > 0 && nlopt_seconds() - s->start >= s->maxtime);
83 int nlopt_stop_evalstime(const nlopt_stopping *stop)
85 return nlopt_stop_evals(stop) || nlopt_stop_time(stop);