向OR-Tools约束(CP-SAT求解器)添加or语句



所以我试图在or工具中构建一个类似于员工调度示例的调度工具。然而,在我的情况下,有十个班次要覆盖,我希望通过确保前两个班次或最后两个班次的休息来防止人们有十个小时的工作日。

我想做这样的事情,但它一直说解决方案是不可行的。

all_nurses = range(5)
all_shifts = range(10)
all_days = range(20)
for n in all_nurses:
for d in all_days:
model.add(sum(shifts[(n,d,s)] for s in [0, 1]) == 0 or sum(shifts[(n,d,s)] for s in [8, 9]) == 0)

这真的是不可行的吗?还是这段代码没有做我认为它正在做的事情?


谢谢Laurent帮我找到答案!为了以后参考,在代码中应该是这样的:

for n in all_nurses:
for d in all_days:
# Implement the contraint
b = model.NewBoolVar(f'constr_{n}_{d}')
model.add(sum(shifts[(n,d,s)] for s in [0, 1]) == 0).OnlyEnforceIf(b)
model.add(sum(shifts[(n,d,s)] for s in [0, 1]) > 0).OnlyEnforceIf(b.Not())
# Apply the contraint
model.add(sum(shifts[(n,d,s)] for s in [8, 9]) == 0).OnlyEnforceIf(b.Not())

请阅读https://github.com/google/or-tools/blob/stable/ortools/sat/doc/channeling.md

简而言之,or, and, min, max python关键字没有被正确解释。在你的例子中,sum() == 0,将在对象上,因此在解析python代码时总是求值为True。

您需要创建所有中间布尔变量,并在这些变量上添加bool_or约束。

最新更新