scipy.optimize.linprog¶

scipy.optimize.
linprog
(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None, method='interiorpoint', callback=None, options=None, x0=None)[source]¶ Linear programming: minimize a linear objective function subject to linear equality and inequality constraints.
Linear programming solves problems of the following form:
\[\begin{split}\min_x \ & c^T x \\ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\ & A_{eq} x = b_{eq},\\ & l \leq x \leq u ,\end{split}\]where \(x\) is a vector of decision variables; \(c\), \(b_{ub}\), \(b_{eq}\), \(l\), and \(u\) are vectors; and \(A_{ub}\) and \(A_{eq}\) are matrices.
Alternatively, that’s:
minimize:
c @ x
such that:
A_ub @ x <= b_ub A_eq @ x == b_eq lb <= x <= ub
Note that by default
lb = 0
andub = None
unless specified withbounds
. Parameters
 c1D array
The coefficients of the linear objective function to be minimized.
 A_ub2D array, optional
The inequality constraint matrix. Each row of
A_ub
specifies the coefficients of a linear inequality constraint onx
. b_ub1D array, optional
The inequality constraint vector. Each element represents an upper bound on the corresponding value of
A_ub @ x
. A_eq2D array, optional
The equality constraint matrix. Each row of
A_eq
specifies the coefficients of a linear equality constraint onx
. b_eq1D array, optional
The equality constraint vector. Each element of
A_eq @ x
must equal the corresponding element ofb_eq
. boundssequence, optional
A sequence of
(min, max)
pairs for each element inx
, defining the minimum and maximum values of that decision variable. UseNone
to indicate that there is no bound. By default, bounds are(0, None)
(all decision variables are nonnegative). If a single tuple(min, max)
is provided, thenmin
andmax
will serve as bounds for all decision variables. methodstr, optional
The algorithm used to solve the standard form problem. ‘highsds’, ‘highsipm’, ‘highs’, ‘interiorpoint’ (default), ‘revised simplex’, and ‘simplex’ (legacy) are supported.
 callbackcallable, optional
If a callback function is provided, it will be called at least once per iteration of the algorithm. The callback function must accept a single
scipy.optimize.OptimizeResult
consisting of the following fields: x1D array
The current solution vector.
 funfloat
The current value of the objective function
c @ x
. successbool
True
when the algorithm has completed successfully. slack1D array
The (nominally positive) values of the slack,
b_ub  A_ub @ x
. con1D array
The (nominally zero) residuals of the equality constraints,
b_eq  A_eq @ x
. phaseint
The phase of the algorithm being executed.
 statusint
An integer representing the status of the algorithm.
0
: Optimization proceeding nominally.1
: Iteration limit reached.2
: Problem appears to be infeasible.3
: Problem appears to be unbounded.4
: Numerical difficulties encountered. nitint
The current iteration number.
 messagestr
A string descriptor of the algorithm status.
Callback functions are not currently supported by the HiGHS methods.
 optionsdict, optional
A dictionary of solver options. All methods accept the following options:
 maxiterint
Maximum number of iterations to perform. Default: see methodspecific documentation.
 dispbool
Set to
True
to print convergence messages. Default:False
. presolvebool
Set to
False
to disable automatic presolve. Default:True
.
All methods except the HiGHS solvers also accept:
 tolfloat
A tolerance which determines when a residual is “close enough” to zero to be considered exactly zero.
 autoscalebool
Set to
True
to automatically perform equilibration. Consider using this option if the numerical values in the constraints are separated by several orders of magnitude. Default:False
. rrbool
Set to
False
to disable automatic redundancy removal. Default:True
. rr_methodstring
Method used to identify and remove redundant rows from the equality constraint matrix after presolve. For problems with dense input, the available methods for redundancy removal are:
 “SVD”:
Repeatedly performs singular value decomposition on the matrix, detecting redundant rows based on nonzeros in the left singular vectors that correspond with zero singular values. May be fast when the matrix is nearly full rank.
 “pivot”:
Uses the algorithm presented in [5] to identify redundant rows.
 “ID”:
Uses a randomized interpolative decomposition. Identifies columns of the matrix transpose not used in a fullrank interpolative decomposition of the matrix.
 None:
Uses “svd” if the matrix is nearly full rank, that is, the difference between the matrix rank and the number of rows is less than five. If not, uses “pivot”. The behavior of this default is subject to change without prior notice.
Default: None. For problems with sparse input, this option is ignored, and the pivotbased algorithm presented in [5] is used.
For methodspecific options, see
show_options('linprog')
. x01D array, optional
Guess values of the decision variables, which will be refined by the optimization algorithm. This argument is currently used only by the ‘revised simplex’ method, and can only be used if x0 represents a basic feasible solution.
 Returns
 resOptimizeResult
