Linear Programming with Python
Install the packages¶
python -m pip install -U "scipy==1.4.*" "pulp==2.1"
!pulptest
To define and solve optimization problems with SciPy¶
from scipy.optimize import linprog
from IPython.display import Image
for url in ("https://bit.ly/3a6qEkq", "https://bit.ly/3krYDsb"):
display(Image(url=url))
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.
(bnd := ((0, float("inf"),),) * 2)
Optimize and Solve¶
(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",
))
opt.fun
opt.x