_linprog_highs.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. """HiGHS Linear Optimization Methods
  2. Interface to HiGHS linear optimization software.
  3. https://highs.dev/
  4. .. versionadded:: 1.5.0
  5. References
  6. ----------
  7. .. [1] Q. Huangfu and J.A.J. Hall. "Parallelizing the dual revised simplex
  8. method." Mathematical Programming Computation, 10 (1), 119-142,
  9. 2018. DOI: 10.1007/s12532-017-0130-5
  10. """
  11. import inspect
  12. import numpy as np
  13. from ._optimize import OptimizeWarning, OptimizeResult
  14. from warnings import warn
  15. from ._highspy._highs_wrapper import _highs_wrapper
  16. from ._highspy._core import(
  17. kHighsInf,
  18. HighsDebugLevel,
  19. ObjSense,
  20. HighsModelStatus,
  21. simplex_constants as s_c, # [1]
  22. )
  23. from scipy.sparse import csc_array, vstack, issparse
  24. # [1]: Directly importing from "._highspy._core.simplex_constants"
  25. # causes problems when reloading.
  26. # See https://github.com/scipy/scipy/pull/22869 for details.
  27. def _highs_to_scipy_status_message(highs_status, highs_message):
  28. """Converts HiGHS status number/message to SciPy status number/message"""
  29. scipy_statuses_messages = {
  30. None: (4, "HiGHS did not provide a status code. "),
  31. HighsModelStatus.kNotset: (4, ""),
  32. HighsModelStatus.kLoadError: (4, ""),
  33. HighsModelStatus.kModelError: (2, ""),
  34. HighsModelStatus.kPresolveError: (4, ""),
  35. HighsModelStatus.kSolveError: (4, ""),
  36. HighsModelStatus.kPostsolveError: (4, ""),
  37. HighsModelStatus.kModelEmpty: (4, ""),
  38. HighsModelStatus.kObjectiveBound: (4, ""),
  39. HighsModelStatus.kObjectiveTarget: (4, ""),
  40. HighsModelStatus.kOptimal: (0, "Optimization terminated successfully. "),
  41. HighsModelStatus.kTimeLimit: (1, "Time limit reached. "),
  42. HighsModelStatus.kIterationLimit: (1, "Iteration limit reached. "),
  43. HighsModelStatus.kInfeasible: (2, "The problem is infeasible. "),
  44. HighsModelStatus.kUnbounded: (3, "The problem is unbounded. "),
  45. HighsModelStatus.kUnboundedOrInfeasible: (4, "The problem is unbounded "
  46. "or infeasible. ")}
  47. unrecognized = (4, "The HiGHS status code was not recognized. ")
  48. scipy_status, scipy_message = (
  49. scipy_statuses_messages.get(highs_status, unrecognized))
  50. hstat = int(highs_status) if highs_status is not None else None
  51. scipy_message = (f"{scipy_message}"
  52. f"(HiGHS Status {hstat}: {highs_message})")
  53. return scipy_status, scipy_message
  54. def _replace_inf(x):
  55. # Replace `np.inf` with kHighsInf
  56. infs = np.isinf(x)
  57. with np.errstate(invalid="ignore"):
  58. x[infs] = np.sign(x[infs])*kHighsInf
  59. return x
  60. def _convert_to_highs_enum(option, option_str, choices):
  61. # If option is in the choices we can look it up, if not use
  62. # the default value taken from function signature and warn:
  63. try:
  64. return choices[option.lower()]
  65. except AttributeError:
  66. return choices[option]
  67. except KeyError:
  68. sig = inspect.signature(_linprog_highs)
  69. default_str = sig.parameters[option_str].default
  70. warn(f"Option {option_str} is {option}, but only values in "
  71. f"{set(choices.keys())} are allowed. Using default: "
  72. f"{default_str}.",
  73. OptimizeWarning, stacklevel=3)
  74. return choices[default_str]
  75. def _linprog_highs(lp, solver, time_limit=None, presolve=True,
  76. disp=False, maxiter=None,
  77. dual_feasibility_tolerance=None,
  78. primal_feasibility_tolerance=None,
  79. ipm_optimality_tolerance=None,
  80. simplex_dual_edge_weight_strategy=None,
  81. mip_rel_gap=None,
  82. mip_max_nodes=None,
  83. **unknown_options):
  84. r"""
  85. Solve the following linear programming problem using one of the HiGHS
  86. solvers:
  87. User-facing documentation is in _linprog_doc.py.
  88. Parameters
  89. ----------
  90. lp : _LPProblem
  91. A ``scipy.optimize._linprog_util._LPProblem`` ``namedtuple``.
  92. solver : "ipm" or "simplex" or None
  93. Which HiGHS solver to use. If ``None``, "simplex" will be used.
  94. Options
  95. -------
  96. maxiter : int
  97. The maximum number of iterations to perform in either phase. For
  98. ``solver='ipm'``, this does not include the number of crossover
  99. iterations. Default is the largest possible value for an ``int``
  100. on the platform.
  101. disp : bool
  102. Set to ``True`` if indicators of optimization status are to be printed
  103. to the console each iteration; default ``False``.
  104. time_limit : float
  105. The maximum time in seconds allotted to solve the problem; default is
  106. the largest possible value for a ``double`` on the platform.
  107. presolve : bool
  108. Presolve attempts to identify trivial infeasibilities,
  109. identify trivial unboundedness, and simplify the problem before
  110. sending it to the main solver. It is generally recommended
  111. to keep the default setting ``True``; set to ``False`` if presolve is
  112. to be disabled.
  113. dual_feasibility_tolerance : double
  114. Dual feasibility tolerance. Default is 1e-07.
  115. The minimum of this and ``primal_feasibility_tolerance``
  116. is used for the feasibility tolerance when ``solver='ipm'``.
  117. primal_feasibility_tolerance : double
  118. Primal feasibility tolerance. Default is 1e-07.
  119. The minimum of this and ``dual_feasibility_tolerance``
  120. is used for the feasibility tolerance when ``solver='ipm'``.
  121. ipm_optimality_tolerance : double
  122. Optimality tolerance for ``solver='ipm'``. Default is 1e-08.
  123. Minimum possible value is 1e-12 and must be smaller than the largest
  124. possible value for a ``double`` on the platform.
  125. simplex_dual_edge_weight_strategy : str (default: None)
  126. Strategy for simplex dual edge weights. The default, ``None``,
  127. automatically selects one of the following.
  128. ``'dantzig'`` uses Dantzig's original strategy of choosing the most
  129. negative reduced cost.
  130. ``'devex'`` uses the strategy described in [15]_.
  131. ``steepest`` uses the exact steepest edge strategy as described in
  132. [16]_.
  133. ``'steepest-devex'`` begins with the exact steepest edge strategy
  134. until the computation is too costly or inexact and then switches to
  135. the devex method.
  136. Currently, using ``None`` always selects ``'steepest-devex'``, but this
  137. may change as new options become available.
  138. mip_max_nodes : int
  139. The maximum number of nodes allotted to solve the problem; default is
  140. the largest possible value for a ``HighsInt`` on the platform.
  141. Ignored if not using the MIP solver.
  142. unknown_options : dict
  143. Optional arguments not used by this particular solver. If
  144. ``unknown_options`` is non-empty, a warning is issued listing all
  145. unused options.
  146. Returns
  147. -------
  148. sol : dict
  149. A dictionary consisting of the fields:
  150. x : 1D array
  151. The values of the decision variables that minimizes the
  152. objective function while satisfying the constraints.
  153. fun : float
  154. The optimal value of the objective function ``c @ x``.
  155. slack : 1D array
  156. The (nominally positive) values of the slack,
  157. ``b_ub - A_ub @ x``.
  158. con : 1D array
  159. The (nominally zero) residuals of the equality constraints,
  160. ``b_eq - A_eq @ x``.
  161. success : bool
  162. ``True`` when the algorithm succeeds in finding an optimal
  163. solution.
  164. status : int
  165. An integer representing the exit status of the algorithm.
  166. ``0`` : Optimization terminated successfully.
  167. ``1`` : Iteration or time limit reached.
  168. ``2`` : Problem appears to be infeasible.
  169. ``3`` : Problem appears to be unbounded.
  170. ``4`` : The HiGHS solver ran into a problem.
  171. message : str
  172. A string descriptor of the exit status of the algorithm.
  173. nit : int
  174. The total number of iterations performed.
  175. For ``solver='simplex'``, this includes iterations in all
  176. phases. For ``solver='ipm'``, this does not include
  177. crossover iterations.
  178. crossover_nit : int
  179. The number of primal/dual pushes performed during the
  180. crossover routine for ``solver='ipm'``. This is ``0``
  181. for ``solver='simplex'``.
  182. ineqlin : OptimizeResult
  183. Solution and sensitivity information corresponding to the
  184. inequality constraints, `b_ub`. A dictionary consisting of the
  185. fields:
  186. residual : np.ndnarray
  187. The (nominally positive) values of the slack variables,
  188. ``b_ub - A_ub @ x``. This quantity is also commonly
  189. referred to as "slack".
  190. marginals : np.ndarray
  191. The sensitivity (partial derivative) of the objective
  192. function with respect to the right-hand side of the
  193. inequality constraints, `b_ub`.
  194. eqlin : OptimizeResult
  195. Solution and sensitivity information corresponding to the
  196. equality constraints, `b_eq`. A dictionary consisting of the
  197. fields:
  198. residual : np.ndarray
  199. The (nominally zero) residuals of the equality constraints,
  200. ``b_eq - A_eq @ x``.
  201. marginals : np.ndarray
  202. The sensitivity (partial derivative) of the objective
  203. function with respect to the right-hand side of the
  204. equality constraints, `b_eq`.
  205. lower, upper : OptimizeResult
  206. Solution and sensitivity information corresponding to the
  207. lower and upper bounds on decision variables, `bounds`.
  208. residual : np.ndarray
  209. The (nominally positive) values of the quantity
  210. ``x - lb`` (lower) or ``ub - x`` (upper).
  211. marginals : np.ndarray
  212. The sensitivity (partial derivative) of the objective
  213. function with respect to the lower and upper
  214. `bounds`.
  215. mip_node_count : int
  216. The number of subproblems or "nodes" solved by the MILP
  217. solver. Only present when `integrality` is not `None`.
  218. mip_dual_bound : float
  219. The MILP solver's final estimate of the lower bound on the
  220. optimal solution. Only present when `integrality` is not
  221. `None`.
  222. mip_gap : float
  223. The difference between the final objective function value
  224. and the final dual bound, scaled by the final objective
  225. function value. Only present when `integrality` is not
  226. `None`.
  227. Notes
  228. -----
  229. The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
  230. `marginals`, or partial derivatives of the objective function with respect
  231. to the right-hand side of each constraint. These partial derivatives are
  232. also referred to as "Lagrange multipliers", "dual values", and
  233. "shadow prices". The sign convention of `marginals` is opposite that
  234. of Lagrange multipliers produced by many nonlinear solvers.
  235. References
  236. ----------
  237. .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code."
  238. Mathematical programming 5.1 (1973): 1-28.
  239. .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge
  240. simplex algorithm." Mathematical Programming 12.1 (1977): 361-371.
  241. """
  242. if unknown_options:
  243. message = (f"Unrecognized options detected: {unknown_options}. "
  244. "These will be passed to HiGHS verbatim.")
  245. warn(message, OptimizeWarning, stacklevel=3)
  246. # Map options to HiGHS enum values
  247. simplex_dual_edge_weight_strategy_enum = _convert_to_highs_enum(
  248. simplex_dual_edge_weight_strategy,
  249. 'simplex_dual_edge_weight_strategy',
  250. choices={'dantzig': \
  251. s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategyDantzig,
  252. 'devex': \
  253. s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategyDevex,
  254. 'steepest-devex': \
  255. s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategyChoose,
  256. 'steepest': \
  257. s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategySteepestEdge,
  258. None: None})
  259. c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp
  260. lb, ub = bounds.T.copy() # separate bounds, copy->C-cntgs
  261. # highs_wrapper solves LHS <= A*x <= RHS, not equality constraints
  262. with np.errstate(invalid="ignore"):
  263. lhs_ub = -np.ones_like(b_ub)*np.inf # LHS of UB constraints is -inf
  264. rhs_ub = b_ub # RHS of UB constraints is b_ub
  265. lhs_eq = b_eq # Equality constraint is inequality
  266. rhs_eq = b_eq # constraint with LHS=RHS
  267. lhs = np.concatenate((lhs_ub, lhs_eq))
  268. rhs = np.concatenate((rhs_ub, rhs_eq))
  269. if issparse(A_ub) or issparse(A_eq):
  270. A = vstack((A_ub, A_eq))
  271. else:
  272. A = np.vstack((A_ub, A_eq))
  273. A = csc_array(A)
  274. options = {
  275. 'presolve': presolve,
  276. 'sense': ObjSense.kMinimize,
  277. 'solver': solver,
  278. 'time_limit': time_limit,
  279. 'highs_debug_level': HighsDebugLevel.kHighsDebugLevelNone,
  280. 'dual_feasibility_tolerance': dual_feasibility_tolerance,
  281. 'ipm_optimality_tolerance': ipm_optimality_tolerance,
  282. 'log_to_console': disp,
  283. 'mip_max_nodes': mip_max_nodes,
  284. 'output_flag': disp,
  285. 'primal_feasibility_tolerance': primal_feasibility_tolerance,
  286. 'simplex_dual_edge_weight_strategy':
  287. simplex_dual_edge_weight_strategy_enum,
  288. 'simplex_strategy': s_c.SimplexStrategy.kSimplexStrategyDual,
  289. 'ipm_iteration_limit': maxiter,
  290. 'simplex_iteration_limit': maxiter,
  291. 'mip_rel_gap': mip_rel_gap,
  292. }
  293. options.update(unknown_options)
  294. # np.inf doesn't work; use very large constant
  295. rhs = _replace_inf(rhs)
  296. lhs = _replace_inf(lhs)
  297. lb = _replace_inf(lb)
  298. ub = _replace_inf(ub)
  299. if integrality is None or np.sum(integrality) == 0:
  300. integrality = np.empty(0)
  301. else:
  302. integrality = np.array(integrality)
  303. res = _highs_wrapper(c, A.indptr, A.indices, A.data, lhs, rhs,
  304. lb, ub, integrality.astype(np.uint8), options)
  305. # HiGHS represents constraints as lhs/rhs, so
  306. # Ax + s = b => Ax = b - s
  307. # and we need to split up s by A_ub and A_eq
  308. if 'slack' in res:
  309. slack = res['slack']
  310. con = np.array(slack[len(b_ub):])
  311. slack = np.array(slack[:len(b_ub)])
  312. else:
  313. slack, con = None, None
  314. # lagrange multipliers for equalities/inequalities and upper/lower bounds
  315. if 'lambda' in res:
  316. lamda = res['lambda']
  317. marg_ineqlin = np.array(lamda[:len(b_ub)])
  318. marg_eqlin = np.array(lamda[len(b_ub):])
  319. marg_upper = np.array(res['marg_bnds'][1, :])
  320. marg_lower = np.array(res['marg_bnds'][0, :])
  321. else:
  322. marg_ineqlin, marg_eqlin = None, None
  323. marg_upper, marg_lower = None, None
  324. # this needs to be updated if we start choosing the solver intelligently
  325. # Convert to scipy-style status and message
  326. highs_status = res.get('status', None)
  327. highs_message = res.get('message', None)
  328. status, message = _highs_to_scipy_status_message(highs_status,
  329. highs_message)
  330. x = res['x'] # is None if not set
  331. sol = {'x': x,
  332. 'slack': slack,
  333. 'con': con,
  334. 'ineqlin': OptimizeResult({
  335. 'residual': slack,
  336. 'marginals': marg_ineqlin,
  337. }),
  338. 'eqlin': OptimizeResult({
  339. 'residual': con,
  340. 'marginals': marg_eqlin,
  341. }),
  342. 'lower': OptimizeResult({
  343. 'residual': None if x is None else x - lb,
  344. 'marginals': marg_lower,
  345. }),
  346. 'upper': OptimizeResult({
  347. 'residual': None if x is None else ub - x,
  348. 'marginals': marg_upper
  349. }),
  350. 'fun': res.get('fun'),
  351. 'status': status,
  352. 'success': res['status'] == HighsModelStatus.kOptimal,
  353. 'message': message,
  354. 'nit': res.get('simplex_nit', 0) or res.get('ipm_nit', 0),
  355. 'crossover_nit': res.get('crossover_nit'),
  356. }
  357. if np.any(x) and integrality is not None:
  358. sol.update({
  359. 'mip_node_count': res.get('mip_node_count', 0),
  360. 'mip_dual_bound': res.get('mip_dual_bound', 0.0),
  361. 'mip_gap': res.get('mip_gap', 0.0),
  362. })
  363. return sol