A
scipy.optimize.OptimizeResult
consisting of the fields: x1D array
The values of the decision variables that minimizes the objective function while satisfying the constraints.
 funfloat
The optimal value of the objective function
c @ x
. slack1D array
The (nominally positive) values of the slack variables,
b_ub  A_ub @ x
. con1D array
The (nominally zero) residuals of the equality constraints,
b_eq  A_eq @ x
. successbool
True
when the algorithm succeeds in finding an optimal solution. statusint
An integer representing the exit status of the algorithm.
0
: Optimization terminated successfully.1
: Iteration limit reached.2
: Problem appears to be infeasible.3
: Problem appears to be unbounded.4
: Numerical difficulties encountered. nitint
The total number of iterations performed in all phases.
 messagestr
A string descriptor of the exit status of the algorithm.
See also
show_options
Additional options accepted by the solvers.
Notes
This section describes the available solvers that can be selected by the ‘method’ parameter.
‘highsds’ and ‘highsipm’ are interfaces to the HiGHS simplex and interiorpoint method solvers [13], respectively. ‘highs’ chooses between the two automatically. These are the fastest linear programming solvers in SciPy, especially for large, sparse problems; which of these two is faster is problemdependent. ‘interiorpoint’ is the default as it was the fastest and most robust method before the recent addition of the HiGHS solvers. ‘revised simplex’ is more accurate than interiorpoint for the problems it solves. ‘simplex’ is the legacy method and is included for backwards compatibility and educational purposes.
Method highsds is a wrapper of the C++ high performance dual revised simplex implementation (HSOL) [13], [14]. Method highsipm is a wrapper of a C++ implementation of an interiorpoint method [13]; it features a crossover routine, so it is as accurate as a simplex solver. Method highs chooses between the two automatically. For new code involving
linprog
, we recommend explicitly choosing one of these three method values.New in version 1.5.0.
Method interiorpoint uses the primaldual path following algorithm as outlined in [4]. This algorithm supports sparse constraint matrices and is typically faster than the simplex methods, especially for large, sparse problems. Note, however, that the solution returned may be slightly less accurate than those of the simplex methods and will not, in general, correspond with a vertex of the polytope defined by the constraints.
New in version 1.0.0.
Method revised simplex uses the revised simplex method as described in [9], except that a factorization [11] of the basis matrix, rather than its inverse, is efficiently maintained and used to solve the linear systems at each iteration of the algorithm.
New in version 1.3.0.
Method simplex uses a traditional, fulltableau implementation of Dantzig’s simplex algorithm [1], [2] (not the NelderMead simplex). This algorithm is included for backwards compatibility and educational purposes.
New in version 0.15.0.
Before applying interiorpoint, revised simplex, or simplex, a presolve procedure based on [8] attempts to identify trivial infeasibilities, trivial unboundedness, and potential problem simplifications. Specifically, it checks for:
rows of zeros in
A_eq
orA_ub
, representing trivial constraints;columns of zeros in
A_eq
andA_ub
, representing unconstrained variables;column singletons in
A_eq
, representing fixed variables; andcolumn singletons in
A_ub
, representing simple bounds.
If presolve reveals that the problem is unbounded (e.g. an unconstrained and unbounded variable has negative cost) or infeasible (e.g., a row of zeros in
A_eq
corresponds with a nonzero inb_eq
), the solver terminates with the appropriate status code. Note that presolve terminates as soon as any sign of unboundedness is detected; consequently, a problem may be reported as unbounded when in reality the problem is infeasible (but infeasibility has not been detected yet). Therefore, if it is important to know whether the problem is actually infeasible, solve the problem again with optionpresolve=False
.If neither infeasibility nor unboundedness are detected in a single pass of the presolve, bounds are tightened where possible and fixed variables are removed from the problem. Then, linearly dependent rows of the
A_eq
matrix are removed, (unless they represent an infeasibility) to avoid numerical difficulties in the primary solve routine. Note that rows that are nearly linearly dependent (within a prescribed tolerance) may also be removed, which can change the optimal solution in rare cases. If this is a concern, eliminate redundancy from your problem formulation and run with optionrr=False
orpresolve=False
.Several potential improvements can be made here: additional presolve checks outlined in [8] should be implemented, the presolve routine should be run multiple times (until no further simplifications can be made), and more of the efficiency improvements from [5] should be implemented in the redundancy removal routines.
After presolve, the problem is transformed to standard form by converting the (tightened) simple bounds to upper bound constraints, introducing nonnegative slack variables for inequality constraints, and expressing unbounded variables as the difference between two nonnegative variables. Optionally, the problem is automatically scaled via equilibration [12]. The selected algorithm solves the standard form problem, and a postprocessing routine converts the result to a solution to the original problem.
References
 1
