我想为我的Max函数及其约束计算如下的线性规划问题(LPP)
我在python 3.7中使用了以下代码。
import random
import pulp
import pandas as pd
L1=[5,10,15]
L2=[1,2,3]
L3=[5,6,7]
n = 10
set_I = range(2, n-1)
set_J = range(2, n)
c = {(i,j): random.normalvariate(0,1) for i in set_I for j in set_J}
a = {(i,j): random.normalvariate(0,5) for i in set_I for j in set_J}
l = {(i,j): random.randint(0,10) for i in set_I for j in set_J}
u = {(i,j): random.randint(10,20) for i in set_I for j in set_J}
b = {j: random.randint(0,30) for j in set_J}
e={0 or 1 or 0.5}
I=L1
P=L2
C=L3
opt_model = pulp.LpProblem(name="LPP")
# if x is Continuous
x_vars = {(i,j):
pulp.LpVariable(cat=pulp.LpContinuous,
lowBound=l[i,j], upBound=u[i,j],
name="x_{0}_{1}".format(i,j))
for i in set_I for j in set_J}
# if x is Binary
x_vars = {(i,j):
pulp.LpVariable(cat=pulp.LpBinary, name="x_{0}_{1}".format(i,j))
for i in set_I for j in set_J}
# if x is Integer
x_vars = {(i,j):
pulp.LpVariable(cat=pulp.LpInteger,
lowBound=l[i,j], upBound= u[i,j],
name="x_{0}_{1}".format(i,j))
for i in set_I for j in set_J}
# Less than equal constraints
constraints = {j :
pulp.LpConstraint(
e=pulp.lpSum(a[i,j] * x_vars[i,j] for i in set_I),
sense=pulp.pulp.LpConstraintLE,
rhs=b[j],
name="constraint_{0}".format(j))
for j in set_J}
# >= constraints
constraints = {j :
pulp.LpConstraint(
e=pulp.lpSum(a[i,j] * x_vars[i,j] for i in set_I),
sense=pulp.LpConstraintGE,
rhs=b[j],
name="constraint_{0}".format(j))
for j in set_J}
# == constraints
constraints = {j :
pulp.LpConstraint(
e=pulp.lpSum(a[i,j] * x_vars[i,j] for i in set_I),
sense=pulp.LpConstraintEQ,
rhs=b[j],
name="constraint_{0}".format(j))
for j in set_J}
objective = pulp.lpSum(x_vars[i,j] * ((e*I*(C[i])) + (1-e)* P(i) )
for i in set_I
for j in set_J)
# for maximization
opt_model.sense = pulp.LpMaximize
opt_model.setObjective(objective)
# solving with CBC
opt_model.solve()
# solving with Glpk
opt_model.solve(solver = GLPK_CMD())
opt_df = pd.DataFrame.from_dict(x_vars, orient="index",
columns = ["variable_object"])
opt_df.index =pd.MultiIndex.from_tuples(opt_df.index,names=
["column_i", "column_j"])
opt_df.reset_index(inplace=True)
opt_df["solution_value"] = opt_df["variable_object"].apply(lambda
item: item.varValue)
opt_df.drop(columns=["variable_object"], inplace=True)
opt_df.to_csv("./optimization_solution.csv")
我是LPP和PULP的初学者。因此我仅根据自己的知识实施了前两个方程式,该代码也给我带来如下错误
TypeError:无法将序列乘以类型为'set'的非整数
如何将方程式3和4的约束添加到我的代码中并解决我的错误。还要指导我我的代码是否正确,我想在哪里修改以满足Max函数的要求。.预先感谢。