I have the following problem.

number_of_machines is controlled by other constraints. I need to set line variable to specific value based on "range" constraint.

number_of_machines = model.NewIntVar(0, 100, '')

model.Add(line == 1).OnlyEnforceIf(number_of_machines > 5 and number_of_machines <= 10)
model.Add(line == 6).OnlyEnforceIf(number_of_machines >= 11 and number_of_machines <= 20)
model.Add(line == 2).OnlyEnforceIf(number_of_machines >= 21 and number_of_machines <= 50)
model.Add(line == 8).OnlyEnforceIf(number_of_machines >= 51 and number_of_machines <= 100)

for "AND" I'm getting the error: NotImplementedError: Evaluating a LinearExpr instance as a Boolean is not implemented. And for linear expression I'm getting another error: 'BoundedLinearExpression' object has no attribute 'Index'

Could you help me with how I should set such conditions in the CP-SAT model?

UPDATED: fixed directions of comparisons (as noticed in the answer)


1 Answer 1


Please read https://github.com/google/or-tools/blob/stable/ortools/sat/doc/channeling.md

OnlyEnforceIf() only accept one or more Boolean literals.

So for the first constraint (assuming there is an error in the direction of the comparisons):

b1 = model.NewBoolVar()
model.AddLinearConstraint(number_of_machines, 6, 10).OnlyEnforceIf(b1)
model.Add(line == 8).OnlyEnforceIf(b1)

and most likely in the end

model.Add(sum(bi) == 1)
  • $\begingroup$ thank you very much!, that should work!! I read this guide, and I was already thinking of using AddImplication, but didn't understand that I should not control b1 directly, the model will pick the only one by itself! $\endgroup$
    – Shkvarka
    Sep 17, 2021 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.