In [1]:
from scipy.optimize import linprog
import numpy as np
Objective function is going to be stored in z
variable, this variable is going to store coefficients of the objective function.
In [2]:
z = np.array([5,4])
Constraints values are going to be stored in C
variable and must be 2-D Array, this variable is going to store all constraints of the problem.
In [3]:
C = np.array([
[1, 1], #C1
[10,6] #C2
])
Upper-bounds values are going to be stored in b
variable and must be 1-D Array. In this case we need to store 5 and 45 for each constraint.
In [4]:
b = np.array([5,45])
Specify bounds, in this case is $\geq0$ for each variable $x_1$ and $x_2$.
In [5]:
x1 = (0, None)
x2 = (0, None)
To solve the problem, we need to call linprog and store the solution in a variable.
The parameters that are going to be used are (z
, A_ub
, b_ub
, bounds
, method
). More detail here.
This LP problem has a maximize objective function and linprog
supports minimize problems. To solve it:
In [6]:
sol = linprog(-z, A_ub = C, b_ub = b, bounds = (x1, x2), method='simplex')
In [7]:
sol
Out[7]:
To print the values that we need:
In [8]:
print(f"x1 = {sol.x[0]}, x2 = {sol.x[1]}, z = {sol.fun*-1}")
Our LP problem is solved, to check the result just replace the values $x_1$ and $x_2$ into the objective function.
$z(max) = 5x_1 + 4x_2$
$z(max) = 5 \times 3.75 + 4 \times 1.25$
$z(max) = 23.75$