bundles / scipy 1.18.0 / scipy / optimize / _linprog / linprog
function
scipy.optimize._linprog:linprog
source: /scipy/optimize/_linprog.py:178
Signature
def linprog(c, A_ub = None, b_ub = None, A_eq = None, b_eq = None, bounds = (0, None), method = highs, callback = None, options = None, x0 = None, integrality = None)Summary
Linear programming: minimize a linear objective function subject to linear equality and inequality constraints.
Extended Summary
Linear programming solves problems of the following form:
\min_x \ & c^T x \\
\mbox{such that} \ & A_{ub} x \leq b_{ub},\\
& A_{eq} x = b_{eq},\\
& l \leq x \leq u ,where is a vector of decision variables; , , , , and are vectors; and and are matrices.
Alternatively, that's:
minimize
c @ xsuch that
A_ub @ x <= b_ub A_eq @ x == b_eq lb <= x <= ub
Note that by default lb = 0 and ub = None. Other bounds can be specified with bounds.
Parameters
c: 1-D arrayThe coefficients of the linear objective function to be minimized.
A_ub: 2-D array, optionalThe inequality constraint matrix. Each row of
A_ubspecifies the coefficients of a linear inequality constraint onx.b_ub: 1-D array, optionalThe inequality constraint vector. Each element represents an upper bound on the corresponding value of
A_ub @ x.A_eq: 2-D array, optionalThe equality constraint matrix. Each row of
A_eqspecifies the coefficients of a linear equality constraint onx.b_eq: 1-D array, optionalThe equality constraint vector. Each element of
A_eq @ xmust equal the corresponding element ofb_eq.bounds: sequence, optionalA sequence of
(min, max)pairs for each element inx, defining the minimum and maximum values of that decision variable. If a single tuple(min, max)is provided, thenminandmaxwill serve as bounds for all decision variables. UseNoneto indicate that there is no bound. For instance, the default bound(0, None)means that all decision variables are non-negative, and the pair(None, None)means no bounds at all, i.e. all variables are allowed to be any real.method: str, optionalThe algorithm used to solve the standard form problem. The following are supported.
'highs' (default)
'interior-point' (legacy)
'revised simplex' (legacy)
'simplex' (legacy)
The legacy methods are deprecated and will be removed in SciPy 1.11.0.
callback: callable, optionalIf 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:
x
The current solution vector.
fun
The current value of the objective function
c @ x.success
Truewhen the algorithm has completed successfully.slack
The (nominally positive) values of the slack,
b_ub - A_ub @ x.con
The (nominally zero) residuals of the equality constraints,
b_eq - A_eq @ x.phase
The phase of the algorithm being executed.
status
An integer representing the status of the algorithm.
0Optimization proceeding nominally.1Iteration limit reached.2Problem appears to be infeasible.3Problem appears to be unbounded.4Numerical difficulties encountered.nit
The current iteration number.
message
A string descriptor of the algorithm status.
Callback functions are not currently supported by the HiGHS methods.
options: dict, optionalA dictionary of solver options. All methods accept the following options:
maxiter
Maximum number of iterations to perform. Default: see method-specific documentation.
disp
Set to
Trueto print convergence messages. Default:False.presolve
Set to
Falseto disable automatic presolve. Default:True.
All methods except the HiGHS solvers also accept:
tol
A tolerance which determines when a residual is "close enough" to zero to be considered exactly zero.
autoscale
Set to
Trueto automatically perform equilibration. Consider using this option if the numerical values in the constraints are separated by several orders of magnitude. Default:False.rr
Set to
Falseto disable automatic redundancy removal. Default:True.rr_method
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 full-rank interpolative decomposition of the matrix.
None:Uses
svdif 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, usespivot. 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 pivot-based algorithm presented in [5] is used.
For method-specific options, see show_options('linprog').
x0: 1-D array, optionalGuess 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
x0represents a basic feasible solution.integrality: 1-D array or int, optionalIndicates the type of integrality constraint on each decision variable.
0Continuous variable; no integrality constraint.1Integer variable; decision variable must be an integer withinbounds.2Semi-continuous variable; decision variable must be withinboundsor0.3Semi-integer variable; decision variable must be an integer withinboundsor0.By default, all variables are continuous.
For mixed integrality constraints, supply an array of shape
c.shape. To infer a constraint on each decision variable from shorter inputs, the argument will be broadcast toc.shapeusing numpy.broadcast_to.This argument is currently used only by the 'highs' method and is ignored otherwise.
Returns
res: OptimizeResultA scipy.optimize.OptimizeResult consisting of the fields below. Note that the return types of the fields may depend on whether the optimization was successful, therefore it is recommended to check
OptimizeResult.statusbefore relying on the other fields:x
The values of the decision variables that minimizes the objective function while satisfying the constraints.
fun
The optimal value of the objective function
c @ x.slack
The (nominally positive) values of the slack variables,
b_ub - A_ub @ x.con
The (nominally zero) residuals of the equality constraints,
b_eq - A_eq @ x.success
Truewhen the algorithm succeeds in finding an optimal solution.status
An integer representing the exit status of the algorithm.
0Optimization terminated successfully.1Iteration limit reached.2Problem appears to be infeasible.3Problem appears to be unbounded.4Numerical difficulties encountered.nit
The total number of iterations performed in all phases.
message
A string descriptor of the exit status of the algorithm.
Notes
This section describes the available solvers that can be selected by the 'method' parameter.
'highs-ds', and 'highs-ipm' are interfaces to the HiGHS simplex and interior-point method solvers [13], respectively. 'highs' (default) 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 problem-dependent. The other solvers are legacy methods and will be removed when callback is supported by the HiGHS methods.
Method 'highs-ds', is a wrapper of the C++ high performance dual revised simplex implementation (HSOL) [13], [14]. Method 'highs-ipm' is a wrapper of a C++ implementation of an iterior-\ point 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.
Method 'interior-point' uses the primal-dual 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.
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.
Method 'simplex' uses a traditional, full-tableau implementation of Dantzig's simplex algorithm [1], [2] (not the Nelder-Mead simplex). This algorithm is included for backwards compatibility and educational purposes.
Before applying 'interior-point', '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_eqorA_ub, representing trivial constraints;columns of zeros in
A_eqandA_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 in b_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 option presolve=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 option rr=False or presolve=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 non-negative slack variables for inequality constraints, and expressing unbounded variables as the difference between two non-negative 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.
Examples
Consider the following problem: .. math:: \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. 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 :math:`-1`. Note also that the last constraint is really the simple bound :math:`-3 \leq x_1 \leq \infty`. Finally, since there are no bounds on :math:`x_0`, we must explicitly specify the bounds :math:`-\infty \leq x_0 \leq \infty`, as the default is for variables to be non-negative. After collecting coeffecients into arrays and tuples, the input for this problem is:from scipy.optimize import linprog c = [-1, 4] A = [[-3, 1], [1, 2]] b = [6, 4] x0_bounds = (None, None) x1_bounds = (-3, None) res = linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]) res.fun res.x res.message✓
'Optimization terminated successfully. (HiGHS Status 7: Optimal)'The marginals (AKA dual values / shadow prices / Lagrange multipliers) and residuals (slacks) are also available.
res.ineqlin
✓residual: [ 3.900e+01 0.000e+00] marginals: [-0.000e+00 -1.000e+00]For example, because the marginal associated with the second inequality constraint is -1, we expect the optimal value of the objective function to decrease by ``eps`` if we add a small amount ``eps`` to the right hand side of the second inequality constraint:
eps = 0.05 b[1] += eps linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]).fun✓
-22.05Also, because the residual on the first inequality constraint is 39, we can decrease the right hand side of the first constraint by 39 without affecting the optimal solution.
b = [6, 4] # reset to original values b[0] -= 39 linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]).fun✓
-22.0
See also
- show_options
Additional options accepted by the solvers.
Aliases
scipy.optimize.linprog