logo

Solving Linear Programming Problems with Python 📂Optimization

Solving Linear Programming Problems with Python

Overview

You can use the scipy package1. Input the linear programming problem expressed in matrix form, as in $A, \mathbf{b}, \mathbf{c}$.

Code

$$ \begin{matrix} \text{Maximize} & & x_{1} & + & x_{2} \\ \text{subject to} &-& x_{1} & + & x_{2} & \le & 1 \\ & & x_{1} & & & \le & 3 \\ & & & & x_{2} & \le & 2 \end{matrix} $$

As a simple example, let us solve the maximization problem in $x_{1} , x_{2} \ge 0$. At the shrimp sushi restaurant, this problem was solved manually using the simplex method, and the answer $\left( x_{1}^{\ast}, x_{2}^{\ast} \right) = (3,2)$ is known. This linear programming problem is

$$ \begin{matrix} \text{Optimize} & \mathbf{c}^{T} \mathbf{x} \\ \text{subject to} & A \mathbf{x} \le \mathbf{b} \end{matrix} $$

with $\mathbf{c} = (1,1)$, $A = \begin{bmatrix} -1 & 1 \\ 1 & 0 \\ 1 & 0 \end{bmatrix}$, $\mathbf{b} = (1,3,2)$, so it can be transcribed and solved as follows.

c = [-1, -1]
A = [[-1, 1], [1, 0], [0, 1]]
b = [1, 3, 2]
x1_bounds = (0, None)
x2_bounds = (0, None)
from scipy.optimize import linprog
res = linprog(c, A_ub=A, b_ub=b, bounds=[x1_bounds, x2_bounds])

The reason for using c = [-1,-1] instead of c = [1,1] is that linprog()’s default optimization direction is for minimization. Just reversing that direction, the result is as we already knew, $\left( x_{1}, x_{2} \right) = \left( 3,2 \right) =$array([3., 2.]).

>>> res
     con: array([], dtype=float64)
     fun: -4.99999999998958
 message: 'Optimization terminated successfully.'
     nit: 4
   slack: array([2.00000000e+00, 2.76267897e-12, 7.65787433e-12])
  status: 0
 success: True
       x: array([3., 2.])

Environment

  • OS: Windows
  • python: v3.9.7
  • scipy v1.7.3

See Also