PuLP目标函数语法不正确

时间:2018-08-30 12:27:51

标签: python optimization scheduling pulp

在为调度优化问题定义目标函数时遇到一些问题。我只是想最小化产能不足。我的设置:

import pulp

nr_employees = 61 #len(dfRolePreferences['Naam'])
nr_shifts = 3
nr_roles = 5 #len(dfRolePreferences.columns) - 1
nr_days = 5

employees = range(1,nr_employees + 1)
roles = range(1, nr_roles + 1)
days = range(1, nr_days + 1)
shifts = range(1, nr_shifts + 1)
hours = range(24) #Export proces

D = {}          # Demand matrix
X = {}          # Assignment matrix

分配矩阵

X = pulp.LpVariable.dicts("X", product(employees, days, shifts, hours), cat=pulp.LpBinary)

需求矩阵 这是我从Excel导入的熊猫数据框。它只有三列

  • “工作日”-工作日(1-5)
  • “小时”-特定时间段(0-23)
  • “需求”-组合所需的资源

我将需求数据框转换为纸浆字典:

for d in days: 
    for h in hours:
        D[(d, h)] = pulp.LpVariable(int(dfDemand.loc[(dfDemand['Weekday']==d) & (dfDemand['Hour']==h), "Demand"]))

但是现在我要创建这样的目标函数:

# Create the problem
scheduling_problem = pulp.LpProblem("Employee Scheduling", pulp.LpMinimize)

obj = None

for d in days:
    for h in hours: 
        obj += (sum(X[(e,d,s,h)] for e in employees for s in shifts) - D[(d,h)])

scheduling_problem += obj
scheduling_problem

我想从X中减去需求值(X值的雇员总和),但是我感觉这种语法对于编写以下公式是不正确的:

enter image description here

您能帮我提供适用于该公式的正确语法吗?

1 个答案:

答案 0 :(得分:0)

您可以通过编写以下内容来对目标函数进行建模:

prob += pulp.lpSum(pulp.lpSum([X[(e,d,s,h)] for e in employees for s in shifts] - D[(d,h)]) for d in days for h in hours)

这导致与写作相同的目标

obj = pulp.LpAffineExpression()
for d in days:
    for h in hours: 
        obj += pulp.lpSum(X[(e,d,s,h)] for e in employees for s in shifts) - D[(d,h)]

prob+= obj # or  prob.setObjective(obj)

示例:

import pulp
import itertools

employees = range(2)
days = range(2)
shifts = range(2)
hours = range(2) 


X = pulp.LpVariable.dicts("X", itertools.product(employees, days, shifts, hours), cat=pulp.LpBinary)
D = pulp.LpVariable.dicts("D", itertools.product(days, hours), cat=pulp.LpBinary)


prob = pulp.LpProblem("example", pulp.LpMinimize)

prob+= pulp.lpSum(pulp.lpSum([X[(e,d,s,h)] for e in employees for s in shifts] - D[(d,h)]) for d in days for h in hours)

结果为:

MINIMIZE
-1*D_(0,_0) + -1*D_(0,_1) + -1*D_(1,_0) + -1*D_(1,_1) + 1*X_(0,_0,_0,_0) + 1*X_(0,_0,_0,_1) + 1*X_(0,_0,_1,_0) + 1*X_(0,_0,_1,_1) + 1*X_(0,_1,_0,_0) + 1*X_(0,_1,_0,_1) + 1*X_(0,_1,_1,_0) + 1*X_(0,_1,_1,_1) + 1*X_(1,_0,_0,_0) + 1*X_(1,_0,_0,_1) + 1*X_(1,_0,_1,_0) + 1*X_(1,_0,_1,_1) + 1*X_(1,_1,_0,_0) + 1*X_(1,_1,_0,_1) + 1*X_(1,_1,_1,_0) + 1*X_(1,_1,_1,_1) + 0