OR-TOOLS - 如果某些 IntVar 的总和大于 0,则如何设置 BoolVar 的值,否则为 0?

问题描述

我已经浏览了很多文档,但无法弄清楚这一点。我正在使用 or-tools python 进行约束编程。我试图找到一种方法,如果某些 IntVar 的总和大于 0,我可以将 BoolVar 的值设置为 1,否则 BoolVar 应为 0。

我尝试过 AddImplication() 和 OnlyEnforceIf(),它们看起来很有希望,但都没有奏效。尝试了其他一些想法,但大多是出于绝望。

这段代码看起来像这样:

for warehouse in WAREHOUSES:
    model.Add(y[warehouse] == 1).OnlyEnforceIf(sum(x[(warehouse,customer)] for customer in CUSTOMERS) > 0)

当前返回:

AttributeError: 'BoundedLinearExpression' object has no attribute 'Index'

我猜这个错误是因为我需要将一个布尔值传递给 OnlyEnforceIf 而不是一个表达式。我试过在一个单独的函数中进行计算并且只传递返回值(真/假)。该程序运行但将所有 BoolVars 设置为 True,这不是很有帮助。

我已经用线性规划解决了这个已知的练习,所以我知道一些 BoolVars 应该是错误的。

# x is the IntVar: dict with keys that are tuples and the IntVar as value
# y is the BoolVar

解决方法

反过来做:

for warehouse in WAREHOUSES:
    model.Add(sum(x[(warehouse,customer)] for customer in CUSTOMERS) > 0).OnlyEnforceIf(y[warehouse])
    model.Add(sum(x[(warehouse,customer)] for customer in CUSTOMERS) == 0).OnlyEnforceIf(y[warehouse].Not())

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...