python-3.x - 如何在 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 功能。在此先感谢。
解决方案
推荐阅读
- actions-on-google - Google 助理对话操作 - 数字交易 - 连接到您的 Play 库存
- c# - 选择表格行并通过ajax添加行时如何更改表格行的颜色
- javascript - 如何使用 JavaScript/jQuery 在 Laravel 中的表单转发器行上自动填充多个字段?
- python - 为什么即使我使用了eratosthenes筛并且我还使用集合而不是列表,我的素数代码也不适用于大数?
- html - CSS flexbox 子行为
- c# - 将行从 datagridview 拖放到 TextBox
- typescript - 更改不是接口对象的类型
- javascript - 使用 ng-pick-date-time 以 12 小时格式显示时间选择器
- java - 如何从命令行合并两个dex文件
- unity3d - Unity3d中的灯光问题