I have been trying to solve a linear programming problem using Pulp in Python. The problem is to maximize 20P_1+12P_2+40P_3+25P_4
, given the conditions P_1+P_2+P_3+P_4<=50, 3P_1+2P_2+P_3<=100, P_2+2P_3+3P_4<=90
. The code below is the Jupyter Notebook for my attempt. I wanted to make the code scalable and so I want to keep everything as an input, something like Object-Oriented Programming. Everything is fine till my objective function, but when I am somehow unable to multiply my constraint_lhs
matrix with the allocation
matrix in the correct order. It seems to be returning 3 equations, which don't make sense to me (the last lines of the code). I am trying to find out what exactly is wrong in my last block of code which is returning this output. Also, are there better ways/libraries to make linear programming problems more scalable, in general.
Thank you
n_prod=4
n_const=3
profit_array = []
for i in range(n_prod):
profit_array.append(float(input("Element:")))
profit_array = np.array(profit_array)
print(np.floor(profit_array))
Element:20
Element:12
Element:40
Element:25
[20. 12. 40. 25.]
constraint_rhs = []
for i in range(n_const):
constraint_rhs.append(float(input("Element:")))
constraint_rhs = np.array(constraint_rhs)
print(np.floor(constraint_rhs))
Element:50
Element:100
Element:90
[ 50. 100. 90.]
constraint_lhs = []
for i in range(n_prod*n_const):
constraint_lhs.append(float(input("Element:")))
constraint_lhs = np.array(constraint_lhs).reshape(n_const,n_prod)
print(np.floor(constraint_lhs))
Element:1
Element:1
Element:1
Element:1
Element:3
Element:2
Element:1
Element:0
Element:0
Element:1
Element:2
Element:3
[[1. 1. 1. 1.]
[3. 2. 1. 0.]
[0. 1. 2. 3.]]
model = LpProblem(name="profit_max", sense=LpMaximize)
DV_variables = LpVariable.matrix("P", variable_names, cat = "Integer", lowBound= 0 )
allocation = np.array(DV_variables)
print("Decision Variable: ")
print(allocation)
Decision Variable:
[P_1 P_2 P_3 P_4]
obj_func = lpSum(allocation.dot(profit_array))
print(obj_func)
model += obj_func
print(model)
20.0*P_1 + 12.0*P_2 + 40.0*P_3 + 25.0*P_4
profit_max:
MAXIMIZE
20.0*P_1 + 12.0*P_2 + 40.0*P_3 + 25.0*P_4 + 0.0
VARIABLES
0 <= P_1 Integer
0 <= P_2 Integer
0 <= P_3 Integer
0 <= P_4 Integer
for i in range(n_const):
print(lpSum(constraint_lhs[i][j]*allocation for j in range(n_prod)) <= constraint_rhs[i])
model+=lpSum(constraint_lhs[i][j]*allocation for j in range(n_prod)) <= constraint_rhs[i]
4.0*P_1 + 4.0*P_2 + 4.0*P_3 + 4.0*P_4 <= 50.0
6.0*P_1 + 6.0*P_2 + 6.0*P_3 + 6.0*P_4 <= 100.0
6.0*P_1 + 6.0*P_2 + 6.0*P_3 + 6.0*P_4 <= 90.0
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…