minimize_trustregion_constr.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. import time
  2. import numpy as np
  3. from scipy.sparse.linalg import LinearOperator
  4. from .._differentiable_functions import VectorFunction
  5. from .._constraints import (
  6. NonlinearConstraint, LinearConstraint, PreparedConstraint, strict_bounds)
  7. from .._hessian_update_strategy import BFGS
  8. from .._optimize import OptimizeResult
  9. from .._differentiable_functions import ScalarFunction
  10. from .equality_constrained_sqp import equality_constrained_sqp
  11. from .canonical_constraint import (CanonicalConstraint,
  12. initial_constraints_as_canonical)
  13. from .tr_interior_point import tr_interior_point
  14. from .report import BasicReport, SQPReport, IPReport
  15. TERMINATION_MESSAGES = {
  16. 0: "The maximum number of function evaluations is exceeded.",
  17. 1: "`gtol` termination condition is satisfied.",
  18. 2: "`xtol` termination condition is satisfied.",
  19. 3: "`callback` function requested termination."
  20. }
  21. class HessianLinearOperator:
  22. """Build LinearOperator from hessp"""
  23. def __init__(self, hessp, n):
  24. self.hessp = hessp
  25. self.n = n
  26. def __call__(self, x, *args):
  27. def matvec(p):
  28. return self.hessp(x, p, *args)
  29. return LinearOperator((self.n, self.n), matvec=matvec)
  30. class LagrangianHessian:
  31. """The Hessian of the Lagrangian as LinearOperator.
  32. The Lagrangian is computed as the objective function plus all the
  33. constraints multiplied with some numbers (Lagrange multipliers).
  34. """
  35. def __init__(self, n, objective_hess, constraints_hess):
  36. self.n = n
  37. self.objective_hess = objective_hess
  38. self.constraints_hess = constraints_hess
  39. def __call__(self, x, v_eq=np.empty(0), v_ineq=np.empty(0)):
  40. H_objective = self.objective_hess(x)
  41. H_constraints = self.constraints_hess(x, v_eq, v_ineq)
  42. def matvec(p):
  43. return H_objective.dot(p) + H_constraints.dot(p)
  44. return LinearOperator((self.n, self.n), matvec)
  45. def update_state_sqp(state, x, last_iteration_failed, objective, prepared_constraints,
  46. start_time, tr_radius, constr_penalty, cg_info):
  47. state.nit += 1
  48. state.nfev = objective.nfev
  49. state.njev = objective.ngev
  50. state.nhev = objective.nhev
  51. state.constr_nfev = [c.fun.nfev if isinstance(c.fun, VectorFunction) else 0
  52. for c in prepared_constraints]
  53. state.constr_njev = [c.fun.njev if isinstance(c.fun, VectorFunction) else 0
  54. for c in prepared_constraints]
  55. state.constr_nhev = [c.fun.nhev if isinstance(c.fun, VectorFunction) else 0
  56. for c in prepared_constraints]
  57. if not last_iteration_failed:
  58. state.x = x
  59. state.fun = objective.f
  60. state.grad = objective.g
  61. state.v = [c.fun.v for c in prepared_constraints]
  62. state.constr = [c.fun.f for c in prepared_constraints]
  63. state.jac = [c.fun.J for c in prepared_constraints]
  64. # Compute Lagrangian Gradient
  65. state.lagrangian_grad = np.copy(state.grad)
  66. for c in prepared_constraints:
  67. state.lagrangian_grad += c.fun.J.T.dot(c.fun.v)
  68. state.optimality = np.linalg.norm(state.lagrangian_grad, np.inf)
  69. # Compute maximum constraint violation
  70. state.constr_violation = 0
  71. for i in range(len(prepared_constraints)):
  72. lb, ub = prepared_constraints[i].bounds
  73. c = state.constr[i]
  74. state.constr_violation = np.max([state.constr_violation,
  75. np.max(lb - c),
  76. np.max(c - ub)])
  77. state.execution_time = time.time() - start_time
  78. state.tr_radius = tr_radius
  79. state.constr_penalty = constr_penalty
  80. state.cg_niter += cg_info["niter"]
  81. state.cg_stop_cond = cg_info["stop_cond"]
  82. return state
  83. def update_state_ip(state, x, last_iteration_failed, objective,
  84. prepared_constraints, start_time,
  85. tr_radius, constr_penalty, cg_info,
  86. barrier_parameter, barrier_tolerance):
  87. state = update_state_sqp(state, x, last_iteration_failed, objective,
  88. prepared_constraints, start_time, tr_radius,
  89. constr_penalty, cg_info)
  90. state.barrier_parameter = barrier_parameter
  91. state.barrier_tolerance = barrier_tolerance
  92. return state
  93. def _minimize_trustregion_constr(fun, x0, args, grad,
  94. hess, hessp, bounds, constraints,
  95. xtol=1e-8, gtol=1e-8,
  96. barrier_tol=1e-8,
  97. sparse_jacobian=None,
  98. callback=None, maxiter=1000,
  99. verbose=0, finite_diff_rel_step=None,
  100. initial_constr_penalty=1.0, initial_tr_radius=1.0,
  101. initial_barrier_parameter=0.1,
  102. initial_barrier_tolerance=0.1,
  103. factorization_method=None,
  104. disp=False):
  105. """Minimize a scalar function subject to constraints.
  106. Parameters
  107. ----------
  108. gtol : float, optional
  109. Tolerance for termination by the norm of the Lagrangian gradient.
  110. The algorithm will terminate when both the infinity norm (i.e., max
  111. abs value) of the Lagrangian gradient and the constraint violation
  112. are smaller than ``gtol``. Default is 1e-8.
  113. xtol : float, optional
  114. Tolerance for termination by the change of the independent variable.
  115. The algorithm will terminate when ``tr_radius < xtol``, where
  116. ``tr_radius`` is the radius of the trust region used in the algorithm.
  117. Default is 1e-8.
  118. barrier_tol : float, optional
  119. Threshold on the barrier parameter for the algorithm termination.
  120. When inequality constraints are present, the algorithm will terminate
  121. only when the barrier parameter is less than `barrier_tol`.
  122. Default is 1e-8.
  123. sparse_jacobian : {bool, None}, optional
  124. Determines how to represent Jacobians of the constraints. If bool,
  125. then Jacobians of all the constraints will be converted to the
  126. corresponding format. If None (default), then Jacobians won't be
  127. converted, but the algorithm can proceed only if they all have the
  128. same format.
  129. initial_tr_radius: float, optional
  130. Initial trust radius. The trust radius gives the maximum distance
  131. between solution points in consecutive iterations. It reflects the
  132. trust the algorithm puts in the local approximation of the optimization
  133. problem. For an accurate local approximation the trust-region should be
  134. large and for an approximation valid only close to the current point it
  135. should be a small one. The trust radius is automatically updated throughout
  136. the optimization process, with ``initial_tr_radius`` being its initial value.
  137. Default is 1 (recommended in [1]_, p. 19).
  138. initial_constr_penalty : float, optional
  139. Initial constraints penalty parameter. The penalty parameter is used for
  140. balancing the requirements of decreasing the objective function
  141. and satisfying the constraints. It is used for defining the merit function:
  142. ``merit_function(x) = fun(x) + constr_penalty * constr_norm_l2(x)``,
  143. where ``constr_norm_l2(x)`` is the l2 norm of a vector containing all
  144. the constraints. The merit function is used for accepting or rejecting
  145. trial points and ``constr_penalty`` weights the two conflicting goals
  146. of reducing objective function and constraints. The penalty is automatically
  147. updated throughout the optimization process, with
  148. ``initial_constr_penalty`` being its initial value. Default is 1
  149. (recommended in [1]_, p 19).
  150. initial_barrier_parameter, initial_barrier_tolerance: float, optional
  151. Initial barrier parameter and initial tolerance for the barrier subproblem.
  152. Both are used only when inequality constraints are present. For dealing with
  153. optimization problems ``min_x f(x)`` subject to inequality constraints
  154. ``c(x) <= 0`` the algorithm introduces slack variables, solving the problem
  155. ``min_(x,s) f(x) + barrier_parameter*sum(ln(s))`` subject to the equality
  156. constraints ``c(x) + s = 0`` instead of the original problem. This subproblem
  157. is solved for decreasing values of ``barrier_parameter`` and with decreasing
  158. tolerances for the termination, starting with ``initial_barrier_parameter``
  159. for the barrier parameter and ``initial_barrier_tolerance`` for the
  160. barrier tolerance. Default is 0.1 for both values (recommended in [1]_ p. 19).
  161. Also note that ``barrier_parameter`` and ``barrier_tolerance`` are updated
  162. with the same prefactor.
  163. factorization_method : string or None, optional
  164. Method to factorize the Jacobian of the constraints. Use None (default)
  165. for the auto selection or one of:
  166. - 'NormalEquation' (requires scikit-sparse)
  167. - 'AugmentedSystem'
  168. - 'QRFactorization'
  169. - 'SVDFactorization'
  170. The methods 'NormalEquation' and 'AugmentedSystem' can be used only
  171. with sparse constraints. The projections required by the algorithm
  172. will be computed using, respectively, the normal equation and the
  173. augmented system approaches explained in [1]_. 'NormalEquation'
  174. computes the Cholesky factorization of ``A A.T`` and 'AugmentedSystem'
  175. performs the LU factorization of an augmented system. They usually
  176. provide similar results. 'AugmentedSystem' is used by default for
  177. sparse matrices.
  178. The methods 'QRFactorization' and 'SVDFactorization' can be used
  179. only with dense constraints. They compute the required projections
  180. using, respectively, QR and SVD factorizations. The 'SVDFactorization'
  181. method can cope with Jacobian matrices with deficient row rank and will
  182. be used whenever other factorization methods fail (which may imply the
  183. conversion of sparse matrices to a dense format when required).
  184. By default, 'QRFactorization' is used for dense matrices.
  185. finite_diff_rel_step : None or array_like, optional
  186. Relative step size for the finite difference approximation.
  187. maxiter : int, optional
  188. Maximum number of algorithm iterations. Default is 1000.
  189. verbose : {0, 1, 2}, optional
  190. Level of algorithm's verbosity:
  191. * 0 (default) : work silently.
  192. * 1 : display a termination report.
  193. * 2 : display progress during iterations.
  194. * 3 : display progress during iterations (more complete report).
  195. disp : bool, optional
  196. If True (default), then `verbose` will be set to 1 if it was 0.
  197. Returns
  198. -------
  199. `OptimizeResult` with the fields documented below. Note the following:
  200. 1. All values corresponding to the constraints are ordered as they
  201. were passed to the solver. And values corresponding to `bounds`
  202. constraints are put *after* other constraints.
  203. 2. All numbers of function, Jacobian or Hessian evaluations correspond
  204. to numbers of actual Python function calls. It means, for example,
  205. that if a Jacobian is estimated by finite differences, then the
  206. number of Jacobian evaluations will be zero and the number of
  207. function evaluations will be incremented by all calls during the
  208. finite difference estimation.
  209. x : ndarray, shape (n,)
  210. Solution found.
  211. optimality : float
  212. Infinity norm of the Lagrangian gradient at the solution.
  213. constr_violation : float
  214. Maximum constraint violation at the solution.
  215. fun : float
  216. Objective function at the solution.
  217. grad : ndarray, shape (n,)
  218. Gradient of the objective function at the solution.
  219. lagrangian_grad : ndarray, shape (n,)
  220. Gradient of the Lagrangian function at the solution.
  221. nit : int
  222. Total number of iterations.
  223. nfev : integer
  224. Number of the objective function evaluations.
  225. njev : integer
  226. Number of the objective function gradient evaluations.
  227. nhev : integer
  228. Number of the objective function Hessian evaluations.
  229. cg_niter : int
  230. Total number of the conjugate gradient method iterations.
  231. method : {'equality_constrained_sqp', 'tr_interior_point'}
  232. Optimization method used.
  233. constr : list of ndarray
  234. List of constraint values at the solution.
  235. jac : list of {ndarray, sparse matrix}
  236. List of the Jacobian matrices of the constraints at the solution.
  237. v : list of ndarray
  238. List of the Lagrange multipliers for the constraints at the solution.
  239. For an inequality constraint a positive multiplier means that the upper
  240. bound is active, a negative multiplier means that the lower bound is
  241. active and if a multiplier is zero it means the constraint is not
  242. active.
  243. constr_nfev : list of int
  244. Number of constraint evaluations for each of the constraints.
  245. constr_njev : list of int
  246. Number of Jacobian matrix evaluations for each of the constraints.
  247. constr_nhev : list of int
  248. Number of Hessian evaluations for each of the constraints.
  249. tr_radius : float
  250. Radius of the trust region at the last iteration.
  251. constr_penalty : float
  252. Penalty parameter at the last iteration, see `initial_constr_penalty`.
  253. barrier_tolerance : float
  254. Tolerance for the barrier subproblem at the last iteration.
  255. Only for problems with inequality constraints.
  256. barrier_parameter : float
  257. Barrier parameter at the last iteration. Only for problems
  258. with inequality constraints.
  259. execution_time : float
  260. Total execution time.
  261. message : str
  262. Termination message.
  263. status : {0, 1, 2, 3}
  264. Termination status:
  265. * 0 : The maximum number of function evaluations is exceeded.
  266. * 1 : `gtol` termination condition is satisfied.
  267. * 2 : `xtol` termination condition is satisfied.
  268. * 3 : `callback` function requested termination.
  269. cg_stop_cond : int
  270. Reason for CG subproblem termination at the last iteration:
  271. * 0 : CG subproblem not evaluated.
  272. * 1 : Iteration limit was reached.
  273. * 2 : Reached the trust-region boundary.
  274. * 3 : Negative curvature detected.
  275. * 4 : Tolerance was satisfied.
  276. References
  277. ----------
  278. .. [1] Conn, A. R., Gould, N. I., & Toint, P. L.
  279. Trust region methods. 2000. Siam. pp. 19.
  280. """
  281. x0 = np.atleast_1d(x0).astype(float)
  282. n_vars = np.size(x0)
  283. if hess is None:
  284. if callable(hessp):
  285. hess = HessianLinearOperator(hessp, n_vars)
  286. else:
  287. hess = BFGS()
  288. if disp and verbose == 0:
  289. verbose = 1
  290. if bounds is not None:
  291. finite_diff_bounds = strict_bounds(bounds.lb, bounds.ub,
  292. bounds.keep_feasible, n_vars)
  293. else:
  294. finite_diff_bounds = (-np.inf, np.inf)
  295. # Define Objective Function
  296. objective = ScalarFunction(fun, x0, args, grad, hess,
  297. finite_diff_rel_step, finite_diff_bounds)
  298. # Put constraints in list format when needed.
  299. if isinstance(constraints, (NonlinearConstraint, LinearConstraint)):
  300. constraints = [constraints]
  301. # Prepare constraints.
  302. prepared_constraints = [
  303. PreparedConstraint(c, x0, sparse_jacobian, finite_diff_bounds)
  304. for c in constraints]
  305. # Check that all constraints are either sparse or dense.
  306. n_sparse = sum(c.fun.sparse_jacobian for c in prepared_constraints)
  307. if 0 < n_sparse < len(prepared_constraints):
  308. raise ValueError("All constraints must have the same kind of the "
  309. "Jacobian --- either all sparse or all dense. "
  310. "You can set the sparsity globally by setting "
  311. "`sparse_jacobian` to either True of False.")
  312. if prepared_constraints:
  313. sparse_jacobian = n_sparse > 0
  314. if bounds is not None:
  315. if sparse_jacobian is None:
  316. sparse_jacobian = True
  317. prepared_constraints.append(PreparedConstraint(bounds, x0,
  318. sparse_jacobian))
  319. # Concatenate initial constraints to the canonical form.
  320. c_eq0, c_ineq0, J_eq0, J_ineq0 = initial_constraints_as_canonical(
  321. n_vars, prepared_constraints, sparse_jacobian)
  322. # Prepare all canonical constraints and concatenate it into one.
  323. canonical_all = [CanonicalConstraint.from_PreparedConstraint(c)
  324. for c in prepared_constraints]
  325. if len(canonical_all) == 0:
  326. canonical = CanonicalConstraint.empty(n_vars)
  327. elif len(canonical_all) == 1:
  328. canonical = canonical_all[0]
  329. else:
  330. canonical = CanonicalConstraint.concatenate(canonical_all,
  331. sparse_jacobian)
  332. # Generate the Hessian of the Lagrangian.
  333. lagrangian_hess = LagrangianHessian(n_vars, objective.hess, canonical.hess)
  334. # Choose appropriate method
  335. if canonical.n_ineq == 0:
  336. method = 'equality_constrained_sqp'
  337. else:
  338. method = 'tr_interior_point'
  339. # Construct OptimizeResult
  340. state = OptimizeResult(
  341. nit=0, nfev=0, njev=0, nhev=0,
  342. cg_niter=0, cg_stop_cond=0,
  343. fun=objective.f, grad=objective.g,
  344. lagrangian_grad=np.copy(objective.g),
  345. constr=[c.fun.f for c in prepared_constraints],
  346. jac=[c.fun.J for c in prepared_constraints],
  347. constr_nfev=[0 for c in prepared_constraints],
  348. constr_njev=[0 for c in prepared_constraints],
  349. constr_nhev=[0 for c in prepared_constraints],
  350. v=[c.fun.v for c in prepared_constraints],
  351. method=method)
  352. # Start counting
  353. start_time = time.time()
  354. # Define stop criteria
  355. if method == 'equality_constrained_sqp':
  356. def stop_criteria(state, x, last_iteration_failed,
  357. optimality, constr_violation,
  358. tr_radius, constr_penalty, cg_info):
  359. state = update_state_sqp(state, x, last_iteration_failed,
  360. objective, prepared_constraints,
  361. start_time, tr_radius, constr_penalty,
  362. cg_info)
  363. if verbose == 2:
  364. BasicReport.print_iteration(state.nit,
  365. state.nfev,
  366. state.cg_niter,
  367. state.fun,
  368. state.tr_radius,
  369. state.optimality,
  370. state.constr_violation)
  371. elif verbose > 2:
  372. SQPReport.print_iteration(state.nit,
  373. state.nfev,
  374. state.cg_niter,
  375. state.fun,
  376. state.tr_radius,
  377. state.optimality,
  378. state.constr_violation,
  379. state.constr_penalty,
  380. state.cg_stop_cond)
  381. state.status = None
  382. state.niter = state.nit # Alias for callback (backward-compatibility)
  383. if callback is not None and callback(np.copy(state.x), state):
  384. state.status = 3
  385. elif state.optimality < gtol and state.constr_violation < gtol:
  386. state.status = 1
  387. elif state.tr_radius < xtol:
  388. state.status = 2
  389. elif state.nit >= maxiter:
  390. state.status = 0
  391. return state.status in (0, 1, 2, 3)
  392. elif method == 'tr_interior_point':
  393. def stop_criteria(state, x, last_iteration_failed, tr_radius,
  394. constr_penalty, cg_info, barrier_parameter,
  395. barrier_tolerance):
  396. state = update_state_ip(state, x, last_iteration_failed,
  397. objective, prepared_constraints,
  398. start_time, tr_radius, constr_penalty,
  399. cg_info, barrier_parameter, barrier_tolerance)
  400. if verbose == 2:
  401. BasicReport.print_iteration(state.nit,
  402. state.nfev,
  403. state.cg_niter,
  404. state.fun,
  405. state.tr_radius,
  406. state.optimality,
  407. state.constr_violation)
  408. elif verbose > 2:
  409. IPReport.print_iteration(state.nit,
  410. state.nfev,
  411. state.cg_niter,
  412. state.fun,
  413. state.tr_radius,
  414. state.optimality,
  415. state.constr_violation,
  416. state.constr_penalty,
  417. state.barrier_parameter,
  418. state.cg_stop_cond)
  419. state.status = None
  420. state.niter = state.nit # Alias for callback (backward compatibility)
  421. if callback is not None and callback(np.copy(state.x), state):
  422. state.status = 3
  423. elif state.optimality < gtol and state.constr_violation < gtol:
  424. state.status = 1
  425. elif (state.tr_radius < xtol
  426. and state.barrier_parameter < barrier_tol):
  427. state.status = 2
  428. elif state.nit >= maxiter:
  429. state.status = 0
  430. return state.status in (0, 1, 2, 3)
  431. if verbose == 2:
  432. BasicReport.print_header()
  433. elif verbose > 2:
  434. if method == 'equality_constrained_sqp':
  435. SQPReport.print_header()
  436. elif method == 'tr_interior_point':
  437. IPReport.print_header()
  438. # Call inferior function to do the optimization
  439. if method == 'equality_constrained_sqp':
  440. def fun_and_constr(x):
  441. f = objective.fun(x)
  442. c_eq, _ = canonical.fun(x)
  443. return f, c_eq
  444. def grad_and_jac(x):
  445. g = objective.grad(x)
  446. J_eq, _ = canonical.jac(x)
  447. return g, J_eq
  448. _, result = equality_constrained_sqp(
  449. fun_and_constr, grad_and_jac, lagrangian_hess,
  450. x0, objective.f, objective.g,
  451. c_eq0, J_eq0,
  452. stop_criteria, state,
  453. initial_constr_penalty, initial_tr_radius,
  454. factorization_method)
  455. elif method == 'tr_interior_point':
  456. _, result = tr_interior_point(
  457. objective.fun, objective.grad, lagrangian_hess,
  458. n_vars, canonical.n_ineq, canonical.n_eq,
  459. canonical.fun, canonical.jac,
  460. x0, objective.f, objective.g,
  461. c_ineq0, J_ineq0, c_eq0, J_eq0,
  462. stop_criteria,
  463. canonical.keep_feasible,
  464. xtol, state, initial_barrier_parameter,
  465. initial_barrier_tolerance,
  466. initial_constr_penalty, initial_tr_radius,
  467. factorization_method)
  468. # Status 3 occurs when the callback function requests termination,
  469. # this is assumed to not be a success.
  470. result.success = True if result.status in (1, 2) else False
  471. result.message = TERMINATION_MESSAGES[result.status]
  472. # Alias (for backward compatibility with 1.1.0)
  473. result.niter = result.nit
  474. if verbose == 2:
  475. BasicReport.print_footer()
  476. elif verbose > 2:
  477. if method == 'equality_constrained_sqp':
  478. SQPReport.print_footer()
  479. elif method == 'tr_interior_point':
  480. IPReport.print_footer()
  481. if verbose >= 1:
  482. print(result.message)
  483. print("Number of iterations: {}, function evaluations: {}, "
  484. "CG iterations: {}, optimality: {:.2e}, "
  485. "constraint violation: {:.2e}, execution time: {:4.2} s."
  486. .format(result.nit, result.nfev, result.cg_niter,
  487. result.optimality, result.constr_violation,
  488. result.execution_time))
  489. return result