Google OR-Tools NotImplementedError: Evaluating a BoundedLinearExpr as a Boolean value is not supported

Question:

I have developed a nurse scheduling program for one of the departments of the hospital I work with in Python. The program makes use of OR-Tools and is based on the following example: https://github.com/google/or-tools/blob/master/examples/python/shift_scheduling_sat.py

In order to constraint the number of shifts employees can work in a week/month I make use of constraints of the following form:

  model.Add(min_hour <= sum(work[k, s, d] for s in range(1, 4) for d in range(i, j)) <= max_hour)

Here (i,j) denotes beginning/end of a week or month.

The program worked fine for a couple of months, up until about 2 weeks ago. Then I started getting the errors on constraints of this type. Specifically I’m getting the following message:

  NotImplementedError: Evaluating a BoundedLinearExpr as a Boolean value is not supported.

Because of run-time issues I usually run the code on a Google Cloud VM, so this is where I run into trouble. However, when I run the code on my local machine, that likely has a different version of OR-Tools, I don’t get any errors at all.

I haven’t been able to find anything in the documentation about this problem. Therefore I’m wondering how to address this issue? Is it something that needs to be fixed in the package or do I need to rewrite my code. If so, what changes would I need to make, the example code seems to have remained unchanged?

Asked By: Michiel V.

||

Answers:

The Python wrapper was updated to catch more user errors.

In ortools==8.2.8710 this prints OPTIMAL:

from ortools.sat.python import cp_model

model = cp_model.CpModel()
a = model.NewIntVar(0, 1, "")

model.Add(2 <= a <= 3)  # doesn't do anything
solver = cp_model.CpSolver()
solver.Solve(model)

print(solver.StatusName())

while in newer versions it raises an error.

You have to split your constraint into 2 model.Add. (or remove the constraint to get the same wrong behaviour)

Edit: in your case

hours = sum(work[k, s, d] for s in range(1, 4) for d in range(i, j))
model.Add(hours >= min_hour)
model.Add(hours <= max_hour)

# or following Laurent's advice
model.AddLinearExpressionInDomain(hours, cp_model.Domain(min_hour, max_hour))
Answered By: Stradivari

I was able to run the code succesfully, without encountering the BoundedLinearExpr error, after rewriting it, and implementing the constraints the way @Stradivari suggested:

hours = sum(work[k, s, d] for s in range(1, 4) for d in range(i, j))
model.Add(hours >= min_hour)
model.Add(hours <= max_hour)
Answered By: Michiel V.

You can also get this error when using

model.add(yourBoolVar)

instead of

model.add(yourBoolVar == 1)
Answered By: Albert Hendriks