cobyla.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. """
  2. Interface to Constrained Optimization By Linear Approximation
  3. Functions
  4. ---------
  5. .. autosummary::
  6. :toctree: generated/
  7. fmin_cobyla
  8. """
  9. from __future__ import division, print_function, absolute_import
  10. import numpy as np
  11. from scipy._lib.six import callable
  12. from scipy.optimize import _cobyla
  13. from .optimize import OptimizeResult, _check_unknown_options
  14. try:
  15. from itertools import izip
  16. except ImportError:
  17. izip = zip
  18. __all__ = ['fmin_cobyla']
  19. def fmin_cobyla(func, x0, cons, args=(), consargs=None, rhobeg=1.0,
  20. rhoend=1e-4, maxfun=1000, disp=None, catol=2e-4):
  21. """
  22. Minimize a function using the Constrained Optimization BY Linear
  23. Approximation (COBYLA) method. This method wraps a FORTRAN
  24. implementation of the algorithm.
  25. Parameters
  26. ----------
  27. func : callable
  28. Function to minimize. In the form func(x, \\*args).
  29. x0 : ndarray
  30. Initial guess.
  31. cons : sequence
  32. Constraint functions; must all be ``>=0`` (a single function
  33. if only 1 constraint). Each function takes the parameters `x`
  34. as its first argument, and it can return either a single number or
  35. an array or list of numbers.
  36. args : tuple, optional
  37. Extra arguments to pass to function.
  38. consargs : tuple, optional
  39. Extra arguments to pass to constraint functions (default of None means
  40. use same extra arguments as those passed to func).
  41. Use ``()`` for no extra arguments.
  42. rhobeg : float, optional
  43. Reasonable initial changes to the variables.
  44. rhoend : float, optional
  45. Final accuracy in the optimization (not precisely guaranteed). This
  46. is a lower bound on the size of the trust region.
  47. disp : {0, 1, 2, 3}, optional
  48. Controls the frequency of output; 0 implies no output.
  49. maxfun : int, optional
  50. Maximum number of function evaluations.
  51. catol : float, optional
  52. Absolute tolerance for constraint violations.
  53. Returns
  54. -------
  55. x : ndarray
  56. The argument that minimises `f`.
  57. See also
  58. --------
  59. minimize: Interface to minimization algorithms for multivariate
  60. functions. See the 'COBYLA' `method` in particular.
  61. Notes
  62. -----
  63. This algorithm is based on linear approximations to the objective
  64. function and each constraint. We briefly describe the algorithm.
  65. Suppose the function is being minimized over k variables. At the
  66. jth iteration the algorithm has k+1 points v_1, ..., v_(k+1),
  67. an approximate solution x_j, and a radius RHO_j.
  68. (i.e. linear plus a constant) approximations to the objective
  69. function and constraint functions such that their function values
  70. agree with the linear approximation on the k+1 points v_1,.., v_(k+1).
  71. This gives a linear program to solve (where the linear approximations
  72. of the constraint functions are constrained to be non-negative).
  73. However the linear approximations are likely only good
  74. approximations near the current simplex, so the linear program is
  75. given the further requirement that the solution, which
  76. will become x_(j+1), must be within RHO_j from x_j. RHO_j only
  77. decreases, never increases. The initial RHO_j is rhobeg and the
  78. final RHO_j is rhoend. In this way COBYLA's iterations behave
  79. like a trust region algorithm.
  80. Additionally, the linear program may be inconsistent, or the
  81. approximation may give poor improvement. For details about
  82. how these issues are resolved, as well as how the points v_i are
  83. updated, refer to the source code or the references below.
  84. References
  85. ----------
  86. Powell M.J.D. (1994), "A direct search optimization method that models
  87. the objective and constraint functions by linear interpolation.", in
  88. Advances in Optimization and Numerical Analysis, eds. S. Gomez and
  89. J-P Hennart, Kluwer Academic (Dordrecht), pp. 51-67
  90. Powell M.J.D. (1998), "Direct search algorithms for optimization
  91. calculations", Acta Numerica 7, 287-336
  92. Powell M.J.D. (2007), "A view of algorithms for optimization without
  93. derivatives", Cambridge University Technical Report DAMTP 2007/NA03
  94. Examples
  95. --------
  96. Minimize the objective function f(x,y) = x*y subject
  97. to the constraints x**2 + y**2 < 1 and y > 0::
  98. >>> def objective(x):
  99. ... return x[0]*x[1]
  100. ...
  101. >>> def constr1(x):
  102. ... return 1 - (x[0]**2 + x[1]**2)
  103. ...
  104. >>> def constr2(x):
  105. ... return x[1]
  106. ...
  107. >>> from scipy.optimize import fmin_cobyla
  108. >>> fmin_cobyla(objective, [0.0, 0.1], [constr1, constr2], rhoend=1e-7)
  109. array([-0.70710685, 0.70710671])
  110. The exact solution is (-sqrt(2)/2, sqrt(2)/2).
  111. """
  112. err = "cons must be a sequence of callable functions or a single"\
  113. " callable function."
  114. try:
  115. len(cons)
  116. except TypeError:
  117. if callable(cons):
  118. cons = [cons]
  119. else:
  120. raise TypeError(err)
  121. else:
  122. for thisfunc in cons:
  123. if not callable(thisfunc):
  124. raise TypeError(err)
  125. if consargs is None:
  126. consargs = args
  127. # build constraints
  128. con = tuple({'type': 'ineq', 'fun': c, 'args': consargs} for c in cons)
  129. # options
  130. opts = {'rhobeg': rhobeg,
  131. 'tol': rhoend,
  132. 'disp': disp,
  133. 'maxiter': maxfun,
  134. 'catol': catol}
  135. sol = _minimize_cobyla(func, x0, args, constraints=con,
  136. **opts)
  137. if disp and not sol['success']:
  138. print("COBYLA failed to find a solution: %s" % (sol.message,))
  139. return sol['x']
  140. def _minimize_cobyla(fun, x0, args=(), constraints=(),
  141. rhobeg=1.0, tol=1e-4, maxiter=1000,
  142. disp=False, catol=2e-4, **unknown_options):
  143. """
  144. Minimize a scalar function of one or more variables using the
  145. Constrained Optimization BY Linear Approximation (COBYLA) algorithm.
  146. Options
  147. -------
  148. rhobeg : float
  149. Reasonable initial changes to the variables.
  150. tol : float
  151. Final accuracy in the optimization (not precisely guaranteed).
  152. This is a lower bound on the size of the trust region.
  153. disp : bool
  154. Set to True to print convergence messages. If False,
  155. `verbosity` is ignored as set to 0.
  156. maxiter : int
  157. Maximum number of function evaluations.
  158. catol : float
  159. Tolerance (absolute) for constraint violations
  160. """
  161. _check_unknown_options(unknown_options)
  162. maxfun = maxiter
  163. rhoend = tol
  164. iprint = int(bool(disp))
  165. # check constraints
  166. if isinstance(constraints, dict):
  167. constraints = (constraints, )
  168. for ic, con in enumerate(constraints):
  169. # check type
  170. try:
  171. ctype = con['type'].lower()
  172. except KeyError:
  173. raise KeyError('Constraint %d has no type defined.' % ic)
  174. except TypeError:
  175. raise TypeError('Constraints must be defined using a '
  176. 'dictionary.')
  177. except AttributeError:
  178. raise TypeError("Constraint's type must be a string.")
  179. else:
  180. if ctype != 'ineq':
  181. raise ValueError("Constraints of type '%s' not handled by "
  182. "COBYLA." % con['type'])
  183. # check function
  184. if 'fun' not in con:
  185. raise KeyError('Constraint %d has no function defined.' % ic)
  186. # check extra arguments
  187. if 'args' not in con:
  188. con['args'] = ()
  189. # m is the total number of constraint values
  190. # it takes into account that some constraints may be vector-valued
  191. cons_lengths = []
  192. for c in constraints:
  193. f = c['fun'](x0, *c['args'])
  194. try:
  195. cons_length = len(f)
  196. except TypeError:
  197. cons_length = 1
  198. cons_lengths.append(cons_length)
  199. m = sum(cons_lengths)
  200. def calcfc(x, con):
  201. f = fun(x, *args)
  202. i = 0
  203. for size, c in izip(cons_lengths, constraints):
  204. con[i: i + size] = c['fun'](x, *c['args'])
  205. i += size
  206. return f
  207. info = np.zeros(4, np.float64)
  208. xopt, info = _cobyla.minimize(calcfc, m=m, x=np.copy(x0), rhobeg=rhobeg,
  209. rhoend=rhoend, iprint=iprint, maxfun=maxfun,
  210. dinfo=info)
  211. if info[3] > catol:
  212. # Check constraint violation
  213. info[0] = 4
  214. return OptimizeResult(x=xopt,
  215. status=int(info[0]),
  216. success=info[0] == 1,
  217. message={1: 'Optimization terminated successfully.',
  218. 2: 'Maximum number of function evaluations '
  219. 'has been exceeded.',
  220. 3: 'Rounding errors are becoming damaging '
  221. 'in COBYLA subroutine.',
  222. 4: 'Did not converge to a solution '
  223. 'satisfying the constraints. See '
  224. '`maxcv` for magnitude of violation.'
  225. }.get(info[0], 'Unknown exit status.'),
  226. nfev=int(info[1]),
  227. fun=info[2],
  228. maxcv=info[3])