how to count the number of values that are greater than zero in OR-Tools

I am using OR-Tools for an employees scheduling problem. I have a dictionary that is defined as an IntVar, where such dictionary contains the number of hours that will be assigned to each employee, ranging from zero to availability_for_day:

intvars[ID_VAR] = model.NewIntVar(0, availability_for_day, ID_VAR)
model.Add(sum[intvars[intv] for intv in intvars.keys()]<= availability_for_day


The ID_VAR keys for intvars are an f-string combination between dates (yyyy-mm-dd) and employee_id. I want to add a constraint that allows me to set a minimum number of employees that are assigned for a task for each day. Therefore, my question is: how do I count how many intvars[intv] values are greater than zero? Then, how do I set the number of intvars[intv] that are greater than zero to be equal or greater than a minimum number of employees that I want to allocate?

So far, I have tried using another IntVar as a counter, but I could not make it work.

You can a look at this doc.

You will create one Boolean variable per integer variable, and sum them.

• I followed the documentation you linked, and created a Boolean variable for each employee, and such variable is "linked" to the Int variable value (it is true only if the int var is greater than zero). However, when I try doing this: model.Add(sum( [ boolvars[boolv] for boolv in boolvars.keys() ]) )<= num_min_resources I get this error: "NotImplementedError evaluating a LinearExpr instance as a Boolean is not implemented" Any idea why is that happening? Commented Jun 5, 2023 at 14:39
• your code is wrong. One ')' is misplaced. Commented Jun 5, 2023 at 15:31

It's like bin packing problem. Just define set of binary variables $$x_{d,s}$$ where $$d,s$$ is same index as your intvar keys -(date d, staff s). Then add constraints
$$x_{d,s} \le H_{d,s} \le A_{d,s}x_{d,s} \\ \forall d,s$$
where $$H_{d,s}$$ is your intvar and $$A_{d,s}$$ is available hours per $$s$$

$$L_d\le \sum_s x_{d,s} \ \forall d$$ where $$L$$ is min staff required for date $$d$$

• The API is different with CP-SAT. It uses indicator constraints instead of big-M. Commented Jun 1, 2023 at 20:18
• @LaurentPerron I don't use CP-SAT, hoping the OP will get it. Most solvers will wave indicator constraints Commented Jun 1, 2023 at 21:31
• yes, actually CP-SAT being SAT based use indicator constraints natively. bigM are recreated on the fly for the underlying (and optional) simplex. Commented Jun 1, 2023 at 21:36