Miguel
Miguel

Reputation: 433

OR-TOOLS - How to set the value of a BoolVar if the sum of some IntVars is greater than 0, else 0?

I've looked through much of the documentation but can't figure this one out. I'm using or-tools python for constraint programming. I'm trying to find a way I can set the value of a BoolVar to 1 if the sum of some IntVars is greater than 0, else the BoolVar should be 0.

I've tried AddImplication() and OnlyEnforceIf() which looked promising, but none worked. Tried a few other ideas but mostly out of desperation.

The piece of code looks like this:

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

This currently returns:

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

I guess the error is because I need to pass a boolean to OnlyEnforceIf instead of an expression. I've tried doing the calculation in a separate funtion and only pass the return value (True/False). The program runs but sets all BoolVars to True which is not very helpfull.

I've already solve this known exercise with Linear Programming so I know some BoolVars should be false.

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

Upvotes: 1

Views: 1934

Answers (1)

Stradivari
Stradivari

Reputation: 2766

Do it the other way around:

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())

Upvotes: 4

Related Questions