1

我正在使用 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'
4

1 回答 1

2

您的数据很可能是 numpy.float()。将其转换为在 SetCoefficient 中浮动。

于 2021-12-02T14:48:25.677 回答