Dantzig, George B., Linear programming and extensions. Rand Corporation Research Study Princeton Univ. Press, Princeton, NJ, 1963
 2
Hillier, S.H. and Lieberman, G.J. (1995), “Introduction to Mathematical Programming”, McGrawHill, Chapter 4.
 3
Bland, Robert G. New finite pivoting rules for the simplex method. Mathematics of Operations Research (2), 1977: pp. 103107.
 4
Andersen, Erling D., and Knud D. Andersen. “The MOSEK interior point optimizer for linear programming: an implementation of the homogeneous algorithm.” High performance optimization. Springer US, 2000. 197232.
 5(1,2,3)
Andersen, Erling D. “Finding all linearly dependent rows in largescale linear programming.” Optimization Methods and Software 6.3 (1995): 219227.
 6
Freund, Robert M. “PrimalDual InteriorPoint Methods for Linear Programming based on Newton’s Method.” Unpublished Course Notes, March 2004. Available 2/25/2017 at https://ocw.mit.edu/courses/sloanschoolofmanagement/15084jnonlinearprogrammingspring2004/lecturenotes/lec14_int_pt_mthd.pdf
 7
Fourer, Robert. “Solving Linear Programs by InteriorPoint Methods.” Unpublished Course Notes, August 26, 2005. Available 2/25/2017 at http://www.4er.org/CourseNotes/Book%20B/BIII.pdf
 8(1,2)
Andersen, Erling D., and Knud D. Andersen. “Presolving in linear programming.” Mathematical Programming 71.2 (1995): 221245.
 9
Bertsimas, Dimitris, and J. Tsitsiklis. “Introduction to linear programming.” Athena Scientific 1 (1997): 997.
 10
Andersen, Erling D., et al. Implementation of interior point methods for large scale linear programming. HEC/Universite de Geneve, 1996.
 11
Bartels, Richard H. “A stabilization of the simplex method.” Journal in Numerische Mathematik 16.5 (1971): 414434.
 12
Tomlin, J. A. “On scaling linear programming problems.” Mathematical Programming Study 4 (1975): 146166.
 13(1,2,3)
Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J. “HiGHS  high performance software for linear optimization.” Accessed 4/16/2020 at https://www.maths.ed.ac.uk/hall/HiGHS/#guide
 14
Huangfu, Q. and Hall, J. A. J. “Parallelizing the dual revised simplex method.” Mathematical Programming Computation, 10 (1), 119142, 2018. DOI: 10.1007/s1253201701305
Examples
Consider the following problem:
\[\begin{split}\min_{x_0, x_1} \ x_0 + 4x_1 & \\ \mbox{such that} \ 3x_0 + x_1 & \leq 6,\\ x_0  2x_1 & \geq 4,\\ x_1 & \geq 3.\end{split}\]The problem is not presented in the form accepted by
linprog
. This is easily remedied by converting the “greater than” inequality constraint to a “less than” inequality constraint by multiplying both sides by a factor of \(1\). Note also that the last constraint is really the simple bound \(3 \leq x_1 \leq \infty\). Finally, since there are no bounds on \(x_0\), we must explicitly specify the bounds \(\infty \leq x_0 \leq \infty\), as the default is for variables to be nonnegative. After collecting coeffecients into arrays and tuples, the input for this problem is:>>> c = [1, 4] >>> A = [[3, 1], [1, 2]] >>> b = [6, 4] >>> x0_bounds = (None, None) >>> x1_bounds = (3, None) >>> from scipy.optimize import linprog >>> res = linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds])
Note that the default method for
linprog
is ‘interiorpoint’, which is approximate by nature.>>> print(res) con: array([], dtype=float64) fun: 21.99999984082494 # may vary message: 'Optimization terminated successfully.' nit: 6 # may vary slack: array([3.89999997e+01, 8.46872439e08] # may vary status: 0 success: True x: array([ 9.99999989, 2.99999999]) # may vary
If you need greater accuracy, try ‘revised simplex’.
>>> res = linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds], method='revised simplex') >>> print(res) con: array([], dtype=float64) fun: 22.0 # may vary message: 'Optimization terminated successfully.' nit: 1 # may vary slack: array([39., 0.]) # may vary status: 0 success: True x: array([10., 3.]) # may vary