Python 遍历 LpSum

问题描述

正在处理纸浆优化问题,我希望它遍历我的数据(特别是通过我的场景列)。在这个示例数据集中,我包含了 4 个独特的场景(名称、类型、限制不会改变,但值和场景会改变)。这优化得很好,但它着眼于数据忽略场景的整个示例(这是意料之中的,因为我没有任何代码告诉它这样做)。我试图将场景连同名称和类型一起包含在索引中,但当我这样做时,它仍然只针对我的约束的解决方案进行了优化。

对于场景 1、场景 2、场景 3、场景 4 等,所需的输出将是独特的纸浆优化(这在现实世界场景中可能从数百到数千不等)。

电流输出 =
选择 john 作为黄色类型
选择 scott 作为蓝色类型
为绿色类型选择丹尼
选择 roger 类型为紫色
为红色选择保罗

期望输出 =
场景一
选择 scott 作为蓝色类型
选择 bob 作为红色类型
为黄色类型选择丹尼
为紫色类型选择凯尔
为绿色类型选择麦克

场景二
选择 john 作为黄色类型
选择红色类型的时间
为紫色类型选择知更鸟
选择 scott 作为蓝色类型
为绿色类型选择 roger

场景三
选择 john 作为绿色类型
选择 scott 作为类型紫色
为黄色类型选择鲍勃
为蓝色类型选择山姆
选择 paul 作为红色类型

场景四
选择 john 作为黄色类型
选择 scott 作为蓝色类型
为紫色类型选择丹尼
为绿色类型选择 roger
为红色选择保罗

import pulp
import pandas as pd

data = [['john','red',12,1108,'scenario_1'],['john','yellow','green',['tim',21,3676,['robin',22,1162,'purple','blue',['scott',50,2756,['bob',47,2381,['sam',16,1636,['danny',30,1414,['roger',41,3028,['kyle',40,1146,['paul',18,3429,['mike',3404,25,'scenario_2'],53,54,43,17,15,'scenario_3'],11,46,33,37,27,44,14,51,'scenario_4'],28,49,'scenario_4']]

df = pd.DataFrame(data,columns= ['name','type','value','limit','scenario'])
print(df)

df.set_index(['name','type'],inplace=True)

name_type_groupings = df.index
name_set = df.index.unique(0)

limit = df['limit'].to_dict()
values = df['value'].to_dict()

select = pulp.LpVariable.dicts('selected',name_type_groupings,cat='Binary')

prob = pulp.LpProblem('optimal_selections',pulp.LpMaximize)

prob += pulp.lpSum([select[n,t]*values[n,t] for (n,t) in name_type_groupings])

prob += pulp.lpSum([select[n,t]*limit[n,t) in name_type_groupings]) <= 12500

prob += pulp.lpSum([select[n,t) in name_type_groupings if t == 'red']) == 1

prob += pulp.lpSum([select[n,t) in name_type_groupings if t == 'yellow']) == 1

prob += pulp.lpSum([select[n,t) in name_type_groupings if t == 'green']) == 1

prob += pulp.lpSum([select[n,t) in name_type_groupings if t == 'blue']) == 1

prob += pulp.lpSum([select[n,t) in name_type_groupings if t == 'purple']) == 1

for name in name_set:
    prob += pulp.lpSum([select[n,t) in name_type_groupings if n == name]) <= 1

prob.solve()

for idx in select:
    if select[idx].varValue:
        print(f'select {idx[0]} for type {idx[1]}')

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)