_shgo.py 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626
  1. """shgo: The simplicial homology global optimisation algorithm."""
  2. from collections import namedtuple
  3. import time
  4. import logging
  5. import warnings
  6. import sys
  7. import numpy as np
  8. from scipy import spatial
  9. from scipy.optimize import OptimizeResult, minimize, Bounds
  10. from scipy.optimize._optimize import MemoizeJac
  11. from scipy.optimize._constraints import new_bounds_to_old
  12. from scipy.optimize._minimize import standardize_constraints
  13. from scipy._lib._util import _FunctionWrapper
  14. from scipy.optimize._shgo_lib._complex import Complex
  15. __all__ = ['shgo']
  16. def shgo(
  17. func, bounds, args=(), constraints=None, n=100, iters=1, callback=None,
  18. minimizer_kwargs=None, options=None, sampling_method='simplicial', *,
  19. workers=1
  20. ):
  21. """
  22. Finds the global minimum of a function using SHG optimization.
  23. SHGO stands for "simplicial homology global optimization".
  24. Parameters
  25. ----------
  26. func : callable
  27. The objective function to be minimized. Must be in the form
  28. ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array
  29. and ``args`` is a tuple of any additional fixed parameters needed to
  30. completely specify the function.
  31. bounds : sequence or `Bounds`
  32. Bounds for variables. There are two ways to specify the bounds:
  33. 1. Instance of `Bounds` class.
  34. 2. Sequence of ``(min, max)`` pairs for each element in `x`.
  35. args : tuple, optional
  36. Any additional fixed parameters needed to completely specify the
  37. objective function.
  38. constraints : {Constraint, dict} or List of {Constraint, dict}, optional
  39. Constraints definition. Only for COBYLA, COBYQA, SLSQP and trust-constr.
  40. See the tutorial [5]_ for further details on specifying constraints.
  41. .. note::
  42. Only COBYLA, COBYQA, SLSQP, and trust-constr local minimize methods
  43. currently support constraint arguments. If the ``constraints``
  44. sequence used in the local optimization problem is not defined in
  45. ``minimizer_kwargs`` and a constrained method is used then the
  46. global ``constraints`` will be used.
  47. (Defining a ``constraints`` sequence in ``minimizer_kwargs``
  48. means that ``constraints`` will not be added so if equality
  49. constraints and so forth need to be added then the inequality
  50. functions in ``constraints`` need to be added to
  51. ``minimizer_kwargs`` too).
  52. COBYLA only supports inequality constraints.
  53. .. versionchanged:: 1.11.0
  54. ``constraints`` accepts `NonlinearConstraint`, `LinearConstraint`.
  55. n : int, optional
  56. Number of sampling points used in the construction of the simplicial
  57. complex. For the default ``simplicial`` sampling method 2**dim + 1
  58. sampling points are generated instead of the default ``n=100``. For all
  59. other specified values `n` sampling points are generated. For
  60. ``sobol``, ``halton`` and other arbitrary `sampling_methods` ``n=100`` or
  61. another specified number of sampling points are generated.
  62. iters : int, optional
  63. Number of iterations used in the construction of the simplicial
  64. complex. Default is 1.
  65. callback : callable, optional
  66. Called after each iteration, as ``callback(xk)``, where ``xk`` is the
  67. current parameter vector.
  68. minimizer_kwargs : dict, optional
  69. Extra keyword arguments to be passed to the minimizer
  70. ``scipy.optimize.minimize``. Some important options could be:
  71. method : str
  72. The minimization method. If not given, chosen to be one of
  73. BFGS, L-BFGS-B, SLSQP, depending on whether or not the
  74. problem has constraints or bounds.
  75. args : tuple
  76. Extra arguments passed to the objective function (``func``) and
  77. its derivatives (Jacobian, Hessian).
  78. options : dict, optional
  79. Note that by default the tolerance is specified as
  80. ``{ftol: 1e-12}``
  81. options : dict, optional
  82. A dictionary of solver options. Many of the options specified for the
  83. global routine are also passed to the ``scipy.optimize.minimize``
  84. routine. The options that are also passed to the local routine are
  85. marked with "(L)".
  86. Stopping criteria, the algorithm will terminate if any of the specified
  87. criteria are met. However, the default algorithm does not require any
  88. to be specified:
  89. maxfev : int (L)
  90. Maximum number of function evaluations in the feasible domain.
  91. (Note only methods that support this option will terminate
  92. the routine at precisely exact specified value. Otherwise the
  93. criterion will only terminate during a global iteration)
  94. f_min : float
  95. Specify the minimum objective function value, if it is known.
  96. f_tol : float
  97. Precision goal for the value of f in the stopping
  98. criterion. Note that the global routine will also
  99. terminate if a sampling point in the global routine is
  100. within this tolerance.
  101. maxiter : int
  102. Maximum number of iterations to perform.
  103. maxev : int
  104. Maximum number of sampling evaluations to perform (includes
  105. searching in infeasible points).
  106. maxtime : float
  107. Maximum processing runtime allowed
  108. minhgrd : int
  109. Minimum homology group rank differential. The homology group of the
  110. objective function is calculated (approximately) during every
  111. iteration. The rank of this group has a one-to-one correspondence
  112. with the number of locally convex subdomains in the objective
  113. function (after adequate sampling points each of these subdomains
  114. contain a unique global minimum). If the difference in the hgr is 0
  115. between iterations for ``maxhgrd`` specified iterations the
  116. algorithm will terminate.
  117. Objective function knowledge:
  118. symmetry : list or bool
  119. Specify if the objective function contains symmetric variables.
  120. The search space (and therefore performance) is decreased by up to
  121. O(n!) times in the fully symmetric case. If `True` is specified
  122. then all variables will be set symmetric to the first variable.
  123. Default
  124. is set to False.
  125. E.g. f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2
  126. In this equation x_2 and x_3 are symmetric to x_1, while x_5 and
  127. x_6 are symmetric to x_4, this can be specified to the solver as::
  128. symmetry = [0, # Variable 1
  129. 0, # symmetric to variable 1
  130. 0, # symmetric to variable 1
  131. 3, # Variable 4
  132. 3, # symmetric to variable 4
  133. 3, # symmetric to variable 4
  134. ]
  135. jac : bool or callable, optional
  136. Jacobian (gradient) of objective function. Only for CG, BFGS,
  137. Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg. If ``jac`` is a
  138. boolean and is True, ``fun`` is assumed to return the gradient
  139. along with the objective function. If False, the gradient will be
  140. estimated numerically. ``jac`` can also be a callable returning the
  141. gradient of the objective. In this case, it must accept the same
  142. arguments as ``fun``. (Passed to `scipy.optimize.minimize`
  143. automatically)
  144. hess, hessp : callable, optional
  145. Hessian (matrix of second-order derivatives) of objective function
  146. or Hessian of objective function times an arbitrary vector p.
  147. Only for Newton-CG, dogleg, trust-ncg. Only one of ``hessp`` or
  148. ``hess`` needs to be given. If ``hess`` is provided, then
  149. ``hessp`` will be ignored. If neither ``hess`` nor ``hessp`` is
  150. provided, then the Hessian product will be approximated using
  151. finite differences on ``jac``. ``hessp`` must compute the Hessian
  152. times an arbitrary vector. (Passed to `scipy.optimize.minimize`
  153. automatically)
  154. Algorithm settings:
  155. minimize_every_iter : bool
  156. If True then promising global sampling points will be passed to a
  157. local minimization routine every iteration. If False then only the
  158. final minimizer pool will be run. Defaults to True.
  159. local_iter : int
  160. Only evaluate a few of the best minimizer pool candidates every
  161. iteration. If False all potential points are passed to the local
  162. minimization routine.
  163. infty_constraints : bool
  164. If True then any sampling points generated which are outside will
  165. the feasible domain will be saved and given an objective function
  166. value of ``inf``. If False then these points will be discarded.
  167. Using this functionality could lead to higher performance with
  168. respect to function evaluations before the global minimum is found,
  169. specifying False will use less memory at the cost of a slight
  170. decrease in performance. Defaults to True.
  171. Feedback:
  172. disp : bool (L)
  173. Set to True to print convergence messages.
  174. sampling_method : str or function, optional
  175. Current built in sampling method options are ``halton``, ``sobol`` and
  176. ``simplicial``. The default ``simplicial`` provides
  177. the theoretical guarantee of convergence to the global minimum in
  178. finite time. ``halton`` and ``sobol`` method are faster in terms of
  179. sampling point generation at the cost of the loss of
  180. guaranteed convergence. It is more appropriate for most "easier"
  181. problems where the convergence is relatively fast.
  182. User defined sampling functions must accept two arguments of ``n``
  183. sampling points of dimension ``dim`` per call and output an array of
  184. sampling points with shape `n x dim`.
  185. workers : int or map-like callable, optional
  186. Sample and run the local serial minimizations in parallel.
  187. Supply -1 to use all available CPU cores, or an int to use
  188. that many Processes (uses `multiprocessing.Pool <multiprocessing>`).
  189. Alternatively supply a map-like callable, such as
  190. `multiprocessing.Pool.map` for parallel evaluation.
  191. This evaluation is carried out as ``workers(func, iterable)``.
  192. Requires that `func` be pickleable.
  193. .. versionadded:: 1.11.0
  194. Returns
  195. -------
  196. res : OptimizeResult
  197. The optimization result represented as a `OptimizeResult` object.
  198. Important attributes are:
  199. ``x`` the solution array corresponding to the global minimum,
  200. ``fun`` the function output at the global solution,
  201. ``xl`` an ordered list of local minima solutions,
  202. ``funl`` the function output at the corresponding local solutions,
  203. ``success`` a Boolean flag indicating if the optimizer exited
  204. successfully,
  205. ``message`` which describes the cause of the termination,
  206. ``nfev`` the total number of objective function evaluations including
  207. the sampling calls,
  208. ``nlfev`` the total number of objective function evaluations
  209. culminating from all local search optimizations,
  210. ``nit`` number of iterations performed by the global routine.
  211. Notes
  212. -----
  213. Global optimization using simplicial homology global optimization [1]_.
  214. Appropriate for solving general purpose NLP and blackbox optimization
  215. problems to global optimality (low-dimensional problems).
  216. In general, the optimization problems are of the form::
  217. minimize f(x) subject to
  218. g_i(x) >= 0, i = 1,...,m
  219. h_j(x) = 0, j = 1,...,p
  220. where x is a vector of one or more variables. ``f(x)`` is the objective
  221. function ``R^n -> R``, ``g_i(x)`` are the inequality constraints, and
  222. ``h_j(x)`` are the equality constraints.
  223. Optionally, the lower and upper bounds for each element in x can also be
  224. specified using the `bounds` argument.
  225. While most of the theoretical advantages of SHGO are only proven for when
  226. ``f(x)`` is a Lipschitz smooth function, the algorithm is also proven to
  227. converge to the global optimum for the more general case where ``f(x)`` is
  228. non-continuous, non-convex and non-smooth, if the default sampling method
  229. is used [1]_.
  230. The local search method may be specified using the ``minimizer_kwargs``
  231. parameter which is passed on to ``scipy.optimize.minimize``. By default,
  232. the ``SLSQP`` method is used. In general, it is recommended to use the
  233. ``SLSQP``, ``COBYLA``, or ``COBYQA`` local minimization if inequality
  234. constraints are defined for the problem since the other methods do not use
  235. constraints.
  236. The ``halton`` and ``sobol`` method points are generated using
  237. `scipy.stats.qmc`. Any other QMC method could be used.
  238. References
  239. ----------
  240. .. [1] Endres, SC, Sandrock, C, Focke, WW (2018) "A simplicial homology
  241. algorithm for lipschitz optimisation", Journal of Global
  242. Optimization.
  243. .. [2] Joe, SW and Kuo, FY (2008) "Constructing Sobol' sequences with
  244. better two-dimensional projections", SIAM J. Sci. Comput. 30,
  245. 2635-2654.
  246. .. [3] Hock, W and Schittkowski, K (1981) "Test examples for nonlinear
  247. programming codes", Lecture Notes in Economics and Mathematical
  248. Systems, 187. Springer-Verlag, New York.
  249. http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf
  250. .. [4] Wales, DJ (2015) "Perspective: Insight into reaction coordinates and
  251. dynamics from the potential energy landscape",
  252. Journal of Chemical Physics, 142(13), 2015.
  253. .. [5] https://docs.scipy.org/doc/scipy/tutorial/optimize.html#constrained-minimization-of-multivariate-scalar-functions-minimize
  254. Examples
  255. --------
  256. First consider the problem of minimizing the Rosenbrock function, `rosen`:
  257. >>> from scipy.optimize import rosen, shgo
  258. >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]
  259. >>> result = shgo(rosen, bounds)
  260. >>> result.x, result.fun
  261. (array([1., 1., 1., 1., 1.]), 2.920392374190081e-18)
  262. Note that bounds determine the dimensionality of the objective
  263. function and is therefore a required input, however you can specify
  264. empty bounds using ``None`` or objects like ``np.inf`` which will be
  265. converted to large float numbers.
  266. >>> bounds = [(None, None), ]*4
  267. >>> result = shgo(rosen, bounds)
  268. >>> result.x
  269. array([0.99999851, 0.99999704, 0.99999411, 0.9999882 ])
  270. Next, we consider the Eggholder function, a problem with several local
  271. minima and one global minimum. We will demonstrate the use of arguments and
  272. the capabilities of `shgo`.
  273. (https://en.wikipedia.org/wiki/Test_functions_for_optimization)
  274. >>> import numpy as np
  275. >>> def eggholder(x):
  276. ... return (-(x[1] + 47.0)
  277. ... * np.sin(np.sqrt(abs(x[0]/2.0 + (x[1] + 47.0))))
  278. ... - x[0] * np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0))))
  279. ... )
  280. ...
  281. >>> bounds = [(-512, 512), (-512, 512)]
  282. `shgo` has built-in low discrepancy sampling sequences. First, we will
  283. input 64 initial sampling points of the *Sobol'* sequence:
  284. >>> result = shgo(eggholder, bounds, n=64, sampling_method='sobol')
  285. >>> result.x, result.fun
  286. (array([512. , 404.23180824]), -959.6406627208397)
  287. `shgo` also has a return for any other local minima that was found, these
  288. can be called using:
  289. >>> result.xl
  290. array([[ 512. , 404.23180824],
  291. [ 283.0759062 , -487.12565635],
  292. [-294.66820039, -462.01964031],
  293. [-105.87688911, 423.15323845],
  294. [-242.97926 , 274.38030925],
  295. [-506.25823477, 6.3131022 ],
  296. [-408.71980731, -156.10116949],
  297. [ 150.23207937, 301.31376595],
  298. [ 91.00920901, -391.283763 ],
  299. [ 202.89662724, -269.38043241],
  300. [ 361.66623976, -106.96493868],
  301. [-219.40612786, -244.06020508]])
  302. >>> result.funl
  303. array([-959.64066272, -718.16745962, -704.80659592, -565.99778097,
  304. -559.78685655, -557.36868733, -507.87385942, -493.9605115 ,
  305. -426.48799655, -421.15571437, -419.31194957, -410.98477763])
  306. These results are useful in applications where there are many global minima
  307. and the values of other global minima are desired or where the local minima
  308. can provide insight into the system (for example morphologies
  309. in physical chemistry [4]_).
  310. If we want to find a larger number of local minima, we can increase the
  311. number of sampling points or the number of iterations. We'll increase the
  312. number of sampling points to 64 and the number of iterations from the
  313. default of 1 to 3. Using ``simplicial`` this would have given us
  314. 64 x 3 = 192 initial sampling points.
  315. >>> result_2 = shgo(eggholder,
  316. ... bounds, n=64, iters=3, sampling_method='sobol')
  317. >>> len(result.xl), len(result_2.xl)
  318. (12, 23)
  319. Note the difference between, e.g., ``n=192, iters=1`` and ``n=64,
  320. iters=3``.
  321. In the first case the promising points contained in the minimiser pool
  322. are processed only once. In the latter case it is processed every 64
  323. sampling points for a total of 3 times.
  324. To demonstrate solving problems with non-linear constraints consider the
  325. following example from Hock and Schittkowski problem 73 (cattle-feed)
  326. [3]_::
  327. minimize: f = 24.55 * x_1 + 26.75 * x_2 + 39 * x_3 + 40.50 * x_4
  328. subject to: 2.3 * x_1 + 5.6 * x_2 + 11.1 * x_3 + 1.3 * x_4 - 5 >= 0,
  329. 12 * x_1 + 11.9 * x_2 + 41.8 * x_3 + 52.1 * x_4 - 21
  330. -1.645 * sqrt(0.28 * x_1**2 + 0.19 * x_2**2 +
  331. 20.5 * x_3**2 + 0.62 * x_4**2) >= 0,
  332. x_1 + x_2 + x_3 + x_4 - 1 == 0,
  333. 1 >= x_i >= 0 for all i
  334. The approximate answer given in [3]_ is::
  335. f([0.6355216, -0.12e-11, 0.3127019, 0.05177655]) = 29.894378
  336. >>> def f(x): # (cattle-feed)
  337. ... return 24.55*x[0] + 26.75*x[1] + 39*x[2] + 40.50*x[3]
  338. ...
  339. >>> def g1(x):
  340. ... return 2.3*x[0] + 5.6*x[1] + 11.1*x[2] + 1.3*x[3] - 5 # >=0
  341. ...
  342. >>> def g2(x):
  343. ... return (12*x[0] + 11.9*x[1] +41.8*x[2] + 52.1*x[3] - 21
  344. ... - 1.645 * np.sqrt(0.28*x[0]**2 + 0.19*x[1]**2
  345. ... + 20.5*x[2]**2 + 0.62*x[3]**2)
  346. ... ) # >=0
  347. ...
  348. >>> def h1(x):
  349. ... return x[0] + x[1] + x[2] + x[3] - 1 # == 0
  350. ...
  351. >>> cons = ({'type': 'ineq', 'fun': g1},
  352. ... {'type': 'ineq', 'fun': g2},
  353. ... {'type': 'eq', 'fun': h1})
  354. >>> bounds = [(0, 1.0),]*4
  355. >>> res = shgo(f, bounds, n=150, constraints=cons)
  356. >>> res
  357. message: Optimization terminated successfully.
  358. success: True
  359. fun: 29.894378159142136
  360. funl: [ 2.989e+01]
  361. x: [ 6.355e-01 1.137e-13 3.127e-01 5.178e-02] # may vary
  362. xl: [[ 6.355e-01 1.137e-13 3.127e-01 5.178e-02]] # may vary
  363. nit: 1
  364. nfev: 142 # may vary
  365. nlfev: 35 # may vary
  366. nljev: 5
  367. nlhev: 0
  368. >>> g1(res.x), g2(res.x), h1(res.x)
  369. (-5.062616992290714e-14, -2.9594104944408173e-12, 0.0)
  370. """
  371. # if necessary, convert bounds class to old bounds
  372. if isinstance(bounds, Bounds):
  373. bounds = new_bounds_to_old(bounds.lb, bounds.ub, len(bounds.lb))
  374. # Initiate SHGO class
  375. # use in context manager to make sure that any parallelization
  376. # resources are freed.
  377. with SHGO(func, bounds, args=args, constraints=constraints, n=n,
  378. iters=iters, callback=callback,
  379. minimizer_kwargs=minimizer_kwargs,
  380. options=options, sampling_method=sampling_method,
  381. workers=workers) as shc:
  382. # Run the algorithm, process results and test success
  383. shc.iterate_all()
  384. if not shc.break_routine:
  385. if shc.disp:
  386. logging.info("Successfully completed construction of complex.")
  387. # Test post iterations success
  388. if len(shc.LMC.xl_maps) == 0:
  389. # If sampling failed to find pool, return lowest sampled point
  390. # with a warning
  391. shc.find_lowest_vertex()
  392. shc.break_routine = True
  393. shc.fail_routine(mes="Failed to find a feasible minimizer point. "
  394. f"Lowest sampling point = {shc.f_lowest}")
  395. shc.res.fun = shc.f_lowest
  396. shc.res.x = shc.x_lowest
  397. shc.res.nfev = shc.fn
  398. shc.res.tnev = shc.n_sampled
  399. else:
  400. # Test that the optimal solutions do not violate any constraints
  401. pass # TODO
  402. # Confirm the routine ran successfully
  403. if not shc.break_routine:
  404. shc.res.message = 'Optimization terminated successfully.'
  405. shc.res.success = True
  406. # Return the final results
  407. return shc.res
  408. class SHGO:
  409. def __init__(self, func, bounds, args=(), constraints=None, n=None,
  410. iters=None, callback=None, minimizer_kwargs=None,
  411. options=None, sampling_method='simplicial', workers=1):
  412. from scipy.stats import qmc
  413. # Input checks
  414. methods = ['halton', 'sobol', 'simplicial']
  415. if isinstance(sampling_method, str) and sampling_method not in methods:
  416. raise ValueError(("Unknown sampling_method specified."
  417. " Valid methods: {}").format(', '.join(methods)))
  418. # copy the options dictionaries so that the user input is not mutated
  419. if minimizer_kwargs is not None and isinstance(minimizer_kwargs, dict):
  420. minimizer_kwargs = minimizer_kwargs.copy()
  421. if options is not None and isinstance(options, dict):
  422. options = options.copy()
  423. if options is not None and options.get('jac', None) is True:
  424. if minimizer_kwargs is None:
  425. minimizer_kwargs = {}
  426. minimizer_kwargs['jac'] = True
  427. options.pop('jac')
  428. # Split obj func if given with Jac
  429. try:
  430. if ((minimizer_kwargs['jac'] is True) and
  431. (not callable(minimizer_kwargs['jac']))):
  432. self.func = MemoizeJac(func)
  433. jac = self.func.derivative
  434. minimizer_kwargs['jac'] = jac
  435. func = self.func # fun
  436. else:
  437. self.func = func # Normal definition of objective function
  438. except (TypeError, KeyError):
  439. self.func = func # Normal definition of objective function
  440. # Initiate class
  441. self.func = _FunctionWrapper(func, args)
  442. self.bounds = bounds
  443. self.args = args
  444. self.callback = callback
  445. # Bounds
  446. abound = np.array(bounds, float)
  447. self.dim = np.shape(abound)[0] # Dimensionality of problem
  448. # Set none finite values to large floats
  449. infind = ~np.isfinite(abound)
  450. abound[infind[:, 0], 0] = -1e50
  451. abound[infind[:, 1], 1] = 1e50
  452. # Check if bounds are correctly specified
  453. bnderr = abound[:, 0] > abound[:, 1]
  454. if bnderr.any():
  455. raise ValueError("Error: lb > ub in bounds "
  456. f"{', '.join(str(b) for b in bnderr)}.")
  457. self.bounds = abound
  458. # Constraints
  459. # Process constraint dict sequence:
  460. self.constraints = constraints
  461. if constraints is not None:
  462. self.min_cons = constraints
  463. self.g_cons = []
  464. self.g_args = []
  465. # shgo internals deals with old-style constraints
  466. # self.constraints is used to create Complex, so need
  467. # to be stored internally in old-style.
  468. # `minimize` takes care of normalising these constraints
  469. # for slsqp/cobyla/cobyqa/trust-constr.
  470. self.constraints = standardize_constraints(
  471. constraints,
  472. np.empty(self.dim, float),
  473. 'old'
  474. )
  475. for cons in self.constraints:
  476. if cons['type'] in ('ineq'):
  477. self.g_cons.append(cons['fun'])
  478. try:
  479. self.g_args.append(cons['args'])
  480. except KeyError:
  481. self.g_args.append(())
  482. self.g_cons = tuple(self.g_cons)
  483. self.g_args = tuple(self.g_args)
  484. else:
  485. self.g_cons = None
  486. self.g_args = None
  487. # Define local minimization keyword arguments
  488. # Start with defaults
  489. self.minimizer_kwargs = {'method': 'SLSQP',
  490. 'bounds': self.bounds,
  491. 'options': {},
  492. 'callback': self.callback
  493. }
  494. if minimizer_kwargs is not None:
  495. # Overwrite with supplied values
  496. self.minimizer_kwargs.update(minimizer_kwargs)
  497. else:
  498. self.minimizer_kwargs['options'] = {'ftol': 1e-12}
  499. if (
  500. self.minimizer_kwargs['method'].lower() in ('slsqp', 'cobyla',
  501. 'cobyqa',
  502. 'trust-constr')
  503. and (
  504. minimizer_kwargs is not None and
  505. 'constraints' not in minimizer_kwargs and
  506. constraints is not None
  507. ) or
  508. (self.g_cons is not None)
  509. ):
  510. self.minimizer_kwargs['constraints'] = self.min_cons
  511. # Process options dict
  512. if options is not None:
  513. self.init_options(options)
  514. else: # Default settings:
  515. self.f_min_true = None
  516. self.minimize_every_iter = True
  517. # Algorithm limits
  518. self.maxiter = None
  519. self.maxfev = None
  520. self.maxev = None
  521. self.maxtime = None
  522. self.f_min_true = None
  523. self.minhgrd = None
  524. # Objective function knowledge
  525. self.symmetry = None
  526. # Algorithm functionality
  527. self.infty_cons_sampl = True
  528. self.local_iter = False
  529. # Feedback
  530. self.disp = False
  531. # normalize grad + hess calls for args
  532. # this has to be done after minimizer_kwargs has finished having its
  533. # jac/hess/args edited.
  534. _grad = self.minimizer_kwargs.get('jac', None)
  535. if callable(_grad):
  536. self.minimizer_kwargs['jac'] = _FunctionWrapper(_grad, self.args)
  537. _hess = self.minimizer_kwargs.get('hess', None)
  538. if callable(_hess):
  539. self.minimizer_kwargs['hess'] = _FunctionWrapper(_hess, self.args)
  540. # we've already wrapped fun, grad, hess, so no need for args
  541. self.minimizer_kwargs.pop("args", None)
  542. self.minimizer_kwargs["options"].pop("args", None)
  543. # Remove unknown arguments in self.minimizer_kwargs
  544. # Start with arguments all the solvers have in common
  545. self.min_solver_args = ['fun', 'x0', 'args',
  546. 'callback', 'options', 'method']
  547. # then add the ones unique to specific solvers
  548. solver_args = {
  549. '_custom': ['jac', 'hess', 'hessp', 'bounds', 'constraints'],
  550. 'nelder-mead': [],
  551. 'powell': [],
  552. 'cg': ['jac'],
  553. 'bfgs': ['jac'],
  554. 'newton-cg': ['jac', 'hess', 'hessp'],
  555. 'l-bfgs-b': ['jac', 'bounds'],
  556. 'tnc': ['jac', 'bounds'],
  557. 'cobyla': ['constraints', 'catol'],
  558. 'cobyqa': ['bounds', 'constraints', 'feasibility_tol'],
  559. 'slsqp': ['jac', 'bounds', 'constraints'],
  560. 'dogleg': ['jac', 'hess'],
  561. 'trust-ncg': ['jac', 'hess', 'hessp'],
  562. 'trust-krylov': ['jac', 'hess', 'hessp'],
  563. 'trust-exact': ['jac', 'hess'],
  564. 'trust-constr': ['jac', 'hess', 'hessp', 'constraints'],
  565. }
  566. method = self.minimizer_kwargs['method']
  567. self.min_solver_args += solver_args[method.lower()]
  568. # Only retain the known arguments
  569. def _restrict_to_keys(dictionary, goodkeys):
  570. """Remove keys from dictionary if not in goodkeys - inplace"""
  571. existingkeys = set(dictionary)
  572. for key in existingkeys - set(goodkeys):
  573. dictionary.pop(key, None)
  574. _restrict_to_keys(self.minimizer_kwargs, self.min_solver_args)
  575. _restrict_to_keys(self.minimizer_kwargs['options'],
  576. self.min_solver_args + ['ftol'])
  577. # Algorithm controls
  578. # Global controls
  579. self.stop_global = False # Used in the stopping_criteria method
  580. self.break_routine = False # Break the algorithm globally
  581. self.iters = iters # Iterations to be ran
  582. self.iters_done = 0 # Iterations completed
  583. self.n = n # Sampling points per iteration
  584. self.nc = 0 # n # Sampling points to sample in current iteration
  585. self.n_prc = 0 # Processed points (used to track Delaunay iters)
  586. self.n_sampled = 0 # To track no. of sampling points already generated
  587. self.fn = 0 # Number of feasible sampling points evaluations performed
  588. self.hgr = 0 # Homology group rank
  589. # Initially attempt to build the triangulation incrementally:
  590. self.qhull_incremental = True
  591. # Default settings if no sampling criteria.
  592. if (self.n is None) and (self.iters is None) \
  593. and (sampling_method == 'simplicial'):
  594. self.n = 2 ** self.dim + 1
  595. self.nc = 0 # self.n
  596. if self.iters is None:
  597. self.iters = 1
  598. if (self.n is None) and not (sampling_method == 'simplicial'):
  599. self.n = self.n = 100
  600. self.nc = 0 # self.n
  601. if (self.n == 100) and (sampling_method == 'simplicial'):
  602. self.n = 2 ** self.dim + 1
  603. if not ((self.maxiter is None) and (self.maxfev is None) and (
  604. self.maxev is None)
  605. and (self.minhgrd is None) and (self.f_min_true is None)):
  606. self.iters = None
  607. # Set complex construction mode based on a provided stopping criteria:
  608. # Initialise sampling Complex and function cache
  609. # Note that sfield_args=() since args are already wrapped in self.func
  610. # using the_FunctionWrapper class.
  611. self.HC = Complex(dim=self.dim, domain=self.bounds,
  612. sfield=self.func, sfield_args=(),
  613. symmetry=self.symmetry,
  614. constraints=self.constraints,
  615. workers=workers)
  616. # Choose complex constructor
  617. if sampling_method == 'simplicial':
  618. self.iterate_complex = self.iterate_hypercube
  619. self.sampling_method = sampling_method
  620. elif sampling_method in ['halton', 'sobol'] or \
  621. not isinstance(sampling_method, str):
  622. self.iterate_complex = self.iterate_delaunay
  623. # Sampling method used
  624. if sampling_method in ['halton', 'sobol']:
  625. if sampling_method == 'sobol':
  626. self.n = int(2 ** np.ceil(np.log2(self.n)))
  627. # self.n #TODO: Should always be self.n, this is
  628. # unacceptable for shgo, check that nfev behaves as
  629. # expected.
  630. self.nc = 0
  631. self.sampling_method = 'sobol'
  632. self.qmc_engine = qmc.Sobol(d=self.dim, scramble=False,
  633. seed=0)
  634. else:
  635. self.sampling_method = 'halton'
  636. self.qmc_engine = qmc.Halton(d=self.dim, scramble=True,
  637. seed=0)
  638. def sampling_method(n, d):
  639. return self.qmc_engine.random(n)
  640. else:
  641. # A user defined sampling method:
  642. self.sampling_method = 'custom'
  643. self.sampling = self.sampling_custom
  644. self.sampling_function = sampling_method # F(n, d)
  645. # Local controls
  646. self.stop_l_iter = False # Local minimisation iterations
  647. self.stop_complex_iter = False # Sampling iterations
  648. # Initiate storage objects used in algorithm classes
  649. self.minimizer_pool = []
  650. # Cache of local minimizers mapped
  651. self.LMC = LMapCache()
  652. # Initialize return object
  653. self.res = OptimizeResult() # scipy.optimize.OptimizeResult object
  654. self.res.nfev = 0 # Includes each sampling point as func evaluation
  655. self.res.nlfev = 0 # Local function evals for all minimisers
  656. self.res.nljev = 0 # Local Jacobian evals for all minimisers
  657. self.res.nlhev = 0 # Local Hessian evals for all minimisers
  658. # Initiation aids
  659. def init_options(self, options):
  660. """
  661. Initiates the options.
  662. Can also be useful to change parameters after class initiation.
  663. Parameters
  664. ----------
  665. options : dict
  666. Returns
  667. -------
  668. None
  669. """
  670. # Update 'options' dict passed to optimize.minimize
  671. # Do this first so we don't mutate `options` below.
  672. self.minimizer_kwargs['options'].update(options)
  673. # Ensure that 'jac', 'hess', and 'hessp' are passed directly to
  674. # `minimize` as keywords, not as part of its 'options' dictionary.
  675. for opt in ['jac', 'hess', 'hessp']:
  676. if opt in self.minimizer_kwargs['options']:
  677. self.minimizer_kwargs[opt] = (
  678. self.minimizer_kwargs['options'].pop(opt))
  679. # Default settings:
  680. self.minimize_every_iter = options.get('minimize_every_iter', True)
  681. # Algorithm limits
  682. # Maximum number of iterations to perform.
  683. self.maxiter = options.get('maxiter', None)
  684. # Maximum number of function evaluations in the feasible domain
  685. self.maxfev = options.get('maxfev', None)
  686. # Maximum number of sampling evaluations (includes searching in
  687. # infeasible points
  688. self.maxev = options.get('maxev', None)
  689. # Maximum processing runtime allowed
  690. self.init = time.time()
  691. self.maxtime = options.get('maxtime', None)
  692. if 'f_min' in options:
  693. # Specify the minimum objective function value, if it is known.
  694. self.f_min_true = options['f_min']
  695. self.f_tol = options.get('f_tol', 1e-4)
  696. else:
  697. self.f_min_true = None
  698. self.minhgrd = options.get('minhgrd', None)
  699. # Objective function knowledge
  700. self.symmetry = options.get('symmetry', False)
  701. if self.symmetry:
  702. self.symmetry = [0, ]*len(self.bounds)
  703. else:
  704. self.symmetry = None
  705. # Algorithm functionality
  706. # Only evaluate a few of the best candidates
  707. self.local_iter = options.get('local_iter', False)
  708. self.infty_cons_sampl = options.get('infty_constraints', True)
  709. # Feedback
  710. self.disp = options.get('disp', False)
  711. def __enter__(self):
  712. return self
  713. def __exit__(self, *args):
  714. return self.HC.V._mapwrapper.__exit__(*args)
  715. # Iteration properties
  716. # Main construction loop:
  717. def iterate_all(self):
  718. """
  719. Construct for `iters` iterations.
  720. If uniform sampling is used, every iteration adds 'n' sampling points.
  721. Iterations if a stopping criteria (e.g., sampling points or
  722. processing time) has been met.
  723. """
  724. if self.disp:
  725. logging.info('Splitting first generation')
  726. while not self.stop_global:
  727. if self.break_routine:
  728. break
  729. # Iterate complex, process minimisers
  730. self.iterate()
  731. self.stopping_criteria()
  732. # Build minimiser pool
  733. # Final iteration only needed if pools weren't minimised every
  734. # iteration
  735. if not self.minimize_every_iter:
  736. if not self.break_routine:
  737. self.find_minima()
  738. self.res.nit = self.iters_done # + 1
  739. self.fn = self.HC.V.nfev
  740. def find_minima(self):
  741. """
  742. Construct the minimizer pool, map the minimizers to local minima
  743. and sort the results into a global return object.
  744. """
  745. if self.disp:
  746. logging.info('Searching for minimizer pool...')
  747. self.minimizers()
  748. if len(self.X_min) != 0:
  749. # Minimize the pool of minimizers with local minimization methods
  750. # Note that if Options['local_iter'] is an `int` instead of default
  751. # value False then only that number of candidates will be minimized
  752. self.minimise_pool(self.local_iter)
  753. # Sort results and build the global return object
  754. self.sort_result()
  755. # Lowest values used to report in case of failures
  756. self.f_lowest = self.res.fun
  757. self.x_lowest = self.res.x
  758. else:
  759. self.find_lowest_vertex()
  760. if self.disp:
  761. logging.info(f"Minimiser pool = SHGO.X_min = {self.X_min}")
  762. def find_lowest_vertex(self):
  763. # Find the lowest objective function value on one of
  764. # the vertices of the simplicial complex
  765. self.f_lowest = np.inf
  766. for x in self.HC.V.cache:
  767. if self.HC.V[x].f < self.f_lowest:
  768. if self.disp:
  769. logging.info(f'self.HC.V[x].f = {self.HC.V[x].f}')
  770. self.f_lowest = self.HC.V[x].f
  771. self.x_lowest = self.HC.V[x].x_a
  772. for lmc in self.LMC.cache:
  773. if self.LMC[lmc].f_min < self.f_lowest:
  774. self.f_lowest = self.LMC[lmc].f_min
  775. self.x_lowest = self.LMC[lmc].x_l
  776. if self.f_lowest == np.inf: # no feasible point
  777. self.f_lowest = None
  778. self.x_lowest = None
  779. # Stopping criteria functions:
  780. def finite_iterations(self):
  781. mi = min(x for x in [self.iters, self.maxiter] if x is not None)
  782. if self.disp:
  783. logging.info(f'Iterations done = {self.iters_done} / {mi}')
  784. if self.iters is not None:
  785. if self.iters_done >= (self.iters):
  786. self.stop_global = True
  787. if self.maxiter is not None: # Stop for infeasible sampling
  788. if self.iters_done >= (self.maxiter):
  789. self.stop_global = True
  790. return self.stop_global
  791. def finite_fev(self):
  792. # Finite function evals in the feasible domain
  793. if self.disp:
  794. logging.info(f'Function evaluations done = {self.fn} / {self.maxfev}')
  795. if self.fn >= self.maxfev:
  796. self.stop_global = True
  797. return self.stop_global
  798. def finite_ev(self):
  799. # Finite evaluations including infeasible sampling points
  800. if self.disp:
  801. logging.info(f'Sampling evaluations done = {self.n_sampled} '
  802. f'/ {self.maxev}')
  803. if self.n_sampled >= self.maxev:
  804. self.stop_global = True
  805. def finite_time(self):
  806. if self.disp:
  807. logging.info(f'Time elapsed = {time.time() - self.init} '
  808. f'/ {self.maxtime}')
  809. if (time.time() - self.init) >= self.maxtime:
  810. self.stop_global = True
  811. def finite_precision(self):
  812. """
  813. Stop the algorithm if the final function value is known
  814. Specify in options (with ``self.f_min_true = options['f_min']``)
  815. and the tolerance with ``f_tol = options['f_tol']``
  816. """
  817. # If no minimizer has been found use the lowest sampling value
  818. self.find_lowest_vertex()
  819. if self.disp:
  820. logging.info(f'Lowest function evaluation = {self.f_lowest}')
  821. logging.info(f'Specified minimum = {self.f_min_true}')
  822. # If no feasible point was return from test
  823. if self.f_lowest is None:
  824. return self.stop_global
  825. # Function to stop algorithm at specified percentage error:
  826. if self.f_min_true == 0.0:
  827. if self.f_lowest <= self.f_tol:
  828. self.stop_global = True
  829. else:
  830. pe = (self.f_lowest - self.f_min_true) / abs(self.f_min_true)
  831. if self.f_lowest <= self.f_min_true:
  832. self.stop_global = True
  833. # 2if (pe - self.f_tol) <= abs(1.0 / abs(self.f_min_true)):
  834. if abs(pe) >= 2 * self.f_tol:
  835. warnings.warn(
  836. f"A much lower value than expected f* = {self.f_min_true} "
  837. f"was found f_lowest = {self.f_lowest}",
  838. stacklevel=3
  839. )
  840. if pe <= self.f_tol:
  841. self.stop_global = True
  842. return self.stop_global
  843. def finite_homology_growth(self):
  844. """
  845. Stop the algorithm if homology group rank did not grow in iteration.
  846. """
  847. if self.LMC.size == 0:
  848. return # pass on no reason to stop yet.
  849. self.hgrd = self.LMC.size - self.hgr
  850. self.hgr = self.LMC.size
  851. if self.hgrd <= self.minhgrd:
  852. self.stop_global = True
  853. if self.disp:
  854. logging.info(f'Current homology growth = {self.hgrd} '
  855. f' (minimum growth = {self.minhgrd})')
  856. return self.stop_global
  857. def stopping_criteria(self):
  858. """
  859. Various stopping criteria ran every iteration
  860. Returns
  861. -------
  862. stop : bool
  863. """
  864. if self.maxiter is not None:
  865. self.finite_iterations()
  866. if self.iters is not None:
  867. self.finite_iterations()
  868. if self.maxfev is not None:
  869. self.finite_fev()
  870. if self.maxev is not None:
  871. self.finite_ev()
  872. if self.maxtime is not None:
  873. self.finite_time()
  874. if self.f_min_true is not None:
  875. self.finite_precision()
  876. if self.minhgrd is not None:
  877. self.finite_homology_growth()
  878. return self.stop_global
  879. def iterate(self):
  880. self.iterate_complex()
  881. # Build minimizer pool
  882. if self.minimize_every_iter:
  883. if not self.break_routine:
  884. self.find_minima() # Process minimizer pool
  885. # Algorithm updates
  886. self.iters_done += 1
  887. def iterate_hypercube(self):
  888. """
  889. Iterate a subdivision of the complex
  890. Note: called with ``self.iterate_complex()`` after class initiation
  891. """
  892. # Iterate the complex
  893. if self.disp:
  894. logging.info('Constructing and refining simplicial complex graph '
  895. 'structure')
  896. if self.n is None:
  897. self.HC.refine_all()
  898. self.n_sampled = self.HC.V.size() # nevs counted
  899. else:
  900. self.HC.refine(self.n)
  901. self.n_sampled += self.n
  902. if self.disp:
  903. logging.info('Triangulation completed, evaluating all constraints '
  904. 'and objective function values.')
  905. # Re-add minimisers to complex
  906. if len(self.LMC.xl_maps) > 0:
  907. for xl in self.LMC.cache:
  908. v = self.HC.V[xl]
  909. v_near = v.star()
  910. for v in v.nn:
  911. v_near = v_near.union(v.nn)
  912. # Reconnect vertices to complex
  913. # if self.HC.connect_vertex_non_symm(tuple(self.LMC[xl].x_l),
  914. # near=v_near):
  915. # continue
  916. # else:
  917. # If failure to find in v_near, then search all vertices
  918. # (very expensive operation:
  919. # self.HC.connect_vertex_non_symm(tuple(self.LMC[xl].x_l)
  920. # )
  921. # Evaluate all constraints and functions
  922. self.HC.V.process_pools()
  923. if self.disp:
  924. logging.info('Evaluations completed.')
  925. # feasible sampling points counted by the triangulation.py routines
  926. self.fn = self.HC.V.nfev
  927. return
  928. def iterate_delaunay(self):
  929. """
  930. Build a complex of Delaunay triangulated points
  931. Note: called with ``self.iterate_complex()`` after class initiation
  932. """
  933. self.nc += self.n
  934. self.sampled_surface(infty_cons_sampl=self.infty_cons_sampl)
  935. # Add sampled points to a triangulation, construct self.Tri
  936. if self.disp:
  937. logging.info(f'self.n = {self.n}')
  938. logging.info(f'self.nc = {self.nc}')
  939. logging.info('Constructing and refining simplicial complex graph '
  940. 'structure from sampling points.')
  941. if self.dim < 2:
  942. self.Ind_sorted = np.argsort(self.C, axis=0)
  943. self.Ind_sorted = self.Ind_sorted.flatten()
  944. tris = []
  945. for ind, ind_s in enumerate(self.Ind_sorted):
  946. if ind > 0:
  947. tris.append(self.Ind_sorted[ind - 1:ind + 1])
  948. tris = np.array(tris)
  949. # Store 1D triangulation:
  950. self.Tri = namedtuple('Tri', ['points', 'simplices'])(self.C, tris)
  951. self.points = {}
  952. else:
  953. if self.C.shape[0] > self.dim + 1: # Ensure a simplex can be built
  954. self.delaunay_triangulation(n_prc=self.n_prc)
  955. self.n_prc = self.C.shape[0]
  956. if self.disp:
  957. logging.info('Triangulation completed, evaluating all '
  958. 'constraints and objective function values.')
  959. if hasattr(self, 'Tri'):
  960. self.HC.vf_to_vv(self.Tri.points, self.Tri.simplices)
  961. # Process all pools
  962. # Evaluate all constraints and functions
  963. if self.disp:
  964. logging.info('Triangulation completed, evaluating all constraints '
  965. 'and objective function values.')
  966. # Evaluate all constraints and functions
  967. self.HC.V.process_pools()
  968. if self.disp:
  969. logging.info('Evaluations completed.')
  970. # feasible sampling points counted by the triangulation.py routines
  971. self.fn = self.HC.V.nfev
  972. self.n_sampled = self.nc # nevs counted in triangulation
  973. return
  974. # Hypercube minimizers
  975. def minimizers(self):
  976. """
  977. Returns the indexes of all minimizers
  978. """
  979. self.minimizer_pool = []
  980. # Note: Can implement parallelization here
  981. for x in self.HC.V.cache:
  982. in_LMC = False
  983. if len(self.LMC.xl_maps) > 0:
  984. for xlmi in self.LMC.xl_maps:
  985. if np.all(np.array(x) == np.array(xlmi)):
  986. in_LMC = True
  987. if in_LMC:
  988. continue
  989. if self.HC.V[x].minimiser():
  990. if self.disp:
  991. logging.info('=' * 60)
  992. logging.info(f'v.x = {self.HC.V[x].x_a} is minimizer')
  993. logging.info(f'v.f = {self.HC.V[x].f} is minimizer')
  994. logging.info('=' * 30)
  995. if self.HC.V[x] not in self.minimizer_pool:
  996. self.minimizer_pool.append(self.HC.V[x])
  997. if self.disp:
  998. logging.info('Neighbors:')
  999. logging.info('=' * 30)
  1000. for vn in self.HC.V[x].nn:
  1001. logging.info(f'x = {vn.x} || f = {vn.f}')
  1002. logging.info('=' * 60)
  1003. self.minimizer_pool_F = []
  1004. self.X_min = []
  1005. # normalized tuple in the Vertex cache
  1006. self.X_min_cache = {} # Cache used in hypercube sampling
  1007. for v in self.minimizer_pool:
  1008. self.X_min.append(v.x_a)
  1009. self.minimizer_pool_F.append(v.f)
  1010. self.X_min_cache[tuple(v.x_a)] = v.x
  1011. self.minimizer_pool_F = np.array(self.minimizer_pool_F)
  1012. self.X_min = np.array(self.X_min)
  1013. # TODO: Only do this if global mode
  1014. self.sort_min_pool()
  1015. return self.X_min
  1016. # Local minimisation
  1017. # Minimiser pool processing
  1018. def minimise_pool(self, force_iter=False):
  1019. """
  1020. This processing method can optionally minimise only the best candidate
  1021. solutions in the minimiser pool
  1022. Parameters
  1023. ----------
  1024. force_iter : int
  1025. Number of starting minimizers to process (can be specified
  1026. globally or locally)
  1027. """
  1028. # Find first local minimum
  1029. # NOTE: Since we always minimize this value regardless it is a waste to
  1030. # build the topograph first before minimizing
  1031. lres_f_min = self.minimize(self.X_min[0], ind=self.minimizer_pool[0])
  1032. # Trim minimized point from current minimizer set
  1033. self.trim_min_pool(0)
  1034. while not self.stop_l_iter:
  1035. # Global stopping criteria:
  1036. self.stopping_criteria()
  1037. # Note first iteration is outside loop:
  1038. if force_iter:
  1039. force_iter -= 1
  1040. if force_iter == 0:
  1041. self.stop_l_iter = True
  1042. break
  1043. if np.shape(self.X_min)[0] == 0:
  1044. self.stop_l_iter = True
  1045. break
  1046. # Construct topograph from current minimizer set
  1047. # (NOTE: This is a very small topograph using only the minizer pool
  1048. # , it might be worth using some graph theory tools instead.
  1049. self.g_topograph(lres_f_min.x, self.X_min)
  1050. # Find local minimum at the miniser with the greatest Euclidean
  1051. # distance from the current solution
  1052. ind_xmin_l = self.Z[:, -1]
  1053. lres_f_min = self.minimize(self.Ss[-1, :], self.minimizer_pool[-1])
  1054. # Trim minimised point from current minimizer set
  1055. self.trim_min_pool(ind_xmin_l)
  1056. # Reset controls
  1057. self.stop_l_iter = False
  1058. return
  1059. def sort_min_pool(self):
  1060. # Sort to find minimum func value in min_pool
  1061. self.ind_f_min = np.argsort(self.minimizer_pool_F)
  1062. self.minimizer_pool = np.array(self.minimizer_pool)[self.ind_f_min]
  1063. self.minimizer_pool_F = np.array(self.minimizer_pool_F)[
  1064. self.ind_f_min]
  1065. return
  1066. def trim_min_pool(self, trim_ind):
  1067. self.X_min = np.delete(self.X_min, trim_ind, axis=0)
  1068. self.minimizer_pool_F = np.delete(self.minimizer_pool_F, trim_ind)
  1069. self.minimizer_pool = np.delete(self.minimizer_pool, trim_ind)
  1070. return
  1071. def g_topograph(self, x_min, X_min):
  1072. """
  1073. Returns the topographical vector stemming from the specified value
  1074. ``x_min`` for the current feasible set ``X_min`` with True boolean
  1075. values indicating positive entries and False values indicating
  1076. negative entries.
  1077. """
  1078. x_min = np.array([x_min])
  1079. self.Y = spatial.distance.cdist(x_min, X_min, 'euclidean')
  1080. # Find sorted indexes of spatial distances:
  1081. self.Z = np.argsort(self.Y, axis=-1)
  1082. self.Ss = X_min[self.Z][0]
  1083. self.minimizer_pool = self.minimizer_pool[self.Z]
  1084. self.minimizer_pool = self.minimizer_pool[0]
  1085. return self.Ss
  1086. # Local bound functions
  1087. def construct_lcb_simplicial(self, v_min):
  1088. """
  1089. Construct locally (approximately) convex bounds
  1090. Parameters
  1091. ----------
  1092. v_min : Vertex object
  1093. The minimizer vertex
  1094. Returns
  1095. -------
  1096. cbounds : list of lists
  1097. List of size dimension with length-2 list of bounds for each
  1098. dimension.
  1099. """
  1100. cbounds = [[x_b_i[0], x_b_i[1]] for x_b_i in self.bounds]
  1101. # Loop over all bounds
  1102. for vn in v_min.nn:
  1103. for i, x_i in enumerate(vn.x_a):
  1104. # Lower bound
  1105. if (x_i < v_min.x_a[i]) and (x_i > cbounds[i][0]):
  1106. cbounds[i][0] = x_i
  1107. # Upper bound
  1108. if (x_i > v_min.x_a[i]) and (x_i < cbounds[i][1]):
  1109. cbounds[i][1] = x_i
  1110. if self.disp:
  1111. logging.info(f'cbounds found for v_min.x_a = {v_min.x_a}')
  1112. logging.info(f'cbounds = {cbounds}')
  1113. return cbounds
  1114. def construct_lcb_delaunay(self, v_min, ind=None):
  1115. """
  1116. Construct locally (approximately) convex bounds
  1117. Parameters
  1118. ----------
  1119. v_min : Vertex object
  1120. The minimizer vertex
  1121. Returns
  1122. -------
  1123. cbounds : list of lists
  1124. List of size dimension with length-2 list of bounds for each
  1125. dimension.
  1126. """
  1127. cbounds = [[x_b_i[0], x_b_i[1]] for x_b_i in self.bounds]
  1128. return cbounds
  1129. # Minimize a starting point locally
  1130. def minimize(self, x_min, ind=None):
  1131. """
  1132. This function is used to calculate the local minima using the specified
  1133. sampling point as a starting value.
  1134. Parameters
  1135. ----------
  1136. x_min : vector of floats
  1137. Current starting point to minimize.
  1138. Returns
  1139. -------
  1140. lres : OptimizeResult
  1141. The local optimization result represented as a `OptimizeResult`
  1142. object.
  1143. """
  1144. # Use minima maps if vertex was already run
  1145. if self.disp:
  1146. logging.info(f'Vertex minimiser maps = {self.LMC.v_maps}')
  1147. if self.LMC[x_min].lres is not None:
  1148. logging.info(f'Found self.LMC[x_min].lres = '
  1149. f'{self.LMC[x_min].lres}')
  1150. return self.LMC[x_min].lres
  1151. if self.callback is not None:
  1152. logging.info(f'Callback for minimizer starting at {x_min}:')
  1153. if self.disp:
  1154. logging.info(f'Starting minimization at {x_min}...')
  1155. if self.sampling_method == 'simplicial':
  1156. x_min_t = tuple(x_min)
  1157. # Find the normalized tuple in the Vertex cache:
  1158. x_min_t_norm = self.X_min_cache[tuple(x_min_t)]
  1159. x_min_t_norm = tuple(x_min_t_norm)
  1160. g_bounds = self.construct_lcb_simplicial(self.HC.V[x_min_t_norm])
  1161. if 'bounds' in self.min_solver_args:
  1162. self.minimizer_kwargs['bounds'] = g_bounds
  1163. logging.info(self.minimizer_kwargs['bounds'])
  1164. else:
  1165. g_bounds = self.construct_lcb_delaunay(x_min, ind=ind)
  1166. if 'bounds' in self.min_solver_args:
  1167. self.minimizer_kwargs['bounds'] = g_bounds
  1168. logging.info(self.minimizer_kwargs['bounds'])
  1169. if self.disp and 'bounds' in self.minimizer_kwargs:
  1170. logging.info('bounds in kwarg:')
  1171. logging.info(self.minimizer_kwargs['bounds'])
  1172. # Local minimization using scipy.optimize.minimize:
  1173. lres = minimize(self.func, x_min, **self.minimizer_kwargs)
  1174. if self.disp:
  1175. logging.info(f'lres = {lres}')
  1176. # Local function evals for all minimizers
  1177. self.res.nlfev += lres.nfev
  1178. if 'njev' in lres:
  1179. self.res.nljev += lres.njev
  1180. if 'nhev' in lres:
  1181. self.res.nlhev += lres.nhev
  1182. try: # Needed because of the brain dead 1x1 NumPy arrays
  1183. lres.fun = lres.fun[0]
  1184. except (IndexError, TypeError):
  1185. lres.fun
  1186. # Append minima maps
  1187. self.LMC[x_min]
  1188. self.LMC.add_res(x_min, lres, bounds=g_bounds)
  1189. return lres
  1190. # Post local minimization processing
  1191. def sort_result(self):
  1192. """
  1193. Sort results and build the global return object
  1194. """
  1195. # Sort results in local minima cache
  1196. results = self.LMC.sort_cache_result()
  1197. self.res.xl = results['xl']
  1198. self.res.funl = results['funl']
  1199. self.res.x = results['x']
  1200. self.res.fun = results['fun']
  1201. # Add local func evals to sampling func evals
  1202. # Count the number of feasible vertices and add to local func evals:
  1203. self.res.nfev = self.fn + self.res.nlfev
  1204. return self.res
  1205. # Algorithm controls
  1206. def fail_routine(self, mes=("Failed to converge")):
  1207. self.break_routine = True
  1208. self.res.success = False
  1209. self.X_min = [None]
  1210. self.res.message = mes
  1211. def sampled_surface(self, infty_cons_sampl=False):
  1212. """
  1213. Sample the function surface.
  1214. There are 2 modes, if ``infty_cons_sampl`` is True then the sampled
  1215. points that are generated outside the feasible domain will be
  1216. assigned an ``inf`` value in accordance with SHGO rules.
  1217. This guarantees convergence and usually requires less objective
  1218. function evaluations at the computational costs of more Delaunay
  1219. triangulation points.
  1220. If ``infty_cons_sampl`` is False, then the infeasible points are
  1221. discarded and only a subspace of the sampled points are used. This
  1222. comes at the cost of the loss of guaranteed convergence and usually
  1223. requires more objective function evaluations.
  1224. """
  1225. # Generate sampling points
  1226. if self.disp:
  1227. logging.info('Generating sampling points')
  1228. self.sampling(self.nc, self.dim)
  1229. if len(self.LMC.xl_maps) > 0:
  1230. self.C = np.vstack((self.C, np.array(self.LMC.xl_maps)))
  1231. if not infty_cons_sampl:
  1232. # Find subspace of feasible points
  1233. if self.g_cons is not None:
  1234. self.sampling_subspace()
  1235. # Sort remaining samples
  1236. self.sorted_samples()
  1237. # Find objective function references
  1238. self.n_sampled = self.nc
  1239. def sampling_custom(self, n, dim):
  1240. """
  1241. Generates uniform sampling points in a hypercube and scales the points
  1242. to the bound limits.
  1243. """
  1244. # Generate sampling points.
  1245. # Generate uniform sample points in [0, 1]^m \subset R^m
  1246. if self.n_sampled == 0:
  1247. self.C = self.sampling_function(n, dim)
  1248. else:
  1249. self.C = self.sampling_function(n, dim)
  1250. # Distribute over bounds
  1251. for i in range(len(self.bounds)):
  1252. self.C[:, i] = (self.C[:, i] *
  1253. (self.bounds[i][1] - self.bounds[i][0])
  1254. + self.bounds[i][0])
  1255. return self.C
  1256. def sampling_subspace(self):
  1257. """Find subspace of feasible points from g_func definition"""
  1258. # Subspace of feasible points.
  1259. for ind, g in enumerate(self.g_cons):
  1260. # C.shape = (Z, dim) where Z is the number of sampling points to
  1261. # evaluate and dim is the dimensionality of the problem.
  1262. # the constraint function may not be vectorised so have to step
  1263. # through each sampling point sequentially.
  1264. feasible = np.array(
  1265. [np.all(g(x_C, *self.g_args[ind]) >= 0.0) for x_C in self.C],
  1266. dtype=bool
  1267. )
  1268. self.C = self.C[feasible]
  1269. if self.C.size == 0:
  1270. self.res.message = ('No sampling point found within the '
  1271. + 'feasible set. Increasing sampling '
  1272. + 'size.')
  1273. # sampling correctly for both 1-D and >1-D cases
  1274. if self.disp:
  1275. logging.info(self.res.message)
  1276. def sorted_samples(self): # Validated
  1277. """Find indexes of the sorted sampling points"""
  1278. self.Ind_sorted = np.argsort(self.C, axis=0)
  1279. self.Xs = self.C[self.Ind_sorted]
  1280. return self.Ind_sorted, self.Xs
  1281. def delaunay_triangulation(self, n_prc=0):
  1282. if hasattr(self, 'Tri') and self.qhull_incremental:
  1283. # TODO: Uncertain if n_prc needs to add len(self.LMC.xl_maps)
  1284. # in self.sampled_surface
  1285. self.Tri.add_points(self.C[n_prc:, :])
  1286. else:
  1287. try:
  1288. self.Tri = spatial.Delaunay(self.C,
  1289. incremental=self.qhull_incremental,
  1290. )
  1291. except spatial.QhullError:
  1292. if str(sys.exc_info()[1])[:6] == 'QH6239':
  1293. logging.warning('QH6239 Qhull precision error detected, '
  1294. 'this usually occurs when no bounds are '
  1295. 'specified, Qhull can only run with '
  1296. 'handling cocircular/cospherical points'
  1297. ' and in this case incremental mode is '
  1298. 'switched off. The performance of shgo '
  1299. 'will be reduced in this mode.')
  1300. self.qhull_incremental = False
  1301. self.Tri = spatial.Delaunay(self.C,
  1302. incremental=
  1303. self.qhull_incremental)
  1304. else:
  1305. raise
  1306. return self.Tri
  1307. class LMap:
  1308. def __init__(self, v):
  1309. self.v = v
  1310. self.x_l = None
  1311. self.lres = None
  1312. self.f_min = None
  1313. self.lbounds = []
  1314. class LMapCache:
  1315. def __init__(self):
  1316. self.cache = {}
  1317. # Lists for search queries
  1318. self.v_maps = []
  1319. self.xl_maps = []
  1320. self.xl_maps_set = set()
  1321. self.f_maps = []
  1322. self.lbound_maps = []
  1323. self.size = 0
  1324. def __getitem__(self, v):
  1325. try:
  1326. v = np.ndarray.tolist(v)
  1327. except TypeError:
  1328. pass
  1329. v = tuple(v)
  1330. try:
  1331. return self.cache[v]
  1332. except KeyError:
  1333. xval = LMap(v)
  1334. self.cache[v] = xval
  1335. return self.cache[v]
  1336. def add_res(self, v, lres, bounds=None):
  1337. v = np.ndarray.tolist(v)
  1338. v = tuple(v)
  1339. self.cache[v].x_l = lres.x
  1340. self.cache[v].lres = lres
  1341. self.cache[v].f_min = lres.fun
  1342. self.cache[v].lbounds = bounds
  1343. # Update cache size
  1344. self.size += 1
  1345. # Cache lists for search queries
  1346. self.v_maps.append(v)
  1347. self.xl_maps.append(lres.x)
  1348. self.xl_maps_set.add(tuple(lres.x))
  1349. self.f_maps.append(lres.fun)
  1350. self.lbound_maps.append(bounds)
  1351. def sort_cache_result(self):
  1352. """
  1353. Sort results and build the global return object
  1354. """
  1355. results = {}
  1356. # Sort results and save
  1357. self.xl_maps = np.array(self.xl_maps)
  1358. self.f_maps = np.array(self.f_maps)
  1359. # Sorted indexes in Func_min
  1360. ind_sorted = np.argsort(self.f_maps)
  1361. # Save ordered list of minima
  1362. results['xl'] = self.xl_maps[ind_sorted] # Ordered x vals
  1363. self.f_maps = np.array(self.f_maps)
  1364. results['funl'] = self.f_maps[ind_sorted]
  1365. results['funl'] = results['funl'].T
  1366. # Find global of all minimizers
  1367. results['x'] = self.xl_maps[ind_sorted[0]] # Save global minima
  1368. results['fun'] = self.f_maps[ind_sorted[0]] # Save global fun value
  1369. self.xl_maps = np.ndarray.tolist(self.xl_maps)
  1370. self.f_maps = np.ndarray.tolist(self.f_maps)
  1371. return results