_linprog.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. """
  2. A top-level linear programming interface.
  3. .. versionadded:: 0.15.0
  4. Functions
  5. ---------
  6. .. autosummary::
  7. :toctree: generated/
  8. linprog
  9. linprog_verbose_callback
  10. linprog_terse_callback
  11. """
  12. import numpy as np
  13. from ._optimize import OptimizeResult, OptimizeWarning
  14. from warnings import warn
  15. from ._linprog_highs import _linprog_highs
  16. from ._linprog_ip import _linprog_ip
  17. from ._linprog_simplex import _linprog_simplex
  18. from ._linprog_rs import _linprog_rs
  19. from ._linprog_doc import (_linprog_highs_doc, _linprog_ip_doc, # noqa: F401
  20. _linprog_rs_doc, _linprog_simplex_doc,
  21. _linprog_highs_ipm_doc, _linprog_highs_ds_doc)
  22. from ._linprog_util import (
  23. _parse_linprog, _presolve, _get_Abc, _LPProblem, _autoscale,
  24. _postsolve, _check_result, _display_summary)
  25. from copy import deepcopy
  26. __all__ = ['linprog', 'linprog_verbose_callback', 'linprog_terse_callback']
  27. __docformat__ = "restructuredtext en"
  28. LINPROG_METHODS = [
  29. 'simplex', 'revised simplex', 'interior-point', 'highs', 'highs-ds', 'highs-ipm'
  30. ]
  31. def linprog_verbose_callback(res):
  32. """
  33. A sample callback function demonstrating the linprog callback interface.
  34. This callback produces detailed output to sys.stdout before each iteration
  35. and after the final iteration of the simplex algorithm.
  36. Parameters
  37. ----------
  38. res : A `scipy.optimize.OptimizeResult` consisting of the following fields:
  39. x : 1-D array
  40. The independent variable vector which optimizes the linear
  41. programming problem.
  42. fun : float
  43. Value of the objective function.
  44. success : bool
  45. True if the algorithm succeeded in finding an optimal solution.
  46. slack : 1-D array
  47. The values of the slack variables. Each slack variable corresponds
  48. to an inequality constraint. If the slack is zero, then the
  49. corresponding constraint is active.
  50. con : 1-D array
  51. The (nominally zero) residuals of the equality constraints, that is,
  52. ``b - A_eq @ x``
  53. phase : int
  54. The phase of the optimization being executed. In phase 1 a basic
  55. feasible solution is sought and the T has an additional row
  56. representing an alternate objective function.
  57. status : int
  58. An integer representing the exit status of the optimization:
  59. ``0`` : Optimization terminated successfully
  60. ``1`` : Iteration limit reached
  61. ``2`` : Problem appears to be infeasible
  62. ``3`` : Problem appears to be unbounded
  63. ``4`` : Serious numerical difficulties encountered
  64. nit : int
  65. The number of iterations performed.
  66. message : str
  67. A string descriptor of the exit status of the optimization.
  68. """
  69. x = res['x']
  70. fun = res['fun']
  71. phase = res['phase']
  72. status = res['status']
  73. nit = res['nit']
  74. message = res['message']
  75. complete = res['complete']
  76. saved_printoptions = np.get_printoptions()
  77. np.set_printoptions(linewidth=500,
  78. formatter={'float': lambda x: f"{x: 12.4f}"})
  79. if status:
  80. print('--------- Simplex Early Exit -------\n')
  81. print(f'The simplex method exited early with status {status:d}')
  82. print(message)
  83. elif complete:
  84. print('--------- Simplex Complete --------\n')
  85. print(f'Iterations required: {nit}')
  86. else:
  87. print(f'--------- Iteration {nit:d} ---------\n')
  88. if nit > 0:
  89. if phase == 1:
  90. print('Current Pseudo-Objective Value:')
  91. else:
  92. print('Current Objective Value:')
  93. print('f = ', fun)
  94. print()
  95. print('Current Solution Vector:')
  96. print('x = ', x)
  97. print()
  98. np.set_printoptions(**saved_printoptions)
  99. def linprog_terse_callback(res):
  100. """
  101. A sample callback function demonstrating the linprog callback interface.
  102. This callback produces brief output to sys.stdout before each iteration
  103. and after the final iteration of the simplex algorithm.
  104. Parameters
  105. ----------
  106. res : A `scipy.optimize.OptimizeResult` consisting of the following fields:
  107. x : 1-D array
  108. The independent variable vector which optimizes the linear
  109. programming problem.
  110. fun : float
  111. Value of the objective function.
  112. success : bool
  113. True if the algorithm succeeded in finding an optimal solution.
  114. slack : 1-D array
  115. The values of the slack variables. Each slack variable corresponds
  116. to an inequality constraint. If the slack is zero, then the
  117. corresponding constraint is active.
  118. con : 1-D array
  119. The (nominally zero) residuals of the equality constraints, that is,
  120. ``b - A_eq @ x``.
  121. phase : int
  122. The phase of the optimization being executed. In phase 1 a basic
  123. feasible solution is sought and the T has an additional row
  124. representing an alternate objective function.
  125. status : int
  126. An integer representing the exit status of the optimization:
  127. ``0`` : Optimization terminated successfully
  128. ``1`` : Iteration limit reached
  129. ``2`` : Problem appears to be infeasible
  130. ``3`` : Problem appears to be unbounded
  131. ``4`` : Serious numerical difficulties encountered
  132. nit : int
  133. The number of iterations performed.
  134. message : str
  135. A string descriptor of the exit status of the optimization.
  136. """
  137. nit = res['nit']
  138. x = res['x']
  139. if nit == 0:
  140. print("Iter: X:")
  141. print(f"{nit: <5d} ", end="")
  142. print(x)
  143. def linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
  144. bounds=(0, None), method='highs', callback=None,
  145. options=None, x0=None, integrality=None):
  146. r"""
  147. Linear programming: minimize a linear objective function subject to linear
  148. equality and inequality constraints.
  149. Linear programming solves problems of the following form:
  150. .. math::
  151. \min_x \ & c^T x \\
  152. \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
  153. & A_{eq} x = b_{eq},\\
  154. & l \leq x \leq u ,
  155. where :math:`x` is a vector of decision variables; :math:`c`,
  156. :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
  157. :math:`A_{ub}` and :math:`A_{eq}` are matrices.
  158. Alternatively, that's:
  159. - minimize ::
  160. c @ x
  161. - such that ::
  162. A_ub @ x <= b_ub
  163. A_eq @ x == b_eq
  164. lb <= x <= ub
  165. Note that by default ``lb = 0`` and ``ub = None``. Other bounds can be
  166. specified with ``bounds``.
  167. Parameters
  168. ----------
  169. c : 1-D array
  170. The coefficients of the linear objective function to be minimized.
  171. A_ub : 2-D array, optional
  172. The inequality constraint matrix. Each row of ``A_ub`` specifies the
  173. coefficients of a linear inequality constraint on ``x``.
  174. b_ub : 1-D array, optional
  175. The inequality constraint vector. Each element represents an
  176. upper bound on the corresponding value of ``A_ub @ x``.
  177. A_eq : 2-D array, optional
  178. The equality constraint matrix. Each row of ``A_eq`` specifies the
  179. coefficients of a linear equality constraint on ``x``.
  180. b_eq : 1-D array, optional
  181. The equality constraint vector. Each element of ``A_eq @ x`` must equal
  182. the corresponding element of ``b_eq``.
  183. bounds : sequence, optional
  184. A sequence of ``(min, max)`` pairs for each element in ``x``, defining
  185. the minimum and maximum values of that decision variable.
  186. If a single tuple ``(min, max)`` is provided, then ``min`` and ``max``
  187. will serve as bounds for all decision variables.
  188. Use ``None`` to indicate that there is no bound. For instance, the
  189. default bound ``(0, None)`` means that all decision variables are
  190. non-negative, and the pair ``(None, None)`` means no bounds at all,
  191. i.e. all variables are allowed to be any real.
  192. method : str, optional
  193. The algorithm used to solve the standard form problem.
  194. The following are supported.
  195. - :ref:`'highs' <optimize.linprog-highs>` (default)
  196. - :ref:`'highs-ds' <optimize.linprog-highs-ds>`
  197. - :ref:`'highs-ipm' <optimize.linprog-highs-ipm>`
  198. - :ref:`'interior-point' <optimize.linprog-interior-point>` (legacy)
  199. - :ref:`'revised simplex' <optimize.linprog-revised_simplex>` (legacy)
  200. - :ref:`'simplex' <optimize.linprog-simplex>` (legacy)
  201. The legacy methods are deprecated and will be removed in SciPy 1.11.0.
  202. callback : callable, optional
  203. If a callback function is provided, it will be called at least once per
  204. iteration of the algorithm. The callback function must accept a single
  205. `scipy.optimize.OptimizeResult` consisting of the following fields:
  206. x : 1-D array
  207. The current solution vector.
  208. fun : float
  209. The current value of the objective function ``c @ x``.
  210. success : bool
  211. ``True`` when the algorithm has completed successfully.
  212. slack : 1-D array
  213. The (nominally positive) values of the slack,
  214. ``b_ub - A_ub @ x``.
  215. con : 1-D array
  216. The (nominally zero) residuals of the equality constraints,
  217. ``b_eq - A_eq @ x``.
  218. phase : int
  219. The phase of the algorithm being executed.
  220. status : int
  221. An integer representing the status of the algorithm.
  222. ``0`` : Optimization proceeding nominally.
  223. ``1`` : Iteration limit reached.
  224. ``2`` : Problem appears to be infeasible.
  225. ``3`` : Problem appears to be unbounded.
  226. ``4`` : Numerical difficulties encountered.
  227. nit : int
  228. The current iteration number.
  229. message : str
  230. A string descriptor of the algorithm status.
  231. Callback functions are not currently supported by the HiGHS methods.
  232. options : dict, optional
  233. A dictionary of solver options. All methods accept the following
  234. options:
  235. maxiter : int
  236. Maximum number of iterations to perform.
  237. Default: see method-specific documentation.
  238. disp : bool
  239. Set to ``True`` to print convergence messages.
  240. Default: ``False``.
  241. presolve : bool
  242. Set to ``False`` to disable automatic presolve.
  243. Default: ``True``.
  244. All methods except the HiGHS solvers also accept:
  245. tol : float
  246. A tolerance which determines when a residual is "close enough" to
  247. zero to be considered exactly zero.
  248. autoscale : bool
  249. Set to ``True`` to automatically perform equilibration.
  250. Consider using this option if the numerical values in the
  251. constraints are separated by several orders of magnitude.
  252. Default: ``False``.
  253. rr : bool
  254. Set to ``False`` to disable automatic redundancy removal.
  255. Default: ``True``.
  256. rr_method : string
  257. Method used to identify and remove redundant rows from the
  258. equality constraint matrix after presolve. For problems with
  259. dense input, the available methods for redundancy removal are:
  260. ``SVD``:
  261. Repeatedly performs singular value decomposition on
  262. the matrix, detecting redundant rows based on nonzeros
  263. in the left singular vectors that correspond with
  264. zero singular values. May be fast when the matrix is
  265. nearly full rank.
  266. ``pivot``:
  267. Uses the algorithm presented in [5]_ to identify
  268. redundant rows.
  269. ``ID``:
  270. Uses a randomized interpolative decomposition.
  271. Identifies columns of the matrix transpose not used in
  272. a full-rank interpolative decomposition of the matrix.
  273. ``None``:
  274. Uses ``svd`` if the matrix is nearly full rank, that is,
  275. the difference between the matrix rank and the number
  276. of rows is less than five. If not, uses ``pivot``. The
  277. behavior of this default is subject to change without
  278. prior notice.
  279. Default: None.
  280. For problems with sparse input, this option is ignored, and the
  281. pivot-based algorithm presented in [5]_ is used.
  282. For method-specific options, see
  283. :func:`show_options('linprog') <show_options>`.
  284. x0 : 1-D array, optional
  285. Guess values of the decision variables, which will be refined by
  286. the optimization algorithm. This argument is currently used only by the
  287. :ref:`'revised simplex' <optimize.linprog-revised_simplex>` method,
  288. and can only be used if `x0` represents a basic feasible solution.
  289. integrality : 1-D array or int, optional
  290. Indicates the type of integrality constraint on each decision variable.
  291. ``0`` : Continuous variable; no integrality constraint.
  292. ``1`` : Integer variable; decision variable must be an integer
  293. within `bounds`.
  294. ``2`` : Semi-continuous variable; decision variable must be within
  295. `bounds` or take value ``0``.
  296. ``3`` : Semi-integer variable; decision variable must be an integer
  297. within `bounds` or take value ``0``.
  298. By default, all variables are continuous.
  299. For mixed integrality constraints, supply an array of shape ``c.shape``.
  300. To infer a constraint on each decision variable from shorter inputs,
  301. the argument will be broadcast to ``c.shape`` using `numpy.broadcast_to`.
  302. This argument is currently used only by the
  303. :ref:`'highs' <optimize.linprog-highs>` method and is ignored otherwise.
  304. Returns
  305. -------
  306. res : OptimizeResult
  307. A :class:`scipy.optimize.OptimizeResult` consisting of the fields
  308. below. Note that the return types of the fields may depend on whether
  309. the optimization was successful, therefore it is recommended to check
  310. `OptimizeResult.status` before relying on the other fields:
  311. x : 1-D array
  312. The values of the decision variables that minimizes the
  313. objective function while satisfying the constraints.
  314. fun : float
  315. The optimal value of the objective function ``c @ x``.
  316. slack : 1-D array
  317. The (nominally positive) values of the slack variables,
  318. ``b_ub - A_ub @ x``.
  319. con : 1-D array
  320. The (nominally zero) residuals of the equality constraints,
  321. ``b_eq - A_eq @ x``.
  322. success : bool
  323. ``True`` when the algorithm succeeds in finding an optimal
  324. solution.
  325. status : int
  326. An integer representing the exit status of the algorithm.
  327. ``0`` : Optimization terminated successfully.
  328. ``1`` : Iteration limit reached.
  329. ``2`` : Problem appears to be infeasible.
  330. ``3`` : Problem appears to be unbounded.
  331. ``4`` : Numerical difficulties encountered.
  332. nit : int
  333. The total number of iterations performed in all phases.
  334. message : str
  335. A string descriptor of the exit status of the algorithm.
  336. See Also
  337. --------
  338. show_options : Additional options accepted by the solvers.
  339. Notes
  340. -----
  341. This section describes the available solvers that can be selected by the
  342. 'method' parameter.
  343. :ref:`'highs-ds' <optimize.linprog-highs-ds>`, and
  344. :ref:`'highs-ipm' <optimize.linprog-highs-ipm>` are interfaces to the
  345. HiGHS simplex and interior-point method solvers [13]_, respectively.
  346. :ref:`'highs' <optimize.linprog-highs>` (default) chooses between
  347. the two automatically. These are the fastest linear
  348. programming solvers in SciPy, especially for large, sparse problems;
  349. which of these two is faster is problem-dependent.
  350. The other solvers are legacy methods and will be removed when `callback` is
  351. supported by the HiGHS methods.
  352. Method :ref:`'highs-ds' <optimize.linprog-highs-ds>`, is a wrapper of the C++ high
  353. performance dual revised simplex implementation (HSOL) [13]_, [14]_.
  354. Method :ref:`'highs-ipm' <optimize.linprog-highs-ipm>` is a wrapper of a C++
  355. implementation of an **i**\ nterior-\ **p**\ oint **m**\ ethod [13]_; it
  356. features a crossover routine, so it is as accurate as a simplex solver.
  357. Method :ref:`'highs' <optimize.linprog-highs>` chooses between the two
  358. automatically.
  359. For new code involving `linprog`, we recommend explicitly choosing one of
  360. these three method values.
  361. .. versionadded:: 1.6.0
  362. Method :ref:`'interior-point' <optimize.linprog-interior-point>`
  363. uses the primal-dual path following algorithm
  364. as outlined in [4]_. This algorithm supports sparse constraint matrices and
  365. is typically faster than the simplex methods, especially for large, sparse
  366. problems. Note, however, that the solution returned may be slightly less
  367. accurate than those of the simplex methods and will not, in general,
  368. correspond with a vertex of the polytope defined by the constraints.
  369. .. versionadded:: 1.0.0
  370. Method :ref:`'revised simplex' <optimize.linprog-revised_simplex>`
  371. uses the revised simplex method as described in
  372. [9]_, except that a factorization [11]_ of the basis matrix, rather than
  373. its inverse, is efficiently maintained and used to solve the linear systems
  374. at each iteration of the algorithm.
  375. .. versionadded:: 1.3.0
  376. Method :ref:`'simplex' <optimize.linprog-simplex>` uses a traditional,
  377. full-tableau implementation of
  378. Dantzig's simplex algorithm [1]_, [2]_ (*not* the
  379. Nelder-Mead simplex). This algorithm is included for backwards
  380. compatibility and educational purposes.
  381. .. versionadded:: 0.15.0
  382. Before applying :ref:`'interior-point' <optimize.linprog-interior-point>`,
  383. :ref:`'revised simplex' <optimize.linprog-revised_simplex>`, or
  384. :ref:`'simplex' <optimize.linprog-simplex>`,
  385. a presolve procedure based on [8]_ attempts
  386. to identify trivial infeasibilities, trivial unboundedness, and potential
  387. problem simplifications. Specifically, it checks for:
  388. - rows of zeros in ``A_eq`` or ``A_ub``, representing trivial constraints;
  389. - columns of zeros in ``A_eq`` `and` ``A_ub``, representing unconstrained
  390. variables;
  391. - column singletons in ``A_eq``, representing fixed variables; and
  392. - column singletons in ``A_ub``, representing simple bounds.
  393. If presolve reveals that the problem is unbounded (e.g. an unconstrained
  394. and unbounded variable has negative cost) or infeasible (e.g., a row of
  395. zeros in ``A_eq`` corresponds with a nonzero in ``b_eq``), the solver
  396. terminates with the appropriate status code. Note that presolve terminates
  397. as soon as any sign of unboundedness is detected; consequently, a problem
  398. may be reported as unbounded when in reality the problem is infeasible
  399. (but infeasibility has not been detected yet). Therefore, if it is
  400. important to know whether the problem is actually infeasible, solve the
  401. problem again with option ``presolve=False``.
  402. If neither infeasibility nor unboundedness are detected in a single pass
  403. of the presolve, bounds are tightened where possible and fixed
  404. variables are removed from the problem. Then, linearly dependent rows
  405. of the ``A_eq`` matrix are removed, (unless they represent an
  406. infeasibility) to avoid numerical difficulties in the primary solve
  407. routine. Note that rows that are nearly linearly dependent (within a
  408. prescribed tolerance) may also be removed, which can change the optimal
  409. solution in rare cases. If this is a concern, eliminate redundancy from
  410. your problem formulation and run with option ``rr=False`` or
  411. ``presolve=False``.
  412. Several potential improvements can be made here: additional presolve
  413. checks outlined in [8]_ should be implemented, the presolve routine should
  414. be run multiple times (until no further simplifications can be made), and
  415. more of the efficiency improvements from [5]_ should be implemented in the
  416. redundancy removal routines.
  417. After presolve, the problem is transformed to standard form by converting
  418. the (tightened) simple bounds to upper bound constraints, introducing
  419. non-negative slack variables for inequality constraints, and expressing
  420. unbounded variables as the difference between two non-negative variables.
  421. Optionally, the problem is automatically scaled via equilibration [12]_.
  422. The selected algorithm solves the standard form problem, and a
  423. postprocessing routine converts the result to a solution to the original
  424. problem.
  425. References
  426. ----------
  427. .. [1] Dantzig, George B., Linear programming and extensions. Rand
  428. Corporation Research Study Princeton Univ. Press, Princeton, NJ,
  429. 1963
  430. .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
  431. Mathematical Programming", McGraw-Hill, Chapter 4.
  432. .. [3] Bland, Robert G. New finite pivoting rules for the simplex method.
  433. Mathematics of Operations Research (2), 1977: pp. 103-107.
  434. .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
  435. optimizer for linear programming: an implementation of the
  436. homogeneous algorithm." High performance optimization. Springer US,
  437. 2000. 197-232.
  438. .. [5] Andersen, Erling D. "Finding all linearly dependent rows in
  439. large-scale linear programming." Optimization Methods and Software
  440. 6.3 (1995): 219-227.
  441. .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
  442. Programming based on Newton's Method." Unpublished Course Notes,
  443. March 2004. Available 2/25/2017 at
  444. https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
  445. .. [7] Fourer, Robert. "Solving Linear Programs by Interior-Point Methods."
  446. Unpublished Course Notes, August 26, 2005. Available 2/25/2017 at
  447. http://www.4er.org/CourseNotes/Book%20B/B-III.pdf
  448. .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
  449. programming." Mathematical Programming 71.2 (1995): 221-245.
  450. .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
  451. programming." Athena Scientific 1 (1997): 997.
  452. .. [10] Andersen, Erling D., et al. Implementation of interior point
  453. methods for large scale linear programming. HEC/Universite de
  454. Geneve, 1996.
  455. .. [11] Bartels, Richard H. "A stabilization of the simplex method."
  456. Journal in Numerische Mathematik 16.5 (1971): 414-434.
  457. .. [12] Tomlin, J. A. "On scaling linear programming problems."
  458. Mathematical Programming Study 4 (1975): 146-166.
  459. .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
  460. "HiGHS - high performance software for linear optimization."
  461. https://highs.dev/
  462. .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
  463. simplex method." Mathematical Programming Computation, 10 (1),
  464. 119-142, 2018. DOI: 10.1007/s12532-017-0130-5
  465. Examples
  466. --------
  467. Consider the following problem:
  468. .. math::
  469. \min_{x_0, x_1} \ -x_0 + 4x_1 & \\
  470. \mbox{such that} \ -3x_0 + x_1 & \leq 6,\\
  471. -x_0 - 2x_1 & \geq -4,\\
  472. x_1 & \geq -3.
  473. The problem is not presented in the form accepted by `linprog`. This is
  474. easily remedied by converting the "greater than" inequality
  475. constraint to a "less than" inequality constraint by
  476. multiplying both sides by a factor of :math:`-1`. Note also that the last
  477. constraint is really the simple bound :math:`-3 \leq x_1 \leq \infty`.
  478. Finally, since there are no bounds on :math:`x_0`, we must explicitly
  479. specify the bounds :math:`-\infty \leq x_0 \leq \infty`, as the
  480. default is for variables to be non-negative. After collecting coeffecients
  481. into arrays and tuples, the input for this problem is:
  482. >>> from scipy.optimize import linprog
  483. >>> c = [-1, 4]
  484. >>> A = [[-3, 1], [1, 2]]
  485. >>> b = [6, 4]
  486. >>> x0_bounds = (None, None)
  487. >>> x1_bounds = (-3, None)
  488. >>> res = linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds])
  489. >>> res.fun
  490. -22.0
  491. >>> res.x
  492. array([10., -3.])
  493. >>> res.message
  494. 'Optimization terminated successfully. (HiGHS Status 7: Optimal)'
  495. The marginals (AKA dual values / shadow prices / Lagrange multipliers)
  496. and residuals (slacks) are also available.
  497. >>> res.ineqlin
  498. residual: [ 3.900e+01 0.000e+00]
  499. marginals: [-0.000e+00 -1.000e+00]
  500. For example, because the marginal associated with the second inequality
  501. constraint is -1, we expect the optimal value of the objective function
  502. to decrease by ``eps`` if we add a small amount ``eps`` to the right hand
  503. side of the second inequality constraint:
  504. >>> eps = 0.05
  505. >>> b[1] += eps
  506. >>> linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]).fun
  507. -22.05
  508. Also, because the residual on the first inequality constraint is 39, we
  509. can decrease the right hand side of the first constraint by 39 without
  510. affecting the optimal solution.
  511. >>> b = [6, 4] # reset to original values
  512. >>> b[0] -= 39
  513. >>> linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]).fun
  514. -22.0
  515. """
  516. meth = method.lower()
  517. methods = {"highs", "highs-ds", "highs-ipm",
  518. "simplex", "revised simplex", "interior-point"}
  519. if meth not in methods:
  520. raise ValueError(f"Unknown solver '{method}'")
  521. if x0 is not None and meth != "revised simplex":
  522. warning_message = "x0 is used only when method is 'revised simplex'. "
  523. warn(warning_message, OptimizeWarning, stacklevel=2)
  524. if np.any(integrality) and not meth == "highs":
  525. integrality = None
  526. warning_message = ("Only `method='highs'` supports integer "
  527. "constraints. Ignoring `integrality`.")
  528. warn(warning_message, OptimizeWarning, stacklevel=2)
  529. elif np.any(integrality):
  530. integrality = np.broadcast_to(integrality, np.shape(c))
  531. else:
  532. integrality = None
  533. lp = _LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality)
  534. lp, solver_options = _parse_linprog(lp, options, meth)
  535. tol = solver_options.get('tol', 1e-9)
  536. # Give unmodified problem to HiGHS
  537. if meth.startswith('highs'):
  538. if callback is not None:
  539. raise NotImplementedError("HiGHS solvers do not support the "
  540. "callback interface.")
  541. highs_solvers = {'highs-ipm': 'ipm', 'highs-ds': 'simplex',
  542. 'highs': None}
  543. sol = _linprog_highs(lp, solver=highs_solvers[meth],
  544. **solver_options)
  545. sol['status'], sol['message'] = (
  546. _check_result(sol['x'], sol['fun'], sol['status'], sol['slack'],
  547. sol['con'], lp.bounds, tol, sol['message'],
  548. integrality))
  549. sol['success'] = sol['status'] == 0
  550. return OptimizeResult(sol)
  551. warn(f"`method='{meth}'` is deprecated and will be removed in SciPy "
  552. "1.11.0. Please use one of the HiGHS solvers (e.g. "
  553. "`method='highs'`) in new code.", DeprecationWarning, stacklevel=2)
  554. iteration = 0
  555. complete = False # will become True if solved in presolve
  556. undo = []
  557. # Keep the original arrays to calculate slack/residuals for original
  558. # problem.
  559. lp_o = deepcopy(lp)
  560. # Solve trivial problem, eliminate variables, tighten bounds, etc.
  561. rr_method = solver_options.pop('rr_method', None) # need to pop these;
  562. rr = solver_options.pop('rr', True) # they're not passed to methods
  563. c0 = 0 # we might get a constant term in the objective
  564. if solver_options.pop('presolve', True):
  565. (lp, c0, x, undo, complete, status, message) = _presolve(lp, rr,
  566. rr_method,
  567. tol)
  568. C, b_scale = 1, 1 # for trivial unscaling if autoscale is not used
  569. postsolve_args = (lp_o._replace(bounds=lp.bounds), undo, C, b_scale)
  570. if not complete:
  571. A, b, c, c0, x0 = _get_Abc(lp, c0)
  572. if solver_options.pop('autoscale', False):
  573. A, b, c, x0, C, b_scale = _autoscale(A, b, c, x0)
  574. postsolve_args = postsolve_args[:-2] + (C, b_scale)
  575. if meth == 'simplex':
  576. x, status, message, iteration = _linprog_simplex(
  577. c, c0=c0, A=A, b=b, callback=callback,
  578. postsolve_args=postsolve_args, **solver_options)
  579. elif meth == 'interior-point':
  580. x, status, message, iteration = _linprog_ip(
  581. c, c0=c0, A=A, b=b, callback=callback,
  582. postsolve_args=postsolve_args, **solver_options)
  583. elif meth == 'revised simplex':
  584. x, status, message, iteration = _linprog_rs(
  585. c, c0=c0, A=A, b=b, x0=x0, callback=callback,
  586. postsolve_args=postsolve_args, **solver_options)
  587. # Eliminate artificial variables, re-introduce presolved variables, etc.
  588. disp = solver_options.get('disp', False)
  589. x, fun, slack, con = _postsolve(x, postsolve_args, complete)
  590. status, message = _check_result(x, fun, status, slack, con, lp_o.bounds,
  591. tol, message, integrality)
  592. if disp:
  593. _display_summary(message, status, fun, iteration)
  594. sol = {
  595. 'x': x,
  596. 'fun': fun,
  597. 'slack': slack,
  598. 'con': con,
  599. 'status': status,
  600. 'message': message,
  601. 'nit': iteration,
  602. 'success': status == 0}
  603. return OptimizeResult(sol)