【问题标题】:Why doesn't this Boolean Variable in or-tools work?为什么 or-tools 中的这个布尔变量不起作用?
【发布时间】:2021-01-08 16:40:32
【问题描述】:

我正在重新使用 Google 的 OR 工具并尝试(相对)简单的优化。我正在使用 CP SAT 求解器,我可能在这里遗漏了一些基本的东西。 我有一些变量 x、y 和一些常数 c。如果 y 小于 c,我希望 x 等于 1,否则为 0。

from ortools.sat.python import cp_model

solver = cp_model.CpSolver()
model = cp_model.CpModel()
c = 50
x = model.NewBoolVar(name='x')
y = model.NewIntVar(name='y', lb=0, ub=2**10)

model.Add(x == (y < c))

model.Maximize(x+y)

status = solver.Solve(model)

我收到一条错误消息

TypeError: bad operand type for unary -: 'BoundedLinearExpression'

看来我在这里为我的约束滥用了 OR 工具语法。我很难理解在线 OR 工具的文档,而且我似乎忘记的内容比我想象的要多。

【问题讨论】:

    标签: python or-tools constraint-programming


    【解决方案1】:

    根据here 的示例,您就快到了。

    构建x == (y &lt; c) 约束

    案例一:x = true

    如果xtrue,那么y &lt; c 也必须是true。这正是OnlyEnforceIf 方法的用途。如果OnlyEnforceIf的参数是true,那么Add方法中的约束就会被激活:

    model.Add(y < c).OnlyEnforceIf(x) 
    

    案例2:x = false,

    案例 1 中所述,OnlyEnforceIf 不会激活约束,如果其参数未评估为 true。因此,您不能只留下 case y &gt;= c 自己,并希望在 x = false 时暗示它。因此,为这种情况添加一个反向约束如下:

    model.Add(y >= c).OnlyEnforceIf(x.Not())
    

    由于对于x = falsex.Not() 将是true,因此在求解方程时将激活并使用约束y &gt;= c

    完整代码

    from ortools.sat.python import cp_model
    
    solver = cp_model.CpSolver()
    model = cp_model.CpModel()
    c = 50
    x = model.NewBoolVar(name='x')
    y = model.NewIntVar(name='y', lb=0, ub=2**10)
    
    model.Add(y < c).OnlyEnforceIf(x) 
    model.Add(y >= c).OnlyEnforceIf(x.Not())
    
    model.Maximize(x+y)
    
    status = solver.Solve(model) 
    

    【讨论】:

      猜你喜欢
      • 2018-05-21
      • 2016-04-02
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      相关资源
      最近更新 更多