# How to add logical OR constraint in OR-Tools?

Let's say nurses normally do 1 shift

for d in all_days:
for s in all_shifts:
model.Add(sum(shifts[(n, d, s)] for n in all_nurses) == 1)


But I want to make nurses either do 1 shift or 3 shifts (but no 2 shifts). How do I combine between

        model.Add(sum(shifts[(n, d, s)] for n in all_nurses) == 1)


and

        model.Add(sum(shifts[(n, d, s)] for n in all_nurses) == 3)


?

• I think it would be better if you use or-tools-discuss groups.google.com/forum/#!forum/or-tools-discuss Commented Jun 6, 2020 at 20:58
• I think my question may also be helpful for other similar optimization libraries Commented Jun 6, 2020 at 21:02

You can also do:

model.AddLinearExpressionInDomain(sum(variables), cp_model.Domain.FromValues([1, 3]))


Or even:

for d in all_days:
for s in all_shifts:
b = model.NewBoolVar("")
model.Add(sum(shifts[(n, d, s)] for n in all_nurses) == 1).OnlyEnforceIf(b)
model.Add(sum(shifts[(n, d, s)] for n in all_nurses) == 3).OnlyEnforceIf(b.Not())


PS:

Let's say nurses normally do 1 shift

Wouldn't that be:

for n in all_nurses:
model.Add(sum(shifts[(n, d, s)] for d in all_days for s in all_shifts) == 1)

• TIL OR-tools has a nice shortcut for that. Do you know where to learn more about those shortcuts? The python reference didn't give enough examples Commented Jun 9, 2020 at 14:19
• I learnt by reading the python reference google.github.io/or-tools/python/ortools/sat/python/… + searching for usage in the repo github.com/google/or-tools/… Commented Jun 9, 2020 at 15:14

Introduce a binary variable $$x_{d,s}$$ and change the right hand side to $$1+2x_{d,s}$$.

• Good library-agnostic solution! Commented Jun 9, 2020 at 5:57