1

I'm working on a variation of the 0-1 knapsack problem using OR tools. I've managed to solve one type of variation, however, on this attempt, I'm having difficulty specifically with the objective function. Here is the code that I'm using. Basically, I want to sum each of the variables associated with an item in the objective function, and then if the item is selected the x[i,j] binary variable will be set to 1:

import math
import pandas as pd
import ortools
from ortools.linear_solver import pywraplp

solver = solver = pywraplp.Solver.CreateSolver('SCIP')

#All of the variables in the dataframe are integer variables
df = pd.read_csv('data.csv') 

#Create a data dictionary to store all of the data items in
data = {}

data['ID'] = df.ID 
data['time'] = df.Time
data['days'] = df.Days
data['canc'] = df.Canc
data['hdu'] = df.HDU
data['priority'] = df['Priority']
  
data['items'] = list(range(len(df.ID)))
data['num_items'] = len(df.ID)
num_knapsacks = 2
data['capacities'] = [480,240]

data['knapsacks'] = list(range(num_knapsacks))

x = {}
for i in data['items']:
    for j in data['knapsacks']:
        x[(i,j)] = solver.IntVar(0,1,'x_%i_%i' % (i, j))
        
#Constraint to limit item to a single knapsack
for i in data['items']:
    solver.Add(sum(x[i,j] for j in data['knapsacks'])<=1)

#Knapsack Capacity Constraint
for j in data['knapsacks']:
    solver.Add(sum(x[(i,j)]*data['time'][i] 
                  for i in data['items']) <= data['capacities'][j])
    
# HDU Constraint
for j in data['knapsacks']:
    solver.Add(sum(x[(i,j)]*data['hdu'][i]
                  for i in data['items']) <= 1)

#objective function
objective = solver.Objective()
for i in data['items']:
    for j in data['knapsacks']:
        objective.SetCoefficient(x[(i,j)], data['days'][i]+data['time'][i]+data['priority'][i]+data['canc'][i])                       
objective.SetMaximization()

The error i'm getting is specifically with the objective function, but I'm not sure why (I got a different version working using a single objective coefficient). The error is:

   return _pywraplp.Objective_SetCoefficient(self, var, coeff)

TypeError: in method 'Objective_SetCoefficient', argument 3 of type 'double'

1 Answer 1

2

most likely you data is a numpy.float(). Cast it to float in SetCoefficient.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.