Python约束

时间:2018-04-18 20:43:24

标签: python mathematical-optimization pulp

我希望找到旧物品的最佳替换物品。旧物品可以有多个替换物品的潜在选项。我只想为每个旧项目选择一个替换项目。

因此,在数据形式中,我们可以说颜色是旧项目

Color-Number
Red-1
Red-2
Red-3
Blue-1
Blue-2

最后,我只想选择一个红色和一个蓝色。

对于我正在使用的变量:

used_vars = LpVariable.dicts("Used",Option,0,1,LpInteger) 

这表示我是否使用了选项。

然后,对于我的约束,我希望每个项目只能在所有选项中使用一次,所以我尝试了这个约束...

prob += lpSum([used_vars['Red']])==1
prob += lpSum([used_vars['Blue']])==1

但是,我收到此错误...键错误'红色'。

那么编写此约束的最佳方法是什么?

**更新

我也试过

for x in final_color_list: prob += sum([used_vars[x] for i in Option] )==1, ''

1 个答案:

答案 0 :(得分:0)

我能想到的唯一方法是为每种颜色创建一个标志1或0,然后制定一个约束,使该标志的最大值不能超过一个。

# Import PuLP modeler functions
from pulp import *

#Import data
import pandas
df = pandas.read_excel('Test.xlsx')

#Set Items
IDS=df['ID'].tolist()

final_color=set(df['Color'].tolist())

#Setting Fields to dictionaries
colors=df.set_index('ID')['Color'].to_dict()
Numbers=df.set_index('ID')['Number'].to_dict()
red=df.set_index('ID')['Red'].to_dict()
blue=df.set_index('ID')['Blue'].to_dict()


# Create the 'prob' variable to contain the problem data
prob = LpProblem("Color Problem",LpMinimize)

#Set Variables
# variable(name, low, upper, discrete/continuous)
used_vars = LpVariable.dicts("Used",IDS,0,1,LpInteger)

# Set Objective Function
prob += lpSum([Numbers[i]*used_vars[i] for i in IDS]),"Minimum Amount"

#Constraints
prob += lpSum([used_vars[i] for i in IDS]) == 2, "Minimum Options"
prob += lpSum([red[i] * used_vars[i] for i in IDS]) == 1, "Red"
prob += lpSum([blue[i] * used_vars[i] for i in IDS]) == 1, "Blue"


# The problem data is written to an .lp file
prob.writeLP("colors.lp")

# The problem is solved using PuLP's choice of Solver
prob.solve()

# The status of the solution is printed to the screen
print ("Status:", LpStatus[prob.status])

# Each of the variables is printed with it's resolved optimum value
for v in prob.variables():
    print (v.name, "=", v.varValue)

# The optimised objective function value is printed to the screen
print ("Total Cost of Diet = ", value(prob.objective))