如何更正Python中OR Tools中的目标函数错误



我正在使用OR工具处理0-1背包问题的变体。我已经设法解决了一种类型的变化,然而,在这次尝试中,我在目标函数方面遇到了困难。这是我正在使用的代码。基本上,我想对目标函数中与某个项目相关的每个变量求和,然后如果选择了该项目,则x[I,j]二进制变量将设置为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()

我得到的错误是与目标函数有关的,但我不确定为什么(我得到了一个使用单个目标系数的不同版本(。错误为:

return _pywraplp.Objective_SetCoefficient(self, var, coeff)
TypeError: in method 'Objective_SetCoefficient', argument 3 of type 'double'

您的数据很可能是numpy.floot((。将其强制转换为SetCoefficient中的float。

相关内容

  • 没有找到相关文章

最新更新