Linear Programming with Python
Install the packages¶
python -m pip install -U "scipy==1.4.*" "pulp==2.1"
In [2]:
!pulptest
To define and solve optimization problems with SciPy¶
In [3]:
from scipy.optimize import linprog
In [4]:
from IPython.display import Image
In [6]:
for url in ("https://bit.ly/3a6qEkq", "https://bit.ly/3krYDsb"):
display(Image(url=url))
In [13]:
obj = (
-1,
-2,
)
lhs_ineq = (
(2, 1,),
(-4, 5,),
(1, -2),
)
rhs_ineq = (
20,
10,
2,
)
lhs_eq = ((-1, 5,),)
rhs_eq = (15,)
The next step is to define the bounds for each variable in the same order as the coefficients. In this case, they’re both between zero and positive infinity
bounds of x
bounds of y
They happen to be the same so create once and multiply by 2.
In [9]:
(bnd := ((0, float("inf"),),) * 2)
Out[9]:
Optimize and Solve¶
In [16]:
(opt := linprog(
c=obj,
A_ub=lhs_ineq,
b_ub=rhs_ineq,
A_eq=lhs_eq,
b_eq=rhs_eq,
bounds=bnd,
method="revised simplex",
))
Out[16]:
In [18]:
opt.fun
Out[18]:
In [19]:
opt.x
Out[19]: