问题描述
我一直在尝试使用 Python 中的 Pulp 解决线性规划问题。问题是在给定条件 20P_1+12P_2+40P_3+25P_4
的情况下最大化 P_1+P_2+P_3+P_4<=50,3P_1+2P_2+P_3<=100,P_2+2P_3+3P_4<=90
。下面的代码是我尝试的 Jupyter Notebook。我想让代码具有可扩展性,所以我想将所有内容都作为输入,比如面向对象编程。在我的目标函数之前一切都很好,但是当我以某种方式无法以正确的顺序将我的 constraint_lhs
矩阵与 allocation
矩阵相乘时。它似乎返回了 3 个方程,这对我来说没有意义(代码的最后几行)。我试图找出返回此输出的最后一段代码中到底出了什么问题。此外,一般来说,是否有更好的方法/库可以使线性规划问题更具可扩展性。
谢谢
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
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)