Search code examples
pythonschedulingconstraint-programmingor-tools

Google Or-Tools Employee Scheduling .The condition does not work properly


Im using that nurse scheduling example. I have 3 employee 2 shifts and 7 days and I have a contiditon that if an employee works in shift 1 he/she cannot work the next day on shift 0. here is my code and it does not work.

    for n in all_nurses:
      for d in all_days:
        model.Add(sum(shifts[(n, d, s)] for s in range(0,1))+sum(shifts[(n, (d+1)%6, s)] for s in range(1,2)) <= 1)

and this is the output . Nurse 2 worked on day 0 and shift 1 and next day also worked on shift1


Solution

  • According to your constraint:

    for n in all_nurses:
        for d in all_days:
            model.Add(sum([shifts[(n, d, 1)], shifts[(n, (d+1)%7, 0)]]) <= 1)
    

    A better formulation would be

    for n in all_nurses:
        for d in all_days:
            model.AddBoolOr([shifts[(n, d, 1)].Not(), shifts[(n, (d + 1) % 7, 0)].Not()])
    

    ref: https://github.com/google/or-tools/blob/aa0c6c42a523ee4c23633585b86fb6d3e090f8c8/ortools/sat/samples/bool_or_sample_sat.py#L23-L28