_linprog_highs.py 17 KB

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