main.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  1. import warnings
  2. import numpy as np
  3. from scipy.optimize import (
  4. Bounds,
  5. LinearConstraint,
  6. NonlinearConstraint,
  7. OptimizeResult,
  8. )
  9. from .framework import TrustRegion
  10. from .problem import (
  11. ObjectiveFunction,
  12. BoundConstraints,
  13. LinearConstraints,
  14. NonlinearConstraints,
  15. Problem,
  16. )
  17. from .utils import (
  18. MaxEvalError,
  19. TargetSuccess,
  20. CallbackSuccess,
  21. FeasibleSuccess,
  22. exact_1d_array,
  23. )
  24. from .settings import (
  25. ExitStatus,
  26. Options,
  27. Constants,
  28. DEFAULT_OPTIONS,
  29. DEFAULT_CONSTANTS,
  30. PRINT_OPTIONS,
  31. )
  32. def minimize(
  33. fun,
  34. x0,
  35. args=(),
  36. bounds=None,
  37. constraints=(),
  38. callback=None,
  39. options=None,
  40. **kwargs,
  41. ):
  42. r"""
  43. Minimize a scalar function using the COBYQA method.
  44. The Constrained Optimization BY Quadratic Approximations (COBYQA) method is
  45. a derivative-free optimization method designed to solve general nonlinear
  46. optimization problems. A complete description of COBYQA is given in [3]_.
  47. Parameters
  48. ----------
  49. fun : {callable, None}
  50. Objective function to be minimized.
  51. ``fun(x, *args) -> float``
  52. where ``x`` is an array with shape (n,) and `args` is a tuple. If `fun`
  53. is ``None``, the objective function is assumed to be the zero function,
  54. resulting in a feasibility problem.
  55. x0 : array_like, shape (n,)
  56. Initial guess.
  57. args : tuple, optional
  58. Extra arguments passed to the objective function.
  59. bounds : {`scipy.optimize.Bounds`, array_like, shape (n, 2)}, optional
  60. Bound constraints of the problem. It can be one of the cases below.
  61. #. An instance of `scipy.optimize.Bounds`. For the time being, the
  62. argument ``keep_feasible`` is disregarded, and all the constraints
  63. are considered unrelaxable and will be enforced.
  64. #. An array with shape (n, 2). The bound constraints for ``x[i]`` are
  65. ``bounds[i][0] <= x[i] <= bounds[i][1]``. Set ``bounds[i][0]`` to
  66. :math:`-\infty` if there is no lower bound, and set ``bounds[i][1]``
  67. to :math:`\infty` if there is no upper bound.
  68. The COBYQA method always respect the bound constraints.
  69. constraints : {Constraint, list}, optional
  70. General constraints of the problem. It can be one of the cases below.
  71. #. An instance of `scipy.optimize.LinearConstraint`. The argument
  72. ``keep_feasible`` is disregarded.
  73. #. An instance of `scipy.optimize.NonlinearConstraint`. The arguments
  74. ``jac``, ``hess``, ``keep_feasible``, ``finite_diff_rel_step``, and
  75. ``finite_diff_jac_sparsity`` are disregarded.
  76. #. A list, each of whose elements are described in the cases above.
  77. callback : callable, optional
  78. A callback executed at each objective function evaluation. The method
  79. terminates if a ``StopIteration`` exception is raised by the callback
  80. function. Its signature can be one of the following:
  81. ``callback(intermediate_result)``
  82. where ``intermediate_result`` is a keyword parameter that contains an
  83. instance of `scipy.optimize.OptimizeResult`, with attributes ``x``
  84. and ``fun``, being the point at which the objective function is
  85. evaluated and the value of the objective function, respectively. The
  86. name of the parameter must be ``intermediate_result`` for the callback
  87. to be passed an instance of `scipy.optimize.OptimizeResult`.
  88. Alternatively, the callback function can have the signature:
  89. ``callback(xk)``
  90. where ``xk`` is the point at which the objective function is evaluated.
  91. Introspection is used to determine which of the signatures to invoke.
  92. options : dict, optional
  93. Options passed to the solver. Accepted keys are:
  94. disp : bool, optional
  95. Whether to print information about the optimization procedure.
  96. Default is ``False``.
  97. maxfev : int, optional
  98. Maximum number of function evaluations. Default is ``500 * n``.
  99. maxiter : int, optional
  100. Maximum number of iterations. Default is ``1000 * n``.
  101. target : float, optional
  102. Target on the objective function value. The optimization
  103. procedure is terminated when the objective function value of a
  104. feasible point is less than or equal to this target. Default is
  105. ``-numpy.inf``.
  106. feasibility_tol : float, optional
  107. Tolerance on the constraint violation. If the maximum
  108. constraint violation at a point is less than or equal to this
  109. tolerance, the point is considered feasible. Default is
  110. ``numpy.sqrt(numpy.finfo(float).eps)``.
  111. radius_init : float, optional
  112. Initial trust-region radius. Typically, this value should be in
  113. the order of one tenth of the greatest expected change to `x0`.
  114. Default is ``1.0``.
  115. radius_final : float, optional
  116. Final trust-region radius. It should indicate the accuracy
  117. required in the final values of the variables. Default is
  118. ``1e-6``.
  119. nb_points : int, optional
  120. Number of interpolation points used to build the quadratic
  121. models of the objective and constraint functions. Default is
  122. ``2 * n + 1``.
  123. scale : bool, optional
  124. Whether to scale the variables according to the bounds. Default
  125. is ``False``.
  126. filter_size : int, optional
  127. Maximum number of points in the filter. The filter is used to
  128. select the best point returned by the optimization procedure.
  129. Default is ``sys.maxsize``.
  130. store_history : bool, optional
  131. Whether to store the history of the function evaluations.
  132. Default is ``False``.
  133. history_size : int, optional
  134. Maximum number of function evaluations to store in the history.
  135. Default is ``sys.maxsize``.
  136. debug : bool, optional
  137. Whether to perform additional checks during the optimization
  138. procedure. This option should be used only for debugging
  139. purposes and is highly discouraged to general users. Default is
  140. ``False``.
  141. Other constants (from the keyword arguments) are described below. They
  142. are not intended to be changed by general users. They should only be
  143. changed by users with a deep understanding of the algorithm, who want
  144. to experiment with different settings.
  145. Returns
  146. -------
  147. `scipy.optimize.OptimizeResult`
  148. Result of the optimization procedure, with the following fields:
  149. message : str
  150. Description of the cause of the termination.
  151. success : bool
  152. Whether the optimization procedure terminated successfully.
  153. status : int
  154. Termination status of the optimization procedure.
  155. x : `numpy.ndarray`, shape (n,)
  156. Solution point.
  157. fun : float
  158. Objective function value at the solution point.
  159. maxcv : float
  160. Maximum constraint violation at the solution point.
  161. nfev : int
  162. Number of function evaluations.
  163. nit : int
  164. Number of iterations.
  165. If ``store_history`` is True, the result also has the following fields:
  166. fun_history : `numpy.ndarray`, shape (nfev,)
  167. History of the objective function values.
  168. maxcv_history : `numpy.ndarray`, shape (nfev,)
  169. History of the maximum constraint violations.
  170. A description of the termination statuses is given below.
  171. .. list-table::
  172. :widths: 25 75
  173. :header-rows: 1
  174. * - Exit status
  175. - Description
  176. * - 0
  177. - The lower bound for the trust-region radius has been reached.
  178. * - 1
  179. - The target objective function value has been reached.
  180. * - 2
  181. - All variables are fixed by the bound constraints.
  182. * - 3
  183. - The callback requested to stop the optimization procedure.
  184. * - 4
  185. - The feasibility problem received has been solved successfully.
  186. * - 5
  187. - The maximum number of function evaluations has been exceeded.
  188. * - 6
  189. - The maximum number of iterations has been exceeded.
  190. * - -1
  191. - The bound constraints are infeasible.
  192. * - -2
  193. - A linear algebra error occurred.
  194. Other Parameters
  195. ----------------
  196. decrease_radius_factor : float, optional
  197. Factor by which the trust-region radius is reduced when the reduction
  198. ratio is low or negative. Default is ``0.5``.
  199. increase_radius_factor : float, optional
  200. Factor by which the trust-region radius is increased when the reduction
  201. ratio is large. Default is ``numpy.sqrt(2.0)``.
  202. increase_radius_threshold : float, optional
  203. Threshold that controls the increase of the trust-region radius when
  204. the reduction ratio is large. Default is ``2.0``.
  205. decrease_radius_threshold : float, optional
  206. Threshold used to determine whether the trust-region radius should be
  207. reduced to the resolution. Default is ``1.4``.
  208. decrease_resolution_factor : float, optional
  209. Factor by which the resolution is reduced when the current value is far
  210. from its final value. Default is ``0.1``.
  211. large_resolution_threshold : float, optional
  212. Threshold used to determine whether the resolution is far from its
  213. final value. Default is ``250.0``.
  214. moderate_resolution_threshold : float, optional
  215. Threshold used to determine whether the resolution is close to its
  216. final value. Default is ``16.0``.
  217. low_ratio : float, optional
  218. Threshold used to determine whether the reduction ratio is low. Default
  219. is ``0.1``.
  220. high_ratio : float, optional
  221. Threshold used to determine whether the reduction ratio is high.
  222. Default is ``0.7``.
  223. very_low_ratio : float, optional
  224. Threshold used to determine whether the reduction ratio is very low.
  225. This is used to determine whether the models should be reset. Default
  226. is ``0.01``.
  227. penalty_increase_threshold : float, optional
  228. Threshold used to determine whether the penalty parameter should be
  229. increased. Default is ``1.5``.
  230. penalty_increase_factor : float, optional
  231. Factor by which the penalty parameter is increased. Default is ``2.0``.
  232. short_step_threshold : float, optional
  233. Factor used to determine whether the trial step is too short. Default
  234. is ``0.5``.
  235. low_radius_factor : float, optional
  236. Factor used to determine which interpolation point should be removed
  237. from the interpolation set at each iteration. Default is ``0.1``.
  238. byrd_omojokun_factor : float, optional
  239. Factor by which the trust-region radius is reduced for the computations
  240. of the normal step in the Byrd-Omojokun composite-step approach.
  241. Default is ``0.8``.
  242. threshold_ratio_constraints : float, optional
  243. Threshold used to determine which constraints should be taken into
  244. account when decreasing the penalty parameter. Default is ``2.0``.
  245. large_shift_factor : float, optional
  246. Factor used to determine whether the point around which the quadratic
  247. models are built should be updated. Default is ``10.0``.
  248. large_gradient_factor : float, optional
  249. Factor used to determine whether the models should be reset. Default is
  250. ``10.0``.
  251. resolution_factor : float, optional
  252. Factor by which the resolution is decreased. Default is ``2.0``.
  253. improve_tcg : bool, optional
  254. Whether to improve the steps computed by the truncated conjugate
  255. gradient method when the trust-region boundary is reached. Default is
  256. ``True``.
  257. References
  258. ----------
  259. .. [1] J. Nocedal and S. J. Wright. *Numerical Optimization*. Springer Ser.
  260. Oper. Res. Financ. Eng. Springer, New York, NY, USA, second edition,
  261. 2006. `doi:10.1007/978-0-387-40065-5
  262. <https://doi.org/10.1007/978-0-387-40065-5>`_.
  263. .. [2] M. J. D. Powell. A direct search optimization method that models the
  264. objective and constraint functions by linear interpolation. In S. Gomez
  265. and J.-P. Hennart, editors, *Advances in Optimization and Numerical
  266. Analysis*, volume 275 of Math. Appl., pages 51--67. Springer, Dordrecht,
  267. Netherlands, 1994. `doi:10.1007/978-94-015-8330-5_4
  268. <https://doi.org/10.1007/978-94-015-8330-5_4>`_.
  269. .. [3] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
  270. and Software*. PhD thesis, Department of Applied Mathematics, The Hong
  271. Kong Polytechnic University, Hong Kong, China, 2022. URL:
  272. https://theses.lib.polyu.edu.hk/handle/200/12294.
  273. Examples
  274. --------
  275. To demonstrate how to use `minimize`, we first minimize the Rosenbrock
  276. function implemented in `scipy.optimize` in an unconstrained setting.
  277. .. testsetup::
  278. import numpy as np
  279. np.set_printoptions(precision=3, suppress=True)
  280. >>> from cobyqa import minimize
  281. >>> from scipy.optimize import rosen
  282. To solve the problem using COBYQA, run:
  283. >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
  284. >>> res = minimize(rosen, x0)
  285. >>> res.x
  286. array([1., 1., 1., 1., 1.])
  287. To see how bound and constraints are handled using `minimize`, we solve
  288. Example 16.4 of [1]_, defined as
  289. .. math::
  290. \begin{aligned}
  291. \min_{x \in \mathbb{R}^2} & \quad (x_1 - 1)^2 + (x_2 - 2.5)^2\\
  292. \text{s.t.} & \quad -x_1 + 2x_2 \le 2,\\
  293. & \quad x_1 + 2x_2 \le 6,\\
  294. & \quad x_1 - 2x_2 \le 2,\\
  295. & \quad x_1 \ge 0,\\
  296. & \quad x_2 \ge 0.
  297. \end{aligned}
  298. >>> import numpy as np
  299. >>> from scipy.optimize import Bounds, LinearConstraint
  300. Its objective function can be implemented as:
  301. >>> def fun(x):
  302. ... return (x[0] - 1.0)**2 + (x[1] - 2.5)**2
  303. This problem can be solved using `minimize` as:
  304. >>> x0 = [2.0, 0.0]
  305. >>> bounds = Bounds([0.0, 0.0], np.inf)
  306. >>> constraints = LinearConstraint([
  307. ... [-1.0, 2.0],
  308. ... [1.0, 2.0],
  309. ... [1.0, -2.0],
  310. ... ], -np.inf, [2.0, 6.0, 2.0])
  311. >>> res = minimize(fun, x0, bounds=bounds, constraints=constraints)
  312. >>> res.x
  313. array([1.4, 1.7])
  314. To see how nonlinear constraints are handled, we solve Problem (F) of [2]_,
  315. defined as
  316. .. math::
  317. \begin{aligned}
  318. \min_{x \in \mathbb{R}^2} & \quad -x_1 - x_2\\
  319. \text{s.t.} & \quad x_1^2 - x_2 \le 0,\\
  320. & \quad x_1^2 + x_2^2 \le 1.
  321. \end{aligned}
  322. >>> from scipy.optimize import NonlinearConstraint
  323. Its objective and constraint functions can be implemented as:
  324. >>> def fun(x):
  325. ... return -x[0] - x[1]
  326. >>>
  327. >>> def cub(x):
  328. ... return [x[0]**2 - x[1], x[0]**2 + x[1]**2]
  329. This problem can be solved using `minimize` as:
  330. >>> x0 = [1.0, 1.0]
  331. >>> constraints = NonlinearConstraint(cub, -np.inf, [0.0, 1.0])
  332. >>> res = minimize(fun, x0, constraints=constraints)
  333. >>> res.x
  334. array([0.707, 0.707])
  335. Finally, to see how to supply linear and nonlinear constraints
  336. simultaneously, we solve Problem (G) of [2]_, defined as
  337. .. math::
  338. \begin{aligned}
  339. \min_{x \in \mathbb{R}^3} & \quad x_3\\
  340. \text{s.t.} & \quad 5x_1 - x_2 + x_3 \ge 0,\\
  341. & \quad -5x_1 - x_2 + x_3 \ge 0,\\
  342. & \quad x_1^2 + x_2^2 + 4x_2 \le x_3.
  343. \end{aligned}
  344. Its objective and nonlinear constraint functions can be implemented as:
  345. >>> def fun(x):
  346. ... return x[2]
  347. >>>
  348. >>> def cub(x):
  349. ... return x[0]**2 + x[1]**2 + 4.0*x[1] - x[2]
  350. This problem can be solved using `minimize` as:
  351. >>> x0 = [1.0, 1.0, 1.0]
  352. >>> constraints = [
  353. ... LinearConstraint(
  354. ... [[5.0, -1.0, 1.0], [-5.0, -1.0, 1.0]],
  355. ... [0.0, 0.0],
  356. ... np.inf,
  357. ... ),
  358. ... NonlinearConstraint(cub, -np.inf, 0.0),
  359. ... ]
  360. >>> res = minimize(fun, x0, constraints=constraints)
  361. >>> res.x
  362. array([ 0., -3., -3.])
  363. """
  364. # Get basic options that are needed for the initialization.
  365. if options is None:
  366. options = {}
  367. else:
  368. options = dict(options)
  369. verbose = options.get(Options.VERBOSE, DEFAULT_OPTIONS[Options.VERBOSE])
  370. verbose = bool(verbose)
  371. feasibility_tol = options.get(
  372. Options.FEASIBILITY_TOL,
  373. DEFAULT_OPTIONS[Options.FEASIBILITY_TOL],
  374. )
  375. feasibility_tol = float(feasibility_tol)
  376. scale = options.get(Options.SCALE, DEFAULT_OPTIONS[Options.SCALE])
  377. scale = bool(scale)
  378. store_history = options.get(
  379. Options.STORE_HISTORY,
  380. DEFAULT_OPTIONS[Options.STORE_HISTORY],
  381. )
  382. store_history = bool(store_history)
  383. if Options.HISTORY_SIZE in options and options[Options.HISTORY_SIZE] <= 0:
  384. raise ValueError("The size of the history must be positive.")
  385. history_size = options.get(
  386. Options.HISTORY_SIZE,
  387. DEFAULT_OPTIONS[Options.HISTORY_SIZE],
  388. )
  389. history_size = int(history_size)
  390. if Options.FILTER_SIZE in options and options[Options.FILTER_SIZE] <= 0:
  391. raise ValueError("The size of the filter must be positive.")
  392. filter_size = options.get(
  393. Options.FILTER_SIZE,
  394. DEFAULT_OPTIONS[Options.FILTER_SIZE],
  395. )
  396. filter_size = int(filter_size)
  397. debug = options.get(Options.DEBUG, DEFAULT_OPTIONS[Options.DEBUG])
  398. debug = bool(debug)
  399. # Initialize the objective function.
  400. if not isinstance(args, tuple):
  401. args = (args,)
  402. obj = ObjectiveFunction(fun, verbose, debug, *args)
  403. # Initialize the bound constraints.
  404. if not hasattr(x0, "__len__"):
  405. x0 = [x0]
  406. n_orig = len(x0)
  407. bounds = BoundConstraints(_get_bounds(bounds, n_orig))
  408. # Initialize the constraints.
  409. linear_constraints, nonlinear_constraints = _get_constraints(constraints)
  410. linear = LinearConstraints(linear_constraints, n_orig, debug)
  411. nonlinear = NonlinearConstraints(nonlinear_constraints, verbose, debug)
  412. # Initialize the problem (and remove the fixed variables).
  413. pb = Problem(
  414. obj,
  415. x0,
  416. bounds,
  417. linear,
  418. nonlinear,
  419. callback,
  420. feasibility_tol,
  421. scale,
  422. store_history,
  423. history_size,
  424. filter_size,
  425. debug,
  426. )
  427. # Set the default options.
  428. _set_default_options(options, pb.n)
  429. constants = _set_default_constants(**kwargs)
  430. # Initialize the models and skip the computations whenever possible.
  431. if not pb.bounds.is_feasible:
  432. # The bound constraints are infeasible.
  433. return _build_result(
  434. pb,
  435. 0.0,
  436. False,
  437. ExitStatus.INFEASIBLE_ERROR,
  438. 0,
  439. options,
  440. )
  441. elif pb.n == 0:
  442. # All variables are fixed by the bound constraints.
  443. return _build_result(
  444. pb,
  445. 0.0,
  446. True,
  447. ExitStatus.FIXED_SUCCESS,
  448. 0,
  449. options,
  450. )
  451. if verbose:
  452. print("Starting the optimization procedure.")
  453. print(f"Initial trust-region radius: {options[Options.RHOBEG]}.")
  454. print(f"Final trust-region radius: {options[Options.RHOEND]}.")
  455. print(
  456. f"Maximum number of function evaluations: "
  457. f"{options[Options.MAX_EVAL]}."
  458. )
  459. print(f"Maximum number of iterations: {options[Options.MAX_ITER]}.")
  460. print()
  461. try:
  462. framework = TrustRegion(pb, options, constants)
  463. except TargetSuccess:
  464. # The target on the objective function value has been reached
  465. return _build_result(
  466. pb,
  467. 0.0,
  468. True,
  469. ExitStatus.TARGET_SUCCESS,
  470. 0,
  471. options,
  472. )
  473. except CallbackSuccess:
  474. # The callback raised a StopIteration exception.
  475. return _build_result(
  476. pb,
  477. 0.0,
  478. True,
  479. ExitStatus.CALLBACK_SUCCESS,
  480. 0,
  481. options,
  482. )
  483. except FeasibleSuccess:
  484. # The feasibility problem has been solved successfully.
  485. return _build_result(
  486. pb,
  487. 0.0,
  488. True,
  489. ExitStatus.FEASIBLE_SUCCESS,
  490. 0,
  491. options,
  492. )
  493. except MaxEvalError:
  494. # The maximum number of function evaluations has been exceeded.
  495. return _build_result(
  496. pb,
  497. 0.0,
  498. False,
  499. ExitStatus.MAX_ITER_WARNING,
  500. 0,
  501. options,
  502. )
  503. except np.linalg.LinAlgError:
  504. # The construction of the initial interpolation set failed.
  505. return _build_result(
  506. pb,
  507. 0.0,
  508. False,
  509. ExitStatus.LINALG_ERROR,
  510. 0,
  511. options,
  512. )
  513. # Start the optimization procedure.
  514. success = False
  515. n_iter = 0
  516. k_new = None
  517. n_short_steps = 0
  518. n_very_short_steps = 0
  519. n_alt_models = 0
  520. while True:
  521. # Stop the optimization procedure if the maximum number of iterations
  522. # has been exceeded. We do not write the main loop as a for loop
  523. # because we want to access the number of iterations outside the loop.
  524. if n_iter >= options[Options.MAX_ITER]:
  525. status = ExitStatus.MAX_ITER_WARNING
  526. break
  527. n_iter += 1
  528. # Update the point around which the quadratic models are built.
  529. if (
  530. np.linalg.norm(
  531. framework.x_best - framework.models.interpolation.x_base
  532. )
  533. >= constants[Constants.LARGE_SHIFT_FACTOR] * framework.radius
  534. ):
  535. framework.shift_x_base(options)
  536. # Evaluate the trial step.
  537. radius_save = framework.radius
  538. normal_step, tangential_step = framework.get_trust_region_step(options)
  539. step = normal_step + tangential_step
  540. s_norm = np.linalg.norm(step)
  541. # If the trial step is too short, we do not attempt to evaluate the
  542. # objective and constraint functions. Instead, we reduce the
  543. # trust-region radius and check whether the resolution should be
  544. # enhanced and whether the geometry of the interpolation set should be
  545. # improved. Otherwise, we entertain a classical iteration. The
  546. # criterion for performing an exceptional jump is taken from NEWUOA.
  547. if (
  548. s_norm
  549. <= constants[Constants.SHORT_STEP_THRESHOLD] * framework.resolution
  550. ):
  551. framework.radius *= constants[Constants.DECREASE_RESOLUTION_FACTOR]
  552. if radius_save > framework.resolution:
  553. n_short_steps = 0
  554. n_very_short_steps = 0
  555. else:
  556. n_short_steps += 1
  557. n_very_short_steps += 1
  558. if s_norm > 0.1 * framework.resolution:
  559. n_very_short_steps = 0
  560. enhance_resolution = n_short_steps >= 5 or n_very_short_steps >= 3
  561. if enhance_resolution:
  562. n_short_steps = 0
  563. n_very_short_steps = 0
  564. improve_geometry = False
  565. else:
  566. try:
  567. k_new, dist_new = framework.get_index_to_remove()
  568. except np.linalg.LinAlgError:
  569. status = ExitStatus.LINALG_ERROR
  570. break
  571. improve_geometry = dist_new > max(
  572. framework.radius,
  573. constants[Constants.RESOLUTION_FACTOR]
  574. * framework.resolution,
  575. )
  576. else:
  577. # Increase the penalty parameter if necessary.
  578. same_best_point = framework.increase_penalty(step)
  579. if same_best_point:
  580. # Evaluate the objective and constraint functions.
  581. try:
  582. fun_val, cub_val, ceq_val = _eval(
  583. pb,
  584. framework,
  585. step,
  586. options,
  587. )
  588. except TargetSuccess:
  589. status = ExitStatus.TARGET_SUCCESS
  590. success = True
  591. break
  592. except FeasibleSuccess:
  593. status = ExitStatus.FEASIBLE_SUCCESS
  594. success = True
  595. break
  596. except CallbackSuccess:
  597. status = ExitStatus.CALLBACK_SUCCESS
  598. success = True
  599. break
  600. except MaxEvalError:
  601. status = ExitStatus.MAX_EVAL_WARNING
  602. break
  603. # Perform a second-order correction step if necessary.
  604. merit_old = framework.merit(
  605. framework.x_best,
  606. framework.fun_best,
  607. framework.cub_best,
  608. framework.ceq_best,
  609. )
  610. merit_new = framework.merit(
  611. framework.x_best + step, fun_val, cub_val, ceq_val
  612. )
  613. if (
  614. pb.type == "nonlinearly constrained"
  615. and merit_new > merit_old
  616. and np.linalg.norm(normal_step)
  617. > constants[Constants.BYRD_OMOJOKUN_FACTOR] ** 2.0
  618. * framework.radius
  619. ):
  620. soc_step = framework.get_second_order_correction_step(
  621. step, options
  622. )
  623. if np.linalg.norm(soc_step) > 0.0:
  624. step += soc_step
  625. # Evaluate the objective and constraint functions.
  626. try:
  627. fun_val, cub_val, ceq_val = _eval(
  628. pb,
  629. framework,
  630. step,
  631. options,
  632. )
  633. except TargetSuccess:
  634. status = ExitStatus.TARGET_SUCCESS
  635. success = True
  636. break
  637. except FeasibleSuccess:
  638. status = ExitStatus.FEASIBLE_SUCCESS
  639. success = True
  640. break
  641. except CallbackSuccess:
  642. status = ExitStatus.CALLBACK_SUCCESS
  643. success = True
  644. break
  645. except MaxEvalError:
  646. status = ExitStatus.MAX_EVAL_WARNING
  647. break
  648. # Calculate the reduction ratio.
  649. ratio = framework.get_reduction_ratio(
  650. step,
  651. fun_val,
  652. cub_val,
  653. ceq_val,
  654. )
  655. # Choose an interpolation point to remove.
  656. try:
  657. k_new = framework.get_index_to_remove(
  658. framework.x_best + step
  659. )[0]
  660. except np.linalg.LinAlgError:
  661. status = ExitStatus.LINALG_ERROR
  662. break
  663. # Update the interpolation set.
  664. try:
  665. ill_conditioned = framework.models.update_interpolation(
  666. k_new, framework.x_best + step, fun_val, cub_val,
  667. ceq_val
  668. )
  669. except np.linalg.LinAlgError:
  670. status = ExitStatus.LINALG_ERROR
  671. break
  672. framework.set_best_index()
  673. # Update the trust-region radius.
  674. framework.update_radius(step, ratio)
  675. # Attempt to replace the models by the alternative ones.
  676. if framework.radius <= framework.resolution:
  677. if ratio >= constants[Constants.VERY_LOW_RATIO]:
  678. n_alt_models = 0
  679. else:
  680. n_alt_models += 1
  681. grad = framework.models.fun_grad(framework.x_best)
  682. try:
  683. grad_alt = framework.models.fun_alt_grad(
  684. framework.x_best
  685. )
  686. except np.linalg.LinAlgError:
  687. status = ExitStatus.LINALG_ERROR
  688. break
  689. if np.linalg.norm(grad) < constants[
  690. Constants.LARGE_GRADIENT_FACTOR
  691. ] * np.linalg.norm(grad_alt):
  692. n_alt_models = 0
  693. if n_alt_models >= 3:
  694. try:
  695. framework.models.reset_models()
  696. except np.linalg.LinAlgError:
  697. status = ExitStatus.LINALG_ERROR
  698. break
  699. n_alt_models = 0
  700. # Update the Lagrange multipliers.
  701. framework.set_multipliers(framework.x_best + step)
  702. # Check whether the resolution should be enhanced.
  703. try:
  704. k_new, dist_new = framework.get_index_to_remove()
  705. except np.linalg.LinAlgError:
  706. status = ExitStatus.LINALG_ERROR
  707. break
  708. improve_geometry = (
  709. ill_conditioned
  710. or ratio <= constants[Constants.LOW_RATIO]
  711. and dist_new
  712. > max(
  713. framework.radius,
  714. constants[Constants.RESOLUTION_FACTOR]
  715. * framework.resolution,
  716. )
  717. )
  718. enhance_resolution = (
  719. radius_save <= framework.resolution
  720. and ratio <= constants[Constants.LOW_RATIO]
  721. and not improve_geometry
  722. )
  723. else:
  724. # When increasing the penalty parameter, the best point so far
  725. # may change. In this case, we restart the iteration.
  726. enhance_resolution = False
  727. improve_geometry = False
  728. # Reduce the resolution if necessary.
  729. if enhance_resolution:
  730. if framework.resolution <= options[Options.RHOEND]:
  731. success = True
  732. status = ExitStatus.RADIUS_SUCCESS
  733. break
  734. framework.enhance_resolution(options)
  735. framework.decrease_penalty()
  736. if verbose:
  737. maxcv_val = pb.maxcv(
  738. framework.x_best, framework.cub_best, framework.ceq_best
  739. )
  740. _print_step(
  741. f"New trust-region radius: {framework.resolution}",
  742. pb,
  743. pb.build_x(framework.x_best),
  744. framework.fun_best,
  745. maxcv_val,
  746. pb.n_eval,
  747. n_iter,
  748. )
  749. print()
  750. # Improve the geometry of the interpolation set if necessary.
  751. if improve_geometry:
  752. try:
  753. step = framework.get_geometry_step(k_new, options)
  754. except np.linalg.LinAlgError:
  755. status = ExitStatus.LINALG_ERROR
  756. break
  757. # Evaluate the objective and constraint functions.
  758. try:
  759. fun_val, cub_val, ceq_val = _eval(pb, framework, step, options)
  760. except TargetSuccess:
  761. status = ExitStatus.TARGET_SUCCESS
  762. success = True
  763. break
  764. except FeasibleSuccess:
  765. status = ExitStatus.FEASIBLE_SUCCESS
  766. success = True
  767. break
  768. except CallbackSuccess:
  769. status = ExitStatus.CALLBACK_SUCCESS
  770. success = True
  771. break
  772. except MaxEvalError:
  773. status = ExitStatus.MAX_EVAL_WARNING
  774. break
  775. # Update the interpolation set.
  776. try:
  777. framework.models.update_interpolation(
  778. k_new,
  779. framework.x_best + step,
  780. fun_val,
  781. cub_val,
  782. ceq_val,
  783. )
  784. except np.linalg.LinAlgError:
  785. status = ExitStatus.LINALG_ERROR
  786. break
  787. framework.set_best_index()
  788. return _build_result(
  789. pb,
  790. framework.penalty,
  791. success,
  792. status,
  793. n_iter,
  794. options,
  795. )
  796. def _get_bounds(bounds, n):
  797. """
  798. Uniformize the bounds.
  799. """
  800. if bounds is None:
  801. return Bounds(np.full(n, -np.inf), np.full(n, np.inf))
  802. elif isinstance(bounds, Bounds):
  803. if bounds.lb.shape != (n,) or bounds.ub.shape != (n,):
  804. raise ValueError(f"The bounds must have {n} elements.")
  805. return Bounds(bounds.lb, bounds.ub)
  806. elif hasattr(bounds, "__len__"):
  807. bounds = np.asarray(bounds)
  808. if bounds.shape != (n, 2):
  809. raise ValueError(
  810. "The shape of the bounds is not compatible with "
  811. "the number of variables."
  812. )
  813. return Bounds(bounds[:, 0], bounds[:, 1])
  814. else:
  815. raise TypeError(
  816. "The bounds must be an instance of "
  817. "scipy.optimize.Bounds or an array-like object."
  818. )
  819. def _get_constraints(constraints):
  820. """
  821. Extract the linear and nonlinear constraints.
  822. """
  823. if isinstance(constraints, dict) or not hasattr(constraints, "__len__"):
  824. constraints = (constraints,)
  825. # Extract the linear and nonlinear constraints.
  826. linear_constraints = []
  827. nonlinear_constraints = []
  828. for constraint in constraints:
  829. if isinstance(constraint, LinearConstraint):
  830. lb = exact_1d_array(
  831. constraint.lb,
  832. "The lower bound of the linear constraints must be a vector.",
  833. )
  834. ub = exact_1d_array(
  835. constraint.ub,
  836. "The upper bound of the linear constraints must be a vector.",
  837. )
  838. linear_constraints.append(
  839. LinearConstraint(
  840. constraint.A,
  841. *np.broadcast_arrays(lb, ub),
  842. )
  843. )
  844. elif isinstance(constraint, NonlinearConstraint):
  845. lb = exact_1d_array(
  846. constraint.lb,
  847. "The lower bound of the "
  848. "nonlinear constraints must be a "
  849. "vector.",
  850. )
  851. ub = exact_1d_array(
  852. constraint.ub,
  853. "The upper bound of the "
  854. "nonlinear constraints must be a "
  855. "vector.",
  856. )
  857. nonlinear_constraints.append(
  858. NonlinearConstraint(
  859. constraint.fun,
  860. *np.broadcast_arrays(lb, ub),
  861. )
  862. )
  863. elif isinstance(constraint, dict):
  864. if "type" not in constraint or constraint["type"] not in (
  865. "eq",
  866. "ineq",
  867. ):
  868. raise ValueError('The constraint type must be "eq" or "ineq".')
  869. if "fun" not in constraint or not callable(constraint["fun"]):
  870. raise ValueError("The constraint function must be callable.")
  871. nonlinear_constraints.append(
  872. {
  873. "fun": constraint["fun"],
  874. "type": constraint["type"],
  875. "args": constraint.get("args", ()),
  876. }
  877. )
  878. else:
  879. raise TypeError(
  880. "The constraints must be instances of "
  881. "scipy.optimize.LinearConstraint, "
  882. "scipy.optimize.NonlinearConstraint, or dict."
  883. )
  884. return linear_constraints, nonlinear_constraints
  885. def _set_default_options(options, n):
  886. """
  887. Set the default options.
  888. """
  889. if Options.RHOBEG in options and options[Options.RHOBEG] <= 0.0:
  890. raise ValueError("The initial trust-region radius must be positive.")
  891. if Options.RHOEND in options and options[Options.RHOEND] < 0.0:
  892. raise ValueError("The final trust-region radius must be nonnegative.")
  893. if Options.RHOBEG in options and Options.RHOEND in options:
  894. if options[Options.RHOBEG] < options[Options.RHOEND]:
  895. raise ValueError(
  896. "The initial trust-region radius must be greater "
  897. "than or equal to the final trust-region radius."
  898. )
  899. elif Options.RHOBEG in options:
  900. options[Options.RHOEND.value] = np.min(
  901. [
  902. DEFAULT_OPTIONS[Options.RHOEND],
  903. options[Options.RHOBEG],
  904. ]
  905. )
  906. elif Options.RHOEND in options:
  907. options[Options.RHOBEG.value] = np.max(
  908. [
  909. DEFAULT_OPTIONS[Options.RHOBEG],
  910. options[Options.RHOEND],
  911. ]
  912. )
  913. else:
  914. options[Options.RHOBEG.value] = DEFAULT_OPTIONS[Options.RHOBEG]
  915. options[Options.RHOEND.value] = DEFAULT_OPTIONS[Options.RHOEND]
  916. options[Options.RHOBEG.value] = float(options[Options.RHOBEG])
  917. options[Options.RHOEND.value] = float(options[Options.RHOEND])
  918. if Options.NPT in options and options[Options.NPT] <= 0:
  919. raise ValueError("The number of interpolation points must be "
  920. "positive.")
  921. if (
  922. Options.NPT in options
  923. and options[Options.NPT] > ((n + 1) * (n + 2)) // 2
  924. ):
  925. raise ValueError(
  926. f"The number of interpolation points must be at most "
  927. f"{((n + 1) * (n + 2)) // 2}."
  928. )
  929. options.setdefault(Options.NPT.value, DEFAULT_OPTIONS[Options.NPT](n))
  930. options[Options.NPT.value] = int(options[Options.NPT])
  931. if Options.MAX_EVAL in options and options[Options.MAX_EVAL] <= 0:
  932. raise ValueError(
  933. "The maximum number of function evaluations must be positive."
  934. )
  935. options.setdefault(
  936. Options.MAX_EVAL.value,
  937. np.max(
  938. [
  939. DEFAULT_OPTIONS[Options.MAX_EVAL](n),
  940. options[Options.NPT] + 1,
  941. ]
  942. ),
  943. )
  944. options[Options.MAX_EVAL.value] = int(options[Options.MAX_EVAL])
  945. if Options.MAX_ITER in options and options[Options.MAX_ITER] <= 0:
  946. raise ValueError("The maximum number of iterations must be positive.")
  947. options.setdefault(
  948. Options.MAX_ITER.value,
  949. DEFAULT_OPTIONS[Options.MAX_ITER](n),
  950. )
  951. options[Options.MAX_ITER.value] = int(options[Options.MAX_ITER])
  952. options.setdefault(Options.TARGET.value, DEFAULT_OPTIONS[Options.TARGET])
  953. options[Options.TARGET.value] = float(options[Options.TARGET])
  954. options.setdefault(
  955. Options.FEASIBILITY_TOL.value,
  956. DEFAULT_OPTIONS[Options.FEASIBILITY_TOL],
  957. )
  958. options[Options.FEASIBILITY_TOL.value] = float(
  959. options[Options.FEASIBILITY_TOL]
  960. )
  961. options.setdefault(Options.VERBOSE.value, DEFAULT_OPTIONS[Options.VERBOSE])
  962. options[Options.VERBOSE.value] = bool(options[Options.VERBOSE])
  963. options.setdefault(Options.SCALE.value, DEFAULT_OPTIONS[Options.SCALE])
  964. options[Options.SCALE.value] = bool(options[Options.SCALE])
  965. options.setdefault(
  966. Options.FILTER_SIZE.value,
  967. DEFAULT_OPTIONS[Options.FILTER_SIZE],
  968. )
  969. options[Options.FILTER_SIZE.value] = int(options[Options.FILTER_SIZE])
  970. options.setdefault(
  971. Options.STORE_HISTORY.value,
  972. DEFAULT_OPTIONS[Options.STORE_HISTORY],
  973. )
  974. options[Options.STORE_HISTORY.value] = bool(options[Options.STORE_HISTORY])
  975. options.setdefault(
  976. Options.HISTORY_SIZE.value,
  977. DEFAULT_OPTIONS[Options.HISTORY_SIZE],
  978. )
  979. options[Options.HISTORY_SIZE.value] = int(options[Options.HISTORY_SIZE])
  980. options.setdefault(Options.DEBUG.value, DEFAULT_OPTIONS[Options.DEBUG])
  981. options[Options.DEBUG.value] = bool(options[Options.DEBUG])
  982. # Check whether they are any unknown options.
  983. for key in options:
  984. if key not in Options.__members__.values():
  985. warnings.warn(f"Unknown option: {key}.", RuntimeWarning, 3)
  986. def _set_default_constants(**kwargs):
  987. """
  988. Set the default constants.
  989. """
  990. constants = dict(kwargs)
  991. constants.setdefault(
  992. Constants.DECREASE_RADIUS_FACTOR.value,
  993. DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_FACTOR],
  994. )
  995. constants[Constants.DECREASE_RADIUS_FACTOR.value] = float(
  996. constants[Constants.DECREASE_RADIUS_FACTOR]
  997. )
  998. if (
  999. constants[Constants.DECREASE_RADIUS_FACTOR] <= 0.0
  1000. or constants[Constants.DECREASE_RADIUS_FACTOR] >= 1.0
  1001. ):
  1002. raise ValueError(
  1003. "The constant decrease_radius_factor must be in the interval "
  1004. "(0, 1)."
  1005. )
  1006. constants.setdefault(
  1007. Constants.INCREASE_RADIUS_THRESHOLD.value,
  1008. DEFAULT_CONSTANTS[Constants.INCREASE_RADIUS_THRESHOLD],
  1009. )
  1010. constants[Constants.INCREASE_RADIUS_THRESHOLD.value] = float(
  1011. constants[Constants.INCREASE_RADIUS_THRESHOLD]
  1012. )
  1013. if constants[Constants.INCREASE_RADIUS_THRESHOLD] <= 1.0:
  1014. raise ValueError(
  1015. "The constant increase_radius_threshold must be greater than 1."
  1016. )
  1017. if (
  1018. Constants.INCREASE_RADIUS_FACTOR in constants
  1019. and constants[Constants.INCREASE_RADIUS_FACTOR] <= 1.0
  1020. ):
  1021. raise ValueError(
  1022. "The constant increase_radius_factor must be greater than 1."
  1023. )
  1024. if (
  1025. Constants.DECREASE_RADIUS_THRESHOLD in constants
  1026. and constants[Constants.DECREASE_RADIUS_THRESHOLD] <= 1.0
  1027. ):
  1028. raise ValueError(
  1029. "The constant decrease_radius_threshold must be greater than 1."
  1030. )
  1031. if (
  1032. Constants.INCREASE_RADIUS_FACTOR in constants
  1033. and Constants.DECREASE_RADIUS_THRESHOLD in constants
  1034. ):
  1035. if (
  1036. constants[Constants.DECREASE_RADIUS_THRESHOLD]
  1037. >= constants[Constants.INCREASE_RADIUS_FACTOR]
  1038. ):
  1039. raise ValueError(
  1040. "The constant decrease_radius_threshold must be "
  1041. "less than increase_radius_factor."
  1042. )
  1043. elif Constants.INCREASE_RADIUS_FACTOR in constants:
  1044. constants[Constants.DECREASE_RADIUS_THRESHOLD.value] = np.min(
  1045. [
  1046. DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_THRESHOLD],
  1047. 0.5 * (1.0 + constants[Constants.INCREASE_RADIUS_FACTOR]),
  1048. ]
  1049. )
  1050. elif Constants.DECREASE_RADIUS_THRESHOLD in constants:
  1051. constants[Constants.INCREASE_RADIUS_FACTOR.value] = np.max(
  1052. [
  1053. DEFAULT_CONSTANTS[Constants.INCREASE_RADIUS_FACTOR],
  1054. 2.0 * constants[Constants.DECREASE_RADIUS_THRESHOLD],
  1055. ]
  1056. )
  1057. else:
  1058. constants[Constants.INCREASE_RADIUS_FACTOR.value] = DEFAULT_CONSTANTS[
  1059. Constants.INCREASE_RADIUS_FACTOR
  1060. ]
  1061. constants[Constants.DECREASE_RADIUS_THRESHOLD.value] = (
  1062. DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_THRESHOLD])
  1063. constants.setdefault(
  1064. Constants.DECREASE_RESOLUTION_FACTOR.value,
  1065. DEFAULT_CONSTANTS[Constants.DECREASE_RESOLUTION_FACTOR],
  1066. )
  1067. constants[Constants.DECREASE_RESOLUTION_FACTOR.value] = float(
  1068. constants[Constants.DECREASE_RESOLUTION_FACTOR]
  1069. )
  1070. if (
  1071. constants[Constants.DECREASE_RESOLUTION_FACTOR] <= 0.0
  1072. or constants[Constants.DECREASE_RESOLUTION_FACTOR] >= 1.0
  1073. ):
  1074. raise ValueError(
  1075. "The constant decrease_resolution_factor must be in the interval "
  1076. "(0, 1)."
  1077. )
  1078. if (
  1079. Constants.LARGE_RESOLUTION_THRESHOLD in constants
  1080. and constants[Constants.LARGE_RESOLUTION_THRESHOLD] <= 1.0
  1081. ):
  1082. raise ValueError(
  1083. "The constant large_resolution_threshold must be greater than 1."
  1084. )
  1085. if (
  1086. Constants.MODERATE_RESOLUTION_THRESHOLD in constants
  1087. and constants[Constants.MODERATE_RESOLUTION_THRESHOLD] <= 1.0
  1088. ):
  1089. raise ValueError(
  1090. "The constant moderate_resolution_threshold must be greater than "
  1091. "1."
  1092. )
  1093. if (
  1094. Constants.LARGE_RESOLUTION_THRESHOLD in constants
  1095. and Constants.MODERATE_RESOLUTION_THRESHOLD in constants
  1096. ):
  1097. if (
  1098. constants[Constants.MODERATE_RESOLUTION_THRESHOLD]
  1099. > constants[Constants.LARGE_RESOLUTION_THRESHOLD]
  1100. ):
  1101. raise ValueError(
  1102. "The constant moderate_resolution_threshold "
  1103. "must be at most large_resolution_threshold."
  1104. )
  1105. elif Constants.LARGE_RESOLUTION_THRESHOLD in constants:
  1106. constants[Constants.MODERATE_RESOLUTION_THRESHOLD.value] = np.min(
  1107. [
  1108. DEFAULT_CONSTANTS[Constants.MODERATE_RESOLUTION_THRESHOLD],
  1109. constants[Constants.LARGE_RESOLUTION_THRESHOLD],
  1110. ]
  1111. )
  1112. elif Constants.MODERATE_RESOLUTION_THRESHOLD in constants:
  1113. constants[Constants.LARGE_RESOLUTION_THRESHOLD.value] = np.max(
  1114. [
  1115. DEFAULT_CONSTANTS[Constants.LARGE_RESOLUTION_THRESHOLD],
  1116. constants[Constants.MODERATE_RESOLUTION_THRESHOLD],
  1117. ]
  1118. )
  1119. else:
  1120. constants[Constants.LARGE_RESOLUTION_THRESHOLD.value] = (
  1121. DEFAULT_CONSTANTS[Constants.LARGE_RESOLUTION_THRESHOLD]
  1122. )
  1123. constants[Constants.MODERATE_RESOLUTION_THRESHOLD.value] = (
  1124. DEFAULT_CONSTANTS[Constants.MODERATE_RESOLUTION_THRESHOLD]
  1125. )
  1126. if Constants.LOW_RATIO in constants and (
  1127. constants[Constants.LOW_RATIO] <= 0.0
  1128. or constants[Constants.LOW_RATIO] >= 1.0
  1129. ):
  1130. raise ValueError(
  1131. "The constant low_ratio must be in the interval (0, 1)."
  1132. )
  1133. if Constants.HIGH_RATIO in constants and (
  1134. constants[Constants.HIGH_RATIO] <= 0.0
  1135. or constants[Constants.HIGH_RATIO] >= 1.0
  1136. ):
  1137. raise ValueError(
  1138. "The constant high_ratio must be in the interval (0, 1)."
  1139. )
  1140. if Constants.LOW_RATIO in constants and Constants.HIGH_RATIO in constants:
  1141. if constants[Constants.LOW_RATIO] > constants[Constants.HIGH_RATIO]:
  1142. raise ValueError(
  1143. "The constant low_ratio must be at most high_ratio."
  1144. )
  1145. elif Constants.LOW_RATIO in constants:
  1146. constants[Constants.HIGH_RATIO.value] = np.max(
  1147. [
  1148. DEFAULT_CONSTANTS[Constants.HIGH_RATIO],
  1149. constants[Constants.LOW_RATIO],
  1150. ]
  1151. )
  1152. elif Constants.HIGH_RATIO in constants:
  1153. constants[Constants.LOW_RATIO.value] = np.min(
  1154. [
  1155. DEFAULT_CONSTANTS[Constants.LOW_RATIO],
  1156. constants[Constants.HIGH_RATIO],
  1157. ]
  1158. )
  1159. else:
  1160. constants[Constants.LOW_RATIO.value] = DEFAULT_CONSTANTS[
  1161. Constants.LOW_RATIO
  1162. ]
  1163. constants[Constants.HIGH_RATIO.value] = DEFAULT_CONSTANTS[
  1164. Constants.HIGH_RATIO
  1165. ]
  1166. constants.setdefault(
  1167. Constants.VERY_LOW_RATIO.value,
  1168. DEFAULT_CONSTANTS[Constants.VERY_LOW_RATIO],
  1169. )
  1170. constants[Constants.VERY_LOW_RATIO.value] = float(
  1171. constants[Constants.VERY_LOW_RATIO]
  1172. )
  1173. if (
  1174. constants[Constants.VERY_LOW_RATIO] <= 0.0
  1175. or constants[Constants.VERY_LOW_RATIO] >= 1.0
  1176. ):
  1177. raise ValueError(
  1178. "The constant very_low_ratio must be in the interval (0, 1)."
  1179. )
  1180. if (
  1181. Constants.PENALTY_INCREASE_THRESHOLD in constants
  1182. and constants[Constants.PENALTY_INCREASE_THRESHOLD] < 1.0
  1183. ):
  1184. raise ValueError(
  1185. "The constant penalty_increase_threshold must be "
  1186. "greater than or equal to 1."
  1187. )
  1188. if (
  1189. Constants.PENALTY_INCREASE_FACTOR in constants
  1190. and constants[Constants.PENALTY_INCREASE_FACTOR] <= 1.0
  1191. ):
  1192. raise ValueError(
  1193. "The constant penalty_increase_factor must be greater than 1."
  1194. )
  1195. if (
  1196. Constants.PENALTY_INCREASE_THRESHOLD in constants
  1197. and Constants.PENALTY_INCREASE_FACTOR in constants
  1198. ):
  1199. if (
  1200. constants[Constants.PENALTY_INCREASE_FACTOR]
  1201. < constants[Constants.PENALTY_INCREASE_THRESHOLD]
  1202. ):
  1203. raise ValueError(
  1204. "The constant penalty_increase_factor must be "
  1205. "greater than or equal to "
  1206. "penalty_increase_threshold."
  1207. )
  1208. elif Constants.PENALTY_INCREASE_THRESHOLD in constants:
  1209. constants[Constants.PENALTY_INCREASE_FACTOR.value] = np.max(
  1210. [
  1211. DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_FACTOR],
  1212. constants[Constants.PENALTY_INCREASE_THRESHOLD],
  1213. ]
  1214. )
  1215. elif Constants.PENALTY_INCREASE_FACTOR in constants:
  1216. constants[Constants.PENALTY_INCREASE_THRESHOLD.value] = np.min(
  1217. [
  1218. DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_THRESHOLD],
  1219. constants[Constants.PENALTY_INCREASE_FACTOR],
  1220. ]
  1221. )
  1222. else:
  1223. constants[Constants.PENALTY_INCREASE_THRESHOLD.value] = (
  1224. DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_THRESHOLD]
  1225. )
  1226. constants[Constants.PENALTY_INCREASE_FACTOR.value] = DEFAULT_CONSTANTS[
  1227. Constants.PENALTY_INCREASE_FACTOR
  1228. ]
  1229. constants.setdefault(
  1230. Constants.SHORT_STEP_THRESHOLD.value,
  1231. DEFAULT_CONSTANTS[Constants.SHORT_STEP_THRESHOLD],
  1232. )
  1233. constants[Constants.SHORT_STEP_THRESHOLD.value] = float(
  1234. constants[Constants.SHORT_STEP_THRESHOLD]
  1235. )
  1236. if (
  1237. constants[Constants.SHORT_STEP_THRESHOLD] <= 0.0
  1238. or constants[Constants.SHORT_STEP_THRESHOLD] >= 1.0
  1239. ):
  1240. raise ValueError(
  1241. "The constant short_step_threshold must be in the interval (0, 1)."
  1242. )
  1243. constants.setdefault(
  1244. Constants.LOW_RADIUS_FACTOR.value,
  1245. DEFAULT_CONSTANTS[Constants.LOW_RADIUS_FACTOR],
  1246. )
  1247. constants[Constants.LOW_RADIUS_FACTOR.value] = float(
  1248. constants[Constants.LOW_RADIUS_FACTOR]
  1249. )
  1250. if (
  1251. constants[Constants.LOW_RADIUS_FACTOR] <= 0.0
  1252. or constants[Constants.LOW_RADIUS_FACTOR] >= 1.0
  1253. ):
  1254. raise ValueError(
  1255. "The constant low_radius_factor must be in the interval (0, 1)."
  1256. )
  1257. constants.setdefault(
  1258. Constants.BYRD_OMOJOKUN_FACTOR.value,
  1259. DEFAULT_CONSTANTS[Constants.BYRD_OMOJOKUN_FACTOR],
  1260. )
  1261. constants[Constants.BYRD_OMOJOKUN_FACTOR.value] = float(
  1262. constants[Constants.BYRD_OMOJOKUN_FACTOR]
  1263. )
  1264. if (
  1265. constants[Constants.BYRD_OMOJOKUN_FACTOR] <= 0.0
  1266. or constants[Constants.BYRD_OMOJOKUN_FACTOR] >= 1.0
  1267. ):
  1268. raise ValueError(
  1269. "The constant byrd_omojokun_factor must be in the interval (0, 1)."
  1270. )
  1271. constants.setdefault(
  1272. Constants.THRESHOLD_RATIO_CONSTRAINTS.value,
  1273. DEFAULT_CONSTANTS[Constants.THRESHOLD_RATIO_CONSTRAINTS],
  1274. )
  1275. constants[Constants.THRESHOLD_RATIO_CONSTRAINTS.value] = float(
  1276. constants[Constants.THRESHOLD_RATIO_CONSTRAINTS]
  1277. )
  1278. if constants[Constants.THRESHOLD_RATIO_CONSTRAINTS] <= 1.0:
  1279. raise ValueError(
  1280. "The constant threshold_ratio_constraints must be greater than 1."
  1281. )
  1282. constants.setdefault(
  1283. Constants.LARGE_SHIFT_FACTOR.value,
  1284. DEFAULT_CONSTANTS[Constants.LARGE_SHIFT_FACTOR],
  1285. )
  1286. constants[Constants.LARGE_SHIFT_FACTOR.value] = float(
  1287. constants[Constants.LARGE_SHIFT_FACTOR]
  1288. )
  1289. if constants[Constants.LARGE_SHIFT_FACTOR] < 0.0:
  1290. raise ValueError("The constant large_shift_factor must be "
  1291. "nonnegative.")
  1292. constants.setdefault(
  1293. Constants.LARGE_GRADIENT_FACTOR.value,
  1294. DEFAULT_CONSTANTS[Constants.LARGE_GRADIENT_FACTOR],
  1295. )
  1296. constants[Constants.LARGE_GRADIENT_FACTOR.value] = float(
  1297. constants[Constants.LARGE_GRADIENT_FACTOR]
  1298. )
  1299. if constants[Constants.LARGE_GRADIENT_FACTOR] <= 1.0:
  1300. raise ValueError(
  1301. "The constant large_gradient_factor must be greater than 1."
  1302. )
  1303. constants.setdefault(
  1304. Constants.RESOLUTION_FACTOR.value,
  1305. DEFAULT_CONSTANTS[Constants.RESOLUTION_FACTOR],
  1306. )
  1307. constants[Constants.RESOLUTION_FACTOR.value] = float(
  1308. constants[Constants.RESOLUTION_FACTOR]
  1309. )
  1310. if constants[Constants.RESOLUTION_FACTOR] <= 1.0:
  1311. raise ValueError(
  1312. "The constant resolution_factor must be greater than 1."
  1313. )
  1314. constants.setdefault(
  1315. Constants.IMPROVE_TCG.value,
  1316. DEFAULT_CONSTANTS[Constants.IMPROVE_TCG],
  1317. )
  1318. constants[Constants.IMPROVE_TCG.value] = bool(
  1319. constants[Constants.IMPROVE_TCG]
  1320. )
  1321. # Check whether they are any unknown options.
  1322. for key in kwargs:
  1323. if key not in Constants.__members__.values():
  1324. warnings.warn(f"Unknown constant: {key}.", RuntimeWarning, 3)
  1325. return constants
  1326. def _eval(pb, framework, step, options):
  1327. """
  1328. Evaluate the objective and constraint functions.
  1329. """
  1330. if pb.n_eval >= options[Options.MAX_EVAL]:
  1331. raise MaxEvalError
  1332. x_eval = framework.x_best + step
  1333. fun_val, cub_val, ceq_val = pb(x_eval, framework.penalty)
  1334. r_val = pb.maxcv(x_eval, cub_val, ceq_val)
  1335. if (
  1336. fun_val <= options[Options.TARGET]
  1337. and r_val <= options[Options.FEASIBILITY_TOL]
  1338. ):
  1339. raise TargetSuccess
  1340. if pb.is_feasibility and r_val <= options[Options.FEASIBILITY_TOL]:
  1341. raise FeasibleSuccess
  1342. return fun_val, cub_val, ceq_val
  1343. def _build_result(pb, penalty, success, status, n_iter, options):
  1344. """
  1345. Build the result of the optimization process.
  1346. """
  1347. # Build the result.
  1348. x, fun, maxcv = pb.best_eval(penalty)
  1349. success = success and np.isfinite(fun) and np.isfinite(maxcv)
  1350. if status not in [ExitStatus.TARGET_SUCCESS, ExitStatus.FEASIBLE_SUCCESS]:
  1351. success = success and maxcv <= options[Options.FEASIBILITY_TOL]
  1352. result = OptimizeResult()
  1353. result.message = {
  1354. ExitStatus.RADIUS_SUCCESS: "The lower bound for the trust-region "
  1355. "radius has been reached",
  1356. ExitStatus.TARGET_SUCCESS: "The target objective function value has "
  1357. "been reached",
  1358. ExitStatus.FIXED_SUCCESS: "All variables are fixed by the bound "
  1359. "constraints",
  1360. ExitStatus.CALLBACK_SUCCESS: "The callback requested to stop the "
  1361. "optimization procedure",
  1362. ExitStatus.FEASIBLE_SUCCESS: "The feasibility problem received has "
  1363. "been solved successfully",
  1364. ExitStatus.MAX_EVAL_WARNING: "The maximum number of function "
  1365. "evaluations has been exceeded",
  1366. ExitStatus.MAX_ITER_WARNING: "The maximum number of iterations has "
  1367. "been exceeded",
  1368. ExitStatus.INFEASIBLE_ERROR: "The bound constraints are infeasible",
  1369. ExitStatus.LINALG_ERROR: "A linear algebra error occurred",
  1370. }.get(status, "Unknown exit status")
  1371. result.success = success
  1372. result.status = status.value
  1373. result.x = pb.build_x(x)
  1374. result.fun = fun
  1375. result.maxcv = maxcv
  1376. result.nfev = pb.n_eval
  1377. result.nit = n_iter
  1378. if options[Options.STORE_HISTORY]:
  1379. result.fun_history = pb.fun_history
  1380. result.maxcv_history = pb.maxcv_history
  1381. # Print the result if requested.
  1382. if options[Options.VERBOSE]:
  1383. _print_step(
  1384. result.message,
  1385. pb,
  1386. result.x,
  1387. result.fun,
  1388. result.maxcv,
  1389. result.nfev,
  1390. result.nit,
  1391. )
  1392. return result
  1393. def _print_step(message, pb, x, fun_val, r_val, n_eval, n_iter):
  1394. """
  1395. Print information about the current state of the optimization process.
  1396. """
  1397. print()
  1398. print(f"{message}.")
  1399. print(f"Number of function evaluations: {n_eval}.")
  1400. print(f"Number of iterations: {n_iter}.")
  1401. if not pb.is_feasibility:
  1402. print(f"Least value of {pb.fun_name}: {fun_val}.")
  1403. print(f"Maximum constraint violation: {r_val}.")
  1404. with np.printoptions(**PRINT_OPTIONS):
  1405. print(f"Corresponding point: {x}.")