首页 > 解决方案 > 如何在 python 3.7 中使用 PULP 实现 LPP 功能?

问题描述

我想为我的 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 功能。在此先感谢。

标签: python-3.xpulp

解决方案


推荐阅读