-1

I am looking to find the best replacement item for an old item. An old item can have several potential options for replacement items. I want to only choose one replacement item for each old item.

So in data form lets say that the color is the old item

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

At the end, I want only one red and one blue selected.

For my variable I am using:

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

This is to indicate if I used an option or not.

Then for my constraint I want each item to be used only once to be used in all the options so I tried this for my constraint...

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

However, I get this error... Key Error 'Red'.

So what's the best way to write this constraint?

**UPDATE

I have also tried

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

1 Answers1

0

The only method I could figure out was to create a flag, 1 or 0, for each color and then make a constraint that the max value for that flag could not be more than one.

# 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))